# /// script
# requires-python = ">=3.11"
# dependencies = [
#   "matplotlib",
#   "numpy",
# ]
# ///
"""
All analyses and result figures for "Resampling discontinuous power to 1 Hz".

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

Reads the CSVs written by extract_sessions.py and prints every number used in
the post. Writes rate_sweep.png and mean_max_error.png.

Datasets
- Rowing, real: 209 strokes from five PM5 recordings (light: ~100-120 W, ~22 spm).
- Rowing, assembled: a 34 min session built from those real strokes: real force
  curve shapes, programmed stroke rate and power (warm-up, 3 x 4 min hard,
  4 x 30 s sprints, easy rowing in between), 2% stroke-to-stroke variation in
  stroke duration and 4% in power. 20 versions with different random strokes and
  a different offset to the 1 s grid. Drive time 0.70 s at 22 spm, 0.004 s
  shorter per extra stroke per minute (an assumption, roughly what the real
  strokes show).
- Cycling, real: a 16 min Wattbike session, 1361 revolutions, 95-1220 W.

Ground truth is per-stroke (per-revolution) power held over the duration of
the stroke, at 100 Hz: what "power" means in rowing, and what a stroke-boundary
file contains. Every 1 Hz value covers one whole second [s, s + 1) and is
rounded to whole watts, as FIT stores it.
"""

import csv
import json
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np

HERE = Path(__file__).resolve().parent
IMAGES = HERE.parent.parent / "images" / "resampling-discontinuous-power"
FS = 100
DURATIONS = [1, 5, 10, 30, 60, 300]
SEEDS = 20
METHODS = ["A", "B", "C", "D", "E", "F"]
METHOD_NAMES = {
    "A": "A. average each second",
    "B": "B. hold last completed",
    "C": "C. stroke the second falls in",
    "D": "D. time-weighted",
    "E": "E. linear interpolation",
    "F": "F. strokes ending in the second",
}

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,
})
# Categorical slots 1-6 of the default palette, in fixed order.
COLORS = dict(zip(METHODS, ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300"]))


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


# --- Strokes and the ground truth ------------------------------------------------


class Strokes:
    """Contiguous-ish strokes: start, end and average power of each."""

    def __init__(self, start, end, power):
        self.start = np.asarray(start, dtype=float)
        self.end = np.asarray(end, dtype=float)
        self.power = np.asarray(power, dtype=float)
        self.duration = self.end - self.start
        self.cumwork = np.concatenate([[0.0], np.cumsum(self.power * self.duration)])

    def __len__(self):
        return len(self.start)

    def work_until(self, t):
        """Work done from the first catch until time t (vectorised)."""
        t = np.asarray(t, dtype=float)
        k = np.searchsorted(self.start, t, side="right") - 1
        kc = np.clip(k, 0, len(self) - 1)
        inside = np.clip(t - self.start[kc], 0, self.duration[kc]) * self.power[kc]
        return np.where(k < 0, 0.0, self.cumwork[kc] + inside)

    def grid(self):
        """Whole seconds after the first stroke has ended, up to the last stroke's end."""
        return np.arange(np.ceil(self.end[0]), np.floor(self.end[-1]))


def true_mean_max(strokes, seconds, duration):
    t = np.arange(seconds[0], seconds[-1] + 1 - duration + 1e-9, 1 / FS)
    return ((strokes.work_until(t + duration) - strokes.work_until(t)) / duration).max()


def true_np(strokes, seconds):
    t = np.arange(seconds[0], seconds[-1] + 1 - 30 + 1e-9, 1 / FS)
    rolling = (strokes.work_until(t + 30) - strokes.work_until(t)) / 30
    return np.mean(rolling**4) ** 0.25


def true_work(strokes, seconds):
    return float(strokes.work_until(seconds[-1] + 1) - strokes.work_until(seconds[0]))


# --- The six methods ---------------------------------------------------------------


def resample(strokes, seconds, a_values):
    s = seconds
    out = {"A": np.asarray(a_values, dtype=float)}

    # B: the last stroke that ended by the end of the second.
    out["B"] = strokes.power[np.searchsorted(strokes.end, s + 1, side="right") - 1]

    # C: the stroke the middle of the second falls in (0 in a gap between strokes).
    k = np.clip(np.searchsorted(strokes.start, s + 0.5, side="right") - 1, 0, len(strokes) - 1)
    out["C"] = np.where(s + 0.5 < strokes.end[k], strokes.power[k], 0.0)

    # D: time-weighted, i.e. the work done in the second.
    out["D"] = strokes.work_until(s + 1) - strokes.work_until(s)

    # E: interpolate between stroke values placed at the middle of each stroke.
    out["E"] = np.interp(s + 0.5, (strokes.start + strokes.end) / 2, strokes.power)

    # F: average of the strokes that ended within the second, else repeat the previous value.
    first = np.searchsorted(strokes.end, s, side="left")
    last = np.searchsorted(strokes.end, s + 1, side="left")
    f, previous = [], out["B"][0]
    for i, j in zip(first, last):
        previous = strokes.power[i:j].mean() if j > i else previous
        f.append(previous)
    out["F"] = np.array(f)

    return {m: np.round(v) for m, v in out.items()}  # FIT stores whole watts


def mean_max(x, duration):
    c = np.concatenate([[0.0], np.cumsum(x)])
    return ((c[duration:] - c[:-duration]) / duration).max()


def normalised_power(x):
    c = np.concatenate([[0.0], np.cumsum(x)])
    rolling = (c[30:] - c[:-30]) / 30
    return np.mean(rolling**4) ** 0.25


def errors(strokes, seconds, series):
    """Relative error (%) of each method vs the ground truth, per measure."""
    truth = {f"mm{d}": true_mean_max(strokes, seconds, d) for d in DURATIONS}
    truth["np"] = true_np(strokes, seconds)
    truth["work"] = true_work(strokes, seconds)
    result = {}
    for m, x in series.items():
        got = {f"mm{d}": mean_max(x, d) for d in DURATIONS}
        got["np"] = normalised_power(x)
        got["work"] = x.sum()
        result[m] = {k: 100 * (got[k] - truth[k]) / truth[k] for k in truth}
    return result


# --- Instantaneous power (for method A) -------------------------------------------


def per_second_instantaneous(strokes, drive_times, shapes, seconds):
    """Per-second mean of derived instantaneous power: each stroke's force shape over
    its drive, zero in the recovery, scaled to the stroke's work."""
    t = np.arange(seconds[0], seconds[-1] + 1, 1 / FS)
    p = np.zeros_like(t)
    for start, dur, power, drive, shape in zip(strokes.start, strokes.duration, strokes.power, drive_times, shapes):
        i0, i1 = np.searchsorted(t, [start, start + drive])
        if i1 <= i0:
            continue
        values = np.interp((t[i0:i1] - start) / drive, np.linspace(0, 1, len(shape)), shape)
        p[i0:i1] = values * (power * dur) / (values.sum() / FS)
    return p.reshape(len(seconds), FS).mean(axis=1)


# --- Data -------------------------------------------------------------------------


def load_rowing():
    strokes = read_csv("rowing_strokes_all.csv")
    shapes = {(r["trace"], r["interval"], r["stroke"]): np.array([float(r[f"p{i}"]) for i in range(50)])
              for r in read_csv("rowing_shapes.csv")}
    intervals = {}
    for r in strokes:
        key = (r["trace"], r["interval"])
        intervals.setdefault(key, []).append({
            "start": float(r["start_s"]), "end": float(r["end_s"]), "power": float(r["power_w"]),
            "drive": float(r["drive_time_s"]), "shape": shapes[(r["trace"], r["interval"], r["stroke"])],
        })
    # Keep runs of contiguous strokes (a dropped stroke splits an interval).
    runs = []
    for rows in intervals.values():
        run = [rows[0]]
        for prev, row in zip(rows, rows[1:]):
            if abs(row["start"] - prev["end"]) < 1e-6:
                run.append(row)
            else:
                runs.append(run)
                run = [row]
        runs.append(run)
    return [r for r in runs if len(r) >= 8], [s["shape"] for rows in intervals.values() for s in rows]


SESSION = (  # (duration s, stroke rate spm, power W)
    [(300, 20, 120)]
    + [(240, 28, 230), (120, 18, 90)] * 3
    + [(30, 34, 380), (90, 18, 90)] * 4
    + [(180, 18, 90)]
)


def assembled_rowing_session(shapes, rng):
    start = rng.uniform(0, 1)
    rows, t, seg_end = [], start, start
    for duration, spm, watts in SESSION:
        seg_end += duration
        while t < seg_end:
            rate = spm * (1 + rng.normal(0, 0.02))
            period = 60 / rate
            rows.append({
                "start": t, "end": t + period, "power": watts * (1 + rng.normal(0, 0.04)),
                "drive": 0.70 - 0.004 * (rate - 22), "shape": shapes[rng.integers(len(shapes))],
            })
            t += period
    return rows


def to_strokes(rows):
    return Strokes([r["start"] for r in rows], [r["end"] for r in rows], [r["power"] for r in rows])


def rowing_series(rows):
    strokes = to_strokes(rows)
    seconds = strokes.grid()
    a = per_second_instantaneous(strokes, [r["drive"] for r in rows], [r["shape"] for r in rows], seconds)
    return strokes, seconds, resample(strokes, seconds, a)


# --- Stroke-level measures ----------------------------------------------------------


def stroke_recovery(strokes, seconds, series):
    """Recover each stroke's power from the 1 Hz series with its natural inverse.

    total_cycles = strokes completed by the end of the second (FIT's cumulative count).
    B: seconds where total_cycles = k + 1 hold stroke k.
    F: seconds where exactly one stroke ended hold that stroke.
    C: label each second with the stroke in progress at its middle.
    D: seconds without a stroke boundary inside hold that stroke exactly.
    A, E: no exact inverse; average the seconds whose middle falls in the stroke.
    Only strokes fully inside the grid count. Exact = within 0.5 W (whole watts).
    """
    s = seconds
    count = np.searchsorted(strokes.end, s + 1, side="right")
    previous = np.searchsorted(strokes.end, s, side="right")
    mid = np.searchsorted(strokes.start, s + 0.5, side="right") - 1
    pure = np.searchsorted(strokes.start, s, side="right") - 1
    pure = np.where((pure >= 0) & (strokes.end[np.clip(pure, 0, None)] >= s + 1), pure, -1)
    inside = [k for k in range(len(strokes)) if strokes.start[k] >= s[0] and strokes.end[k] <= s[-1] + 1]

    labels = {
        "B": np.where(count >= 1, count - 1, -1),
        "F": np.where(count - previous == 1, count - 1, -1),
        "C": mid, "D": pure, "A": mid, "E": mid,
    }
    result = {}
    for m, x in series.items():
        recovered = {}
        for k in inside:
            values = x[labels[m] == k]
            if len(values):
                recovered[k] = values[0] if m in "BCDF" else values.mean()
        err = np.array([abs(recovered[k] - strokes.power[k]) for k in recovered])
        result[m] = {
            "strokes": len(inside),
            "recovered": len(recovered),
            "exact": int((err <= 0.5 + 1e-9).sum()),
            "mae": float(err.mean()) if len(err) else float("nan"),
        }
    # Without total_cycles: a stroke is only visible where the value changes.
    for m in "BC":
        x = series[m]
        result[m]["runs"] = int(1 + (np.diff(x) != 0).sum())
        result[m]["strokes_in_series"] = int(len(set(labels[m][labels[m] >= 0])))
    return result


def variation(strokes, seconds, series):
    """CV of each 1 Hz series relative to the CV of the strokes it was made from."""
    cv_strokes = strokes.power.std() / strokes.power.mean()
    return {m: (x.std() / x.mean()) / cv_strokes for m, x in series.items()}


def write_delay(strokes, seconds):
    """How long after the end of each second (s) its 1 Hz value can be written.

    A stroke's power is known once the stroke is over (at the next catch).
    A, B, F only use strokes that are already over: no delay.
    C needs the stroke in progress at the middle of the second.
    D needs every stroke that overlaps the second.
    E needs the stroke after the one whose middle precedes the middle of the second.
    """
    s = seconds
    n = len(strokes) - 1
    mid_k = np.clip(np.searchsorted(strokes.start, s + 0.5, side="right") - 1, 0, n)
    last_k = np.clip(np.searchsorted(strokes.start, s + 1, side="left") - 1, 0, n)
    mids = (strokes.start + strokes.end) / 2
    next_k = np.clip(np.searchsorted(mids, s + 0.5, side="right"), 0, n)
    zero = np.zeros(len(s))
    delays = {
        "A": zero, "B": zero, "F": zero,
        "C": np.maximum(0, strokes.end[mid_k] - (s + 1)),
        "D": np.maximum(0, strokes.end[last_k] - (s + 1)),
        "E": np.maximum(0, strokes.end[next_k] - (s + 1)),
    }
    return {m: (float(d.mean()), float(d.max())) for m, d in delays.items()}


def lag(strokes, seconds, series, max_lag=6.0, step=0.05):
    """Time shift (s) that best aligns each 1 Hz series with the ground truth.
    Positive = the series is late."""
    t = np.arange(seconds[0], seconds[-1] + 1, step)
    truth = (strokes.work_until(t + step) - strokes.work_until(t)) / step
    truth -= truth.mean()
    shifts = np.arange(-max_lag, max_lag + step / 2, step)
    result = {}
    for m, x in series.items():
        y = np.repeat(x, int(round(1 / step)))[: len(t)] - x.mean()
        n = int(round(max_lag / step))
        scores = [np.dot(y[n + i: len(y) - n + i], truth[n: len(t) - n]) for i in range(-n, n + 1)]
        result[m] = float(shifts[int(np.argmax(scores))])
    return result


# --- Rate sweep (synthetic, constant power) -------------------------------------------


def sweep(shape_pick, period_of, drive_of, rates, rng, minutes=5, phases=10):
    """Relative RMS error (%) of A (average each second) vs D, at constant power."""
    out = []
    for rate in rates:
        errs = []
        for _ in range(phases):
            t, rows = rng.uniform(0, 1), []
            while t < 60 * minutes:
                period = period_of(rate) * (1 + rng.normal(0, 0.02))
                rows.append({"start": t, "end": t + period, "power": 200.0,
                             "drive": drive_of(rate, period), "shape": shape_pick()})
                t += period
            strokes, seconds, series = rowing_series(rows)
            errs.append(np.sqrt(np.mean((series["A"] - series["D"]) ** 2)) / series["D"].mean())
        out.append(100 * np.mean(errs))
    return np.array(out)


# --- Main ---------------------------------------------------------------------------


def fmt(x, digits=1):
    return f"{x:+.{digits}f}"


def main():
    rng = np.random.default_rng(1)
    runs, shapes = load_rowing()
    results = {}

    # 1. Rate sweep: why averaging each second is chaos for rowing and fine for cycling.
    cycling_shape = np.array([float(r["power"]) for r in read_csv("cycling_shape.csv")])
    spm = np.arange(16, 46, 1.0)
    rpm = np.arange(50, 131, 2.0)
    row_err = sweep(lambda: shapes[rng.integers(len(shapes))], lambda r: 60 / r,
                    lambda r, p: 0.70 - 0.004 * (r - 22), spm, rng)
    # A cycling revolution is one "stroke" whose force shape covers the whole revolution.
    cyc_err = sweep(lambda: cycling_shape, lambda r: 60 / r, lambda r, p: p, rpm, rng)
    results["sweep"] = {"spm": spm.tolist(), "rowing": row_err.tolist(),
                        "rpm": rpm.tolist(), "cycling": cyc_err.tolist()}
    print("Sweep, A vs D, relative RMS error per second:")
    for r in (18, 22, 26, 30, 36, 44):
        print(f"  rowing {r} spm: {row_err[spm == r][0]:5.1f}%")
    for r in (60, 70, 80, 90, 100, 110, 120):
        print(f"  cycling {r} rpm: {cyc_err[rpm == r][0]:5.1f}%")

    fig, ax = plt.subplots(figsize=(7, 3.4))
    ax.plot(spm, row_err, color=COLORS["A"], linewidth=1.5, marker="o", markersize=3)
    ax.plot(rpm, cyc_err, color=COLORS["C"], linewidth=1.5, marker="o", markersize=3)
    ax.text(spm[-1] + 2, row_err[-1], "rowing [spm]", va="center", fontsize=9)
    ax.text(rpm[-1] + 2, cyc_err[-1], "cycling [rpm]", va="center", fontsize=9)
    ax.set_xlabel("stroke rate [spm] / cadence [rpm]")
    ax.set_ylabel("error per second [%]")
    ax.set_xlim(10, 160)
    ax.set_ylim(0, None)
    ax.grid(axis="y", color="#e4e3df", linewidth=0.6)
    fig.tight_layout()
    IMAGES.mkdir(parents=True, exist_ok=True)
    fig.savefig(IMAGES / "rate_sweep.png", dpi=250, bbox_inches="tight")
    plt.close(fig)

    # 2. Work, mean-max and normalised power.
    session_errors = []
    for seed in range(SEEDS):
        rows = assembled_rowing_session(shapes, np.random.default_rng(100 + seed))
        strokes, seconds, series = rowing_series(rows)
        session_errors.append(errors(strokes, seconds, series))
        if seed == 0:
            first_session = (strokes, seconds, series)
    keys = list(session_errors[0]["A"].keys())
    rowing_err = {m: {k: float(np.mean([e[m][k] for e in session_errors])) for k in keys} for m in METHODS}
    rowing_err_max = {m: {k: float(np.max(np.abs([e[m][k] for e in session_errors]))) for k in keys} for m in METHODS}

    revs = read_csv("cycling_revolutions.csv")
    cyc = Strokes([float(r["start_s"]) for r in revs], [float(r["end_s"]) for r in revs],
                  [float(r["power_w"]) for r in revs])
    cyc_seconds = cyc.grid()
    a = np.array([float(r["power_w"]) for r in read_csv("cycling_per_second.csv")])
    cyc_series = resample(cyc, cyc_seconds, a[cyc_seconds.astype(int)])
    cycling_err = errors(cyc, cyc_seconds, cyc_series)
    results["rowing_session"] = {"mean": rowing_err, "max_abs": rowing_err_max}
    results["cycling_session"] = cycling_err

    for label, err in (("Rowing, assembled session (mean of 20)", rowing_err), ("Cycling, Wattbike", cycling_err)):
        print(f"\n{label}: error vs ground truth [%]")
        print("  method " + " ".join(f"{k:>7}" for k in keys))
        for m in METHODS:
            print(f"  {m:6} " + " ".join(f"{fmt(err[m][k], 2):>7}" for k in keys))
    print("\nRowing, worst case over 20 sessions [|%|]")
    for m in METHODS:
        print(f"  {m:6} " + " ".join(f"{rowing_err_max[m][k]:7.2f}" for k in keys))

    fig, axes = plt.subplots(1, 2, figsize=(7.5, 3.4), sharey=False)
    for ax, (title, err) in zip(axes, (("(a) Rowing, assembled session", rowing_err),
                                       ("(b) Cycling, Wattbike session", cycling_err))):
        for m in METHODS:
            # F equals B whenever at most one stroke ends per second: dash it so B shows through.
            ax.plot(DURATIONS, [err[m][f"mm{d}"] for d in DURATIONS], color=COLORS[m],
                    linewidth=1.4, marker="o", markersize=3, label=METHOD_NAMES[m],
                    linestyle="--" if m == "F" else "-", clip_on=True)
        ax.axhline(0, color="#222222", linewidth=0.6)
        ax.set_xscale("log")
        ax.set_xticks(DURATIONS, ["1 s", "5 s", "10 s", "30 s", "1 min", "5 min"])
        ax.minorticks_off()
        ax.set_title(title, loc="left", fontsize=10)
        ax.set_xlabel("mean-max duration")
        ax.grid(axis="y", color="#e4e3df", linewidth=0.6)
    axes[0].set_ylabel("mean-max error [%]")
    # A's 1 s error is far off this scale; clip it and say so.
    axes[0].set_ylim(-2.5, 8)
    axes[0].text(5.6, 7.3, f"A: {rowing_err['A']['mm1']:+.0f}% at 1 s (off scale)", fontsize=9, color="#222222")
    handles, labels = axes[0].get_legend_handles_labels()
    fig.legend(handles, labels, loc="upper center", ncols=3, bbox_to_anchor=(0.5, 1.0), fontsize=9)
    fig.tight_layout(rect=(0, 0, 1, 0.84))
    fig.savefig(IMAGES / "mean_max_error.png", dpi=250, bbox_inches="tight")
    plt.close(fig)

    # 3. Stroke-level measures on the real rowing strokes.
    rec_total = {m: {"strokes": 0, "recovered": 0, "exact": 0, "abs_err": 0.0} for m in METHODS}
    runs_total = {m: {"runs": 0, "strokes": 0} for m in "BC"}
    var, lags = {m: [] for m in METHODS}, {m: [] for m in METHODS}
    for rows in runs:
        strokes, seconds, series = rowing_series(rows)
        rec = stroke_recovery(strokes, seconds, series)
        for m in METHODS:
            r = rec[m]
            rec_total[m]["strokes"] += r["strokes"]
            rec_total[m]["recovered"] += r["recovered"]
            rec_total[m]["exact"] += r["exact"]
            rec_total[m]["abs_err"] += r["mae"] * r["recovered"] if r["recovered"] else 0
        for m in "BC":
            runs_total[m]["runs"] += rec[m]["runs"]
            runs_total[m]["strokes"] += rec[m]["strokes_in_series"]
        steady = to_strokes(rows[4:])  # skip the start of each piece
        s2 = steady.grid()
        if len(s2) >= 10:
            idx = np.isin(seconds, s2)
            for m, v in variation(steady, s2, {k: x[idx] for k, x in series.items()}).items():
                var[m].append(v)
    for m, (strokes, seconds, series) in [(None, first_session)]:
        lags = lag(strokes, seconds, series)

    print(f"\nReal rowing: {len(runs)} pieces, {sum(len(r) for r in runs)} strokes")
    print("Stroke recovery (with total_cycles):")
    for m in METHODS:
        r = rec_total[m]
        print(f"  {m}: {r['recovered']}/{r['strokes']} recovered, {r['exact']} exact, "
              f"mean abs error {r['abs_err'] / max(r['recovered'], 1):.2f} W")
    print("Without total_cycles, strokes visible as a change in value:")
    for m in "BC":
        print(f"  {m}: {runs_total[m]['runs']} runs for {runs_total[m]['strokes']} strokes")

    # The same on the assembled sessions, which include 34 spm sprints.
    session_rec = {m: {"strokes": 0, "recovered": 0, "exact": 0} for m in METHODS}
    for seed in range(SEEDS):
        rows = assembled_rowing_session(shapes, np.random.default_rng(100 + seed))
        strokes, seconds, series = rowing_series(rows)
        for m, r in stroke_recovery(strokes, seconds, series).items():
            for k in session_rec[m]:
                session_rec[m][k] += r[k]
    print("Stroke recovery, assembled sessions (with total_cycles):")
    for m in METHODS:
        r = session_rec[m]
        print(f"  {m}: {100 * r['recovered'] / r['strokes']:.1f}% recovered, "
              f"{100 * r['exact'] / r['strokes']:.1f}% exact")
    results["recovery_session"] = session_rec
    print("Stroke-to-stroke variation, CV of 1 Hz series / CV of strokes (mean over pieces):")
    for m in METHODS:
        print(f"  {m}: {np.mean(var[m]):.2f}")
    print("Lag vs ground truth, assembled session [s]:")
    for m in METHODS:
        print(f"  {m}: {lags[m]:+.2f}")
    print(f"  (mean stroke duration there: {np.mean(first_session[0].duration):.2f} s)")

    # How long each method has to wait before it can write a second.
    delays = {}
    for label, rows_list in (("real strokes, ~22 spm", runs),
                             ("sprints in the assembled session, ~34 spm", None)):
        if rows_list is None:
            # Each sprint as its own run of contiguous strokes, over all 20 sessions.
            rows_list = []
            for seed in range(SEEDS):
                run = []
                for r in assembled_rowing_session(shapes, np.random.default_rng(100 + seed)):
                    if 60 / (r["end"] - r["start"]) > 30:
                        run.append(r)
                    elif run:
                        rows_list.append(run)
                        run = []
        all_d = {m: [] for m in METHODS}
        for rows in rows_list:
            st = to_strokes(rows)
            sec = st.grid()
            if len(sec) == 0:
                continue
            for m, (mean_d, max_d) in write_delay(st, sec).items():
                all_d[m].append((mean_d, max_d, len(sec)))
        delays[label] = {m: (sum(a * n for a, _, n in v) / sum(n for *_, n in v), max(b for _, b, _ in v))
                         for m, v in all_d.items()}
        print(f"Write delay after the end of the second, {label} [mean / max s]:")
        for m in METHODS:
            print(f"  {m}: {delays[label][m][0]:.1f} / {delays[label][m][1]:.1f}")
    results["write_delay"] = delays

    results["recovery"] = rec_total
    results["runs"] = runs_total
    results["variation"] = {m: float(np.mean(v)) for m, v in var.items()}
    results["lag"] = lags
    (HERE / "results.json").write_text(json.dumps(results, indent=1))
    print(f"\nWrote {HERE / 'results.json'}, rate_sweep.png and mean_max_error.png")


if __name__ == "__main__":
    main()
