"""Q-25: Find foot contacts in an ankle trace -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q25-foot-contacts/
Data:     https://apopt.com/data/tutorials/q25-foot-contacts/ (keep raw/ next to this file)
"""

# %% [markdown]
# Chapter 9's running example is a runner on a treadmill, filmed from behind at 30 frames per
# second for 15.5 s. A pose model found both ankles in every frame, and the table keeps their
# image position and confidence. A foot on the belt is at its lowest point in the picture,
# which in image coordinates is its **largest** y. So a contact is a peak of y.

# %%
# Open the ankle table and count the obvious way
import numpy as np
import pandas as pd
from scipy.signal import find_peaks

FPS = 30
df = pd.read_csv("raw/form1_ankles.csv")
print(df.shape, f"{len(df) / FPS:.1f} s; median ankle confidence "
      f"{df[['l_ankle_c', 'r_ankle_c']].median().min():.2f}")
naive, _ = find_peaks(df["l_ankle_y"])                 # every local peak, no guards
print(f"left ankle, every local peak: {len(naive)} 'contacts'")

# %% [markdown]
# A runner at 170 steps a minute makes 85 contacts a minute on each foot, about 22 in 15.5 s.
# Every local peak gives 107, five times too many: a noisy trace has small bumps, and each bump is a
# peak. The running app adds three guards (checked in its source, `form/src/lib/metrics.ts`):
# smooth the trace over about 0.08 s (3 frames at 30 per second); accept only peaks in the
# bottom 15% of the foot's range, above the 85th percentile of y; and keep peaks at least
# 0.2 s apart.

# %%
# The app's three guards
def contacts(y, fps=FPS):
    s = pd.Series(y).rolling(3, center=True, min_periods=1).mean().to_numpy()   # about 0.08 s
    peaks, _ = find_peaks(s, height=np.percentile(s, 85), distance=int(0.2 * fps))
    return peaks

found = {side: contacts(df[f"{side}_ankle_y"].to_numpy()) for side in "lr"}
for side, p in found.items():
    gaps = np.diff(p) / FPS
    print(f"{side}: {len(p)} contacts; same-foot interval median {np.median(gaps):.3f} s, "
          f"range {gaps.min():.3f} to {gaps.max():.3f} s")

# %%
# The trace with its contacts
import matplotlib.pyplot as plt

first = df["t"] < 4
fig, ax = plt.subplots(figsize=(7, 3.2))
for side, style, mark in (("l", "-", "o"), ("r", "--", "s")):
    ax.plot(df["t"][first], df[f"{side}_ankle_y"][first], style, lw=1.2, label=f"{side} ankle")
    p = [i for i in found[side] if df["t"][i] < 4]
    ax.plot(df["t"][p], df[f"{side}_ankle_y"][p], mark, mfc="none", ms=8, color="black")
ax.invert_yaxis()
ax.set(xlabel="time (s)", ylabel="ankle y (pixels, down is down)")
ax.legend(loc="lower center", bbox_to_anchor=(0.5, 1.0), ncol=2, fontsize=8, frameon=False)
plt.tight_layout()

# %% [markdown]
# With the guards, each foot gives 22 contacts, one per stride, and the same-foot interval
# stays between about 0.67 and 0.73 s, 20 to 22 frames. That narrow range is the check that
# no contact was doubled or missed: a doubled contact would show as an interval near half a
# stride, a missed one as an interval near a whole extra stride. Notice that the intervals can
# only be whole frames, 33 ms apart; Q-26 shows what that does to a cadence.
#
# **For the athlete:** a phone can find every foot contact in a steady run, as long as the
# whole foot stays in the frame.
