"""Q-27: An asymmetry index, three definitions -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# An **asymmetry index** compares a left value with a right value. Section 9.5 gives the common
# form, the difference as a percentage of the mean of the two sides:
#
# A = 100 × |L − R| / ((L + R) / 2).
#
# It is not the only one. The walking app uses three definitions for three of its measures
# (checked in `walk/src/lib/metrics.ts`): stance time uses the mean of the two sides as the
# denominator, arm swing uses the **larger** side, and knee bend uses the plain difference in
# degrees. Apply all three to one runner's contact times and see how much the definition and the
# frame rate decide the answer.

# %%
# Contact time of every foot plant, left and right
import numpy as np
import pandas as pd
from scipy.signal import find_peaks

FPS = 30
df = pd.read_csv("raw/form1_ankles.csv")

def contact_frames(y):
    y = pd.Series(y).rolling(3, center=True, min_periods=1).mean().to_numpy()
    hi, lo = np.percentile(y, 85), np.percentile(y, 70)
    peaks, _ = find_peaks(y, height=hi, distance=int(0.2 * FPS))
    out = []
    for p in peaks:                                   # grow the stance while the foot stays low
        i = j = p
        while i > 0 and y[i - 1] >= lo: i -= 1
        while j < len(y) - 1 and y[j + 1] >= lo: j += 1
        out.append(j - i + 1)
    return np.array(out)

L, R = contact_frames(df["l_ankle_y"]), contact_frames(df["r_ankle_y"])
print(f"left:  {len(L)} contacts, frames {np.bincount(L)[4:].tolist()} (counts of 4, 5, 6, ... frames)")
print(f"right: {len(R)} contacts, frames {np.bincount(R)[4:].tolist()}")
print(f"mean contact: left {L.mean() / FPS * 1000:.0f} ms, right {R.mean() / FPS * 1000:.0f} ms")

# %% [markdown]
# Every contact is a whole number of frames, mostly 6 or 7 (200 or 233 ms), and the two feet
# have exactly the same mix: 13 contacts of 6 frames and 8 of 7 on each side. Now the three
# definitions, on the runner's two means and on a pair of values that do differ, the median
# single-leg hop heights of Section 10.2's worked example (0.142 m left, 0.121 m right).

# %%
# Three definitions, two examples
def a_mean(l, r): return 100 * abs(l - r) / ((l + r) / 2)     # stance time in the walking app
def a_max(l, r): return 100 * abs(l - r) / max(l, r)          # arm swing in the walking app
def a_diff(l, r): return abs(l - r)                           # knee bend in the walking app (deg)

l_ms, r_ms = L.mean() / FPS * 1000, R.mean() / FPS * 1000
for name, (l, r, unit) in {"runner, contact time": (l_ms, r_ms, "ms"),
                           "hops, height (Section 10.2)": (14.2, 12.1, "cm")}.items():
    print(f"{name}: mean denominator {a_mean(l, r):.1f} %, larger denominator {a_max(l, r):.1f} %, "
          f"plain difference {a_diff(l, r):.1f} {unit}")
print(f"one frame in a 6-frame contact: {a_mean(6, 7):.1f} % by the mean, {a_max(6, 7):.1f} % by the larger")

# %%
# Asymmetry step by step
import matplotlib.pyplot as plt

n = min(len(L), len(R))
pairs = [a_mean(l, r) for l, r in zip(L[:n], R[:n])]
fig, ax = plt.subplots(figsize=(6.4, 3.2))
ax.plot(range(1, n + 1), pairs, "o-", ms=4, label="each left-right pair")
ax.axhline(a_mean(l_ms, r_ms), color="black", lw=2, label="from the two means")
for level in (3, 8):
    ax.axhline(level, color="gray", ls="--", lw=1)
ax.set(xlabel="pair of contacts", ylabel="asymmetry (% of the mean)")
ax.legend(fontsize=8)
plt.tight_layout()
print(f"pairs: median {np.median(pairs):.1f} %, {sum(p == 0 for p in pairs)} of {n} exactly 0")

# %% [markdown]
# Three lessons, one per cell.
#
# * **The definition matters.** For the same two hops, the asymmetry is 16.0% with the mean as
#   denominator, 14.8% with the larger side, and 2.1 cm as a plain difference. A published
#   value can be compared with yours only if the formula matches (Section 9.5).
# * **The frame grid matters more.** At 30 frames per second a contact of 6 frames against one
#   of 7 is already 15.4% by the mean. Pair by pair, this runner swings between 0% and 15.4%
#   (median 15.4%, 9 of 22 pairs exactly 0, one pair 33%), only because each contact is rounded
#   to whole frames. The walking app's stance-time bands for walking, good under 3% and okay
#   under 8% (the dashed lines), are smaller than one frame here.
# * **Average before comparing.** The two feet's means are identical, 211 ms each, so the
#   asymmetry of the means is 0.0%. Compare means over many contacts, never single pairs.
#
# **For the athlete:** a left–right difference in contact time from a 30-frames-per-second clip
# means nothing unless it is larger than one frame and shows in the average over many steps.
