# /// script
# requires-python = ">=3.11"
# dependencies = [
#   "matplotlib",
#   "numpy",
# ]
# ///
"""
Figure for "Methods tested" in "Resampling discontinuous power to 1 Hz".

    uv run static/files/resampling-discontinuous-power/methods_compared.py

The same three rowing strokes as per_second_vs_per_cycle.py, resampled to 1 Hz
in six ways. Method A works on instantaneous power (rowing_crop.csv), B to F on
per-stroke values only (rowing_strokes.csv: start = catch, end = next catch,
power = work / stroke duration). Both files come from extract_crops.py.

Every 1 Hz value covers one whole second [s, s + 1).
"""

import csv
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np

HERE = Path(__file__).resolve().parent
OUTPUT = HERE.parent.parent / "images" / "resampling-discontinuous-power" / "methods_compared.png"

INSTANT_COLOR = "#222222"
PER_CYCLE_FILL = "#2a78d62e"  # blue edge colour at 18% opacity, so the grid shows through
PER_CYCLE_EDGE = "#2a78d6"
PER_SECOND_COLOR = "#eb6834"

plt.rcParams.update({
    "font.family": "serif",
    "font.serif": ["STIX Two Text", "STIXGeneral", "Times New Roman", "DejaVu Serif"],
    "mathtext.fontset": "stix",
    "font.size": 9,
    "axes.linewidth": 0.6,
    "axes.spines.top": False,
    "axes.spines.right": False,
    "xtick.direction": "out",
    "ytick.direction": "out",
    "xtick.major.width": 0.6,
    "ytick.major.width": 0.6,
    "xtick.major.size": 3,
    "ytick.major.size": 3,
    "legend.frameon": False,
})


def read_csv(name):
    with (HERE / name).open() as f:
        return list(csv.DictReader(f))


crop = read_csv("rowing_crop.csv")
t = np.array([float(r["time_s"]) for r in crop])
power = np.array([float(r["power_w"]) for r in crop])

strokes = [(float(r["start_s"]), float(r["end_s"]), float(r["power_w"])) for r in read_csv("rowing_strokes.csv")]
shown = strokes[1:-1]  # the three strokes; the outer two are context for B, E and F
window = (shown[0][0], shown[-1][1])
seconds = np.arange(np.floor(window[0]), np.ceil(window[1]))


# --- Methods: each returns one value per second in `seconds` ---------------------


def a_average_instantaneous():
    return np.array([power[(t >= s) & (t < s + 1)].mean() for s in seconds])


def b_hold_last_completed():
    """Causal: the last stroke that ended by the end of the second."""
    return np.array([[p for _, end, p in strokes if end <= s + 1][-1] for s in seconds])


def c_stroke_it_falls_in():
    """The stroke the middle of the second falls in."""
    return np.array([next(p for start, end, p in strokes if start <= s + 0.5 < end) for s in seconds])


def d_time_weighted():
    """Each stroke's power weighted by how much of the second it covers. Preserves work."""
    return np.array([
        sum(max(0.0, min(end, s + 1) - max(start, s)) * p for start, end, p in strokes)
        for s in seconds
    ])


def e_linear_interpolation():
    """Stroke values placed at the middle of each stroke, interpolated at mid-second."""
    mids = [(start + end) / 2 for start, end, _ in strokes]
    return np.interp(seconds + 0.5, mids, [p for _, _, p in strokes])


def f_events_in_second():
    """Average of strokes that ended within the second. None ended: repeat the previous value."""
    values, previous = [], strokes[0][2]  # the stroke before the window
    for s in seconds:
        ended = [p for _, end, p in strokes if s <= end < s + 1]
        previous = np.mean(ended) if ended else previous
        values.append(previous)
    return np.array(values)


METHODS = [
    ("A. average each second", "from instantaneous power", a_average_instantaneous),
    ("B. hold last completed stroke", "causal, lags up to one stroke", b_hold_last_completed),
    ("C. stroke the second falls in", "no lag, only after the fact", c_stroke_it_falls_in),
    ("D. time-weighted average", "preserves total work", d_time_weighted),
    ("E. linear interpolation", "between stroke midpoints", e_linear_interpolation),
    ("F. strokes ending in the second", "else repeat previous", f_events_in_second),
]


fig, axes = plt.subplots(3, 2, figsize=(7.5, 7.5))
for ax, (name, note, method) in zip(axes.flat, METHODS):
    for start, end, p in shown:
        ax.bar(start, p, width=end - start, align="edge",
               color=PER_CYCLE_FILL, edgecolor=PER_CYCLE_EDGE, linewidth=0.8, zorder=1)
    values = method()
    ax.bar(seconds, values, width=1, align="edge",
           facecolor="none", edgecolor=PER_SECOND_COLOR, linewidth=1.2, zorder=3)

    ax.set_title(f"{name}\n", loc="left", fontsize=9)
    ax.text(0, 1.02, note, transform=ax.transAxes, fontsize=8, color="#52514e", va="bottom")
    ax.grid(axis="x", color="#999999", linewidth=0.6, linestyle=(0, (4, 3)))
    ax.set_axisbelow(True)
    ax.set_xticks(np.arange(seconds[0], seconds[-1] + 2))
    ax.set_xlim(*window)  # after set_xticks, which would widen it

    # Each panel scales to its own data: the 1 Hz result and the strokes shown.
    # For B to F that means the y-axis doesn't start at 0, so small differences show.
    visible = np.concatenate([values, [p for _, _, p in shown]])
    lo, hi = visible.min(), visible.max()
    pad = max(0.15 * (hi - lo), 1.0)
    ax.set_ylim(max(0.0, lo - pad), hi + pad)

    # Instantaneous power on a right twin axis, as in per_second_vs_per_cycle.py.
    ax_instant = ax.twinx()
    ax_instant.plot(t, power, color=INSTANT_COLOR, linewidth=0.7)
    ax_instant.spines["right"].set_visible(True)
    ax_instant.set_ylim(0, power.max() * 1.05)
    if ax in axes[:, -1]:
        ax_instant.set_ylabel("instantaneous power [W]")

for ax in axes[:, 0]:
    ax.set_ylabel("average power [W]")
for ax in axes[-1, :]:
    ax.set_xlabel("time [s]")

handles = [
    plt.Line2D([], [], color=INSTANT_COLOR, linewidth=0.7),
    plt.Rectangle((0, 0), 1, 1, facecolor=PER_CYCLE_FILL, edgecolor=PER_CYCLE_EDGE, linewidth=0.8),
    plt.Rectangle((0, 0), 1, 1, facecolor="none", edgecolor=PER_SECOND_COLOR, linewidth=1.2),
]
fig.legend(handles, ["instantaneous power", "average per stroke (PM5)", "1 Hz result"],
           loc="upper center", ncols=3, bbox_to_anchor=(0.5, 1.0))

fig.tight_layout(rect=(0, 0, 1, 0.95))
OUTPUT.parent.mkdir(parents=True, exist_ok=True)
fig.savefig(OUTPUT, dpi=250, bbox_inches="tight")
print(f"Wrote {OUTPUT}")
