"""Q-40: Export a run from the running simulator and read it -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q40-running-sim-export/
Data:     https://apopt.com/data/tutorials/q40-running-sim-export/ (keep raw/ next to this file)
"""

# %% [markdown]
# ### A treadmill you can run in a browser
#
# The [running simulator](https://apmonitor.com/apps/treadmill-runner/) puts a modeled runner on
# a treadmill. You set the belt speed; the model answers with heart rate, blood lactate, oxygen
# uptake, core temperature, fuel and an anaerobic reserve, once a second. Its **Export CSV**
# button writes every logged second to a file. This page reads one such file.
#
# The file comes from the simulator's scenario **2 · A speed step by hand**: a minute standing,
# then the belt steps to 9.4 km/h, and at 15 minutes it steps to 11.2 km/h and stays there until
# the runner drifts off the back of the belt. The runner is the simulator's recreational male
# preset. Every number is **simulated**. That is the point of the exercise: the file holds both
# what a sensor would read (`hr_meas_bpm`, with noise) and what the model knows and no real test
# can give you (`hr_bpm`, the true value, and `wp_J`, the anaerobic reserve). You can check each
# method against the truth.
#
# To make the file yourself: open the simulator, choose that scenario, press **Run** (the fastest
# speed is fine), wait for the runner to go off the back, and press **Export CSV**.

# %%
# Open the export and keep the columns you need
import numpy as np
import pandas as pd

raw = pd.read_csv("raw/treadmill-runner_20261202_221900.csv", comment="#")   # 2 header lines start with #
tcol = raw.columns[0]                     # the app picks the time unit from the run's length
scale = {"Time (s)": 1, "Time (min)": 60, "Time (h)": 3600}[tcol]
print(f"{raw.shape[0]} rows, {raw.shape[1]} columns; time column '{tcol}'")

run = pd.DataFrame({
    "t_s": (raw[tcol] * scale).round(2),
    "speed_kmh": raw["speed_kmh"],
    "hr_bpm": raw["hr_meas_bpm"],         # what a chest strap would read
    "lac_mmol": raw["lac_meas_mmol"],     # what a lactate meter would read
    "hr_true": raw["hr_bpm"],             # the model's own value: no real test has it
    "reserve_J": raw["wp_J"],             # the anaerobic reserve, also hidden in real life
})
print(run.describe().loc[["min", "max"]].round(1).to_string())
print(f"the run ended at {run.t_s.iloc[-1]:.0f} s after {raw['dist_km'].iloc[-1]:.2f} km")

# %% [markdown]
# A one-second log of 24.5 minutes is 1,470 rows. The export has 124 columns: the settings
# (`param_…`), the controllers (`ctrl_…`), scores (`metric_…`) and the signals. Reading the header
# for the time unit matters: a run under a minute is written in seconds and a run over an hour in
# hours, so a fixed `* 60` would be wrong for someone else's file.
#
# ### Look before you fit

# %%
# Belt speed, heart rate and lactate on one time axis
import matplotlib.pyplot as plt

m = run.t_s / 60
fig, ax = plt.subplots(3, 1, figsize=(6.4, 5.4), sharex=True)
ax[0].plot(m, run.speed_kmh, "k-")
ax[1].plot(m, run.hr_bpm, ".", color="0.6", ms=2, label="strap (noisy)")
ax[1].plot(m, run.hr_true, "k-", lw=1, label="model's true value")
ax[2].plot(m, run.lac_mmol, "k-")
ax[0].set_ylabel("belt (km/h)")
ax[1].set_ylabel("heart rate (bpm)")
ax[2].set_ylabel("lactate (mmol/L)")
ax[2].set_xlabel("time (min)")
ax[1].legend(loc="lower right", fontsize=8)
for a in ax:
    a.axvline(15, color="k", ls=":", lw=1)
plt.tight_layout()
print(f"heart rate at 14.9 min {run.hr_bpm[run.t_s.between(890, 899)].mean():.0f} bpm, "
      f"at 24 min {run.hr_bpm[run.t_s.between(1435, 1445)].mean():.0f} bpm")

# %% [markdown]
# Both curves bend toward a level in the first stage. In the second, heart rate nearly levels
# off but lactate keeps climbing. Heart rate alone would not tell you the second stage was too
# fast.
#
# ### How fast does heart rate answer?
#
# Q-6 fitted a first-order response. The belt takes a few seconds to reach speed and the heart
# lags behind the legs, so this fit adds a **dead time** θ (theta), a delay before the curve starts.

# %%
# Fit a first-order response with a dead time to the first stage
from scipy.optimize import curve_fit

def fopdt(t, y0, gain, tau, theta):
    x = np.clip(t - 60 - theta, 0, None)          # the belt starts at 60 s
    return y0 + gain * (1 - np.exp(-x / tau))

st1 = run[(run.t_s >= 60) & (run.t_s < 900)]
fits = {}
for col in ["hr_bpm", "hr_true"]:
    p, cov = curve_fit(fopdt, st1.t_s, st1[col], p0=(60, 90, 60, 10))
    se = np.sqrt(np.diag(cov))
    fits[col] = p
    print(f"{col:7s} gain {p[1]:.1f} bpm, tau {p[2]:.1f} +/- {se[2]:.1f} s, "
          f"dead time {p[3]:.1f} s")
gain, tau, theta = fits["hr_bpm"][1:]
print(f"strap: within 5% of the new level {(theta + 3 * tau) / 60:.1f} min after the belt starts")

# %% [markdown]
# The noisy strap and the true value give the same time constant, 68 s, to within its standard
# error: one-second noise of about 1 bpm averages out over 840 points. The dead time does not
# agree: 31 s for the strap and 25 s for the true value. The simulated strap smooths its readings
# with a 6 s filter, as a real one smooths its beat-to-beat values, and smoothing delays a signal.
# In the chart above the gray dots run just to the right of the black line on the climb. Three
# time constants after the delay, heart rate is within 5% of its new level: about four minutes
# after the belt starts, so a heart rate read in the first three minutes of a stage is too low.
#
# ### Steady or not, and how long is left?
#
# A stage is below the threshold if lactate levels off. Measure that as the slope over the last
# five minutes of each stage. Then use the critical-speed model of Section 6.5:
# t_lim = D′ / (v − CS). The export carries both numbers: `speed_sus_mps` is the model's critical
# speed and `param_dprime_m` its D′.

# %%
# Lactate slope in each stage, and the critical-speed forecast
for a, b in [(600, 900), (1140, 1440)]:
    w = run[(run.t_s >= a) & (run.t_s < b)]
    slope = np.polyfit(w.t_s / 60, w.lac_mmol, 1)[0]
    print(f"{a / 60:.0f}-{b / 60:.0f} min at {w.speed_kmh.iloc[0]:.1f} km/h: lactate "
          f"{slope:+.2f} mmol/L per min")

i = run.index[run.t_s == 900][0]                 # the moment of the second step
cs = raw["speed_sus_mps"].iloc[i]
dprime = raw["param_dprime_m"].iloc[i]
v = raw["speed_mps"].iloc[i + 10]                # the belt's new speed
t_lim = dprime / (v - cs)
print(f"CS {cs * 3.6:.2f} km/h, D' {dprime:.0f} m, belt {v * 3.6:.2f} km/h")
print(f"forecast: off the back at {(900 + t_lim) / 60:.1f} min; "
      f"the simulator says {run.t_s.iloc[-1] / 60:.1f} min")

# %% [markdown]
# The first stage gains 0.07 mmol/L a minute, close to level; the second gains 0.24, more than
# three times as fast. The critical-speed forecast says 25.1 minutes and the runner actually went
# off at 24.5, 38 s early. The miss has a cause you can find in the file: the model's critical
# speed is not fixed. Plot `speed_sus_mps` and you will see it fall from 10.03 to 9.77 km/h as the
# runner heats up and tires, so the reserve drains a little faster than the forecast assumed.
#
# **For the athlete:** "At 9.4 km/h your lactate settles near 3 mmol/L and you could hold it; at
# 11.2 km/h it never settles, and you have about ten minutes before you must slow down."
