"""Q-28: Height from flight time, with one frame of error -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# Once the feet leave the ground the body is a projectile. If it lands in the same position it
# took off in, the rise and the fall each take half the flight time t, so the center of mass
# rises
#
# h = g t² / 8, with g = 9.80665 m/s² (the value the jump app uses).
#
# The raw file is a hand count from Chapter 1: someone stepped through the course's clip
# `jump2_120fps.mp4`, a jump filmed in slow motion at 120 frames per second and stored at 30,
# and wrote down the frame where the shoes first cleared the grass and the frame where the first
# shoe came back.

# %%
# Flight and height from a frame count, at the right and the wrong rate
import numpy as np
import pandas as pd

G = 9.80665
def height(t): return G * t ** 2 / 8

count = pd.read_csv("raw/jump2_hand_count.csv").iloc[0]
frames = count["landing_frame"] - count["takeoff_frame"]
for label, fps in (("capture rate", count["capture_fps"]), ("stored rate", count["stored_fps"])):
    t = frames / fps
    print(f"{label} {fps} fps: {frames} frames = {t:.3f} s -> h = {height(t):.3f} m")

# %% [markdown]
# At the capture rate the flight is 0.367 s and the jump 0.165 m. At the stored rate the same
# count gives 1.467 s and 2.637 m, an impossible jump: the jump app refuses any flight over 1.1 s or
# height over 1.5 m (`jump/src/lib/metrics.ts`) and asks you to check the rate. Always divide by
# the rate the camera filmed at.
#
# ### One frame either way
#
# An event between two frames can only be placed on one of them, so a flight time is uncertain by
# about one frame. Height grows with the square of time, so the height moves by more than the
# time does, in percent.

# %%
# One frame of error at four frame rates
rows = []
t = frames / count["capture_fps"]
for fps in (30, 60, 120, 240):
    lo, hi = height(t - 1 / fps), height(t + 1 / fps)
    rows.append({"fps": fps, "frames in flight": round(t * fps, 1), "h one short (m)": round(lo, 3),
                 "h one long (m)": round(hi, 3), "span (cm)": round(100 * (hi - lo), 1),
                 "span (% of h)": round(100 * (hi - lo) / height(t), 1)})
budget = pd.DataFrame(rows)
print(f"flight {t:.3f} s, height {height(t):.3f} m")
print(budget.to_string(index=False))
print(f"hand count +/- 2 frames at 120 fps: {height(42 / 120):.3f} to {height(46 / 120):.3f} m")

# %%
# The frame budget of this jump
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6, 3.2))
ax.errorbar(budget["fps"], [height(t)] * 4,
            yerr=[height(t) - budget["h one short (m)"], budget["h one long (m)"] - height(t)],
            fmt="o", color="black", capsize=6)
ax.set_xscale("log", base=2); ax.set_xticks([30, 60, 120, 240], ["30", "60", "120", "240"])
ax.set(xlabel="capture rate (frames per second)", ylabel="height (m)")
plt.tight_layout()

# %% [markdown]
# At 120 frames per second, one frame either way spans 1.5 cm, 9.1% of this 0.165 m jump; at 30
# it would span 6.0 cm, 36.4%. Each doubling of the frame rate halves the span. A short jump
# suffers more than a high one, because one frame is a bigger share of a short flight (Chapter
# 10's 0.50 s example spans 8.2 cm at 30 frames per second). The grass adds its own error here:
# two frames either way, 0.150 to 0.180 m. And Chapter 8 found that this file repeats every
# sixth frame, so the 44 frames may hold only about 37 distinct ones: check that frames are
# distinct before trusting any count.
#
# **For the athlete:** this jump was 0.165 m, give or take a centimeter or two; film at the
# highest frame rate your phone offers, and tell the app the rate you filmed at.
