"""Q-8: Speed from positions, and what noise does to it -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q08-speed-noise/
Data:     https://apopt.com/data/tutorials/q08-speed-noise/ (keep raw/ next to this file)
"""

# %% [markdown]
# ### Positions in, speed out
#
# Video gives positions, one per frame. Speed (velocity) is the change of position per unit of
# time, so it has to be computed, and the usual way is the **central difference**: the positions
# on either side of a frame, divided by the time between them (Section 3.2.1):
#
# v_i ≈ (y_(i+1) − y_(i−1)) / (2 Δt)
#
# The file holds the height of Jordan's hips through one flight, 60 samples a second, with 5 mm
# of made-up keypoint jitter added to a perfect parabola (the book's **synthetic** example of
# Section 3.2.4). Because it is synthetic, the true height and speed are in the file too, so you
# can see exactly what the jitter does.

# %%
# Central-difference speed from noisy positions
import numpy as np
import pandas as pd

f = pd.read_csv("raw/noise_flight.csv")
t, y = f["t"].to_numpy(), f["y"].to_numpy() / 100          # the file is in cm; work in m
dt = np.median(np.diff(t))
v = (y[2:] - y[:-2]) / (2 * dt)                              # central difference
v_err = v - f["vtrue"].to_numpy()[1:-1]
print(f"{len(t)} samples, dt = {1000 * dt:.1f} ms; position error sd "
      f"{1000 * (y - f['ytrue'] / 100).std():.1f} mm")
print(f"speed error: sd {v_err.std():.2f} m/s (theory sigma/(sqrt(2) dt) = {0.005 / (np.sqrt(2) * dt):.2f})")

# %% [markdown]
# Five millimeters of jitter becomes about 0.2 m/s of error in speed, close to the theory of
# Section 3.2.4: the difference of two independent errors is √2 times bigger, and dividing by the
# short time 2Δt magnifies it. Take the difference once more and you get acceleration.

# %%
# Differentiate twice, then try a faster camera
a = (y[2:] - 2 * y[1:-1] + y[:-2]) / dt**2                  # second difference
print(f"acceleration: mean {a.mean():.1f} m/s², sd {a.std():.0f} m/s² (truth: -9.81, sd 0)")
for fps in (30, 60, 120, 240):
    d = 1 / fps
    print(f"{fps:3d} fps: speed noise {0.005 / (np.sqrt(2) * d):5.2f} m/s, "
          f"acceleration noise {np.sqrt(6) * 0.005 / d**2:7.0f} m/s²")
c = np.polyfit(t, y, 2)                                      # one parabola, all samples at once
print(f"a parabola fitted to the whole flight: acceleration {2 * c[0]:.2f} m/s²")

# %% [markdown]
# The raw acceleration swings by about 50 m/s² around a mean that is not even gravity. And a
# faster camera makes it **worse**: halving Δt doubles the speed noise and quadruples the
# acceleration noise. Fitting one parabola to the whole flight, which uses the physics as well as
# the data, recovers gravity almost exactly (Q-9 does this on a real jump).
#
# ### One chart

# %%
# True and computed speed through the flight
import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 1, figsize=(6.4, 4.6), sharex=True)
ax[0].plot(t[1:-1], v, "o", ms=4, color="k", label="central difference")
ax[0].plot(t, f["vtrue"], "--", color="0.5", label="true")
ax[0].set(ylabel="speed (m/s)")
ax[0].legend(loc="upper right")
ax[1].plot(t[1:-1], a, "s", ms=4, color="k", label="second difference")
ax[1].axhline(-9.81, ls="--", color="0.5", label="gravity")
ax[1].set(xlabel="time in flight (s)", ylabel="acceleration (m/s²)")
ax[1].legend(loc="upper right")
plt.tight_layout()
print(f"largest speed error {np.abs(v_err).max():.2f} m/s; largest acceleration {np.abs(a).max():.0f} m/s²")

# %% [markdown]
# The speed is usable: it follows the true line with a scatter you can state. The acceleration is
# not, without smoothing or a model. That is why the apps smooth keypoints before they
# differentiate them, and why a takeoff speed read from two frames carries an error band.
#
# **For the athlete:** "Your takeoff speed from video is good to about 0.2 m/s; we'll compare
# sessions by speeds and heights, not by accelerations read frame to frame."
