"""CS-3: Predict the arc of a jump -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# ### Step 1 · Gather: the jump as a table
#
# Once the feet leave the ground, nothing but gravity acts on the body, so its center of mass
# follows a parabola set entirely by the takeoff velocity (Section 3.4.4):
#
# x(t) = x₀ + vₓ t,  y(t) = y₀ + v_y t − ½ g t²
#
# This study predicts that arc **before** looking at the track, lays it over the hip midpoint
# frame by frame, and explains the gap. The data are the pose table of the course's example jump
# from CS-1 (17 keypoints a frame, filmed at 120 frames per second, stored at 30) and CS-1's
# repeated-frame check. CS-1 found takeoff at frame 80 and landing at frame 124, and a scale of
# 859 pixels per meter from an assumed stature of 1.70 m.

# %%
# Step 1 · Open the tables and set the clock and the scale
import numpy as np
import pandas as pd

kp = pd.read_csv("raw/jump2_keypoints_yolo26s.csv")
fc = pd.read_csv("raw/jump2_frame_check.csv")
FPS, G, TAKEOFF, LANDING = 120, 9.80665, 80, 124
ankle_y = kp[["l_ankle_y", "r_ankle_y"]].max(axis=1)
ear_y = (kp["l_ear_y"] + kp["r_ear_y"]) / 2
K = (ankle_y - ear_y)[:10].median() * 1.115 / 1.70           # px per m, CS-1's scale
hip = pd.DataFrame({"frame": kp["frame"],
                    "x_m": (kp["l_hip_x"] + kp["r_hip_x"]) / 2 / K,
                    "y_m": -(kp["l_hip_y"] + kp["r_hip_y"]) / 2 / K,     # minus: up is up
                    "repeat": fc["diff_prev"] < 0.5})
t_flight = (LANDING - TAKEOFF) / FPS
print(f"scale {K:.0f} px/m; flight {LANDING - TAKEOFF} frames = {t_flight:.3f} s")
print(hip.iloc[TAKEOFF - 2:TAKEOFF + 3].round(3).to_string(index=False))

# %% [markdown]
# ### Predict first: the takeoff velocity, two ways
#
# **From the clock.** A body that leaves and lands at the same height rises for half the flight,
# so v_y = g t / 2. That needs no scale at all.
#
# **From the last frames before takeoff.** Difference the hip positions around frame 80 (Section
# 3.2.1). That needs the scale, and differencing magnifies keypoint jitter (Section 3.2.4), so try
# several pairs of frames and see how much the answer moves.

# %%
# Takeoff speed from the clock and from the hips
v_clock = G * t_flight / 2
print(f"from the clock: v_y = {v_clock:.2f} m/s -> apex {100 * v_clock**2 / (2 * G):.1f} cm "
      f"at {v_clock / G:.3f} s, flight {2 * v_clock / G:.3f} s")
y = hip["y_m"].to_numpy()
for a, b in [(76, 80), (78, 82), (79, 81), (77, 83)]:
    v = (y[b] - y[a]) / ((b - a) / FPS)
    print(f"frames {a}-{b}: v_y = {v:.2f} m/s -> apex {100 * v**2 / (2 * G):5.1f} cm, flight {2 * v / G:.3f} s")
vx = (hip["x_m"][LANDING] - hip["x_m"][TAKEOFF]) / t_flight
print(f"sideways drift in the air: {vx:+.2f} m/s (the camera is behind the jumper)")

# %% [markdown]
# The clock says 1.80 m/s straight up, an apex 16.5 cm above takeoff 0.183 s later. The hips give
# anything from 1.4 to 2.3 m/s depending on which frames you difference: four frames span only
# 33 ms, and a few pixels of jitter swing the answer by a fifth. The clock's estimate is the
# prediction to test. The sideways drift is small, so the arc is close to straight up.
#
# ### Step 2 · Statistics: is the scale the same in the air?
#
# A scale measured on standing frames assumes the jumper stays the same distance from the camera.
# Check it with the leg, hip to knee to ankle, whose length cannot change. Compare frames where the
# leg is straight: standing at the start, and the five frames around takeoff and around landing.
# (In between, the knees bend, and a bent leg seen from behind looks shorter.)

# %%
# Step 2 · Segment lengths standing and in flight
seg = {}
for name, (a, b) in {"thigh": ("hip", "knee"), "shank": ("knee", "ankle")}.items():
    seg[name] = np.hypot(kp[f"l_{a}_x"] - kp[f"l_{b}_x"], kp[f"l_{a}_y"] - kp[f"l_{b}_y"])
leg = seg["thigh"] + seg["shank"]
edges = list(range(TAKEOFF - 2, TAKEOFF + 3)) + list(range(LANDING - 2, LANDING + 3))
standing, flying = leg[:10].median(), leg[edges].median()
grow = flying / standing
print(f"straight left leg: standing {standing:.0f} px, at takeoff and landing {flying:.0f} px "
      f"({100 * (grow - 1):+.0f}%); standing again at the end {leg[-10:].median():.0f} px")
inside = hip["repeat"][TAKEOFF + 1:LANDING + 1]
print(f"frames in the air: {LANDING - TAKEOFF}; repeated frames among them: {int(inside.sum())}")

# %% [markdown]
# The straight leg is 9% longer at takeoff and landing than standing, and back to its standing
# length at the end. Bones do not grow in flight: during the jump the jumper is closer to the camera,
# or the hand-held camera moved closer, so in the air every pixel stands for about 9% less distance
# than the standing scale says, and heights measured there come out about 9% too large. Seven of the
# 44 frames in the air are repeats.
#
# ### Step 3 · Visualize: the prediction over the track

# %%
# Step 3 · Predicted arc, tracked hips, and the gap
import matplotlib.pyplot as plt

air = hip[(hip["frame"] >= TAKEOFF) & (hip["frame"] <= LANDING)].copy()
air["t"] = (air["frame"] - TAKEOFF) / FPS
air["track_cm"] = 100 * (air["y_m"] - y[TAKEOFF])
air["pred_cm"] = 100 * (v_clock * air["t"] - 0.5 * G * air["t"] ** 2)
air["gap_cm"] = air["track_cm"] - air["pred_cm"]
fig, ax = plt.subplots(2, 1, figsize=(6.4, 5), sharex=True, gridspec_kw={"height_ratios": [2, 1]})
ax[0].plot(air["t"], air["pred_cm"], "k-", lw=2, label=f"predicted from the clock, v = {v_clock:.2f} m/s")
new = ~air["repeat"]
ax[0].plot(air["t"][new], air["track_cm"][new], "o", ms=4, color="0.3", label="hip midpoint")
ax[0].plot(air["t"][~new], air["track_cm"][~new], "o", ms=5, mfc="white", color="0.3", label="repeated frame")
ax[0].set(ylabel="height above takeoff (cm)"); ax[0].legend(loc="lower center", fontsize=8)
ax[1].plot(air["t"], air["gap_cm"], "s-", ms=3, color="k")
ax[1].axhline(0, color="0.5", lw=1)
ax[1].set(xlabel="time since takeoff (s, 120 frames per second)", ylabel="track − prediction (cm)")
plt.tight_layout()
print(f"largest gap {air['gap_cm'].max():.1f} cm at {air.loc[air['gap_cm'].idxmax(), 't']:.3f} s; "
      f"gap at landing {air['gap_cm'].iloc[-1]:.1f} cm")

# %% [markdown]
# The hips rise **above** the prediction, by up to about 6 cm near the top, and come back toward it
# at landing. Section 3.4.4 expects the opposite sign from posture: arms swung up or knees tucked
# lift the center of mass relative to the hips, so the hips should sag **below** the arc. A gap of
# this sign points at the measurement instead: a scale 9% too small in the air (Step 2) makes the
# hips' 22 cm read about 2 cm too high, and the stature behind the scale was never measured.
#
# ### Step 4 · Cleanse: one rule before the fit
#
# A repeated frame is a copy of the frame before it, not a new measurement, so it is left out of
# the fit (it is kept in the table and flagged, as in CS-1). Then fit a parabola to the flight and
# read its curvature as a "gravity", g_fit = −2c₂ (Q-9). Do it on two clocks: **each file frame is
# 1/120 s**, the reading CS-1 used; and **only the distinct frames are 1/120 s apart**, the
# reading in which the repeats were padding added to the recording, which made CS-1's jump 11.7 cm.

# %%
# Step 4 · Drop repeats from the fit, and fit the arc on two clocks
fit = air[~air["repeat"] & (air["frame"] >= TAKEOFF + 2) & (air["frame"] <= LANDING - 2)]
print(f"rule: repeated frames out of the fit -> {len(fit)} of {len(air)} frames used")
distinct = np.cumsum(~hip["repeat"].to_numpy())                     # count of distinct frames so far
clocks = {"each file frame 1/120 s": fit["frame"] / FPS,
          "distinct frames 1/120 s": distinct[fit["frame"]] / FPS}
gfit = {}
for name, tt in clocks.items():
    c2, c1, c0 = np.polyfit(tt, fit["y_m"], 2)
    gfit[name] = -2 * c2
    print(f"{name}: g_fit {gfit[name]:5.1f} m/s², {gfit[name] / G:.2f} x gravity")

# %% [markdown]
# ### Step 5 · Features: what the curvature says about the scale and the clock
#
# Section 10.2 gives the rule for reading a fitted gravity: g_fit / g = (k / k_used) × (f_used / f)²,
# where k and f are the true scale and frame rate and k_used, f_used the ones you assumed. Two
# readings of the clock and one known scale error can now be weighed against each other.

# %%
# Step 5 · The scale each clock would need
for name, g in gfit.items():
    need = g / G                                  # k/k_used that would make g_fit equal gravity
    print(f"{name}: needs a scale {100 * (need - 1):+.0f}% off; "
          f"after the {100 * (grow - 1):.0f}% flight correction, {100 * (need / grow - 1):+.0f}% remains")
f_true = FPS * np.sqrt(G / gfit["each file frame 1/120 s"])
print(f"or, with the scale exactly right, the true rate would be {f_true:.0f} frames per second")
print(f"takeoff speed {v_clock:.2f} m/s: 10% faster would raise the jump to "
      f"{100 * (1.1 * v_clock) ** 2 / (2 * G):.1f} cm")

# %% [markdown]
# Read the two lines together. With each file frame as 1/120 s, the arc is 24% too steep; the
# flight-scale correction found in Step 2 explains 9 points of that, leaving 14% for a stature
# nobody measured and a hip point that is not the center of mass. With the repeats read as padding,
# the arc is 81% too steep, and no plausible scale error explains that. Put the other way: if the
# scale were exact, the file's frames would be 1/108 s apart, while the padding reading needs them
# 1/144 s apart; the data fall on the other side of 1/120 s. So the curvature supports the
# 1/120 s clock, and with it CS-1's 0.367 s flight and 16.5 cm jump. Gravity checked the clock.
#
# What limits this jump? Not the shape of the flight: once the scale doubt is set aside, the hips
# follow the predicted arc to within a few centimeters. The takeoff speed is low, 1.80 m/s, and
# height goes with its square, so a 10% faster takeoff would give 19.9 cm.
#
# ### Explore: takeoff speed and angle
#
# Move the takeoff speed and angle in the viewer below and watch the apex, the flight time and the
# distance change. Set a vertical takeoff at 1.80 m/s to see this jump; then tilt it forward.

# %% [markdown]
# ### The horizontal jump
#
# Tilt the takeoff forward and the arc becomes a standing long jump. Section 3.4.5 splits its
# distance into three parts: the lean at takeoff (the center of mass is already ahead of the
# toes), the flight, and the reach of the heels at landing. And the best angle is not 45°, because
# a jumper pushes much harder along than straight up, so takeoff speed falls as the angle rises.
# The cell uses the book's assumed numbers (lean 0.30 m, reach 0.45 m, a 0.35 m drop of the center
# of mass, 3.2 m/s at 30° falling by 1.7 m/s per radian); the slope is borrowed for illustration.

# %%
# A standing long jump, angle by angle
def long_jump(angle_deg, v30=3.2, slope=1.7, lean=0.30, reach=0.45, drop=0.35):
    a = np.radians(angle_deg)
    s = v30 - slope * (a - np.radians(30))           # assumed: speed falls as the angle rises
    vx, vy = s * np.cos(a), s * np.sin(a)
    flight = vx * (vy + np.sqrt(vy**2 + 2 * G * drop)) / G
    return lean + flight + reach, flight

angles = np.arange(5, 60.01, 0.01)
total, flight = long_jump(angles)
best = angles[np.argmax(total)]
print(f"best {best:.1f} deg: {long_jump(best)[0]:.2f} m; at 45 deg: {long_jump(45)[0]:.2f} m "
      f"({100 * (long_jump(best)[0] - long_jump(45)[0]):.0f} cm less); lean + reach = 0.75 m")
fig, ax = plt.subplots(figsize=(6.4, 3.4))
ax.plot(angles, total, "k-", lw=2, label="lean + flight + reach")
ax.plot(angles, flight, "k--", lw=1, label="flight only")
ax.axvline(best, color="0.5", lw=1)
ax.set(xlabel="takeoff angle (deg)", ylabel="distance (m)")
ax.legend(loc="lower center")
plt.tight_layout()

# %% [markdown]
# The best angle is about 22°, far below 45°, and jumping at 45° would cost about a third of a
# meter. The top of the curve is flat: a few degrees either way cost a centimeter or two, while 10%
# more takeoff speed is worth far more. The same lesson as the vertical jump: speed at takeoff is
# the number to build.
