"""Q-9: Fit a parabola to a flight and recover gravity -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# ### Gravity is the one number you know before you film
#
# In flight the center of mass follows a parabola, y = c₀ + c₁t + c₂t², with c₂ = −g/2
# (Section 3.4.4). Fit that parabola to a tracked point and read off a "gravity",
# g_fit = −2c₂. You already know the answer, 9.81 m/s², so the fit checks the two things you
# supplied: the **scale** that turns pixels into meters and the **frame rate** that turns frame
# numbers into seconds (Section 10.2, "The arc as a check on scale and frame rate").
#
# The file is the pose table of the course's example jump from CS-1 (filmed at 120 frames per
# second, stored at 30). Take the hip midpoint through the frames in the air, 82 to 122, leaving a
# couple of frames at each end where the feet are still near the ground.

# %%
# The hip midpoint in the air, in meters
import numpy as np
import pandas as pd

kp = pd.read_csv("raw/jump2_keypoints_yolo26s.csv")
air = kp[(kp["frame"] >= 82) & (kp["frame"] <= 122)]
hip_px = -(air["l_hip_y"] + air["r_hip_y"]) / 2      # minus: image y grows downward
PX_PER_M = 859                                        # CS-1's scale (stature 1.70 m, assumed)
y = (hip_px - hip_px.iloc[0]).to_numpy() / PX_PER_M   # meters above the first frame
frames = air["frame"].to_numpy() - 82
print(f"{len(frames)} frames; the hips rise {100 * y.max():.1f} cm and come back to {100 * y[-1]:.1f} cm")

# %% [markdown]
# ### Fit the parabola on both clocks

# %%
# Two clocks, two gravities
for fps in (30, 120):
    c2, c1, c0 = np.polyfit(frames / fps, y, 2)
    print(f"time = frame / {fps:3d}: g_fit = {-2 * c2:6.2f} m/s²,  takeoff speed {c1:.2f} m/s")
g30 = -2 * np.polyfit(frames / 30, y, 2)[0]
g120 = -2 * np.polyfit(frames / 120, y, 2)[0]
print(f"ratio {g120 / g30:.1f}; at 120 fps the fit is {g120 / 9.80665:.2f} times true gravity")

# %% [markdown]
# On the file's clock the jumper falls with a gravity of 0.75 m/s², sixteen times too small:
# every time is four times too long, and gravity divides by time squared. On the camera's clock the
# answer is 12.1 m/s², the right size but 23% too large. Section 10.2 says how to read that:
#
# g_fit / g = (k / k_used) × (f_used / f)²
#
# where k and f are the true scale and frame rate and k_used and f_used the ones you assumed.
# A factor of 1.23 is not a slow-motion error (those come in factors of 4, 16, 64). It points at
# the scale (a stature nobody measured, a hand-held camera), at the hips not being the center of
# mass, or at a frame rate a little below 120. CS-3 untangles them.
#
# ### One chart

# %%
# The hip track and its parabola
import matplotlib.pyplot as plt

t = frames / 120
c = np.polyfit(t, y, 2)
fig, ax = plt.subplots(figsize=(6.4, 3.6))
ax.plot(t, 100 * y, "o", ms=5, color="k", label="hip midpoint")
tt = np.linspace(0, t.max(), 100)
ax.plot(tt, 100 * np.polyval(c, tt), "-", color="0.5", lw=2, label=f"parabola, g_fit = {-2 * c[0]:.1f} m/s²")
ax.set(xlabel="time from frame 82 (s, at 120 frames per second)", ylabel="hip height (cm)")
ax.legend(loc="lower center")
plt.tight_layout()
print(f"residual sd {100 * np.std(y - np.polyval(c, t)):.1f} cm; implied frame rate if the scale is right: "
      f"{120 * np.sqrt(9.80665 / (-2 * c[0])):.0f} fps")

# %% [markdown]
# The points hug the parabola to within about a centimeter, so the fit itself is sound; it is the
# inputs that are in doubt. If the scale were exactly right, the gravity of 12.1 would mean a
# frame rate of 108, not 120. Neither the scale nor the posture is known well enough here to say
# which it is, but a factor of sixteen would have been impossible to miss.
#
# **For the athlete:** "Before trusting any height from your slow-motion clip, we check that your
# flight follows gravity; at the file's frame rate it doesn't, at the camera's it nearly does."
