"""Q-26: Cadence from a cycle length -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# **Cadence** is steps per minute. A **stride** is one foot's contact to that foot's next
# contact, and holds two steps, so
#
# cadence = 60 / step time = 120 / stride time.
#
# The ankle table is Chapter 9's treadmill runner, filmed from behind at 30 frames per second.
# Three ways to get the cycle length give three cadences. Find out why, and which to report.

# %%
# Way 1 · The stride from the autocorrelation
import numpy as np
import pandas as pd
from scipy.signal import find_peaks

FPS = 30
df = pd.read_csv("raw/form1_ankles.csv")
y = df["l_ankle_y"].to_numpy()
z = y - y.mean()
ac = np.correlate(z, z, "full")[len(z) - 1:] / (z @ z)     # 1 at lag 0
lo, hi = int(0.4 * FPS), int(1.5 * FPS)                     # strides of 0.4 to 1.5 s
lag = lo + int(np.argmax(ac[lo:hi]))
print(f"stride {lag} frames = {lag / FPS:.3f} s -> cadence {120 * FPS / lag:.1f} steps/min")

# %% [markdown]
# ### Way 2 and Way 3 · From the contacts
#
# Find each foot's contacts, at most one per 0.6 of a stride, merge the two feet into one list
# of steps, and take either the **median** step or the **span**: the number of steps divided
# by the time from the first contact to the last.

# %%
# Median step against the span of all steps
t = []
for side in "lr":
    s = df[f"{side}_ankle_y"].to_numpy()
    peaks, _ = find_peaks(s, distance=int(0.6 * lag), height=np.percentile(s, 70))
    t += list(peaks / FPS)
t = np.sort(t)
steps = np.diff(t)
print(f"{len(t)} contacts, {len(steps)} steps; step lengths in frames: "
      f"{pd.Series(np.round(steps * FPS).astype(int)).value_counts().sort_index().to_dict()}")
print(f"median step {np.median(steps):.3f} s -> {60 / np.median(steps):.1f} steps/min")
print(f"span: {len(steps)} steps in {t[-1] - t[0]:.2f} s -> {60 * len(steps) / (t[-1] - t[0]):.1f} steps/min")
slope = np.polyfit(np.arange(len(t)), t, 1)[0]              # seconds per step, all contacts at once
print(f"line through all contacts: {slope:.4f} s per step -> {60 / slope:.1f} steps/min")

# %%
# Why the median is stuck
import matplotlib.pyplot as plt

frames = np.round(steps * FPS).astype(int)
counts = pd.Series(frames).value_counts().sort_index()
fig, ax = plt.subplots(1, 2, figsize=(8, 3.2), gridspec_kw={"width_ratios": [1, 1.3]})
ax[0].bar(counts.index, counts.values, color="gray", edgecolor="black")
ax[0].set(xlabel="step length (frames at 30 per second)", ylabel="number of steps")
grid = 60 * FPS / np.arange(9, 13)                          # cadences a whole-frame step can give
ax[1].plot(np.arange(9, 13), grid, "o--", color="gray", label="whole-frame steps")
ax[1].axhline(60 * len(steps) / (t[-1] - t[0]), color="black", lw=2, label="span of all steps")
ax[1].set(xlabel="step length (frames)", ylabel="cadence (steps/min)")
ax[1].legend(fontsize=8)
plt.tight_layout()

# %% [markdown]
# At 30 frames per second a step can only be read as a whole number of frames: 10 frames gives
# 180 steps a minute, 11 frames gives 163.6, and nothing in between. Most of this runner's steps
# (30 of 43) are 10 or 11 frames, so the median lands on one of them, 163.6 here, and the
# autocorrelation's stride of 21 frames lands on 171.4. The span uses every step at once, so the rounding at its two ends
# is shared by 43 steps: 169.4 steps a minute, and a straight line through all the contact times
# agrees with it (169.7). The key idea from Chapter 9: a median of rounded intervals is still rounded;
# estimate a rate from many events at once.
#
# **For the athlete:** your cadence from this clip is about 169 steps a minute; read it from the
# whole run, not from one or two steps.
