"""CS-14: The arc of a shot or a throw -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# ### Step 1 · Gather: ball positions from two clips
#
# Two of the course's example clips show a ball leaving a hand: a basketball jump shot
# (`hoops1_60fps.mp4`) and a tennis serve toss (`tennis1_60fps.mp4`), both filmed on a phone in
# portrait. The cell below runs the YOLO detector on every frame of each and keeps the most
# confident "sports ball" (the same class the basketball app tracks). It also flags each frame
# whose picture is the same as the one before it, a check Chapter 8 recommends for every clip.
# It needs `ultralytics` and `opencv`, so it runs on your computer or in Colab. Both clips show a
# person, so they stay there: only the ball tables are published. Without the clips, start at
# Step 2, which reads the published tables.

# %%
# Step 1 · Track the ball and flag repeated pictures
import os
import cv2
import numpy as np
import pandas as pd
from ultralytics import YOLO

model = YOLO("yolo26n.pt")                                      # COCO class 32 is "sports ball"
os.makedirs("clean", exist_ok=True)
for clip in ["hoops1", "tennis1"]:
    cap, rows, prev = cv2.VideoCapture(f"{clip}_60fps.mp4"), [], None
    print(f"{clip}: header {cap.get(cv2.CAP_PROP_FPS):.0f} fps, {int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))} x "
          f"{int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))} px", end="; ")
    while (got := cap.read())[0]:
        small = cv2.resize(got[1], (108, 192)).astype(float)
        repeat = prev is not None and np.abs(small - prev).mean() < 0.3   # same picture again
        r = model(got[1], verbose=False, device="cpu", classes=[32], conf=0.1)[0]
        ball = [np.nan] * 5
        if len(r.boxes):
            x1, y1, x2, y2 = r.boxes.xyxy[int(r.boxes.conf.argmax())].tolist()
            ball = [(x1 + x2) / 2, (y1 + y2) / 2, x2 - x1, y2 - y1, float(r.boxes.conf.max())]
        rows.append([len(rows), repeat] + ball)
        prev = small
    t = pd.DataFrame(rows, columns=["frame", "repeat", "x", "y", "w", "h", "conf"]).round(2)
    t.to_csv(f"clean/ball_{clip}.csv", index=False)
    print(f"{len(t)} frames; ball in {t['x'].notna().sum()}; repeated pictures: {int(t['repeat'].sum())}")

# %% [markdown]
# ### Step 2 · Statistics: what is in each table?
#
# From here on everything runs in this page from the two published tables. Profile each one: the
# runs of frames with a ball (gaps of up to three frames allowed), the ball's size in pixels,
# whether the ball's box touches the top edge of the picture, and how often a picture repeats.

# %%
# Step 2 · Profile the two ball tables
import numpy as np
import pandas as pd

def longest_run(t):
    seen = t[t["x"].notna()]
    run = (seen["frame"].diff() > 3).cumsum()
    return seen[run == run.value_counts().idxmax()]

tabs = {c: pd.read_csv(f"clean/ball_{c}.csv") for c in ["hoops1", "tennis1"]}
for c, t in tabs.items():
    seen = t[t["x"].notna()]
    runs = seen.groupby((seen["frame"].diff() > 3).cumsum())["frame"].agg(["min", "max"])
    edge = seen[seen["y"] - seen["h"] / 2 <= 1]["frame"].tolist()          # box touches the top
    print(f"{c}: ball in {len(seen)} of {len(t)} frames; runs {[f'{a}-{b}' for a, b in runs.values]}; "
          f"size median {np.median((seen['w'] + seen['h']) / 2):.0f} px; touches the top edge at {edge}; "
          f"repeated pictures {int(t['repeat'].sum())}")

# %% [markdown]
# ### Step 3 · Visualize: is there an arc to fit?
#
# Plot the ball's height in the picture against frame number for both clips, with the repeated
# pictures marked.

# %%
# Step 3 · Ball height in both clips
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, 2, figsize=(9, 3.4), sharey=True)
for a, (c, t) in zip(ax, tabs.items()):
    a.plot(t["frame"], t["y"], "o", ms=3, color="black", label="ball center")
    rep = t[t["repeat"] & t["y"].notna()]
    a.plot(rep["frame"], rep["y"], "s", ms=8, mfc="none", color="gray", label="repeated picture")
    a.axhline(0, color="gray", lw=1, ls="--")
    a.set(title=c, xlabel="frame in the file")
ax[0].set(ylabel="y (px, up is up)"); ax[0].invert_yaxis(); ax[1].legend(fontsize=8)
plt.tight_layout()

# %% [markdown]
# The basketball clip has no arc to fit. The ball arrives as a pass (frames 2 to 31), sits in the
# hands, rises with them (35 to 49) and touches the top of the picture (the dashed line) at
# frames 47 and 48, about when it leaves the hands; the few later detections are not the ball in
# flight. A
# portrait phone close to the shooter films the shot, not the ball's flight. That is the first
# finding, and it is about filming: to measure an arc, the whole flight has to be in the frame.
# The tennis toss has a full arc, up and down, so the rest of this study uses it. A toss is a
# throw, and its height and consistency are what a server practises.
#
# ### Step 4 · Cleanse: one clock for the toss
#
# Q-30 fitted a parabola to this toss against the file's frame number and found that neither
# 30 nor 60 frames per second gave gravity back. The repeated pictures are why. A file that shows
# the same picture twice has not moved forward in real time between them, so a frame number is
# not a clock. The rules: keep the longest run of the toss; drop the repeated pictures; count time
# in **distinct pictures**. Then compare the fit with both clocks.

# %%
# Step 4 · File frames against distinct pictures as the clock
toss = longest_run(tabs["tennis1"])
distinct = (~tabs["tennis1"]["repeat"]).cumsum() - 1           # index of each distinct picture
toss = toss.assign(k=distinct[toss.index].to_numpy())
log = {"detections in the run": len(toss), "repeated pictures dropped": int(toss["repeat"].sum())}
toss = toss[~toss["repeat"]]

def fit(t, clock):
    p = np.polyfit(t[clock], t["y"], 2)
    return p, t["y"] - np.polyval(p, t[clock])

for clock in ["frame", "k"]:
    _, res = fit(toss, clock)
    print(f"clock = {clock:5s}: residual SD {res.std():.1f} px, largest {res.abs().max():.1f} px "
          f"at frame {int(toss.loc[res.abs().idxmax(), 'frame'])}")
print(log)

# %% [markdown]
# Neither clock fits the whole run: with either one, the worst misfit sits at frames 68 and 69.
# Look at the table there. Between frames 68 and 69 the ball moves about twice its usual step,
# and frames 69, 70 and 71 hold the same picture: the file dropped a picture and filled the gap
# with copies. Times across that break are unknown, so the last rule is to fit only the part
# before it, with distinct pictures as the clock.

# %%
# Step 4 · Fit before the break, and check it
before = toss[toss["frame"] < 69]
py, res = fit(before, "k")
px = np.polyfit(before["k"], before["x"], 1)
print(f"fit on frames {before['frame'].min()}-{before['frame'].max()} ({len(before)} distinct pictures): "
      f"residual SD {res.std():.1f} px, largest {res.abs().max():.1f} px "
      f"(with file frames as the clock: {fit(before, 'frame')[1].std():.1f} px)")
print(f"curvature {2 * py[0]:.3f} px per picture²; x {px[0]:+.2f} px per picture; "
      f"apex at picture {-py[1] / (2 * py[0]):.1f}")
before.to_csv("clean/toss_clean.csv", index=False)

# %% [markdown]
# Before the break, with distinct pictures as the clock, the residual SD falls to 1.5 pixels,
# small next to a 28-pixel ball: the path is now a clean parabola, good enough to measure from.
# Fitted against file frames, the same points leave 5.2 pixels, and Q-30's 9.3 also included
# the break.
#
# ### Step 5 · Features: gravity gives the clock, the ball gives the scale
#
# Two things are known without the video: the ball is 6.54 to 6.86 cm across (ITF Rules of
# Tennis, Appendix I) and gravity is 9.81 m/s². The ball's size turns pixels into meters. Gravity
# then turns pictures into seconds, because the curvature must equal g. And some quantities need
# no clock at all: the height of the toss, and the angle of the path, are pure geometry. The speed
# at the first tracked point follows from the height alone, v_up = √(2 g h), the flight-height
# relation of Section 3.4 run backward.

# %%
# Step 5 · Release speed, angle and height, with no clock from the file
G = 9.80665
size_px = np.median((before["w"] + before["h"]) / 2)
k0, k_apex = before["k"].iloc[0], -py[1] / (2 * py[0])
rise_px = np.polyval(py, k0) - np.polyval(py, k_apex)           # image y grows downward
for label, d in (("small ball 6.54 cm", 0.0654), ("6.70 cm", 0.067), ("large ball 6.86 cm", 0.0686)):
    m_per_px = d / size_px
    rise = rise_px * m_per_px
    v_up = np.sqrt(2 * G * rise)
    v_side = v_up * abs(px[0]) / abs(2 * py[0] * (k_apex - k0))  # same ratio as the path's slope
    rate = np.sqrt(G / (2 * py[0] * m_per_px))                  # pictures per real second
    print(f"{label}: rise {rise:.2f} m, speed {np.hypot(v_up, v_side):.2f} m/s at "
          f"{np.degrees(np.arctan2(v_up, v_side)):.1f}° above horizontal; clock {rate:.1f} pictures/s")
print(f"the same speed computed with the file's 30 or 60 fps would be off by a factor "
      f"{30 / rate:.2f} or {60 / rate:.2f}")

# %% [markdown]
# From the first point where the detector found the ball, the toss rises 1.47 m, at 5.37 m/s,
# 87.5° above the horizontal: nearly straight up, drifting slightly sideways in the picture. The
# legal range of ball sizes moves the rise from 1.43 to 1.51 m and the speed from 5.31 to
# 5.44 m/s, a few percent. None of these numbers used the file's clock. The clock gravity finds,
# about 44 distinct pictures a real second, is the surprise: neither the header's 30 nor the
# name's 60. A speed worked out with 30 would be 31% too low, with 60 37% too high.
#
# Two limits. The first tracked point is not the release: the hand lets go a little earlier and
# lower, so the true release speed is a little higher than 5.37 m/s. And one toss says nothing
# about consistency, or about good tosses against bad ones; that needs many tosses, filmed the
# same way (the challenge).
#
# Finally, draw the toss as measured beside the parabola, in meters, with the real time from the
# clock that gravity found.

# %%
# The toss in meters and seconds
m_per_px = 0.067 / size_px
rate = np.sqrt(G / (2 * py[0] * m_per_px))
t = (before["k"] - k0) / rate
h = (np.polyval(py, k0) - before["y"]) * m_per_px
kk = np.linspace(k0, before["k"].iloc[-1], 100)
fig, ax = plt.subplots(figsize=(6.4, 3.4))
ax.plot(t, h, "o", ms=4, color="black", label="ball, cleaned detections")
ax.plot((kk - k0) / rate, (np.polyval(py, k0) - np.polyval(py, kk)) * m_per_px, "-", color="gray",
        label=f"parabola, g = 9.81 m/s² at {rate:.1f} pictures/s")
ax.set(xlabel="time from the first tracked point (s)", ylabel="height above it (m)")
ax.legend(fontsize=8, loc="lower center")
plt.tight_layout()
print(f"apex {h.max():.2f} m at {t[h.idxmax()]:.2f} s; tracked for {t.iloc[-1]:.2f} s")
