"""Q-19: Interpolate a threshold from four points -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q19-interpolate-threshold/
Data:     https://apopt.com/data/tutorials/q19-interpolate-threshold/ (keep raw/ next to this file)
"""

# %% [markdown]
# In a step test the athlete runs a few minutes at each of several rising speeds, and a drop of
# blood at the end of each stage gives a lactate value. A threshold is a rule applied to those
# points (Section 7.4). The table here is the book's **illustrative** step test, not a real
# athlete: the four stages of the book's example, 12 to 15 km/h, and two easy stages before them,
# with heart rate.
#
# ### The step test

# %%
# Six stages, lactate and heart rate
import numpy as np
import pandas as pd

test = pd.read_csv("raw/lactate_step_illustrative.csv")   # speed_kmh, lactate_mmol, hr_bpm
v, lac = test["speed_kmh"].to_numpy(float), test["lactate_mmol"].to_numpy()
print(test.to_string(index=False))

# %% [markdown]
# ### A straight line between two stages
#
# Find the first stage at or above the level, and draw a straight line from the stage before it:
# speed = v₁ + (level − L₁) × (v₂ − v₁) / (L₂ − L₁).

# %%
# Two rules, one interpolation
def cross(level):
    i = int(np.argmax(lac >= level))                      # first stage at or above the level
    return v[i - 1] + (level - lac[i - 1]) * (v[i] - v[i - 1]) / (lac[i] - lac[i - 1])

fixed = cross(4.0)
individual = cross(lac.min() + 1.0)
print(f"fixed 4.0 mmol/L:          {fixed:.2f} km/h")
print(f"lowest + 1.0 mmol/L ({lac.min() + 1.0:.1f}): {individual:.2f} km/h")
print(f"heart rate at the 4.0 crossing: {np.interp(fixed, v, test['hr_bpm']):.0f} beats/min")

# %% [markdown]
# The two rules are 1.2 km/h apart on the same six points. Neither is wrong; they are different
# definitions. Whichever you use, name it and compare an athlete only with numbers made by the
# same rule.
#
# ### A second opinion: a smooth curve

# %%
# Straight segments against an exponential fit
from scipy.optimize import curve_fit, brentq
import matplotlib.pyplot as plt

model = lambda x, a, b, c: a + b * np.exp(c * (x - 10))
p, _ = curve_fit(model, v, lac, p0=(1, 0.1, 0.8))
smooth = brentq(lambda x: model(x, *p) - 4.0, v[0], v[-1])
print(f"fixed 4.0 mmol/L from the exponential fit: {smooth:.2f} km/h "
      f"({smooth - fixed:+.2f} against the straight line)")

xs = np.linspace(v[0], v[-1], 200)
fig, ax = plt.subplots(figsize=(6.4, 3.6))
ax.plot(v, lac, "o-", color="k", label="stages, straight segments")
ax.plot(xs, model(xs, *p), "--", label="exponential fit")
for level in (4.0, lac.min() + 1.0):
    ax.axhline(level, ls=":", color="gray")
ax.plot([fixed, individual], [4.0, lac.min() + 1.0], "s", ms=8, mfc="none", color="k")
ax.set(xlabel="speed (km/h)", ylabel="blood lactate (mmol/L)")
ax.legend(loc="upper left")
plt.tight_layout()

# %% [markdown]
# A straight line between two points of an upward-bending curve lies above the curve, so the
# straight-line crossing comes a little early; the smooth fit puts it 0.1 km/h later. The choice
# of rule moved the answer more than ten times as far as the choice of arithmetic.
#
# **For the athlete:** "On this test your lactate reached 4.0 at about 14.3 km/h, at a heart rate
# near 173; that is one definition of threshold, and we will use the same one next time."
