"""Q-6: A first-order response: heart rate after a step -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q06-first-order/
Data:     https://apopt.com/data/tutorials/q06-first-order/ (keep raw/ next to this file)
"""

# %% [markdown]
# ### A step in work, a curve in heart rate
#
# When Sam steps onto the bench, the work jumps to its new level at once. Heart rate does not: it
# climbs toward a new level over tens of seconds. Section 2.4 models that climb as a
# **first-order response**, the curve of a tank filling through a valve:
#
# y(t) = y∞ + (y₀ − y∞) e^(−t/τ)
#
# where y₀ is the heart rate before the step, y∞ the level it settles toward, and τ (tau) the
# **time constant**: the time to cover 63% of the change. The file is a chest strap's heart
# rate, one value a second, through Sam's step test. Sam is made up; the data are the book's
# **synthetic** test, built with a time constant of 35 s for the climb, so you can check the fit.

# %%
# Open the strap file and cut out the first stage
import numpy as np
import pandas as pd

hr = pd.read_csv("raw/steptest_hr.csv")
print(hr["phase"].value_counts().to_string())
stage = hr[(hr["time_s"] >= 120) & (hr["time_s"] < 300)]
t = stage["time_s"].to_numpy() - 120        # seconds since the step
y = stage["hr_bpm"].to_numpy()
print(f"stage 1: {len(t)} s, heart rate {y[0]} -> {y[-10:].mean():.0f} bpm (mean of the last 10 s)")

# %% [markdown]
# ### Fit the curve
#
# `curve_fit` from SciPy adjusts y₀, y∞ and τ together until the squared misses, in beats a
# minute, are as small as possible. It needs a rough starting guess: the first value, the last
# values, and 30 s.

# %%
# Fit a first-order response
from scipy.optimize import curve_fit

def first_order(t, y0, yinf, tau):
    return yinf + (y0 - yinf) * np.exp(-t / tau)

p, cov = curve_fit(first_order, t, y, p0=(y[0], y[-10:].mean(), 30))
se = np.sqrt(np.diag(cov))
y0, yinf, tau = p
print(f"y0 {y0:.1f} bpm, y_inf {yinf:.1f} bpm, tau {tau:.1f} +/- {se[2]:.1f} s")
y63 = y0 + 0.63 * (yinf - y0)
print(f"63% of the rise is {y63:.0f} bpm; the data first reach it at t = {t[np.argmax(y >= y63)]} s")

# %% [markdown]
# The fit gives a time constant of 37 ± 1.4 s, against the 35 s the data were built with. The
# 63% rule read straight off the data gives 35 s. The fit is a little long because
# the synthetic heart rate also drifts up slowly through the stage (Section 2.4, "Drift"), which a
# single exponential cannot follow, so it stretches τ to absorb it.
#
# ### One chart

# %%
# Data, fit and the time constant
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6.4, 3.6))
ax.plot(t, y, ".", color="0.6", label="strap, every second")
ax.plot(t, first_order(t, *p), "k-", lw=2, label=f"first-order fit, tau = {tau:.0f} s")
ax.axvline(tau, color="k", ls="--", lw=1)
ax.axhline(y63, color="k", ls=":", lw=1, label="63% of the rise")
ax.set(xlabel="time since the step (s)", ylabel="heart rate (beats/min)")
ax.legend(loc="lower right")
plt.tight_layout()
print(f"after 3 tau ({3 * tau:.0f} s) the fit is within {100 * np.exp(-3):.0f}% of its new level")

# %% [markdown]
# After three time constants, just under two minutes, heart rate is within 5% of its new level. That
# is why the step test's stages last three minutes: a count taken earlier would catch heart rate
# still climbing.
#
# **For the athlete:** "Your heart rate takes 35 to 40 seconds to cover most of its rise when you
# start a new effort, so judge an interval's intensity by your heart rate only after the first two
# minutes."
