"""Q-1: Run your first cell and change one number -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q01-first-cell/
Data:     https://apopt.com/data/tutorials/q01-first-cell/ (keep raw/ next to this file)
"""

# %% [markdown]
# ### A cell is a calculator you can rerun
#
# A code cell holds a few lines of Python. Press **Run** and the page runs them and prints the
# result underneath. Nothing is installed and nothing leaves your browser.
#
# The first calculation of the course is the height of a jump from its **flight time**, the time
# the feet are off the ground. The body rises for half the flight and falls for the other half,
# so the rise is h = g t² / 8, where g is the acceleration of gravity (Section 1.3.2). Maya filmed
# her jump at 60 frames per second and counted 32 frames in the air.

# %%
# Run your first cell
g = 9.80665        # m/s², the standard gravity the jump app uses
frames = 32        # frames counted in the air
fps = 60           # frames per second the camera recorded
t = frames / fps   # flight time, s
h = g * t**2 / 8   # rise from takeoff to the top, m
print(f"flight {t:.3f} s -> height {100 * h:.1f} cm")

# %% [markdown]
# ### Change one number
#
# Now edit the cell below: it is the same calculation with one more frame in the air. Change the
# `33` to any count you like and press Run again. Watch how fast the height moves.

# %%
# One frame more
frames = 33
t2 = frames / fps
h2 = g * t2**2 / 8
print(f"flight {t2:.3f} s -> height {100 * h2:.1f} cm")
print(f"flight {100 * (t2 / t - 1):+.1f}%, height {100 * (h2 / h - 1):+.1f}%")

# %% [markdown]
# The flight grew by 3.1% and the height by 6.3%, about twice as much, because the time is
# squared. One frame at 60 frames per second is worth about 2 cm of height. That is the
# **resolution** of a 60-frame-per-second count (Section 1.4).
#
# ### The same formula on a real app file
#
# The jump app at apopt.com writes a text file of its results. Open the one it wrote for the
# course's example clip, find the flight time, and repeat the app's arithmetic. The clip was filmed
# in slow motion at 120 frames per second but stored as a 30-frame-per-second file, so the cell also
# shows what happens if you divide by the wrong rate.

# %%
# Read the app's flight time and check it
text = open("raw/results_jump2_120fps.md").read()
for line in text.splitlines():
    if line.startswith("- Flight time:"):
        print(line)
        ms = float(line.split(":")[1].split("ms")[0])
t_app = ms / 1000
print(f"app's flight {t_app:.3f} s -> {100 * g * t_app**2 / 8:.1f} cm")
t_wrong = t_app * 120 / 30          # the same frames divided by the file's rate
print(f"read at 30 fps by mistake: {t_wrong:.3f} s -> {100 * g * t_wrong**2 / 8:.0f} cm")

# %% [markdown]
# The arithmetic matches the app: 0.367 s gives 16.5 cm. Divided by the file's 30 frames per
# second instead of the camera's 120, the flight is four times too long and the "height" sixteen
# times too large, 264 cm, higher than a basketball rim. Always divide by the rate the camera
# recorded at.
#
# ### One chart
#
# Draw the formula as a curve and mark the three flights you have met. Change `t_list` to add your
# own.

# %%
# Height against flight time
import numpy as np
import matplotlib.pyplot as plt

tt = np.linspace(0.2, 0.7, 101)
t_list = [t_app, t, t2]
names = ["example clip (app)", "Maya, 32 frames", "Maya, 33 frames"]
fig, ax = plt.subplots(figsize=(6.4, 3.6))
ax.plot(tt, 100 * g * tt**2 / 8, "k-", label="h = g t² / 8")
for ti, name, m in zip(t_list, names, ["o", "s", "^"]):
    ax.plot(ti, 100 * g * ti**2 / 8, m, ms=8, label=name)
ax.set(xlabel="flight time (s)", ylabel="jump height (cm)")
ax.legend()
plt.tight_layout()
print("a 0.6 s flight is", round(100 * g * 0.6**2 / 8, 1), "cm")

# %% [markdown]
# The curve bends upward: each extra hundredth of a second of flight is worth more height than
# the one before. Notice that the formula only ever sees the time. Get the frame count or the frame
# rate wrong and the height is wrong, however careful the arithmetic.
#
# **For the athlete:** "Your flight time was 0.37 s, which works out to a 16.5 cm rise; next time
# film at a known frame rate and we can compare jumps to within about a centimeter."
