# /// script
# requires-python = ">=3.11"
# dependencies = [
#   "matplotlib",
#   "numpy",
# ]
# ///
"""
Figure for "Why cycling gets away with it" in "Resampling discontinuous power to 1 Hz".

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

Three revolutions on a Wattbike and three strokes on a Concept2 rowing machine, from
cycling_crop.csv and rowing_crop.csv (made by extract_crops.py, which also
explains how instantaneous power is derived). On top of the instantaneous
power: the average per revolution/stroke and the average per second.
"""

import csv
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np

HERE = Path(__file__).resolve().parent
FS = 100  # Hz, sample rate of the crops

OUTPUT = HERE.parent.parent / "images" / "resampling-discontinuous-power" / "per_second_vs_per_cycle.png"

# Minimal, paper-like styling.
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": 10,
    "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 load(name):
    with (HERE / name).open() as f:
        rows = list(csv.DictReader(f))
    t = np.array([float(r["time_s"]) for r in rows])
    power = np.array([float(r["power_w"]) for r in rows])
    cycle = np.array([int(r["cycle"]) if r["cycle"] else -1 for r in rows])
    return t, power, cycle


def per_cycle_average(t, power, cycle):
    """(start, end, mean power) per revolution/stroke."""
    segments = []
    for k in sorted(set(cycle) - {-1}):
        mask = cycle == k
        segments.append((t[mask][0], t[mask][-1] + 1 / FS, power[mask].mean()))
    return segments


def per_second_average(t, power):
    """Mean power per whole second. The crops start and end on whole seconds."""
    seconds = np.arange(np.floor(t[0]), np.ceil(t[-1]))
    means = np.array([power[(t >= s) & (t < s + 1)].mean() for s in seconds])
    return seconds, means


def plot(ax, title, unit, t, power, cycle):
    """Averages on the left axis, instantaneous power on a right twin axis."""
    cycles = per_cycle_average(t, power, cycle)
    window = (cycles[0][0], cycles[-1][1])
    rate = 60 * len(cycles) / (window[1] - window[0])

    # Average per revolution/stroke as bars spanning each cycle.
    for start, end, avg in cycles:
        ax.bar(start, avg, width=end - start, align="edge",
               color=PER_CYCLE_FILL, edgecolor=PER_CYCLE_EDGE, linewidth=0.8, zorder=1)

    # Average per second as outlined bars, so second boundaries are visible.
    # The bars at the edges are clipped by the window but average a full second.
    seconds, sec = per_second_average(t, power)
    ax.bar(seconds, sec, width=1, align="edge",
           facecolor="none", edgecolor=PER_SECOND_COLOR, linewidth=1.2, zorder=3)

    ax_instant = ax.twinx()
    ax_instant.plot(t, power, color=INSTANT_COLOR, linewidth=0.7)
    ax_instant.spines["right"].set_visible(True)

    ax.set_title(f"{title}, {rate:.0f} {unit}", loc="left", fontsize=10)
    ax.set_ylabel("average power [W]")
    ax_instant.set_ylabel("instantaneous power [W]")
    ax.set_xlabel("time [s]")
    ax.set_xticks(np.arange(np.floor(window[0]), np.ceil(window[1]) + 1))
    ax.set_xlim(*window)  # after set_xticks, which would widen it
    ax.grid(axis="x", color="#999999", linewidth=0.6, linestyle=(0, (4, 3)))  # second boundaries
    ax.set_axisbelow(True)

    # Each panel scales to its own data.
    ax.set_ylim(0, max(sec.max(), max(c[2] for c in cycles)) * 1.1)
    ax_instant.set_ylim(0, power.max() * 1.05)


fig, (ax_cycling, ax_rowing) = plt.subplots(2, 1, figsize=(7, 5.5))
plot(ax_cycling, "(a) Cycling, Wattbike", "rpm", *load("cycling_crop.csv"))
plot(ax_rowing, "(b) Rowing, Concept2", "spm", *load("rowing_crop.csv"))

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),
]
labels = ["instantaneous power", "average per revolution / stroke", "average per second"]
fig.legend(handles, labels, loc="upper center", ncols=3, bbox_to_anchor=(0.5, 1.0))

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