"""CS-8: Find a lactate threshold, and see if it moved -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# **Every number in this study is simulated.** There are no real step tests in the course
# files, and nobody in the course is asked to give blood. Instead, two step tests of one
# invented runner were generated from the production–clearance model of Section 7.4, with the
# meter noise and day-to-day variation a real test has. That has one large advantage: the true
# threshold is known, so you can see which threshold rules find it.
#
# ### Step 1 · Gather

# %%
# Step 1 · Two simulated step tests, eight weeks apart
import numpy as np
import pandas as pd

raw = pd.read_csv("raw/steptests_simulated.csv")
print(raw.fillna({"note": ""}).to_string(index=False))

# %% [markdown]
# Each test is a row per 3-minute stage, from 10 km/h upward by 1 km/h, stopped after the first
# stage above 6 mmol/L. One reading of test B is missing: the strip failed.
#
# ### Step 2 · Statistics

# %%
# Step 2 · Profile each test
prof = raw.groupby("test").agg(date=("date", "first"), stages=("stage", "count"),
                               readings=("lactate_mmol", "count"), lowest=("lactate_mmol", "min"),
                               highest=("lactate_mmol", "max"), top_speed=("speed_kmh", "max"))
print(prof.to_string())

# %% [markdown]
# Both tests reached 17 km/h and stopped there, above 6 mmol/L. The lowest readings differ (0.7
# against 0.8 mmol/L), which matters for any rule that starts from the lowest value.
#
# ### Step 3 · Visualize, and Step 4 · Cleanse
#
# The cleaning rule is short and written first: a stage without a reading is left out, never
# filled in, because every threshold rule below interpolates between stages anyway, and a filled
# value would be a guess dressed as a measurement.

# %%
# Steps 3–4 · The two curves, missing reading left out
import matplotlib.pyplot as plt
import os

clean = raw.dropna(subset=["lactate_mmol"]).reset_index(drop=True)
os.makedirs("clean", exist_ok=True)
clean.to_csv("clean/steptests_simulated_clean.csv", index=False)
print(f"kept {len(clean)} of {len(raw)} stages; left out: "
      f"{raw.loc[raw['lactate_mmol'].isna(), ['test', 'speed_kmh', 'note']].values.tolist()}")
fig, ax = plt.subplots(figsize=(6.4, 3.6))
for (name, g), m in zip(clean.groupby("test"), ["o-", "s--"]):
    ax.plot(g["speed_kmh"], g["lactate_mmol"], m, mfc="none", color="k", label=f"test {name} ({g['date'].iloc[0]})")
ax.set(xlabel="speed (km/h)", ylabel="blood lactate (mmol/L), simulated")
ax.legend(loc="upper left")
plt.tight_layout()

# %% [markdown]
# The two curves nearly overlap. Test B reads a little lower at 16 km/h (3.6 against 4.1) and
# the same at 17. Whether there is a real shift under that noise is the question of this study.
#
# ### Step 5 · Features: four threshold rules
#
# A threshold is a rule applied to the curve, and there are dozens (Faude and colleagues
# counted 25 concepts in three families). Four common ones:
#
# * **Fixed 2.0** and **fixed 4.0**: the speed where lactate crosses 2.0 or 4.0 mmol/L.
# * **Baseline + 1.0**: the speed where it rises 1.0 mmol/L above the lowest reading.
# * **Dmax**: fit a smooth curve (exponential plus a constant), draw the straight line from its
#   first to its last point, and take the speed where the curve lies farthest below that line.

# %%
# Step 5 · Four rules on both tests
from scipy.optimize import curve_fit

def cross(v, lac, 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]) if i else np.nan

def dmax(v, lac):
    f = lambda x, a, b, c: a + b * np.exp(c * (x - 10))
    p, _ = curve_fit(f, v, lac, p0=(1, 0.05, 1), maxfev=5000)
    x = np.linspace(v[0], v[-1], 601)
    line = f(v[0], *p) + (f(v[-1], *p) - f(v[0], *p)) * (x - v[0]) / (v[-1] - v[0])
    return x[np.argmax(line - f(x, *p))]

RULES = {"fixed 2.0": lambda v, l: cross(v, l, 2.0), "fixed 4.0": lambda v, l: cross(v, l, 4.0),
         "baseline + 1.0": lambda v, l: cross(v, l, l.min() + 1.0), "Dmax": dmax}
found = pd.DataFrame({t: {r: f(g["speed_kmh"].to_numpy(), g["lactate_mmol"].to_numpy()) for r, f in RULES.items()}
                      for t, g in clean.groupby("test")})
found["B - A"] = found["B"] - found["A"]
print(found.round(2).to_string())

# %% [markdown]
# The four rules spread over 1.45 km/h on the same test (14.50 to 15.95 km/h on test A), and
# they disagree on the change too: from −0.11 to +0.17 km/h. A coach who switched rules between
# tests could report almost any change. The rule must be fixed before the first test.
#
# Which, if any, is right? In real life nobody knows. Here the model is known, so ask it.
#
# ### Step 5 · The model behind the curves
#
# Lactate is made all the time and used all the time: it is a major fuel for other tissues and
# the main raw material from which the liver makes glucose (Brooks, 2018). Section 7.4 writes
# blood lactate as a tank: V dL/dt = P − R(L). Production P rises with speed
# as faster fibres are recruited; clearance R grows with L but saturates at a ceiling, Rmax.
# While P stays below Rmax, lactate settles at a steady value, L* = K·P / (Rmax − P). Above it,
# no steady state exists and lactate climbs for as long as the pace is held. The speed where
# P = Rmax is the true threshold of this runner, the highest speed with a steady state. The
# simulation used K = 0.5 mmol/L and Rmax = 3.0 mmol/L per minute before training, 3.3 after (10%
# more clearance, a size chosen for illustration; MacRae and colleagues found higher lactate clearance
# after nine weeks of endurance training).

# %%
# Step 5 · True thresholds, and three 30-minute runs
from scipy.optimize import brentq

K, RMAX = 0.5, {"A": 3.0, "B": 3.3}
P = lambda v: 1.9 + 0.05 * np.exp(0.55 * (v - 10))         # production, mmol/L per min
true = {t: brentq(lambda v: P(v) - r, 10, 20) for t, r in RMAX.items()}
print(f"true threshold: A {true['A']:.2f}, B {true['B']:.2f} km/h; moved {true['B'] - true['A']:+.2f} km/h")
print(f"true steady-state lactate at the true threshold minus 0.5 km/h (A): "
      f"{K * P(true['A'] - 0.5) / (RMAX['A'] - P(true['A'] - 0.5)):.1f} mmol/L")
fig, ax = plt.subplots(1, 2, figsize=(9, 3.6))
for (t, r), ls in zip(RMAX.items(), ["-", "--"]):
    v = np.linspace(10, true[t] - 0.02, 300)
    ax[0].plot(v, K * P(v) / (r - P(v)), ls, color="k", label=f"steady state, {t}")
    ax[0].axvspan(true[t], 18, alpha=0.12)
    g = clean[clean["test"] == t]
    ax[0].plot(g["speed_kmh"], g["lactate_mmol"], "o" if t == "A" else "s", mfc="none", label=f"step test {t}")
ax[0].set(xlim=(10, 18), ylim=(0, 10), xlabel="speed (km/h)", ylabel="lactate (mmol/L)", title="shaded: severe domain"); ax[0].legend(fontsize=8, loc="upper left")
for dv, ls in zip([-0.5, -0.1, 0.4], ["-", "--", ":"]):
    L, trace = 1.0, []
    for _ in range(30 * 60):                                 # 30 min in 1-s steps
        L += (P(true["A"] + dv) - RMAX["A"] * L / (K + L)) / 60
        trace.append(L)
    ax[1].plot(np.arange(1, 1801) / 60, trace, ls, color="k", label=f"{true['A'] + dv:.1f} km/h")
ax[1].set(xlabel="time (min)", ylabel="lactate (mmol/L)", title="test A runner, steady runs"); ax[1].legend(fontsize=8)
plt.tight_layout()

# %% [markdown]
# The true threshold moved by +0.44 km/h. On the right, half a kilometre an hour below it
# lactate flattens toward its steady value of 5.2 mmol/L; a little closer, at 15.5 km/h, it is
# still climbing after 30 minutes; above the threshold it never stops rising. Far below the
# threshold, at easy speeds, lactate settles within a few minutes. These are the three intensity
# domains that physiologists describe for lactate and oxygen uptake: a quick steady state
# (moderate), a late and high one (heavy), and none at all (severe). In people the boundary
# between heavy and severe is critical power, or critical speed for a runner (CS-7), and the
# maximal lactate steady state measured with blood sits on average about 7% below it (Jones and
# colleagues, 2019). The model has one boundary, the true threshold here; where its curve
# "first rises" is a matter of definition, which is one reason the rules disagree.
#
# No rule found the true threshold of test A (15.62 km/h): three fell 0.6 to 1.1 km/h below it
# and fixed 4.0 landed 0.3 above. Nothing in the model makes 4.0 special; with other parameters a
# different rule would land closest. With 3-minute stages the blood has no time to reach its
# steady value near the threshold, so each reading there is below the steady state at that
# speed. Change the stage length in the model below and watch the curve move.

# %% [markdown]
# ### Step 5 · How much does a threshold move between two tests of the same runner?
#
# Before saying the threshold moved, you need the typical error of each rule: how much it
# changes between two tests when nothing has changed. With a model, that is easy. Run test A
# 300 times with fresh meter noise and fresh day-to-day variation, and see how much each rule
# scatters.

# %%
# Step 5 · Typical error of each rule, by simulation
def simulate(rmax, day, noise=None):                     # many step tests at once, 3-min stages
    L, read = np.ones(len(day)), []
    for v in np.arange(10.0, 18.0):
        for _ in range(180):
            L = L + (day * P(v) - rmax * L / (K + L)) / 60
        read.append(L if noise is None else np.round(L + noise.normal(0, 0.1 + 0.04 * L), 1))
    return np.array(read).T

def apply_rules(x):
    k = int(np.argmax(x > 6)) + 1 if (x > 6).any() else len(x)    # the stop rule
    return {r: f(np.arange(10.0, 10.0 + k), x[:k]) for r, f in RULES.items()}

rng = np.random.default_rng(1)
rep = pd.DataFrame([apply_rules(x) for x in simulate(RMAX["A"], 1 + rng.normal(0, 0.02, 300), rng)])
te = rep.std()
ideal = {t: apply_rules(simulate(RMAX[t], np.ones(1))[0]) for t in RMAX}     # no noise at all
print(pd.DataFrame({"mean (km/h)": rep.mean(), "typical error (km/h)": te, "as % of mean": 100 * te / rep.mean(),
                    "change without noise": pd.Series(ideal["B"]) - pd.Series(ideal["A"])}).round(2).to_string())

# %% [markdown]
# In the simulation each rule repeats within 0.09 to 0.26 km/h, under 2% of the speed. That is
# the noise that was put in, and no more. Real repeat tests are noisier: in 17 recreational
# runners tested twice in the same way, the threshold speed repeated with a coefficient of
# variation of 3.7% to 5.8%, depending on the curve model, and 5.4% for a fixed 3.5 mmol/L rule
# (Camargo Alves and colleagues, 2016). A simulation shows how the noise you know about
# propagates; it cannot tell you about the noise you left out.
#
# The last column is what each rule would report with no noise at all: +0.09 to +0.66 km/h for
# a true change of +0.44. Even a perfect measurement depends on the rule.
#
# ### Step 5 · Did it move?
#
# Use the decision rule of Section 11.1. The coach and runner agreed beforehand that 0.2 km/h
# is worth having. For each rule, the noise in a change between two single tests is √2 × the
# typical error. Use two typical errors: the simulation's, and 4% of the speed, from real
# repeat tests.

# %%
# Step 5 · Chances of a real gain, rule by rule
from scipy.stats import norm

SWC = 0.2
rows = []
for r in RULES:
    delta = found.loc[r, "B - A"]
    for source, e in (("simulation", te[r]), ("real tests, 4%", 0.04 * found.loc[r, "A"])):
        noise = np.sqrt(2) * e
        gain, loss = 1 - norm.cdf((SWC - delta) / noise), norm.cdf((-SWC - delta) / noise)
        rows.append({"rule": r, "TE from": source, "change": delta, "gain": gain, "trivial": 1 - gain - loss, "loss": loss})
print(pd.DataFrame(rows).round(2).to_string(index=False))

# %% [markdown]
# The measured changes, −0.11 to +0.17 km/h, are smaller than any rule's noise-free change.
# The two test days were different: `prepare.py` gave test A a day with production 3.5% below
# average and test B a day 2.8% above, and that hid most of the gain. Even with the
# simulation's small errors no rule gives better than "possibly" (at most a 46% chance of a
# worthwhile gain), and with the error of real tests every rule sits near even odds. A true gain
# of +0.44 km/h, under 3% of the speed, cannot be seen in one test before and one after when a
# single test varies by about 4%. That is the finding, and it is about the measurement, not the
# runner. To see a change of this size, test twice each time with the rule and stage length
# fixed, or wait longer so the change can grow.
#
# **Without blood.** Most athletes will never have a step test. Critical speed from a watch (CS-7)
# aims at the heavy–severe boundary itself (Jones and colleagues, 2019). The talk test aims
# lower: in 15 people the lactate threshold sat close to the last stages at which they answered
# "yes" or "yes, but" to "can you speak comfortably?" (Quinn and Coons, 2011). Section 7.4 rates four such methods; each has
# its own typical error, and the same arithmetic decides whether a change is real.
