"""Q-30: Track a ball and fit its path -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q30-ball-path/
Data:     https://apopt.com/data/tutorials/q30-ball-path/ (keep raw/ next to this file)
"""

# %% [markdown]
# Once a ball leaves the hand it follows the projectile equations of Chapter 3: its horizontal
# position changes at a steady rate and its vertical position follows a parabola set by gravity.
# The apps find the ball as an object, the "sports ball" class of the YOLO detector, and track
# its center frame by frame (Section 10.5). Here you do the same on a tennis serve toss from the
# course's example clips, `tennis1_60fps.mp4`.
#
# The first cell needs `ultralytics` and `opencv`, so it runs on your computer or in Colab. The
# clip shows a person, so it stays there; only the table of ball positions is published.

# %%
# Detect the ball in every frame
import os
import cv2
import pandas as pd
from ultralytics import YOLO

model = YOLO("yolo26n.pt")                      # COCO class 32 is "sports ball"
cap = cv2.VideoCapture("tennis1_60fps.mp4")
print(f"header: {cap.get(cv2.CAP_PROP_FPS):.0f} fps, {int(cap.get(cv2.CAP_PROP_FRAME_COUNT))} frames")
rows, i = [], 0
while True:
    ok, frame = cap.read()
    if not ok:
        break
    r = model(frame, verbose=False, device="cpu", classes=[32], conf=0.1)[0]
    if len(r.boxes):
        k = int(r.boxes.conf.argmax())              # the most confident ball
        x1, y1, x2, y2 = r.boxes.xyxy[k].tolist()
        rows.append([i, (x1 + x2) / 2, (y1 + y2) / 2, x2 - x1, y2 - y1, float(r.boxes.conf[k])])
    i += 1
os.makedirs("clean", exist_ok=True)
track = pd.DataFrame(rows, columns=["frame", "x", "y", "w", "h", "conf"]).round(2)
track.to_csv("clean/tennis1_ball.csv", index=False)
print(f"ball found in {len(track)} of {i} frames, from frame {track.frame.min()} to {track.frame.max()}")

# %% [markdown]
# ### Fit the path
#
# From here on everything runs in this page from the table. Keep the frames of the toss itself:
# the longest run of detections with no gap over three frames. Fit a straight line to x and a
# parabola to y, both against frame number.

# %%
# A line for x, a parabola for y
import numpy as np
import pandas as pd

track = pd.read_csv("clean/tennis1_ball.csv")
run = (track["frame"].diff() > 3).cumsum()                     # a new run after a gap
toss = track[run == run.value_counts().idxmax()]
n = toss["frame"].to_numpy()
px = np.polyfit(n, toss["x"], 1)
py = np.polyfit(n, toss["y"], 2)
res = toss["y"] - np.polyval(py, n)
print(f"toss: frames {n.min()} to {n.max()} ({len(toss)} detections)")
print(f"x: {px[0]:+.2f} px per frame; y: curvature {2 * py[0]:.3f} px per frame squared; "
      f"apex at frame {-py[1] / (2 * py[0]):.1f}; residual SD {res.std():.1f} px")

# %% [markdown]
# ### Gravity as a check on the clock
#
# The curvature is an acceleration in pixels per frame squared. Turn pixels into meters with the
# ball itself: a tennis ball is 6.54 to 6.86 cm across (ITF Rules of Tennis, Appendix I), so use
# 6.7 cm and the median box size. Turn frames into seconds with a frame rate. Gravity is known,
# 9.81 m/s², so the right frame rate is the one that gives it back.

# %%
# What frame rate gives gravity back?
import matplotlib.pyplot as plt

px_per_m = np.median((toss["w"] + toss["h"]) / 2) / 0.067
a = 2 * py[0] / px_per_m                                       # m per frame squared
for fps in (30, 60):
    print(f"at {fps} fps: gravity comes out {a * fps ** 2:.2f} m/s²")
print(f"ball scale {px_per_m:.0f} px/m; frame rate that gives 9.81 m/s²: {np.sqrt(9.80665 / a):.1f} fps")

fig, ax = plt.subplots(2, 1, figsize=(6.4, 4.2), sharex=True, gridspec_kw={"height_ratios": [3, 1]})
ax[0].plot(n, toss["y"], "o", ms=4, color="black", label="ball center")
ax[0].plot(n, np.polyval(py, n), "-", color="gray", label="fitted parabola")
ax[0].invert_yaxis(); ax[0].set(ylabel="y (px, up is up)"); ax[0].legend(fontsize=8)
ax[1].axhline(0, color="gray", lw=1); ax[1].plot(n, res, "o", ms=3, color="black")
ax[1].set(xlabel="frame in the file", ylabel="residual (px)")
plt.tight_layout()

# %% [markdown]
# The path is a parabola (the apex at frame 57.1), and the curvature is positive because image y
# grows downward. But neither frame rate on offer gives gravity back: the header's 30 gives
# 3.10 m/s², the 60 in the file name 12.41 m/s², and the rate that fits is 53.3 frames per
# second. Something in the clip's clock is not what either label says. Look at the points, too:
# every sixth or so comes in a pair at the same height (frames 30 and 31, 42 and 43, ...), where
# the file shows the same picture twice, and the path jumps at frame 69. The residual SD, 9.3 px,
# comes mostly from those places, not from the detector. CS-14 finds the cause and what it means
# for a release speed.
#
# **For the athlete:** a ball's path checks the video before the video measures the ball; film
# your toss with a known frame rate and the whole flight in the frame.
