"""CS-1: How high did I jump? -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# ### Step 1 · Gather: what is in the clip?
#
# One countermovement jump, filmed in slow motion on a phone: the course's example clip
# `jump2_120fps.mp4` (Section 1.3, Example "A hand count on the course's example clip"). It is
# filmed from behind, hand-held, on grass. You will measure the jump three ways: by counting
# frames, from the rise of the hips in a pose model's keypoints, and with the jump app's own
# formula, then decide what the jump height is and how sure you can be.
#
# The first two cells read the video, so they run on your own computer or in Colab. They write
# tables with no pictures in them; from Step 2 on, everything runs in this page from those tables.

# %%
# Step 1 · Read the clip's header
import cv2

cap = cv2.VideoCapture("local/jump2_120fps.mp4")
fps_file = cap.get(cv2.CAP_PROP_FPS)
n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
w, h = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(f"{n} frames, header {fps_file:.2f} fps, {w} x {h} pixels (portrait)")
print(f"{n / fps_file:.2f} s on the file's clock, {n / 120:.2f} s at the 120 fps capture rate")
cap.release()

# %% [markdown]
# The header says 30. The phone recorded 120 frames a second and stored them to play back four
# times slower. Every time in this study is a frame count divided by **120**, the capture rate;
# dividing by 30 is the slow-motion trap of Section 1.3.2.
#
# The next cell runs a pose model (Chapter 8 explains it) on every frame and keeps, for each
# frame, the x and y of 17 keypoints in pixels and the model's confidence in each. It also
# measures how much each frame differs from the one before, because a frame that repeats the
# previous one is not a new moment (Q-2).

# %%
# Step 1 · Keypoints and a repeat check for every frame
import os
import numpy as np
import pandas as pd
from ultralytics import YOLO

NAMES = ["nose", "l_eye", "r_eye", "l_ear", "r_ear", "l_shoulder", "r_shoulder", "l_elbow", "r_elbow",
         "l_wrist", "r_wrist", "l_hip", "r_hip", "l_knee", "r_knee", "l_ankle", "r_ankle"]
os.makedirs("clean", exist_ok=True)
model = YOLO("yolo26s-pose.pt")
cap = cv2.VideoCapture("local/jump2_120fps.mp4")
rows, check, prev, i = [], [], None, 0
while True:
    ok, frame = cap.read()
    if not ok:
        break
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY).astype(float)
    check.append([i, np.nan if prev is None else np.abs(gray - prev).mean()])
    r = model(frame, verbose=False, device="cpu")[0]
    if r.keypoints is not None and len(r.boxes):
        best = int(r.boxes.conf.argmax())                  # the most confident person
        xy, conf = r.keypoints.xy[best].tolist(), r.keypoints.conf[best].tolist()
        rows.append([i] + [v for p in xy for v in p] + conf)
    prev, i = gray, i + 1
cols = ["frame"] + [f"{k}_{a}" for k in NAMES for a in "xy"] + [f"{k}_c" for k in NAMES]
pd.DataFrame(rows, columns=cols).round(2).to_csv("clean/keypoints.csv", index=False)
pd.DataFrame(check, columns=["frame", "diff_prev"]).round(3).to_csv("clean/frame_check.csv", index=False)
print(f"person found in {len(rows)} of {i} frames")

# %% [markdown]
# ### Step 2 · Statistics: what did the model see?
#
# A profile first. How sure is the model of each joint, and how many frames are repeats?

# %%
# Step 2 · Confidence by joint, and repeated frames
import pandas as pd

NAMES = ["nose", "l_eye", "r_eye", "l_ear", "r_ear", "l_shoulder", "r_shoulder", "l_elbow", "r_elbow",
         "l_wrist", "r_wrist", "l_hip", "r_hip", "l_knee", "r_knee", "l_ankle", "r_ankle"]
kp = pd.read_csv("clean/keypoints.csv")
fc = pd.read_csv("clean/frame_check.csv")
conf = kp[[f"{k}_c" for k in NAMES]].rename(columns=lambda c: c[:-2])
print(conf.median().sort_values().round(2).to_string())
repeat = fc["diff_prev"] < 0.5                 # under half a gray level: the same picture
print(f"{len(kp)} frames; {int(repeat.sum())} repeat the frame before, every "
      f"{int(fc.loc[repeat, 'frame'].diff().median())}th frame")

# %% [markdown]
# The eyes and nose have a median confidence near zero: from behind, the face is hidden, and the
# model is telling the truth. The ears, hips, knees and ankles are found with confidence 0.8 or
# more. And 32 frames, every sixth one, repeat the frame before. That is a fault of the file, not
# of the jump; Step 4 decides what to do about it.
#
# ### Step 3 · Visualize: the jump without the pixels
#
# Draw the keypoints as stick figures at five moments, and plot two traces over the whole clip:
# the hip midpoint (the middle of the two hips, the point the jump app follows) and the lower of
# the two ankles. Pixel y grows downward, so the traces are flipped to make up mean up.

# %%
# Step 3 · Five moments and two traces
import numpy as np
import matplotlib.pyplot as plt

BONES = [("l_shoulder", "r_shoulder"), ("l_shoulder", "l_elbow"), ("l_elbow", "l_wrist"),
         ("r_shoulder", "r_elbow"), ("r_elbow", "r_wrist"), ("l_shoulder", "l_hip"), ("r_shoulder", "r_hip"),
         ("l_hip", "r_hip"), ("l_hip", "l_knee"), ("l_knee", "l_ankle"), ("r_hip", "r_knee"), ("r_knee", "r_ankle")]
hip_y = (kp["l_hip_y"] + kp["r_hip_y"]) / 2
ankle_y = kp[["l_ankle_y", "r_ankle_y"]].max(axis=1)      # the lower ankle (larger y)
fig, ax = plt.subplots(1, 2, figsize=(10, 4), gridspec_kw={"width_ratios": [1.3, 1]})
for j, f in enumerate([0, 45, 80, 100, 124]):
    r = kp.loc[kp["frame"] == f].iloc[0]
    for a, b in BONES:
        ax[0].plot([r[f"{a}_x"] + 500 * j, r[f"{b}_x"] + 500 * j], [r[f"{a}_y"], r[f"{b}_y"]], "k-", lw=2)
    ax[0].text(r["l_hip_x"] + 500 * j, 1950, f"frame {f}", ha="center")
ax[0].invert_yaxis(); ax[0].set_aspect("equal"); ax[0].axis("off")
ax[1].plot(kp["frame"], hip_y[:10].median() - hip_y, "-", label="hip midpoint")
ax[1].plot(kp["frame"], ankle_y[:10].median() - ankle_y, "--", label="lower ankle")
for f in (80, 124):
    ax[1].axvline(f, color="0.6", lw=1)
ax[1].set(xlabel="frame (120 per second)", ylabel="height above standing (pixels)")
ax[1].legend(loc="upper left")
plt.tight_layout()
print(f"hip: standing {hip_y[:10].median():.0f} px, lowest point of the dip at frame {int(hip_y[:80].idxmax())}, "
      f"top at frame {int(hip_y.idxmin())}")

# %% [markdown]
# Read the right panel from left to right. The hips sink in the dip, drive up, keep rising after
# the ankle leaves the ground near frame 80, peak, and fall back before the ankle lands near frame
# 124. The hips start rising long before takeoff, so the rise of the hips is not all flight. The
# ankle trace is not flat before takeoff either: it drifts up by 20 to 50 pixels as the hand-held
# camera moves and the heel comes up, so a fixed height line on the ankle would open the flight
# too early (Section 1.3.3).
#
# Step through the clip frame by frame in the viewer below. It draws the same table at the
# capture rate.

# %% [markdown]
# ### Step 4 · Cleanse: rules first, then the data
#
# Write the rules before applying them (Section 4.3), keep the raw table untouched, and log how
# many values each rule changes. Two rules are enough here:
#
# 1. A keypoint with confidence below 0.5 is set to missing. The hidden face goes; the joints this
#    study uses stay.
# 2. Repeated frames are **flagged, not deleted**. Deleting them would change every frame number
#    and every time after them; a flag keeps the record and lets each method decide.

# %%
# Step 4 · Two rules, a change log and a clean copy
GATE = 0.5
clean = kp.copy()
log = []
for k in NAMES:
    low = clean[f"{k}_c"] < GATE
    clean.loc[low, [f"{k}_x", f"{k}_y"]] = np.nan
    if low.any():
        log.append({"rule": f"confidence < {GATE}", "field": k, "values_set_missing": int(low.sum())})
clean = clean.merge(fc, on="frame")
clean["repeat"] = clean["diff_prev"] < 0.5
log.append({"rule": "repeat flag (diff < 0.5)", "field": "frame", "values_set_missing": 0})
pd.DataFrame(log).to_csv("clean/change_log.csv", index=False)
clean.to_csv("clean/keypoints_clean.csv", index=False)
print(pd.DataFrame(log).to_string(index=False))
print("frames flagged as repeats:", int(clean["repeat"].sum()), "(none deleted)")

# %% [markdown]
# Only face points and a few far-side arm points were removed. Now the three methods.
#
# ### Method 1 · Count the frames in the air
#
# The book's hand count of this clip, stepping through it frame by frame, put takeoff at frame 80
# (the shoes first show above the grass) and landing at frame 124 (the first shoe disappears into
# it again). Print the lower ankle's height around those frames to see the same events in the
# table. Then turn the count into a height with h = g t² / 8, three ways: the right clock, the
# file's clock, and the right clock with the repeated frames left out.

# %%
# Method 1 · Flight time from a frame count
rise = ankle_y[:10].median() - ankle_y
print("ankle above standing (px), frames 77-83: ", rise[77:84].round(0).tolist())
print("ankle above standing (px), frames 121-127:", rise[121:128].round(0).tolist())
G = 9.80665
takeoff, landing = 80, 124
air = landing - takeoff
inside = clean.loc[(clean["frame"] > takeoff) & (clean["frame"] <= landing), "repeat"].sum()
for label, t in [("capture clock, 1/120 s a frame", air / 120),
                 ("file clock, 1/30 s a frame", air / 30),
                 ("repeats left out", (air - inside) / 120)]:
    print(f"{label:32s} {air} frames -> t {t:.3f} s, h {100 * G * t**2 / 8:6.1f} cm")
for k in (air - 2, air + 2):
    print(f"if the count is {k} frames: {100 * G * (k / 120)**2 / 8:.1f} cm")

# %% [markdown]
# In the table the ankle, already about 50 pixels up, climbs fast after frame 80 (58, 78, 103
# pixels) and is back near that level at frame 124. On the capture clock, 44 frames are 0.367 s
# and the jump is 16.5 cm. On the file's clock the
# same count gives 264 cm, sixteen times too much. Grass hides the soles, so the count could be
# off by two frames either way, which moves the height between 15.0 and 18.0 cm.
#
# The third line is a doubt the clip itself raises. Seven of the 44 frames in the air repeat the
# frame before. If the camera's 120 frames a second were each a distinct moment, the file holds
# only 37 distinct moments in the air and the flight was nearer 0.308 s (11.7 cm). This table
# cannot tell which reading is right; CS-3 uses the curve of the flight to test it.
#
# ### Method 2 · The rise of the hips
#
# A pose model gives positions in pixels. To turn the hips' rise into meters you need a scale.
# The jump app gets it from the athlete's stature, which you type in: standing upright, the
# distance from the eyes to the ankles is a fixed share of stature, so stature in pixels is that
# distance times 1.115 (`jump/src/lib/metrics.ts`). Here the eyes are hidden, so the ears, at
# about the same height, stand in for them, and the stature is the 1.70 m the book used. Both are
# assumptions.

# %%
# Method 2 · Hip rise from keypoints, with a scale
STATURE = 1.70                                     # m, assumed, as in the book's app run
ear_y = (clean["l_ear_y"] + clean["r_ear_y"]) / 2
ear_to_ankle = (ankle_y - ear_y)[:10].median()     # standing frames at the start
px_per_m = ear_to_ankle * 1.115 / STATURE
standing, top, at_takeoff = hip_y[:10].median(), hip_y.min(), hip_y[takeoff]
print(f"scale {px_per_m:.0f} px per m (ear to ankle {ear_to_ankle:.0f} px)")
print(f"hip rise, standing to top: {100 * (standing - top) / px_per_m:.1f} cm")
print(f"hip rise, takeoff to top:  {100 * (at_takeoff - top) / px_per_m:.1f} cm")
for s in (1.60, 1.80):
    print(f"  with a stature of {s:.2f} m: {100 * (at_takeoff - top) / (ear_to_ankle * 1.115 / s):.1f} cm")

# %% [markdown]
# Two different questions, two numbers. From **standing** to the top the hips rose 36.3 cm, but
# that includes the rise onto the toes before takeoff, like the wall-reach method of Section
# 1.3.1. From **takeoff** to the top, the quantity flight time measures, they rose 22.2 cm: more
# than the 16.5 cm from flight time, not less. The scale rests on a stature nobody measured (each
# 10 cm of stature moves the answer by about 1.3 cm) and on ears standing in for eyes, the camera
# was hand-held, and the hips are not the center of mass. Method 2 needs a scale; Method 1 needs
# only a clock.
#
# ### Method 3 · The jump app's own result
#
# The jump app ran on the same clip with the capture rate set to 120 and a stature of 1.70 m and
# wrote a text result. Its flight-time height comes from one function, `jumpHeightFromFlight` in
# `jump/src/lib/flight-time.ts`: h = g t² / 8 with g = 9.80665 m/s², the standard gravity. With a
# 17-keypoint model, whose lowest foot point is the ankle, it times takeoff and landing where the
# ankle's motion breaks most sharply, not where the ankle crosses a height line, because the
# ankle rises with the heel before the toes leave the ground (Section 1.3.3).

# %%
# Method 3 · Read the app's result and repeat its formula
text = open("raw/results_jump2_120fps.md").read()
app = {}
for line in text.splitlines():
    if line.startswith("- Flight time:"):
        app["flight_s"] = float(line.split(":")[1].split("ms")[0]) / 1000
    if line.startswith("- Jump height:"):
        app["height_cm"] = float(line.split(":")[1].split("cm")[0])
print(app)
h_app = G * app["flight_s"] ** 2 / 8
print(f"app flight {app['flight_s']:.3f} s -> g t²/8 = {100 * h_app:.1f} cm (the app prints 16.5 cm derived)")
print(f"app 'jump height' (hips, standing to top): {app['height_cm']:.1f} cm")

# %% [markdown]
# The app's flight time is the hand count's, 0.367 s, and its formula gives the same 16.5 cm.
# Its headline "Jump height", 43.0 cm, is the hips' rise from standing to the top on its own
# scale, the same kind of number as Method 2's 36.3 cm, and just as dependent on a scale this
# clip cannot support. The book reached the same verdict: filmed from behind, hand-held and on
# grass, the clip breaks the app's capture instruction, so trust the flight time.
#
# ### All the numbers on one line

# %%
# Five numbers for one jump
methods = {"hand count, flight time": 100 * G * (air / 120) ** 2 / 8,
           "app, flight time": 100 * h_app,
           "hips, takeoff to top": 100 * (at_takeoff - top) / px_per_m,
           "hips, standing to top": 100 * (standing - top) / px_per_m,
           "app, 'jump height'": app["height_cm"]}
lo, hi = [100 * G * (k / 120) ** 2 / 8 for k in (air - 2, air + 2)]
fig, ax = plt.subplots(figsize=(7, 3))
for i, (name, v) in enumerate(methods.items()):
    ax.plot(v, i, "o" if i < 2 else "s", color="k" if i < 2 else "0.5", ms=8)
    print(f"{name:26s} {v:5.1f} cm")
ax.hlines([0, 1], lo, hi, color="k")
ax.set(yticks=range(len(methods)), yticklabels=list(methods), xlabel="height (cm)", xlim=(0, 50))
ax.invert_yaxis()
plt.tight_layout()

# %% [markdown]
# The two flight-time numbers agree, and the bar shows the counting uncertainty of two frames
# either way. The hip numbers spread far wider, and the two from standing measure a different
# thing. For this clip the flight time is the number to report.
#
# ### Track it: start the athlete record
#
# Every measurement from now on goes into one long table, one number per row, rows only ever added
# (the README's format, Appendix J). This study writes the first rows. The clip carries no date,
# so the date is left empty; on your own jump, fill it in.

# %%
# The first rows of the athlete record
cols = ["date", "time", "test", "metric", "value", "unit", "trial", "device", "app", "app_version",
        "protocol_version", "conditions", "note"]
common = {"date": "", "time": "", "test": "cmj", "trial": 1, "device": "phone-120fps",
          "protocol_version": "v0-behind-handheld-grass", "conditions": ""}
record = pd.DataFrame([
    {**common, "metric": "flight_time_s", "value": round(air / 120, 3), "unit": "s", "app": "",
     "app_version": "", "note": "hand count 80-124 at 120 fps; +/-2 frames"},
    {**common, "metric": "jump_height_flight_cm", "value": round(methods["hand count, flight time"], 1),
     "unit": "cm", "app": "", "app_version": "", "note": "g t^2/8; course example clip"},
    {**common, "metric": "jump_height_cm", "value": app["height_cm"], "unit": "cm", "app": "jump",
     "app_version": "2026-11-26", "note": "app hip rise standing to top; scale not trusted"},
], columns=cols)
record.to_csv("clean/athlete-record.csv", index=False)
print(record[["test", "metric", "value", "unit", "app", "note"]].to_string(index=False))

# %% [markdown]
# **The answer.** The jump is **16.5 ± 1.5 cm** by flight time, if every file frame is 1/120 s;
# a change under 1.5 cm between two jumps measured this way is counting noise. One jump cannot
# show how much your jumps scatter from trial to trial, so film three next time (the challenge),
# and film them from the side, on a hard floor, with the phone still.
