"""CS-12: The body-weight force of each foot plant -- Data-Driven Athletics tutorial.

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

# %% [markdown]
# ### The model, before any data
#
# Over one whole step at a steady speed, the vertical force under the runner must average
# exactly one body weight (BW); if it averaged more the runner would rise, less and the runner
# would sink. The foot is on the ground for only part of the step, the **contact time** t_c,
# and in the air for the rest, the **flight time** t_f. So while the foot is down the force
# must average more:
#
# mean force / BW = step time / contact time = 1 + t_f / t_c.
#
# If the force during contact has the shape of half a sine wave, its peak is π/2 times its mean:
#
# peak force / BW = (π/2) × (1 + t_f / t_c).
#
# This is the sine-wave model of the running-stiffness method of Morin and colleagues (2005).
# It needs two times and nothing else. The number it gives is **modeled**, not measured
# (Section 5.1's distinction).
#
# ### Step 1 · Gather
#
# Two files. The timing comes from Chapter 9's treadmill runner, filmed from behind at 30 frames
# per second: both ankles' image position in every frame. The check comes from the Data-Driven
# Engineering running data: an instrumented treadmill that measured the peak force of each
# left-foot step, beside its contact time and stride rate.

# %%
# Step 1 · Open both files, and work one step by hand
import numpy as np
import pandas as pd

FPS = 30
ankles = pd.read_csv("raw/form1_ankles.csv")
lab = pd.read_csv("raw/biomechanics.txt")
print(f"ankle table: {ankles.shape}, {len(ankles) / FPS:.2f} s at {FPS} frames per second")
print(f"treadmill file: {lab.shape}, columns {', '.join(lab.columns)}")

def mean_bw(tc, tf): return 1 + tf / tc
def peak_bw(tc, tf): return np.pi / 2 * (1 + tf / tc)

tc, step = 0.25, 0.349
print(f"by hand: mean {mean_bw(tc, step - tc):.2f} BW, peak {peak_bw(tc, step - tc):.2f} BW "
      f"= {peak_bw(tc, step - tc) * 70 * 9.80665:.0f} N for a 70 kg runner")

# %% [markdown]
# ### Step 2 · Statistics
#
# Profile the columns each model input will come from: the ankle confidence and range, and
# the three treadmill columns the check uses, `lgt` (left contact time, s), `sr` (stride rate,
# strides per second) and `lpeakforce` (measured left peak force, BW).

# %%
# Step 2 · Profile the inputs
cols = ["l_ankle_y", "l_ankle_c", "r_ankle_y", "r_ankle_c"]
print(ankles[cols].describe().loc[["count", "mean", "min", "max"]].round(2).to_string())
print()
print(lab[["lgt", "sr", "lpeakforce"]].describe().loc[["count", "mean", "min", "max"]].round(3).to_string())
print("treadmill rows holding -9999 in these columns:", int((lab[["lgt", "sr", "lpeakforce"]] == -9999).any(axis=1).sum()))

# %% [markdown]
# The ankle table is clean: 464 frames, confidence never below 0.5. The treadmill file has the
# missing-value code −9999 in every column, as CS-13 found; those rows are removed in Step 4
# before any average is taken.
#
# ### Step 3 · Visualize: where is the foot on the belt?
#
# The running app's stance rule (Chapter 9, `form/src/lib/metrics.ts`): smooth the ankle's image
# height over 3 frames, take each lowest point in the bottom 15% of its range as a contact, and
# grow the stance backward and forward while the foot stays in the bottom 30%. Draw the stances
# on the trace before computing anything from them.

# %%
# Step 3 · The ankle traces with each stance shaded
import matplotlib.pyplot as plt

def stances(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 = [i for i in range(1, len(y) - 1) if y[i] >= hi and y[i] >= y[i - 1] and y[i] >= y[i + 1]]
    out, last = [], -99
    for p in peaks:
        if p - last < int(0.2 * FPS):
            continue                                   # contacts at least 0.2 s apart
        i = j = last = 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((i, j))                             # first and last frame on the ground
    return out

st = {s: stances(ankles[f"{s}_ankle_y"].to_numpy()) for s in "lr"}
fig, ax = plt.subplots(figsize=(8, 3.2))
for s, style, shade in (("l", "-", 0.35), ("r", "--", 0.15)):
    ax.plot(ankles["t"], ankles[f"{s}_ankle_y"], style, color="black", lw=1, label=f"{s} ankle")
    for k, (i, j) in enumerate(st[s]):
        ax.axvspan(i / FPS, (j + 1) / FPS, color="gray", alpha=shade, lw=0, label=f"{s} stance" if k == 0 else None)
ax.set(xlim=(0, 4), xlabel="time (s)", ylabel="ankle y (pixels, down is down)")
ax.invert_yaxis(); ax.legend(loc="lower center", bbox_to_anchor=(0.5, 1.0), ncol=4, frameon=False)
plt.tight_layout()
print({s: len(v) for s, v in st.items()}, "stances")

# %% [markdown]
# ### Step 4 · Cleanse: pair each contact with the flight after it
#
# A foot plant is one contact and the flight that follows it, up to the other foot's next
# contact. Rules, written first: a stance must last 0.08 to 0.45 s (the app's bounds); the next
# contact must be the **other** foot; and the flight must be longer than zero (an overlap means
# walking, or an error). Every rule's removals go in a change log.

# %%
# Step 4 · Foot plants, rules and a change log
import os

events = sorted([(i, j, s) for s in "lr" for i, j in st[s]])
rows, log = [], {"stance outside 0.08-0.45 s": 0, "next contact on the same foot": 0, "no flight": 0}
for (i, j, s), (i2, _, s2) in zip(events[:-1], events[1:]):
    tc, tf = (j - i + 1) / FPS, (i2 - j - 1) / FPS
    if not 0.08 <= tc <= 0.45:
        log["stance outside 0.08-0.45 s"] += 1
    elif s2 == s:
        log["next contact on the same foot"] += 1
    elif tf <= 0:
        log["no flight"] += 1
    else:
        rows.append({"foot": s, "start_frame": i, "contact_frames": j - i + 1,
                     "flight_frames": i2 - j - 1, "tc_s": round(tc, 4), "tf_s": round(tf, 4)})
plants = pd.DataFrame(rows)
os.makedirs("clean", exist_ok=True)
plants.to_csv("clean/foot_plants.csv", index=False)
print(f"{len(events) - 1} contacts with a next contact; kept {len(plants)}; removed: {log}")
print(plants.groupby("foot")[["contact_frames", "flight_frames"]].agg(lambda v: v.value_counts().to_dict()).to_string())

# %% [markdown]
# ### Step 5 · Features: the force of each foot plant
#
# Now the model, one foot plant at a time, then the mean of each foot and the asymmetry index of
# Section 9.5, 100 × |L − R| / ((L + R) / 2).

# %%
# Step 5 · Modeled force per foot plant, left against right
plants["mean_bw"] = mean_bw(plants["tc_s"], plants["tf_s"])
plants["peak_bw"] = peak_bw(plants["tc_s"], plants["tf_s"])
plants.round(3).to_csv("clean/foot_plants.csv", index=False)
by_foot = plants.groupby("foot")["peak_bw"].agg(["count", "mean", "std", "min", "max"])
print(by_foot.round(2).to_string())
L, R = by_foot.loc["l", "mean"], by_foot.loc["r", "mean"]
se = np.sqrt((by_foot["std"] ** 2 / by_foot["count"]).sum())   # chance scatter of R - L
print(f"R - L = {R - L:.2f} BW (chance scatter of that difference {se:.2f} BW); "
      f"asymmetry index {100 * abs(L - R) / ((L + R) / 2):.1f} %")
print("mean frames:", plants.groupby("foot")[["contact_frames", "flight_frames"]].mean().round(2).to_dict("index"))
print(f"distinct peak values in the whole run: {plants['peak_bw'].round(3).nunique()}")

# %% [markdown]
# Three things to see. The model gives this runner a peak of about 2.6 BW on the left and 2.8 BW
# on the right: a 7.5% asymmetry, and 0.20 BW is more than three times the 0.06 BW that the
# plant-to-plant scatter alone would produce by chance. But look at where it comes from. Both
# feet's contacts average just over 6 frames; the flights after a right contact average 4.73
# frames, after a left contact 3.90. The whole difference is **less than one frame** of flight.
# And the run produces only 9 distinct values: with contact and flight both counted in whole
# frames, the model can only return a value from a small grid. The next step asks how much one
# frame is worth.
#
# ### Step 5 continued · Carry one frame of error through
#
# Read the contact one frame short or one frame long, with the step held fixed, and recompute.
# Do it for the hand example at 60 and at 30 frames per second, and for this runner's median foot
# plant at the 30 frames per second it was filmed at.

# %%
# Step 5 · One frame of error, at 60 and at 30 frames per second
def one_frame(tc, step, fps):
    base = peak_bw(tc, step - tc)
    short, long_ = (peak_bw(tc + d / fps, step - tc - d / fps) for d in (-1, 1))
    return base, 100 * (short / base - 1), 100 * (long_ / base - 1)

cases = [("hand example", 0.25, 0.349, 60), ("hand example", 0.25, 0.349, 30),
         ("this runner, median", plants["tc_s"].median(), (plants["tc_s"] + plants["tf_s"]).median(), 30)]
for name, tc, step, fps in cases:
    base, up, down = one_frame(tc, step, fps)
    print(f"{name:20s} {fps} fps: peak {base:.2f} BW; one frame short {up:+.1f} %, one frame long {down:+.1f} %")
print(f"left-right difference of the means: {100 * abs(L - R) / ((L + R) / 2):.1f} %")

# %% [markdown]
# One frame too few at 60 frames per second raises the modeled peak by 7.1%; at 30, by 15.4% for
# the hand example and by 20.0% for this runner, whose contact is only 6 frames long. One frame
# too many lowers it by 6.3%, 11.8% and 14.3%. The left–right difference, 7.5%, is about half of
# one frame's worth at 30 frames per second. It is consistent across the run, so it is not
# random rounding, but a rule that ends the stance one frame earlier on one foot than the other
# would produce it, and filmed from behind, the two feet are not seen the same way (Section 9.8).
# That is the finding: from a phone clip at 30 frames per second, a left–right difference in
# modeled force of this size cannot be told from a one-frame bias in the events.
#
# Explore the same model with your own times in the viewer below: move contact time, flight time
# and frame rate and watch the band.

# %% [markdown]
# ### Step 5, checked · The model against a force-measuring treadmill
#
# A model is only as good as its agreement with a measurement. The Data-Driven Engineering file
# has left contact time and stride rate beside the left peak force measured by the treadmill, for
# 2,600 steps after the −9999 rows are dropped. A stride is two steps, so the step time is
# 1 / (2 × stride rate), and the flight is the step time minus the contact time.

# %%
# The model against the measured peak force
ok = lab[["lgt", "sr", "lpeakforce"]].ne(-9999).all(axis=1) & (lab["lgt"] > 0)
tr = lab[ok].copy()
tr["step_s"] = 1 / (2 * tr["sr"])
tr["model_bw"] = peak_bw(tr["lgt"], tr["step_s"] - tr["lgt"])
err = tr["model_bw"] - tr["lpeakforce"]
r2 = 1 - (err ** 2).sum() / ((tr["lpeakforce"] - tr["lpeakforce"].mean()) ** 2).sum()
print(f"{len(tr)} steps; measured {tr['lpeakforce'].mean():.2f} BW, modeled {tr['model_bw'].mean():.2f} BW")
print(f"mean error {err.mean():+.2f} BW ({100 * err.mean() / tr['lpeakforce'].mean():+.0f} %), "
      f"spread (SD) {err.std():.2f} BW, correlation {np.corrcoef(tr['model_bw'], tr['lpeakforce'])[0, 1]:.2f}, R² {r2:.2f}")
print(f"after removing the mean error: typical error {np.sqrt(((err - err.mean()) ** 2).mean()):.2f} BW")

fig, ax = plt.subplots(figsize=(4.8, 4.2))
ax.plot(tr["lpeakforce"], tr["model_bw"], ".", ms=2, alpha=0.4, color="black")
ax.plot([1.5, 5], [1.5, 5], "--", color="gray", lw=1, label="model = measured")
ax.set(xlabel="measured peak force (BW)", ylabel="half-sine model (BW)", aspect="equal")
ax.legend(loc="upper left", fontsize=8)
plt.tight_layout()

# %% [markdown]
# The model rises and falls with the measured force (correlation 0.74), but it runs 0.32 body
# weights low on average, 11% of the measured mean, the same bias CS-13 found on this file; and
# the gap grows at the highest forces. With the bias removed the typical error is still 0.27 BW.
# A real running force curve is more peaked than half a sine wave, so π/2 times the mean
# underestimates the peak. And the impact peak at heel strike is
# not in a sine wave at all. Read a modeled peak as a number to compare with the same runner's
# other numbers, computed the same way, not as a force-plate value.
#
# Set the two parts side by side. A one-frame error at 30 frames per second moves this runner's
# modeled peak by 14 to 20%, about 0.4 to 0.6 BW; the model's own bias against the treadmill is
# 0.32 BW and its scatter 0.27 BW. On a phone clip, the frame rate is the larger error. Film at
# 120 frames per second or more and the one-frame error falls to about 4%, below the model's
# own scatter.
