# CS-15: Is the change real? One test, twelve weeks

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

Web page: https://apopt.com/course/tutorials/cs15-is-change-real/ · Data: https://apopt.com/data/tutorials/cs15-is-change-real/

## The decision

An athlete has filmed three countermovement jumps every Monday for twelve weeks, with a
four-week jump-training block in weeks 7 to 10. The coach must say one of three things:
**improved**, **no clear change**, or **retest**. If the jump has improved, the block stays in
the plan; if not, the time goes elsewhere. The answer has to survive a learning effect, a bad
night's sleep, and a change of phone halfway through.

## Predict first

On this test a Monday's mean wobbles by about a centimeter from week to week. At the end of the block, the last two Mondays average 1.2 cm above the four baseline Mondays, and the smallest change worth having is 0.65 cm. Improved, no clear change, or retest?

## The raw data

- `raw/athlete-record-simulated.csv`: SIMULATED: a 12-week athlete record, 51 rows: three jumps and one resting pulse each Monday, with device, protocol and conditions; week 12 holds a bridge (the same jumps filmed by two phones) Made for this course by `prepare.py` (seed 2027) from a stated model. Not a recording.
- `raw/simulation-truth.csv`: SIMULATED: what was planted in each week: true ability, learning effect, day effect, phone bias Written by the same program, for the check at the end.
- `raw/sessions_fit.csv`: 693 watch activity summaries, June 2024 to November 2026, one row per activity with the FIT session fields in the watch's own names and units (seconds, meters, m/s, bpm; start time in UTC with the local offset beside it); 475 are outdoor runs 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.

| Field | Meaning | Unit | Range | Missing |
|---|---|---|---|---|
| date | session date | local date | 2027-01-04 to 2027-03-22 | none |
| time | session time with the UTC offset | hh:mm±hh:mm | 07:05-07:00 to 07:12-06:00 | none |
| test | the protocol | text | cmj, resting-hr | none |
| metric | what the value is | text with unit at the end | jump_height_cm, resting_hr_bpm | none |
| value | one number | cm or bpm | 29.9–36.0 cm; 49–55 bpm | blank |
| unit | unit of the value | text | cm, bpm | none |
| trial | repeat within the session | count | 1–3 | none |
| device | what measured it | text | phone-120fps, phone-60fps, chest-strap | none |
| app | app that computed the value | text | jump, heart | none |
| app_version | app build date | date | 2026-11-20 or 2026-11-26 | none |
| protocol_version | camera position and frame rate | text | v1-side-3m-waist-120fps, v2-side-3m-knee-60fps, v1-supine-1min | none |
| conditions | sleep the night before | text | slept 5–8 h | none |
| note | anything unusual | text | free text | blank |

What is wrong with it: one jump has no value (the app could not find the takeoff); the first
two weeks are practice, lower because the athlete was still learning the test; week 4 followed
a five-hour night; and from week 11 a new phone filmed from knee height at 60 frames per
second, which reads higher on the same jump. The clock offset changes from −07:00 to −06:00 in
week 11 because of daylight saving time. None of this is hidden: the record's own columns say
all of it, which is why they are there. The watch archive mixes sports (runs, swims, rides,
elliptical, walks) and treadmill runs with outdoor ones; its clock is UTC with the local offset
in a separate column; its cadence counts one foot; and some "runs" are a few hundred meters
long. Its first three months of runs are a minute per kilometer slower, with a lower step rate,
than everything after, and December 2024 and September 2026 have fewer than five steady runs.
Wrist heart rate is weak on swims and can lock onto the step rate on runs.

## Part 1: a simulated twelve-week record

The athlete record (Appendix J) holds one number per row: every jump, every resting pulse,
with the device, the protocol and the conditions beside it. This record is **simulated**. No
student has a full term of weekly tests yet, so the course made one with a program, and
planted in it the things that happen to real records: a learning effect in the first weeks,
a bad Monday, a real training gain, and a new phone. Because the truth is known, you can check
at the end how close each method came. Part 2 repeats the method on a real record: an
athlete's runs from 2024 to 2026.

### Step 1 · Gather

Open the record and list what changed from week to week before looking at any jump height.

*Predict first:* The record has three jumps and one resting pulse each Monday for 12 weeks. How many rows do you expect?

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

rec = pd.read_csv("raw/athlete-record-simulated.csv")
print(rec.shape)
print(rec.groupby(["test", "metric"]).size().to_string())
jump = rec[rec["metric"] == "jump_height_cm"].copy()
jump["week"] = pd.factorize(jump["date"])[0] + 1        # Monday sessions in date order
setup = jump.groupby("week").agg(date=("date", "first"), device=("device", lambda s: " + ".join(sorted(set(s)))),
                                 conditions=("conditions", "first"))
print(setup.to_string())
print(jump.loc[jump["note"].notna(), ["week", "device", "trial", "value", "note"]].to_string(index=False))
```

Output:

```
(51, 13)
test        metric        
cmj         jump_height_cm    39
resting-hr  resting_hr_bpm    12
            date                      device conditions
week                                                   
1     2027-01-04                phone-120fps  slept 7 h
2     2027-01-11                phone-120fps  slept 7 h
3     2027-01-18                phone-120fps  slept 8 h
4     2027-01-25                phone-120fps  slept 5 h
5     2027-02-01                phone-120fps  slept 7 h
6     2027-02-08                phone-120fps  slept 8 h
7     2027-02-15                phone-120fps  slept 7 h
8     2027-02-22                phone-120fps  slept 7 h
9     2027-03-01                phone-120fps  slept 8 h
10    2027-03-08                phone-120fps  slept 7 h
11    2027-03-15                 phone-60fps  slept 7 h
12    2027-03-22  phone-120fps + phone-60fps  slept 8 h
 week       device  trial  value                                        note
    6 phone-120fps      2    NaN   app warning: takeoff not found; no height
   12  phone-60fps      1   36.0 bridge: the same jump filmed by both phones
   12  phone-60fps      2   35.8 bridge: the same jump filmed by both phones
   12  phone-60fps      3   35.2 bridge: the same jump filmed by both phones
   12 phone-120fps      1   35.1 bridge: the same jump filmed by both phones
   12 phone-120fps      2   35.1 bridge: the same jump filmed by both phones
   12 phone-120fps      3   33.9 bridge: the same jump filmed by both phones
```

Fifty-one rows, not 48: in week 12 the same three jumps were filmed by two phones. The
record says three things before any number is read. Week 4 followed a short night. From week
11 a new phone filmed at 60 frames per second from knee height (`protocol_version` v2), where
the old one filmed at 120 from waist height. And one jump in week 6 has no height, because
the app could not find the takeoff.

### Step 2 · Statistics

Profile each session: how many jumps, their mean and their spread.

*Predict first:* How much do three jumps on the same morning differ, in centimeters?

```python
sess = (jump.dropna(subset=["value"]).groupby(["week", "device"])["value"]
        .agg(["count", "mean", "std"]))
print(sess.round(2).to_string())
dof = sess["count"] - 1
within = np.sqrt((sess["std"] ** 2 * dof).sum() / dof.sum())   # pooled over sessions
print(f"jump-to-jump SD within a morning: {within:.2f} cm")
```

Output:

```
                   count   mean   std
week device                          
1    phone-120fps      3  31.30  0.53
2    phone-120fps      3  32.37  0.61
3    phone-120fps      3  33.03  0.15
4    phone-120fps      3  30.93  0.93
5    phone-120fps      3  33.40  0.70
6    phone-120fps      2  32.25  0.07
7    phone-120fps      3  32.27  0.32
8    phone-120fps      3  33.37  0.58
9    phone-120fps      3  33.43  0.38
10   phone-120fps      3  33.77  0.65
11   phone-60fps       3  35.60  0.20
12   phone-120fps      3  34.70  0.69
     phone-60fps       3  35.67  0.42
jump-to-jump SD within a morning: 0.55 cm
```

Jumps on one morning agree to about half a centimeter. Keep that number; Step 2 again
compares it with how much a whole morning moves from week to week.

### Step 3 · Visualize

Plot every jump, not only the means, and mark the device change before reading a trend.

```python
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6.6, 3.4))
for dev, mk in [("phone-120fps", "o"), ("phone-60fps", "^")]:
    d = jump[jump["device"] == dev]
    ax.plot(d["week"], d["value"], mk, color="0.55", mfc="white", ms=5, label=f"each jump, {dev}")
    m = d.groupby("week")["value"].mean()
    ax.plot(m.index, m.values, "-" if dev == "phone-120fps" else ":", marker=mk, color="black", ms=4)
ax.axvline(10.5, color="0.4", ls="--", lw=1)
ax.text(10.6, ax.get_ylim()[0] + 0.3, "new phone", fontsize=8)
ax.set(xlabel="week", ylabel="jump height (cm)", xticks=range(1, 13),
       title="Raw record: the last two weeks jump up with the new phone")
ax.legend(fontsize=8, loc="upper left")
plt.tight_layout()
```

![Jump height against week. Small circles are single jumps with the old phone, triangles with the new phone; a line joins the old phone's weekly means; a dashed line marks the change of phone before week 11.](https://apopt.com/course/tutorials/cs15-is-change-real/c05-1.png)

Three things to notice. Week 1 is low. Week 4 dips and week 5 comes straight back. And the
new phone reads more than a centimeter above the old one on the very same jumps of week 12.

### Step 4 · Cleanse

The rules are written before the analysis, and none of them changes a number in the record:

1. A row with no value is dropped from the analysis and logged.
2. Weeks 1 and 2 are practice. They stay in the record but not in the baseline.
3. The **baseline** is weeks 3 to 6, the four Mondays before the jump-training block began in week 7.
4. A session's value is the mean of its jumps. A different device or protocol starts a new
   segment, which is compared with the old one only through a **bridge**: the same jumps
   filmed by both.

```python
import os

log = [{"rule": "no value", "rows_removed": int(rec["value"].isna().sum())}]
clean = rec.dropna(subset=["value"])
os.makedirs("clean", exist_ok=True)
clean.to_csv("clean/athlete-record.csv", index=False)       # same columns as the record
pd.DataFrame(log).to_csv("clean/change_log.csv", index=False)
ok = jump.dropna(subset=["value"])
old = ok[ok["device"] == "phone-120fps"].groupby("week")["value"].mean()
new = ok[ok["device"] == "phone-60fps"].groupby("week")["value"].mean()
base = old.loc[3:6]
print(pd.DataFrame(log).to_string(index=False))
print("old phone, weekly means:", old.round(2).to_dict())
print("new phone, weekly means:", new.round(2).to_dict())
```

Output:

```
    rule  rows_removed
no value             1
old phone, weekly means: {1: 31.3, 2: 32.37, 3: 33.03, 4: 30.93, 5: 33.4, 6: 32.25, 7: 32.27, 8: 33.37, 9: 33.43, 10: 33.77, 12: 34.7}
new phone, weekly means: {11: 35.6, 12: 35.67}
```

The clean record keeps the record's columns, so any tool that reads the record format can
read it. The chart below draws it.

### Step 2 again · Typical error and the smallest worthwhile change

Chapter 11 measures the wobble of a test with a **test–retest** study. With one athlete, the
baseline Mondays are the retests: nothing was meant to change across weeks 3 to 6, so the
standard deviation of their four means is the **typical error of one session** (the rule of
build step B-11). The **smallest worthwhile change** (SWC) comes from the sport, not the
measurement; this athlete and coach agreed before the term to use the book's 0.65 cm
(Section 11.1.2: a fifth of the spread between teammates).

*Predict first:* Will the week-to-week wobble of a session mean be smaller or larger than the jump-to-jump SD divided by √3?

```python
te_session = base.std()                  # SD of four baseline Monday means
swc = 0.65                               # agreed before the term, cm
print(f"baseline (weeks 3-6): mean {base.mean():.2f} cm, typical error of a session {te_session:.2f} cm")
print(f"expected from jump-to-jump scatter alone: {within / np.sqrt(3):.2f} cm")
print(f"SWC {swc} cm; noise of one session against the 4-week mean: {te_session * np.sqrt(1 + 1/4):.2f} cm")
from scipy.stats import chi2
nu = len(base) - 1                       # four weeks give three degrees of freedom
print(f"90% interval for the typical error: {te_session * np.sqrt(nu / chi2.ppf(0.95, nu)):.2f} "
      f"to {te_session * np.sqrt(nu / chi2.ppf(0.05, nu)):.2f} cm")
```

Output:

```
baseline (weeks 3-6): mean 32.40 cm, typical error of a session 1.09 cm
expected from jump-to-jump scatter alone: 0.32 cm
SWC 0.65 cm; noise of one session against the 4-week mean: 1.22 cm
90% interval for the typical error: 0.68 to 3.19 cm
```

A whole morning moves more than three times as much as three jumps averaged together would
suggest. The jumps of one morning share that morning: its sleep, its warm-up, its mood. So
filming more jumps on one day does not remove the day-to-day wobble; only more days do. And
the noise of one session is larger than the SWC, so a single Monday can never settle the
question.

### Step 3 again · A trend, a band and a run rule

Draw the weekly means against the baseline band (mean ± one typical error) and the SWC, with
a three-week rolling mean. Then apply a **run rule**, written before looking: a change is
flagged when three Mondays in a row sit above the top of the band. One high Monday is not
enough. Weeks 11 and 12 are left out until Step 4 again deals with the new phone.

*Predict first:* In which week will the run rule first fire on the old phone's weeks?

```python
weeks = old.loc[:10]
roll = weeks.rolling(3).mean()
top = base.mean() + te_session
above = weeks > top
run = above & above.shift(1, fill_value=False) & above.shift(2, fill_value=False)
print("above the band:", list(weeks.index[above]))
print("run rule fires in week:", list(weeks.index[run]) or "none yet")

fig, ax = plt.subplots(figsize=(6.6, 3.4))
ax.axhspan(base.mean() - te_session, top, color="0.88", lw=0, label="baseline ± typical error")
for s, lab in ((-swc, None), (swc, "baseline ± SWC")):
    ax.axhline(base.mean() + s, color="0.3", ls="--", lw=0.8, label=lab)
ax.plot(weeks.index, weeks, "o-", color="black", label="weekly mean (old phone)")
ax.plot(roll.index, roll, "-", color="0.5", lw=2.5, alpha=0.7, label="3-week rolling mean")
ax.axvspan(0.5, 2.5, color="0.95", lw=0)
ax.text(1.5, 0.95, "practice", fontsize=8, ha="center", transform=ax.get_xaxis_transform())
ax.set(xlabel="week", ylabel="jump height (cm)", xticks=range(1, 11),
       title="The block lifts the jump, slowly; one Monday never decides")
ax.legend(fontsize=8, loc="lower right")
plt.tight_layout()
```

Output:

```
above the band: [10]
run rule fires in week: none yet
```

![Weekly means of the old phone against week with a gray band for the baseline mean plus or minus one typical error, dashed lines at the baseline mean plus and minus the SWC, a three-week rolling mean, and an arrow where the run rule fires.](https://apopt.com/course/tutorials/cs15-is-change-real/c13-1.png)

The rolling mean climbs through the block, but only week 10 clears the top of the band, so by
week 10 the run rule has not fired. The dashed lines show why one Monday
never settles it: the band is wider than the SWC.

### Step 2 again · The decision rule of Section 11.1.3

For a change Δ with noise σ, the chances that the true change is a worthwhile gain, trivial
or a loss follow from the normal curve, and each chance gets a word (Table 11.2). The chances
then give one of three statuses: **improved** when a worthwhile gain is at least likely (75% or
more), **no clear change** when both a gain and a loss are unlikely (under 25%), and
**retest** when the answer is "possibly". (A likely loss would read **declined**.)

*Predict first:* Week 5 is 2.5 cm above week 4. What status do you expect when week 5 is compared with week 4, and when it is compared with the baseline?

```python
from scipy.stats import norm

WORDS = [(0.005, "most unlikely"), (0.05, "very unlikely"), (0.25, "unlikely"), (0.75, "possibly"),
         (0.95, "likely"), (0.995, "very likely"), (1.01, "most likely")]

def verdict(delta, noise, swc=swc, unit="cm"):
    gain = 1 - norm.cdf((swc - delta) / noise)
    loss = norm.cdf((-swc - delta) / noise)
    word = next(w for cut, w in WORDS if gain < cut)
    status = ("improved" if gain >= 0.75 else "declined" if loss >= 0.75
              else "no clear change" if max(gain, loss) < 0.25 else "retest")
    return (f"change {delta:+.2f} {unit}, noise {noise:.2f}: gain {gain:.0%} ({word}), "
            f"trivial {1 - gain - loss:.0%}, loss {loss:.0%} -> {status}")

print("week 5 vs week 4:       ", verdict(old[5] - old[4], te_session * np.sqrt(2)))
print("week 5 vs baseline:     ", verdict(old[5] - base.mean(), te_session * np.sqrt(1 + 1/4)))
print("weeks 9-10 vs baseline: ", verdict(old.loc[9:10].mean() - base.mean(), te_session * np.sqrt(1/2 + 1/4)))
print("weeks 9-10 vs weeks 1-4:", verdict(old.loc[9:10].mean() - old.loc[1:4].mean(), te_session * np.sqrt(1/2 + 1/4)))
```

Output:

```
week 5 vs week 4:        change +2.47 cm, noise 1.54: gain 88% (likely), trivial 10%, loss 2% -> improved
week 5 vs baseline:      change +1.00 cm, noise 1.22: gain 61% (possibly), trivial 30%, loss 9% -> retest
weeks 9-10 vs baseline:  change +1.20 cm, noise 0.95: gain 72% (possibly), trivial 26%, loss 3% -> retest
weeks 9-10 vs weeks 1-4: change +1.69 cm, noise 0.95: gain 86% (likely), trivial 13%, loss 1% -> improved
```

Read the four lines in order.

* **Week 5 against week 4** says "improved". That is **regression to the mean**: week 4 was a
  bad morning, and the next measurement after an unusually low one is usually closer to the
  athlete's normal, with or without training. Against the whole baseline, week 5 is ordinary.
* **Weeks 9–10 against the baseline**, the honest comparison at the end of the block, says
  "possibly": retest.
* **Against weeks 1–4** the same weeks look like a clearer gain. Weeks 1 and 2 were low
  because the athlete was still learning the test, a **learning effect**, not lost fitness.
  A baseline that includes them flatters any later change.

### Step 4 again · A step that is not training

Week 11 is the first Monday with the new phone. Its mean is far above everything before it.
Is that the block finally showing? The bridge in week 12 answers it: the same three jumps,
filmed by both phones.

*Predict first:* How much higher does the new phone read on the same jump?

```python
w11 = new[11]
print("week 11 (new phone) vs baseline:", verdict(w11 - base.mean(), te_session * np.sqrt(1 + 1/4)))
pair = ok[ok["week"] == 12].pivot(index="trial", columns="device", values="value")
diff = pair["phone-60fps"] - pair["phone-120fps"]
print(pair.assign(difference=diff).to_string())
offset = diff.mean()
print(f"bridge: the new phone reads {offset:+.2f} cm (SD of the three differences {diff.std():.2f})")
series = old.loc[:10].copy()
series[11] = w11 - offset                       # week 11 on the old phone's scale
series[12] = old[12]                            # week 12 from the old phone itself
late = series.loc[9:12]
print("corrected weekly means, weeks 9-12:", late.round(2).to_dict())
print("weeks 9-12 vs baseline:", verdict(late.mean() - base.mean(), te_session * np.sqrt(1/4 + 1/4)))
hi3 = series > base.mean() + te_session
print("run rule on the corrected series fires in week:",
      list(series.index[hi3 & hi3.shift(1, fill_value=False) & hi3.shift(2, fill_value=False)]))
```

Output:

```
week 11 (new phone) vs baseline: change +3.20 cm, noise 1.22: gain 98% (very likely), trivial 2%, loss 0% -> improved
device  phone-120fps  phone-60fps  difference
trial                                        
1               35.1         36.0         0.9
2               35.1         35.8         0.7
3               33.9         35.2         1.3
bridge: the new phone reads +0.97 cm (SD of the three differences 0.31)
corrected weekly means, weeks 9-12: {9: 33.43, 10: 33.77, 11: 34.63, 12: 34.7}
weeks 9-12 vs baseline: change +1.73 cm, noise 0.77: gain 92% (likely), trivial 8%, loss 0% -> improved
run rule on the corrected series fires in week: [12]
```

Uncorrected, week 11 would have been reported as a very likely gain of more than three
centimeters. About a centimeter of that is the phone. On the old phone's scale the last four
weeks give a likely worthwhile gain, and in week 12 the run rule fires as well: three Mondays
in a row above the band. "Improved" is the status to report. Without the bridge the
step could not have been measured at all; a device change in a record needs one, or a fresh
baseline.

### Check against the truth

The simulation's planted values are in `raw/simulation-truth.csv`. Compare each with what the
record let you estimate.

```python
truth = pd.read_csv("raw/simulation-truth.csv").set_index("week")
true_gain = (truth["true_ability_cm"] - 33.0).loc[9:12].mean()
print(f"training gain, weeks 9-12: planted {true_gain:.2f} cm, estimated {late.mean() - base.mean():.2f}")
print(f"learning effect, week 1: planted {truth.loc[1, 'learning_cm']:.1f} cm, "
      f"seen {old[1] - base.mean():+.2f} (includes that morning's day effect)")
print(f"new phone: planted {truth.loc[12, 'device_bias_cm']:.1f} cm, bridge {offset:.2f}")
print("day effects in the baseline weeks:", truth.loc[3:6, "day_effect_cm"].tolist())
```

Output:

```
training gain, weeks 9-12: planted 1.38 cm, estimated 1.73
learning effect, week 1: planted -1.5 cm, seen -1.10 (includes that morning's day effect)
new phone: planted 1.2 cm, bridge 0.97
day effects in the baseline weeks: [-0.32, -2.4, -0.03, -0.2]
```

Every estimate landed within half a centimeter of the truth, and each miss has a cause you
can name. The baseline weeks happened to include the bad Monday of week 4, which pulls the
baseline mean down and the estimated gain up. Three jumps make a short bridge.

### How good is the run rule? Autocorrelation

Mondays are not independent: a good week tends to follow a good week, because sleep, a cold
or a heavy training week last longer than a day. In the simulation each week's day effect
keeps half of the last one (a lag-1 autocorrelation of 0.5). That makes runs above the band
more common by chance. Simulate many unchanged athletes and count false alarms.

*Predict first:* With no real change at all, how often will three-in-a-row fire somewhere in six weeks?

```python
rng = np.random.default_rng(0)

def false_alarms(phi, n=20000, weeks=10):
    e = np.zeros((n, weeks))
    for t in range(1, weeks):
        e[:, t] = phi * e[:, t - 1] + rng.normal(0, np.sqrt(1 - phi**2), n)
    b = e[:, :4]                                      # four baseline weeks, unit noise
    hi = (e[:, 4:] > (b.mean(1) + b.std(1, ddof=1))[:, None])
    three = hi[:, 2:] & hi[:, 1:-1] & hi[:, :-2]
    return three.any(axis=1).mean()

for phi in (0.0, 0.5):
    print(f"lag-1 autocorrelation {phi}: run rule fires by chance in {false_alarms(phi):.0%} of unchanged records")
```

Output:

```
lag-1 autocorrelation 0.0: run rule fires by chance in 9% of unchanged records
lag-1 autocorrelation 0.5: run rule fires by chance in 20% of unchanged records
```

Even with no memory the rule fires by chance in about one unchanged record in eleven,
because four baseline weeks give a rough mean and a rough band. With the planted memory it
fires in one in five. Read a run of
three as "look harder", and confirm it with the decision rule and a retest.

## Part 2: a real record, 2024 to 2026

There is no real weekly jump record yet. There is a real long record: the activity history of
an adult male athlete in his mid-40s, 693 activities from one watch, of which 475 are outdoor
runs. Which number in it can be tracked like a test?

* Pace is there for every run, but a 3 km jog and a 15 km long run are different tests. So
  keep runs of **6 to 12 km**, the athlete's usual steady run, and take the **median pace of
  each month**, which a single race or a walk-jog cannot move much. Months with fewer than
  five such runs are left out. Treadmill runs and the one track session are left out too: a
  treadmill sets its own pace, and the watch measures its distance from the wrist.
* Heart rate is there on almost every run, from the watch's optical sensor. So you can also
  track **meters per heartbeat**: distance divided by the number of beats it took. A fitter
  heart moves you further on each beat.

The file stores time in seconds and distance in meters. Its clock is UTC, with the local offset
in its own column, so the local month comes from `start_time` plus `utc_offset_h`. It is still
not a controlled test: route, weather, hills and intent change from run to run. That is the
lesson of Part 2.

*Predict first:* Do you expect the athlete's pace to drift by more or less than 1% over two years?

```python
raw = pd.read_csv("raw/sessions_fit.csv")
runs = raw[(raw["sport"] == "running") & ~raw["sub_sport"].isin(["indoor_running", "track"])].copy()
runs["start"] = (pd.to_datetime(raw["start_time"].str.rstrip("Z"))
                 + pd.to_timedelta(raw["utc_offset_h"], unit="h"))       # UTC + offset = local
runs["km"] = runs["total_distance"] / 1000
runs["pace_s_km"] = runs["total_timer_time"] / runs["km"]               # pauses excluded
runs["climb_m_km"] = runs["total_ascent"] / runs["km"]
runs["spm"] = 2 * runs["avg_running_cadence"]                           # the file counts one foot
runs["m_per_beat"] = runs["total_distance"] / (runs["total_timer_time"] / 60 * runs["avg_heart_rate"])
steady = runs[runs["km"].between(6, 12)]
month = steady.groupby(steady["start"].dt.to_period("M")).agg(
    runs=("pace_s_km", "size"), pace=("pace_s_km", "median"), climb=("climb_m_km", "median"),
    hr=("avg_heart_rate", "median"), spm=("spm", "median"), m_per_beat=("m_per_beat", "median"))
month = month[month["runs"] >= 5]
month = month.reindex(pd.period_range(month.index.min(), month.index.max(), freq="M"))  # gaps stay missing
month.round(3).to_csv("clean/monthly_pace.csv")
print(f"{len(runs)} outdoor runs, {len(steady)} of 6-12 km; {month['pace'].notna().sum()} months with "
      f"5 or more, {month['pace'].isna().sum()} months missing")
print(month.drop(columns="m_per_beat").dropna().round(1).to_string())
```

Output:

```
475 outdoor runs, 326 of 6-12 km; 27 months with 5 or more, 2 months missing
         runs   pace  climb     hr    spm
2024-07   8.0  415.9    7.8  153.0  167.0
2024-08   9.0  415.3    7.3  152.0  160.0
2024-09   6.0  363.1    7.0  158.0  165.0
2024-10  11.0  313.1    7.7  163.0  176.0
2024-11  11.0  325.4   10.9  160.0  176.0
2025-01  11.0  303.4    8.1  163.0  176.0
2025-02  11.0  313.4   10.4  162.0  176.0
2025-03  12.0  303.2    6.7  159.5  176.0
2025-04  14.0  304.7    7.0  160.5  177.0
2025-05  15.0  315.7    5.9  155.0  176.0
2025-06   5.0  328.8    7.7  151.0  178.0
2025-07  13.0  318.1    6.8  158.0  176.0
2025-08  14.0  307.1    5.0  154.0  176.0
2025-09  19.0  303.9    6.5  155.0  178.0
2025-10  17.0  309.7    7.6  156.0  178.0
2025-11  17.0  310.6    5.7  154.0  176.0
2025-12   7.0  312.2    6.4  159.0  176.0
2026-01  15.0  309.8    6.0  156.0  176.0
2026-02   5.0  298.5    6.9  165.0  178.0
2026-03  14.0  310.6    5.1  158.0  175.0
2026-04  14.0  306.2    5.7  157.0  174.0
2026-05   6.0  314.4    6.9  156.0  173.0
2026-06  14.0  298.9    4.6  161.0  176.0
2026-07  14.0  310.1    5.3  156.0  176.0
2026-08   7.0  324.1    4.1  150.0  174.0
2026-10  17.0  322.9    3.7  150.0  176.0
2026-11  14.0  307.8    3.5  158.0  177.0
```

Read the table before any statistics. The first three months, July to September 2024, are
about a minute per kilometer slower than everything after, with a lower step rate and a
lower heart rate. Walk breaks show up as a lower step rate. The file cannot say why; it can
say these runs were not the same test. Like the practice weeks of Part 1, they stay in the
record but not in the baseline. Two months (December 2024 and September 2026) had fewer than
five steady runs. They are missing, not slow and not zero, and they stay missing. The slowest
later months, June 2025 and August and October 2026, also have the lowest heart rates (150 to
151 bpm): easier runs, which is intent, not lost fitness. And the climb per kilometer falls
by half over the two years: the routes changed too.

```python
first6 = month["pace"].dropna().iloc[:6]                   # naive: the first six months
base_p = month.loc["2024-10":, "pace"].dropna().iloc[:6]   # after the start-up: Oct 2024 - Apr 2025
last = month["pace"].dropna().iloc[-5:]                    # Jun - Nov 2026
te_p, swc_p = base_p.std(), 0.01 * base_p.mean()           # SWC: 1% of pace, agreed in advance
r1 = month.loc["2024-10":, "pace"].autocorr(1)
n_eff = len(last) * (1 - r1) / (1 + r1)
print(f"baseline {base_p.mean():.1f} s/km, typical error of a month {te_p:.1f}, SWC {swc_p:.1f}")
print(f"lag-1 autocorrelation from Oct 2024 {r1:.2f}; 5 months carry about {n_eff:.1f} months' information")
print("last 5 vs first 6 months:", verdict(first6.mean() - last.mean(),      # faster = positive
      first6.std() * np.sqrt(1 / 5 + 1 / 6), 0.01 * first6.mean(), "s/km"))
print("last 5 months vs baseline:", verdict(base_p.mean() - last.mean(),
      te_p * np.sqrt(1 / len(last) + 1 / len(base_p)), swc_p, "s/km"))
import matplotlib.dates
fig, ax = plt.subplots(figsize=(6.6, 3.2))
ax.axhspan(base_p.mean() - te_p, base_p.mean() + te_p, color="0.88", lw=0, label="baseline ± typical error")
ax.plot(month.index.to_timestamp(), month["pace"], "o-", color="black", mfc="white", ms=4, label="monthly median")
ax.plot(last.index.to_timestamp(), last, "o", color="black", ms=5, label="last five months")
ax.invert_yaxis()                                          # faster is up
ax.xaxis.set_major_locator(matplotlib.dates.MonthLocator(bymonth=[1, 7]))
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%b %Y"))
ax.set(xlabel="month", ylabel="pace (s/km), faster up", title="After the start-up, steady-run pace barely moves")
ax.legend(fontsize=8, loc="lower right")
plt.tight_layout()
```

Output:

```
baseline 310.5 s/km, typical error of a month 8.6, SWC 3.1
lag-1 autocorrelation from Oct 2024 0.13; 5 months carry about 3.8 months' information
last 5 vs first 6 months: change +43.29 s/km, noise 30.52: gain 90% (likely), trivial 3%, loss 6% -> improved
last 5 months vs baseline: change -2.21 s/km, noise 5.23: gain 15% (unlikely), trivial 41%, loss 43% -> retest
```

![Monthly median pace of 6 to 12 km runs from July 2024 to November 2026, faster up, with slow start-up months in 2024, a gray baseline band from October 2024 to April 2025, gaps in December 2024 and September 2026, and filled markers for the last five months.](https://apopt.com/course/tutorials/cs15-is-change-real/c25-1.png)

The two baselines give opposite answers. Against the first six months, start-up included, the
last five months are more than 40 s/km faster: "likely improved". That is the learning effect
of Part 1 again; a baseline that holds the start-up flatters everything after it. Against the
honest baseline, the last five months are about 2 s/km (under 1%) *slower*, which is possibly
a small loss and possibly nothing, so the status is "retest". Once the start-up is left out,
the months carry little memory from one to the next. With the start-up in, a long climb makes
neighboring months look alike, and a run rule would fire on the trend.

Pace leaves out how hard the athlete worked. Heart rate puts that back.

*Predict first:* Pace did not improve. Will distance per heartbeat improve, stay the same, or fall?

```python
mpb = month["m_per_beat"]
base_e, last_e = mpb.loc[base_p.index], mpb.loc[last.index]   # the same months as for pace
pct = lambda v: 100 * v / base_e.mean()                       # work in % of the baseline
te_e = pct(base_e.std())
r1_e = mpb.loc["2024-10":].autocorr(1)
print(f"baseline {base_e.mean():.3f} m/beat, typical error {te_e:.1f}%; last 5 months {last_e.mean():.3f} m/beat")
print("baseline months:", dict(zip(base_e.index.astype(str), base_e.round(3))))
print(f"lag-1 autocorrelation from Oct 2024 {r1_e:.2f}; 5 months carry about "
      f"{len(last_e) * (1 - r1_e) / (1 + r1_e):.1f} months' information")
print("last 5 months vs baseline:", verdict(pct(last_e.mean()) - 100,          # SWC: 1% again
      te_e * np.sqrt(1 / len(last_e) + 1 / len(base_e)), 1.0, "%"))
```

Output:

```
baseline 1.193 m/beat, typical error 3.3%; last 5 months 1.238 m/beat
baseline months: {'2024-10': 1.172, '2024-11': 1.145, '2025-01': 1.177, '2025-02': 1.183, '2025-03': 1.249, '2025-04': 1.232}
lag-1 autocorrelation from Oct 2024 0.43; 5 months carry about 2.0 months' information
last 5 months vs baseline: change +3.76 %, noise 1.99: gain 92% (likely), trivial 7%, loss 1% -> improved
```

At about the same pace, the heart now beats less often. The last five months cover 3.8% more
ground per beat than the baseline, a likely worthwhile gain (92%). Read the baseline months
before you believe it. The rise happened *inside* the baseline, from 1.172 m/beat in October
2024 to 1.249 in March 2025, and the last five months average 1.238: the number rose in the
first winter and has held since. A baseline that is still climbing is not a steady baseline.
The memory from month to month is also larger here (0.43), so five months carry about two
months' information. And heat, hills, easy days and a wrist sensor all move heart rate. The
summer months sit in the last five and not in the baseline, and heat raises heart rate, so
heat did not make this gain. The honest reading: the steady run got cheaper for the heart
during the first winter and has stayed cheaper; pace has not changed. To track fitness rather
than routes, use a fixed test, the same course or a treadmill at a fixed speed with heart rate,
recorded the same way each time. That is exactly what the weekly record of Part 1 was
designed to be.

## How good is the number?

The typical error of one Monday, 1.09 cm, comes from only four baseline weeks; its 90%
interval runs from 0.68 to 3.19 cm, so every chance computed from it is rough. The Mondays
also carry memory from week to week: in simulation, the three-in-a-row run rule fires by
chance in 9% of unchanged records with no memory and in 20% with the planted memory, so a run
is a reason to look harder, not proof. The bridge used three jumps; its estimate of the phone
offset (0.97 cm) missed the planted 1.2 cm by about a quarter of a centimeter. Against the
planted truth, the estimated gain (1.73 cm) was 0.35 cm too high, because the baseline
happened to include the bad Monday. In the watch archive, the typical error of a month's pace
(8.6 s/km) comes from six baseline months, and the gain in distance per heartbeat happened
inside those months, so the 92% chance there rests on a baseline that was still moving.

## Track it

One row per jump: `date, time, test=cmj, metric=jump_height_cm, value, unit=cm, trial,
device, app=jump, app_version, protocol_version, conditions, note`. When the phone or the
camera position changes, change `device` or `protocol_version`, and film one bridge session
with both, noted as such. Never edit a row; add one.

## With your own data

Start your own record now: three jumps every Monday, filmed the same way, saved with the jump
app's results file and added as rows in the record format. After six Mondays you have a
baseline; after ten, a trend. Run this notebook with `raw/athlete-record-simulated.csv`
replaced by your file, and set the baseline weeks and device names in Step 4 to yours.

## The same method in another field

A plant historian faces the same problem with a sensor: readings drift, and a replaced or
recalibrated sensor shifts the whole trend by itself. Engineers run the old and new sensor side
by side for a while (a bridge) and judge a change against a baseline band before calling it
real. See the Data-Driven Engineering page on [sensors](https://apmonitor.com/dde/index.php/Main/SensorSignal),
which covers calibration, drift and noise.

## Acknowledgements

The simulated record was made for this course. The watch archive is a COROS Training Hub
export of an adult male athlete in his mid-40s, published in the course case file.

## Action card

- **Finding:** Your jump has likely improved by a worthwhile amount, about 1.7 cm, since the block began.
- **Evidence:** The last four Mondays averaged 34.1 cm on the old phone's scale against 32.4 cm in weeks 3–6, and three Mondays in a row sat above your usual range.
- **Sure:** Likely (92%), not certain: the baseline is only four weeks, and the new phone needed a correction of about 1 cm.
- **Action:** Keep the jump work in the plan, and film every Monday with the same phone, from the same spot.
- **Retest:** In four weeks, three jumps on the new phone, plus one more bridge week with both phones.

## Challenge: Another record, the same rule

Apply the method of this case study to a second record: your own weekly jumps if you have
six or more Mondays, a classmate's under a written data-sharing agreement, or the resting
pulse rows of this simulated record (`metric=resting_hr_bpm`), where a *lower* value is
better.

1. Write the cleaning rules, the baseline weeks and the SWC before you look at the later weeks, and keep them with your notebook.
2. Compute the typical error of a session from the baseline weeks, with its 90% interval.
3. Draw the record with the band, the SWC and a rolling mean, and mark every change of device or protocol.
4. Apply the run rule and the decision rule, and give the status (improved, no clear change, retest) with its chance and word.
5. For the watch archive: repeat Part 2 with a different distance band (for example 4–6 km) and say whether the status changes, or why it cannot be given.

Deliverables:

- a notebook that runs top to bottom
- the rules, written before the analysis
- one status sentence for the athlete, with its chance in words

## References

- Hopkins, W. G. (2000). Measures of reliability in sports medicine and science. *Sports Medicine*, 30(1), 1–15. (Recommends the typical error as the standard measure of reliability.)
- Hopkins, W. G. *A New View of Statistics*: [Reliability Applications](https://www.sportsci.org/resource/stats/relyappl.html) (typical error and the smallest worthwhile change for one individual).
- Chapter 11 of *Data-Driven Athletics*: One Athlete, Many Days; Time Series; How Good Is the Number?; Build Step B-11.

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