"""Q-7: The angle from three points -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# ### Three points make an angle
#
# A joint angle needs three keypoints: one on each segment and one at the joint. For the knee,
# take the hip A, the knee B and the ankle C. The two vectors that leave the knee, u = A − B and
# w = C − B, meet at the **included angle** θ, and the dot product gives it (Section 3.2.2):
#
# θ = arccos( u·w / (|u| |w|) )
#
# A straight leg is 180°. Clinicians often report **flexion**, 180° − θ, which is 0° for a straight
# leg. Check the function on the book's example first: in one frame of Jordan's jump the hip is at
# (0.50, 0.40), the knee at (0.55, 0.60) and the ankle at (0.48, 0.80).

# %%
# The angle function, checked on known cases
import numpy as np

def angle(a, b, c):
    """Included angle at b, in degrees, between b->a and b->c (works on arrays of points too)."""
    u, w = np.asarray(a, float) - np.asarray(b, float), np.asarray(c, float) - np.asarray(b, float)
    cos = (u * w).sum(axis=-1) / (np.linalg.norm(u, axis=-1) * np.linalg.norm(w, axis=-1))
    return np.degrees(np.arccos(np.clip(cos, -1.0, 1.0)))   # clip: rounding can push |cos| past 1

k = angle((0.50, 0.40), (0.55, 0.60), (0.48, 0.80))
print(f"Jordan's knee: included {k:.1f} deg, flexion {180 - k:.1f} deg")
print(f"straight leg {angle((0, 0), (0, 1), (0, 2)):.1f} deg; right angle {angle((1, 0), (0, 0), (0, 1)):.1f} deg")
print(f"same points in pixels {angle((500, 400), (550, 600), (480, 800)):.1f} deg")
assert abs(k - 146.7) < 0.05

# %% [markdown]
# 146.7°, a flexion of 33.3°, as in Example "Jordan's knee angle by hand". The units of the points
# do not matter, because the lengths divide out: the same frame in pixels gives the same angle.
#
# ### The same function on every frame of a clip
#
# The file is a pose model's table for a running clip from the course's example set,
# `form2_60fps.mp4`, filmed from the side: one row per frame, x and y in pixels for 17 keypoints,
# and a confidence for each. The video is not published; the table shows no one. The function
# works on whole columns at once.

# %%
# Knee angles for every frame
import pandas as pd

kp = pd.read_csv("raw/form2_keypoints_yolo26s.csv")
for side in ["l", "r"]:
    pts = [kp[[f"{side}_{j}_x", f"{side}_{j}_y"]].to_numpy() for j in ("hip", "knee", "ankle")]
    kp[f"{side}_knee_flex"] = 180 - angle(*pts)
    low = kp[[f"{side}_{j}_c" for j in ("hip", "knee", "ankle")]].min(axis=1) < 0.5
    print(f"{side} knee flexion: {kp[f'{side}_knee_flex'].min():.0f} to {kp[f'{side}_knee_flex'].max():.0f} deg; "
          f"{int(low.sum())} of {len(kp)} frames with a point below 0.5 confidence")

# %% [markdown]
# ### One chart

# %%
# Knee flexion through the clip
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(9, 3.4))
ax.plot(kp["frame"], kp["l_knee_flex"], "k.-", ms=3, lw=1, label="left knee")
ax.plot(kp["frame"], kp["r_knee_flex"], "--", color="0.55", lw=1, label="right knee")
ax.set(xlabel="frame number", ylabel="knee flexion (deg)")
ax.legend(loc="upper right", ncol=2)
plt.tight_layout()
from scipy.signal import find_peaks
peaks, _ = find_peaks(kp["l_knee_flex"], height=60, distance=12)   # swings at least 12 frames apart
print(f"left knee: {len(peaks)} swing peaks, median {kp['l_knee_flex'].iloc[peaks].median():.0f} deg; "
      f"median of the 20% straightest frames {kp['l_knee_flex'].quantile(0.2):.0f} deg")

# %% [markdown]
# The left knee bends and straightens once a stride, 16 times in the clip: nearly straight
# (10 to 20°) around foot contact, folded to about 100° in the swing, when the foot comes up behind
# the body. The right knee follows half a stride later, but its trace is more jagged. In a side
# view one leg is always partly behind the other, and the model sometimes moves a point or swaps
# the two legs' labels for a frame. And every angle here is measured in the image plane: if the leg
# is not square to the camera, the true knee angle differs (Section 3.9.1).
#
# **For the athlete:** "From the side, your knee folds to about 100 degrees in each swing and is
# nearly straight when your foot lands; to compare sessions we'll film from the same side, square to
# your path, every time."
