"""Q-20: Find the lag between two signals -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q20-signal-lag/
Data:     https://apopt.com/data/tutorials/q20-signal-lag/ (keep raw/ next to this file)
"""

# %% [markdown]
# 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

# %%
# Sensor against reference, as recorded
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")

# %% [markdown]
# ### 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.

# %%
# Correlation at each trial lag
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()

# %% [markdown]
# ### Align, then measure the error

# %%
# MARD and bias after removing the lag
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")

# %% [markdown]
# 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."
