"""Q-41: Drag and rolling resistance from a cycling-simulator export -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# ### A road you can ride in a browser
#
# The [cycling simulator](https://apmonitor.com/apps/cycling-rider/) puts a modeled rider on a
# road bicycle. You set the exertion; the model answers with crank power, cadence, gear, speed,
# heart rate, lactate and an anaerobic reserve, once a second. Its **Export CSV** button writes
# every logged second to a file.
#
# This file comes from scenario **2 · Exertion steps, and the step that fades**: on a level road
# with no wind, exertion steps to 30, 55, 70 and 85% and back to 30%. It runs for 25 minutes.
# Every number is **simulated**.
#
# Section 3.8 says the road and the air take back the power the rider supplies. At the wheel,
# force = power / speed, and on level ground that force goes to three places:
#
# F = Crr·m·g + ½·ρ·CdA·v² + m·a
#
# rolling resistance (coefficient Crr), air drag (drag area CdA, air density ρ) and speeding up
# (mass m times acceleration a). Your job: estimate Crr and CdA from power and speed alone, as
# you would from a real power meter, then compare them with the values the simulator used.
# The export carries those too, in its `param_…` columns, which no real ride gives you.
#
# To make the file yourself: open the simulator, choose that scenario, press **Run**, let it
# pass 25 minutes, and press **Export CSV**.

# %%
# Open the export and keep the columns the force balance needs
import numpy as np
import pandas as pd

raw = pd.read_csv("raw/cycling-rider_20261202_221900.csv", comment="#")
tcol = raw.columns[0]
scale = {"Time (s)": 1, "Time (min)": 60, "Time (h)": 3600}[tcol]
ride = pd.DataFrame({
    "t_s": (raw[tcol] * scale).round(2),
    "power_W": raw["power_meas_W"],     # the power meter: noisy and smoothed
    "speed_mps": raw["speed_mps"],
    "grade_pct": raw["grade_pct"],
})
m = raw["param_mass_kg"].iloc[0] + raw["param_bike_mass_kg"].iloc[0]
print(f"{raw.shape[0]} rows, {raw.shape[1]} columns; rider and bicycle {m} kg")
print(f"grade {ride.grade_pct.min()} to {ride.grade_pct.max()} %, headwind "
      f"{raw['headwind_mps'].max()} m/s")
print(f"the truth to check against: CdA {raw['param_cda_m2'].iloc[0]} m2, "
      f"Crr {raw['param_crr'].iloc[0]}")

# %% [markdown]
# The road is level and still, so the grade and wind terms drop out. Some numbers the force
# balance needs are not in the file. The simulator's **Show Model** dialog lists them on its
# **Parameters** tab: the drivetrain passes 97.5% of the crank power to the wheel, air density
# is 1.20 kg/m³, and the wheels (0.335 m radius, 0.14 kg·m² of rotational inertia) add a little
# to the mass that has to be sped up. Write such constants down when you export; a file that
# leaves them out is a common fault in real data too.

# %%
# Power and speed through the ride
import matplotlib.pyplot as plt

mins = ride.t_s / 60
fig, ax = plt.subplots(2, 1, figsize=(6.4, 4.2), sharex=True)
ax[0].plot(mins, ride.power_W, "k-", lw=0.8)
ax[1].plot(mins, ride.speed_mps * 3.6, "k-")
ax[0].set_ylabel("crank power (W)")
ax[1].set_ylabel("speed (km/h)")
ax[1].set_xlabel("time (min)")
plt.tight_layout()
for a, b in [(240, 300), (540, 600), (840, 900), (1440, 1500)]:
    w = ride[ride.t_s.between(a, b)]
    print(f"{a / 60:4.0f}-{b / 60:.0f} min: {w.power_W.mean():5.0f} W, "
          f"{3.6 * w.speed_mps.mean():5.1f} km/h")

# %% [markdown]
# Speed takes a minute or more to catch up with each change in power, and at 85% power fades
# while the anaerobic reserve drains, so the bicycle is speeding up or slowing down for a good
# part of the ride. If you
# fit only the force at the wheel, the force that went into speeding up would be blamed on drag
# and rolling. So the acceleration term stays in. With F, v and a in hand, the balance is a
# straight-line model with two unknowns and no intercept, which least squares solves.

# %%
# Fit Crr and CdA by least squares
G, RHO, ETA = 9.81, 1.20, 0.975
m_eff = m + 0.14 / 0.335**2          # spinning wheels: inertia / radius^2 of extra mass

def fit(df, with_accel=True):
    t, v, P = df.t_s.to_numpy(), df.speed_mps.to_numpy(), df.power_W.to_numpy()
    a = np.gradient(v, t)
    ok = (v > 4) & (P > 20)             # rolling and pedaling: no start, no coasting
    F = ETA * P[ok] / v[ok] - (m_eff * a[ok] if with_accel else 0)
    X = np.column_stack([np.full(ok.sum(), m * G), 0.5 * RHO * v[ok] ** 2])
    (crr, cda), *_ = np.linalg.lstsq(X, F, rcond=None)
    return crr, cda, ok.sum()

for label, kw in [("with acceleration", {}), ("without acceleration", {"with_accel": False})]:
    crr, cda, n = fit(ride, **kw)
    print(f"{label:21s} Crr {crr:.5f}, CdA {cda:.3f} m2 ({n} s)")
crr, cda, n = fit(ride.assign(power_W=raw["power_W"]))
print(f"{'true power, with a':21s} Crr {crr:.5f}, CdA {cda:.3f} m2")

# %% [markdown]
# With the acceleration term the fit gives CdA 0.324 m² and Crr 0.00435, against the simulator's
# 0.32 and 0.0045. Without it, CdA comes out 0.309 and Crr 0.00532: rolling resistance is
# overestimated by 18%, because the force that sped the bicycle up during each step lands on the
# only constant term in the model. Fitting the model's true power instead of the power meter
# gives 0.320 and 0.0045 almost exactly, so the small remaining miss is the meter's noise and
# smoothing, not the method.
#
# ### What the athlete can use

# %%
# Speed at 200 W, and what a lower position is worth
from scipy.optimize import brentq

crr, cda, _ = fit(ride)
def speed_at(P, cda):                 # level road, steady speed: power in = power out
    return brentq(lambda v: ETA * P - (crr * m * G + 0.5 * RHO * cda * v**2) * v, 1, 30)

v_hoods, v_drops = speed_at(200, cda), speed_at(200, 0.25)
print(f"200 W on the hoods (CdA {cda:.3f}): {3.6 * v_hoods:.1f} km/h")
print(f"200 W in the drops (CdA 0.25):   {3.6 * v_drops:.1f} km/h, "
      f"+{3.6 * (v_drops - v_hoods):.1f} km/h")
print(f"40 km at 200 W: {40e3 / v_hoods / 60:.1f} min on the hoods, "
      f"{40e3 / v_drops / 60:.1f} min in the drops")

# %% [markdown]
# At 200 W the fitted rider holds 33.8 km/h on the brake hoods. The simulator's hint for the
# drops is a CdA of 0.25 m²; at the same 200 W that is 36.7 km/h, 2.8 km/h faster for no extra
# work, and 40 km takes 5.5 minutes less. The prediction assumes the fitted Crr and that only
# the position changes. Set the simulator's drag area to 0.25, ride the same scenario, and check
# it: "With your own data" below says how.
#
# **For the athlete:** "In the drops you would ride about 2.8 km/h faster at the same 200 W; over
# 40 km that saves about five and a half minutes without training any harder."
