# Q-20: Find the lag between two signals

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

Web page: https://apopt.com/course/tutorials/q20-signal-lag/ · Data: https://apopt.com/data/tutorials/q20-signal-lag/

## The decision

A runner's glucose sensor disagrees with finger-stick readings during a long run. Is the
sensor inaccurate, or just late? The answer decides how to read it during the next run.

## The raw data

- `raw/glucose_pair_synthetic.csv`: SYNTHETIC record, one row a minute: a reference blood glucose and a sensor built from it 7 minutes late, 0.4 mmol/L high, with noise (minute, reference_mmol, sensor_mmol) Made by `book/ch07-emerging/code/make_glucose.py` for Section 7.3 of *Data-Driven Athletics*; the same file as `book/ch07-emerging/data/glucose_pair.csv`.

A glucose sensor under the skin reads the fluid between cells, which follows blood glucose a
few minutes late. A sensor that trails its reference looks inaccurate whenever glucose is
changing, even if it would be exact with its clock moved. The fix is to find the lag first.
The file is the **synthetic** record of Section 7.3: a reference blood glucose every minute
through a 3.5-hour run, and a sensor built from it with a known lag, a known offset and random
noise. Because the answers are known, you can check yours.

### Compare the two as recorded

*Predict first:* A sensor that is late but otherwise good: will its mean absolute relative difference (MARD) be small (under 5%) or large (over 10%)?

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

df = pd.read_csv("raw/glucose_pair_synthetic.csv")         # minute, reference_mmol, sensor_mmol
ref, sen = df["reference_mmol"].to_numpy(), df["sensor_mmol"].to_numpy()

def mard(r, s):                                           # mean absolute relative difference, %
    return 100 * np.mean(np.abs(s - r) / r)

print(f"{len(df)} minutes; reference {ref.min():.1f} to {ref.max():.1f} mmol/L")
print(f"MARD as recorded {mard(ref, sen):.1f}%, mean difference {np.mean(sen - ref):+.2f} mmol/L")
```

Output:

```
271 minutes; reference 3.5 to 6.8 mmol/L
MARD as recorded 10.4%, mean difference +0.41 mmol/L
```

### Slide one signal along the other

Shift the sensor back by k minutes, compute the correlation with the reference at each shift,
and take the shift with the highest correlation. This is cross-correlation.

```python
import matplotlib.pyplot as plt

def corr_at(k):                                           # sensor shifted k minutes earlier
    return np.corrcoef(ref[:len(ref) - k], sen[k:])[0, 1]

lags = np.arange(0, 21)
r = np.array([corr_at(k) for k in lags])
best = int(lags[np.argmax(r)])
print(f"best lag {best} min: r = {r.max():.3f} (r at 0 min = {r[0]:.3f})")

fig, ax = plt.subplots(figsize=(6.4, 3.2))
ax.plot(lags, r, "o-", color="k")
ax.axvline(best, ls="--", color="gray")
ax.set(xlabel="trial lag (min)", ylabel="correlation r")
plt.tight_layout()
```

Output:

```
best lag 7 min: r = 0.939 (r at 0 min = 0.838)
```

![Correlation between reference and shifted sensor against trial lag in minutes, from 0 to 20; it rises from about 0.84 at zero to a peak near 0.94 at 7 minutes and falls after.](https://apopt.com/course/tutorials/q20-signal-lag/c03-1.png)

### Align, then measure the error

```python
a, b = ref[:len(ref) - best], sen[best:]
print(f"after shifting {best} min: MARD {mard(a, b):.1f}%, bias {np.mean(b - a):+.2f} mmol/L")
print("built into the synthetic sensor: lag 7 min, offset +0.4 mmol/L, plus noise")
```

Output:

```
after shifting 7 min: MARD 8.4%, bias +0.38 mmol/L
built into the synthetic sensor: lag 7 min, offset +0.4 mmol/L, plus noise
```

Cross-correlation found the 7-minute lag that was built in, and after aligning, the bias of
+0.38 mmol/L is close to the +0.4 built in. About two points of the 10.4% MARD came from the
lag alone; the rest is the offset and the noise, which no shift removes. The same method aligns
two heart-rate devices, or a watch and a video, whenever two clocks disagree.

**For the athlete:** "Your sensor runs about 7 minutes behind your blood; read it as where your
glucose was a few minutes ago, not where it is now."

## With your own data

Any two recordings of the same quantity on two clocks work: a wrist and a chest heart rate,
or the strap's displayed heart rate against the rate from its beat intervals (Q-14). Put
them on a common one-second or one-minute grid first.

## Action card

- **Finding:** The sensor trails the reference by 7 minutes and reads about 0.4 mmol/L high.
- **Evidence:** The correlation peaks at a 7-minute shift (r 0.939 against 0.838 unshifted); after aligning, the bias is +0.38 mmol/L and MARD falls from 10.4% to 8.4%.
- **Sure:** High on this synthetic record, which has the answers built in.
- **Action:** Read the sensor as glucose a few minutes ago, and judge its accuracy only after aligning the clocks.
- **Retest:** Repeat with finger-stick readings at known times on your next long run.

## References

- *Data-Driven Athletics*, Chapter 7, Continuous Glucose Sensing: units and accuracy, lag by cross-correlation (Section 7.3).

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