"""CS-11: From keypoints to a knee angle over a stride -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# ### Step 2 · Statistics: three model sizes, one clip
#
# The input is a keypoint table, not a video: one row per frame, 17 keypoints with x, y and a
# confidence. Chapter 8's running example is a hand-drawn runner, animated and seen from the
# side (`form3_30fps.mp4`, 117 frames at 30 frames per second), and the book publishes its
# keypoints from five YOLO26 pose model sizes. Three are used here: n (nano, the smallest),
# s (small) and x (extra large). A knee angle needs three points on each leg, so profile those
# first: how many frames, how sure the model is of each hip, knee and ankle, and one more check
# that every video deserves, whether consecutive frames are really different pictures.

# %%
# Step 2 · Profile the leg keypoints of three model sizes
import numpy as np
import pandas as pd

LEG = [f"{s}_{j}" for s in "lr" for j in ("hip", "knee", "ankle")]
tables = {m: pd.read_csv(f"raw/form3_30fps_yolo26{m}-pose.csv") for m in "nsx"}
for m, kp in tables.items():
    conf = kp[[f"{k}_c" for k in LEG]]
    xy = kp[[c for c in kp.columns if c.endswith(("_x", "_y"))]].to_numpy()
    held = (np.abs(np.diff(xy, axis=0)).max(axis=1) < 3).sum()   # no point moved 3 px
    print(f"{m}: {len(kp)} of 117 frames, leg points below 0.3: {(conf < 0.3).to_numpy().sum()}, "
          f"median leg confidence {np.median(conf):.2f}, frames repeating the one before: {held}")

# %% [markdown]
# All three sizes are confident about the legs; x is the only one with no leg point below 0.3
# and no missing frame. The last column is the surprise: more than a quarter of the rows repeat
# the frame before. The animation was drawn "on twos", each drawing held for two frames, so the
# clip holds about 15 new pictures a second, not 30. That does not break a knee angle, but it
# halves the real time resolution, and a frame count read from this clip overstates it.
#
# ### Step 3 · Visualize: the raw knee angles
#
# The knee angle is the included angle at the knee between the thigh (knee to hip) and the shank
# (knee to ankle), from the dot product of the two vectors (Section 3.2). 180° is a straight leg.
# Plot it for both legs as the model labelled them, before any cleaning.

# %%
# Step 3 · Left and right knee angle, as labelled
import matplotlib.pyplot as plt

def knee_angle(kp, side):
    hip, kn, an = (kp[[f"{side}_{j}_x", f"{side}_{j}_y"]].to_numpy() for j in ("hip", "knee", "ankle"))
    u, v = hip - kn, an - kn                                      # thigh and shank from the knee
    cos = (u * v).sum(1) / np.linalg.norm(u, axis=1) / np.linalg.norm(v, axis=1)
    return np.degrees(np.arccos(np.clip(cos, -1, 1)))

kx = tables["x"]
left, right = knee_angle(kx, "l"), knee_angle(kx, "r")
jumps = (np.abs(np.diff(left)) > 40).sum()
print(f"left knee: {left.min():.0f} to {left.max():.0f} deg; frame-to-frame jumps over 40 deg: {jumps}")

fig, ax = plt.subplots(figsize=(8, 3.2))
ax.plot(kx["frame"], left, "o-", ms=3, lw=1, label="labelled left")
ax.plot(kx["frame"], right, "s--", ms=3, lw=1, label="labelled right")
ax.set(xlabel="frame (30 per second)", ylabel="knee angle (deg, 180 = straight)")
ax.legend(loc="lower center", bbox_to_anchor=(0.5, 1.0), ncol=2, frameon=False)
plt.tight_layout()

# %% [markdown]
# Each trace jumps between two smooth curves. Those are not knee movements: a knee cannot change
# by 40° or more in one frame, 33 ms, and back again. They are **left–right swaps**: the model's
# "left knee" sits on one leg in some frames and on the other leg in others. In a sketch the
# two legs are drawn alike, so the model has almost nothing to tell them apart (Chapter 8,
# "Cleaning Keypoints").
#
# ### Step 4 · Cleanse: gate, go side-blind, smooth
#
# Three rules, written before looking for the answer:
#
# 1. **Gate.** A knee angle needs all three of its points at 0.3 confidence or more, the
#    threshold most of the apps use. Below that, the angle is missing, never zero.
# 2. **Side-blind.** Since the labels cannot be trusted, stop asking which leg is which. At
#    every frame take the **more bent** of the two knees. In running, that is the swinging leg
#    for most of each step, and its tightest bend is the *peak swing flexion*, a standard measure
#    (it is a column, `lkneeswing`, in the CS-13 treadmill data).
# 3. **Smooth over 0.1 s.** A centered average over 3 frames, the canvas app's rule at 30 frames
#    per second (0.1 × 30 = 3), taken only where at least two of the three frames have a value.

# %%
# Step 4 · Gate, take the more bent knee, smooth
import os

def gated_knee(kp, side, gate=0.3):
    ok = kp[[f"{side}_{j}_c" for j in ("hip", "knee", "ankle")]].min(axis=1) >= gate
    return np.where(ok, knee_angle(kp, side), np.nan)

def swing_knee(kp):
    full = kp.set_index("frame").reindex(range(117)).reset_index()   # missing frames stay missing
    bent = np.fmin(gated_knee(full, "l"), gated_knee(full, "r"))      # the more bent knee
    smooth = pd.Series(bent).rolling(3, center=True, min_periods=2).mean()
    return pd.DataFrame({"frame": full["frame"], "t_s": full["frame"] / 30,
                         "bent_knee_deg": bent.round(1), "smoothed_deg": smooth.round(1)})

os.makedirs("clean", exist_ok=True)
series = {m: swing_knee(kp) for m, kp in tables.items()}
for m, s in series.items():
    s.to_csv(f"clean/swing_knee_{m}.csv", index=False)
    print(f"{m}: {s['bent_knee_deg'].isna().sum()} frames without an angle; "
          f"largest frame-to-frame change {s['smoothed_deg'].diff().abs().max():.0f} deg after smoothing")

# %% [markdown]
# ### Step 5 · Features: find the strides, then average them
#
# Period first, events second (Chapter 9). The autocorrelation of the smoothed series finds the
# lag at which the pattern repeats, searched between 0.4 and 1.5 s. Each tightest bend is then
# taken as one event, no closer than 0.6 of a period to the last, and a window of one period is
# cut around each event, so every cycle is lined up on its peak swing flexion.

# %%
# Step 5 · Period, events and the peak swing flexion of each cycle
from scipy.signal import find_peaks

def cycles(s):
    y = s["smoothed_deg"].to_numpy()
    z = np.nan_to_num(y - np.nanmean(y))
    ac = np.correlate(z, z, "full")[len(z) - 1:] / (z @ z)
    lag = 12 + int(np.argmax(ac[12:46]))                         # 0.4 to 1.5 s at 30 fps
    ev, _ = find_peaks(-np.nan_to_num(y, nan=180), distance=int(0.6 * lag))
    half = lag // 2
    ev = [int(e) for e in ev if half <= e < len(y) - half]        # whole windows only
    return lag, ev, np.array([y[e - half:e + half + 1] for e in ev])

found = {m: cycles(s) for m, s in series.items()}
for m, (lag, ev, cyc) in found.items():
    peak = cyc[:, len(cyc[0]) // 2]
    print(f"{m}: period {lag} frames = {lag / 30:.2f} s; {len(ev)} cycles at frames {ev}; "
          f"peak flexion {', '.join(f'{p:.0f}' for p in peak)} deg")

# %% [markdown]
# Two of the three sizes agree on the period, 34 frames (1.13 s), and both find three whole
# cycles, though not at the same frames after the first. The s model does not agree at all: its
# series is so broken by swaps that the autocorrelation finds a repeat less than half as long,
# and peak flexions from 56° to 142°. That is a reason to look at a series before trusting its
# period, and the reason the rest of this study uses x, with n as the check.
#
# Two more checks on the period. First, a side-blind series cannot tell one leg's fold from the
# other's, so the pattern it repeats is a **step** (one foot to the other), and a stride for one
# leg needs labels you trust; here, a cycle is the repeat of the side-blind pattern. Second,
# compare it with a real runner: Chapter 9's treadmill runner takes a whole stride, two steps, in
# 0.70 s. A cycle of 1.13 s means the animation plays far slower than any real run. Times read
# from this clip mean nothing; angles do not depend on the clock, so they can still be read.
#
# Now the curve the coach asked for: the cycles laid over each other, their mean, and a band of
# one standard deviation either side.

# %%
# Step 5 · One curve with its band
lag, ev, cyc = found["x"]
pct = np.linspace(-50, 50, cyc.shape[1])                       # % of the cycle from the event
mean, sd = np.nanmean(cyc, axis=0), np.nanstd(cyc, axis=0, ddof=1)
curve = pd.DataFrame({"pct_cycle": pct.round(1), "mean_deg": mean.round(1), "sd_deg": sd.round(1)})
curve.to_csv("clean/knee_curve_x.csv", index=False)
print(f"x: {len(ev)} cycles; peak flexion {mean[len(mean) // 2]:.0f} ± {sd[len(sd) // 2]:.0f} deg; "
      f"median band half-width {np.median(sd):.0f} deg")
nmean = np.nanmean(found["n"][2], axis=0)
print(f"n: peak flexion {nmean[len(nmean) // 2]:.0f} deg; mean |x - n| over the cycle "
      f"{np.nanmean(np.abs(mean - nmean)):.0f} deg")

fig, ax = plt.subplots(figsize=(6.4, 3.6))
for c in cyc:
    ax.plot(pct, c, color="gray", lw=0.8)
ax.fill_between(pct, mean - sd, mean + sd, color="C0", alpha=0.25, label="x: mean ± 1 SD")
ax.plot(pct, mean, color="C0", lw=2.5, label=f"x: mean of {len(ev)} cycles")
ax.plot(pct, nmean, "k--", lw=1.5, label="n: mean")
ax.set(xlabel="% of cycle from peak swing flexion", ylabel="knee angle (deg, 180 = straight)")
ax.legend(loc="lower right", fontsize=8)
plt.tight_layout()

# %% [markdown]
# The curve has the shape you would expect around a fold: the knee closes to its tightest bend
# and opens again. Read the band as carefully as the line. At the event itself the three cycles
# agree well, 56 ± 6° (51, 55 and 63°), and the nano model's mean, 53°, is inside that. Away
# from the event they do not: the median half-width of the band is 14°, and the two models'
# means differ by 17° on average over the cycle. The band mixes three things this clip cannot
# separate: real differences between drawn cycles, keypoint placement error, and the side-blind
# rule switching from one leg to the other. So the one number this clip supports is the angle
# at peak swing flexion; the rest of the curve is a picture, not a measurement. In flexion terms
# (180° minus the included angle) that is a fold of about 124°.
#
# One more limit applies to every angle in this study. It is an angle **in the image plane**,
# measured on a flat picture. It equals the joint angle only when the leg moves in a plane
# square to the camera (Section 3.9), and a keypoint is where an annotator would click, not the
# joint's center (Section 8.3). For a hand-drawn runner there is no true joint at all. The
# method transfers to a real clip unchanged; the numbers belong to this drawing.
