#!/usr/bin/env python3
"""Generate 1600x900 explanatory figures and verified manifest for MIT 6.874 Lecture 24 (v1 r2)."""

from __future__ import annotations

import json
import subprocess
import tempfile
import xml.etree.ElementTree as ET
from pathlib import Path

import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import root

OUT_DIR = Path(__file__).resolve().parent
CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
FONT = "Helvetica Neue, Helvetica, Arial, sans-serif"

PALETTE = {
    "background": "#FAF6EE",
    "surface": "#F3EEE3",
    "ink": "#1F2A2E",
    "muted": "#4F4A44",
    "grid": "#DCD4C6",
    "blue": "#356482",
    "terracotta": "#B5493A",
    "sage": "#4B6B46",
    "ochre": "#A87919",
    "ochre_text": "#7A560E",
}

# Single source of truth: L24a Slide 38 embedded layers (Yamins et al., PNAS 2014)
SLIDE38_EXPLAINED_VARIANCE = [
    ("Category Ideal", 0.08, 0.15),
    ("V1-Like", 0.11, 0.16),
    ("HMAX", 0.24, 0.25),
    ("V2-Like", 0.34, 0.26),
    ("HMO Layer 1", 0.08, 0.04),
    ("HMO Layer 2", 0.48, 0.21),
    ("HMO Layer 3", 0.52, 0.36),
    ("HMO Top Layer", 0.33, 0.48),
]

# Single source of truth: L24a Slide 54 embedded summary (Bashivan, Kar & DiCarlo, Science 2019)
SLIDE54_CONTROL_BENCHMARKS = [
    ("Super-activate\n(> natural max)", 68.0, 1.0),
    ("One-hot V4\nsubpopulation", 76.0, 1.0),
    ("Novel synthetic\nprediction", 54.0, 0.0),
]


def arrow_polygon(
    tip_x: float,
    tip_y: float,
    dx: float,
    dy: float,
    length: float = 18.0,
    half_w: float = 8.0,
) -> str:
    """Return explicit SVG <polygon> points for an arrowhead at (tip_x, tip_y)."""
    norm = float(np.hypot(dx, dy))
    ux, uy = dx / norm, dy / norm
    px, py = -uy, ux
    bx, by = tip_x - length * ux, tip_y - length * uy
    p1 = (bx + half_w * px, by + half_w * py)
    p2 = (bx - half_w * px, by - half_w * py)
    return f"{tip_x:.1f},{tip_y:.1f} {p1[0]:.1f},{p1[1]:.1f} {p2[0]:.1f},{p2[1]:.1f}"


def draw_arrow(
    x1: float,
    y1: float,
    x2: float,
    y2: float,
    color: str = "#4F4A44",
    width: float = 4.2,
    dashed: bool = False,
) -> str:
    """Draw a straight line terminating with an explicit <polygon> arrowhead."""
    dx, dy = x2 - x1, y2 - y1
    norm = float(np.hypot(dx, dy))
    ux, uy = dx / norm, dy / norm
    lx2, ly2 = x2 - 14.0 * ux, y2 - 14.0 * uy
    dash_attr = ' stroke-dasharray="12,8"' if dashed else ""
    return (
        f'<line x1="{x1:.1f}" y1="{y1:.1f}" x2="{lx2:.1f}" y2="{ly2:.1f}" '
        f'stroke="{color}" stroke-width="{width:.1f}" stroke-linecap="round"{dash_attr} />'
        f'<polygon points="{arrow_polygon(x2, y2, dx, dy)}" fill="{color}" />'
    )


def render_svg_to_png(svg_path: Path, png_path: Path, width: int = 1600, height: int = 900) -> None:
    """Validate XML and rasterize SVG to a 1600x900 PNG using headless Chrome."""
    ET.parse(svg_path)
    html_content = (
        "<!DOCTYPE html><html><body style='margin:0;padding:0;background:#FAF6EE;overflow:hidden;'>"
        f"<img src='{svg_path.as_uri()}' width='{width}' height='{height}' style='display:block;'/>"
        "</body></html>"
    )
    with tempfile.NamedTemporaryFile("w", suffix=".html", delete=False) as tf:
        tf.write(html_content)
        tmp_html = Path(tf.name)
    try:
        subprocess.run(
            [
                CHROME,
                "--headless",
                "--disable-gpu",
                f"--window-size={width},{height}",
                f"--screenshot={png_path}",
                tmp_html.as_uri(),
            ],
            check=True,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        )
    finally:
        tmp_html.unlink(missing_ok=True)


def build_figure1_architecture() -> int:
    """Build Figure 1: Feed-legible (<=90 words, large type) ventral stream reverse-engineering loop."""
    svg_path = OUT_DIR / "ventral-stream-reverse-engineering-loop.svg"
    png_path = OUT_DIR / "ventral-stream-reverse-engineering-loop.png"

    els: list[str] = [
        f'<rect width="1600" height="900" fill="{PALETTE["background"]}" />',
        f'<text x="56" y="70" font-family="{FONT}" font-size="40" font-weight="700" fill="{PALETTE["ink"]}">'
        'Task Optimization Links Visual Cortex to Neural Control</text>',
        f'<text x="56" y="114" font-family="{FONT}" font-size="25" font-weight="500" fill="{PALETTE["muted"]}">'
        'MIT 6.874 Lecture 24 (DiCarlo): ventral hierarchy, held-out V4/IT prediction, and closed-loop synthesis</text>',
    ]

    # Three large feed-legible stage cards across the center
    cards = [
        {
            "x": 56, "y": 162, "w": 440, "h": 430, "stroke": PALETTE["blue"],
            "tag": "1. TRAIN CNN ON VISION",
            "title": "Task-Optimized Model",
            "lines": [
                ("V1 → V2 → V4 → IT hierarchy", PALETTE["ink"], 24),
                ("Optimize core object loss", PALETTE["ink"], 24),
                ("No neural data during training", PALETTE["muted"], 22),
            ],
        },
        {
            "x": 580, "y": 162, "w": 440, "h": 430, "stroke": PALETTE["sage"],
            "tag": "2. MATCH &amp; PREDICT",
            "title": "Held-Out Brain Alignment",
            "lines": [
                ("Match model units to V4/IT sites", PALETTE["ink"], 24),
                ("HMO L3 → V4: 0.52 variance", PALETTE["blue"], 25),
                ("HMO Top → IT: 0.48 variance", PALETTE["terracotta"], 25),
            ],
        },
        {
            "x": 1104, "y": 162, "w": 440, "h": 430, "stroke": PALETTE["terracotta"],
            "tag": "3. SYNTHESIZE &amp; TEST",
            "title": "Closed-Loop V4 Control",
            "lines": [
                ("68% super-activate (1% chance)", PALETTE["sage"], 25),
                ("76% one-hot control (1% chance)", PALETTE["sage"], 25),
                ("54% novel prediction (0% chance)", PALETTE["ochre_text"], 24),
            ],
        },
    ]

    for c in cards:
        x, y, w, h = c["x"], c["y"], c["w"], c["h"]
        cx = x + w / 2.0
        els.append(
            f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="18" '
            f'fill="{PALETTE["surface"]}" stroke="{c["stroke"]}" stroke-width="3.2" />'
        )
        els.append(
            f'<text x="{cx:.1f}" y="{y + 52}" text-anchor="middle" font-family="{FONT}" '
            f'font-size="22" font-weight="700" fill="{c["stroke"]}">{c["tag"]}</text>'
        )
        els.append(
            f'<text x="{cx:.1f}" y="{y + 106}" text-anchor="middle" font-family="{FONT}" '
            f'font-size="31" font-weight="700" fill="{PALETTE["ink"]}">{c["title"]}</text>'
        )
        els.append(
            f'<line x1="{x + 32}" y1="{y + 132}" x2="{x + w - 32}" y2="{y + 132}" '
            f'stroke="{PALETTE["grid"]}" stroke-width="2.2" />'
        )
        for idx, (txt, col, fsz) in enumerate(c["lines"]):
            ly = y + 204 + idx * 82
            els.append(
                f'<text x="{cx:.1f}" y="{ly}" text-anchor="middle" font-family="{FONT}" '
                f'font-size="{fsz}" font-weight="700" fill="{col}">{txt}</text>'
            )

    # Arrows between cards
    els.append(draw_arrow(496, 377, 580, 377, PALETTE["blue"], width=4.6))
    els.append(draw_arrow(1020, 377, 1104, 377, PALETTE["sage"], width=4.6))

    # Bottom Measure-Break-Build Loop Card
    els.append(
        f'<rect x="56" y="656" width="1488" height="172" rx="18" '
        f'fill="#FAF6EE" stroke="{PALETTE["ochre"]}" stroke-width="3.2" />'
    )
    els.append(
        f'<text x="88" y="718" font-family="{FONT}" font-size="30" font-weight="700" fill="{PALETTE["ochre_text"]}">'
        '4. Measure–Break–Build Cycle (Brain-Score)</text>'
    )
    els.append(
        f'<text x="88" y="778" font-family="{FONT}" font-size="26" font-weight="600" fill="{PALETTE["ink"]}">'
        'Remaining gaps: fast recurrence (Kar et al. 2019) &amp; V1 robustness (Dapello et al. 2020) → refine model</text>'
    )

    # Feedback loop arrows connecting Stage 3 -> Stage 4 -> Stage 1
    els.append(draw_arrow(1324, 592, 1324, 656, PALETTE["ochre"], width=4.2, dashed=True))
    els.append(draw_arrow(276, 656, 276, 592, PALETTE["ochre"], width=4.2, dashed=True))

    els.append(
        f'<text x="56" y="874" font-family="{FONT}" font-size="18" font-weight="500" fill="{PALETTE["muted"]}">'
        'Sources: MIT 6.874 L24a Slides 38, 40–46, 54, 61–63 (Yamins et al. 2014; Bashivan et al. Science 2019; Kar et al. 2019; Dapello et al. 2020).</text>'
    )

    svg_text = (
        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 900" width="1600" height="900">\n'
        + "\n".join(els)
        + "\n</svg>\n"
    )
    svg_path.write_text(svg_text, encoding="utf-8")
    render_svg_to_png(svg_path, png_path, 1600, 900)

    root_xml = ET.fromstring(svg_text)
    words = sum(len((el.text or "").split()) for el in root_xml.iter() if el.tag.endswith("text"))
    return words


def build_figure2_benchmarks() -> None:
    """Build Figure 2: Measured lecture benchmarks (Slide 38 V4/IT explained variance & Slide 54 V4 control)."""
    svg_path = OUT_DIR / "ventral-hierarchy-variance-and-control.svg"
    png_path = OUT_DIR / "ventral-hierarchy-variance-and-control.png"

    plt.rcParams.update({
        "font.family": "sans-serif",
        "font.sans-serif": ["Helvetica Neue", "Helvetica", "Arial"],
        "svg.fonttype": "none",
        "axes.edgecolor": PALETTE["ink"],
        "axes.linewidth": 1.3,
        "text.color": PALETTE["ink"],
        "axes.labelcolor": PALETTE["ink"],
        "xtick.color": PALETTE["ink"],
        "ytick.color": PALETTE["ink"],
    })

    fig, (ax1, ax2) = plt.subplots(
        1, 2, figsize=(16, 9), dpi=100,
        gridspec_kw={"width_ratios": [1.35, 1.0], "wspace": 0.24},
    )
    fig.patch.set_facecolor(PALETTE["background"])

    fig.text(
        0.045, 0.942,
        "Task-Optimized Layers Align with Cortical Depth and Drive V4 Control",
        fontsize=24, fontweight="bold", color=PALETTE["ink"],
    )
    fig.text(
        0.045, 0.892,
        "MIT 6.874 Lecture 24 (DiCarlo): held-out neural variance explained (Slide 38) and closed-loop V4 synthesis (Slide 54)",
        fontsize=15, color=PALETTE["muted"],
    )

    # Panel A: Horizontal grouped bar chart (zero baseline) for V4 vs IT
    ax1.set_facecolor(PALETTE["background"])
    labels = [row[0] for row in SLIDE38_EXPLAINED_VARIANCE]
    v4_vals = [row[1] for row in SLIDE38_EXPLAINED_VARIANCE]
    it_vals = [row[2] for row in SLIDE38_EXPLAINED_VARIANCE]

    y = np.arange(len(labels))
    h = 0.36
    bars_v4 = ax1.barh(
        y + h / 2, v4_vals, height=h, color=PALETTE["blue"], edgecolor=PALETTE["ink"],
        linewidth=1.0, label="Cortical Area V4 (mid-level)",
    )
    bars_it = ax1.barh(
        y - h / 2, it_vals, height=h, color=PALETTE["terracotta"], edgecolor=PALETTE["ink"],
        linewidth=1.0, hatch="//", label="Cortical Area IT (high-level)",
    )

    ax1.set_yticks(y)
    ax1.set_yticklabels(labels, fontsize=13.5, fontweight="bold")
    ax1.invert_yaxis()
    ax1.set_xlim(0.0, 0.66)
    ax1.set_xlabel("Median Single-Site Explained Variance (new images)", fontsize=14, fontweight="bold", labelpad=8)
    ax1.set_title("A. Hierarchical Alignment (Yamins et al., PNAS 2014)", loc="left", fontsize=15, fontweight="bold", pad=12)
    ax1.grid(axis="x", color=PALETTE["grid"], linestyle="-", linewidth=1.0, zorder=0)
    ax1.set_axisbelow(True)
    ax1.spines["top"].set_visible(False)
    ax1.spines["right"].set_visible(False)

    for bar, val in zip(bars_v4, v4_vals):
        fw = "bold" if val == max(v4_vals) else "normal"
        ax1.text(val + 0.012, bar.get_y() + bar.get_height() / 2, f"{val:.2f}", va="center", fontsize=12.5, fontweight=fw, color=PALETTE["blue"])
    for bar, val in zip(bars_it, it_vals):
        fw = "bold" if val == max(it_vals) else "normal"
        ax1.text(val + 0.012, bar.get_y() + bar.get_height() / 2, f"{val:.2f}", va="center", fontsize=12.5, fontweight=fw, color=PALETTE["terracotta"])

    ax1.legend(loc="upper right", frameon=True, facecolor=PALETTE["surface"], edgecolor=PALETTE["grid"], fontsize=12.5)
    ax1.text(
        0.49, 2.35, "V4 peak: HMO L3 (0.52)\nIT peak: HMO Top (0.48)",
        ha="center", va="center", fontsize=12.5, fontweight="bold", color=PALETTE["ink"],
        bbox=dict(boxstyle="round,pad=0.4", facecolor=PALETTE["surface"], edgecolor=PALETTE["ochre"], lw=1.6),
    )

    # Panel B: Closed-Loop Control Benchmarks (zero baseline, 0-100%)
    ax2.set_facecolor(PALETTE["background"])
    c_labels = [row[0] for row in SLIDE54_CONTROL_BENCHMARKS]
    c_obs = [row[1] for row in SLIDE54_CONTROL_BENCHMARKS]
    c_chance = [row[2] for row in SLIDE54_CONTROL_BENCHMARKS]

    x = np.arange(len(c_labels))
    w = 0.40
    bars_obs = ax2.bar(
        x - 0.12, c_obs, width=w, color=PALETTE["sage"], edgecolor=PALETTE["ink"],
        linewidth=1.2, label="Model-synthesized stimuli",
    )
    bars_ch = ax2.bar(
        x + 0.21, c_chance, width=0.22, color=PALETTE["ochre"], edgecolor=PALETTE["ink"],
        linewidth=1.0, hatch="..", label="Reported chance baseline",
    )

    ax2.set_xticks(x)
    ax2.set_xticklabels(c_labels, fontsize=12.5, fontweight="bold")
    ax2.set_ylim(0, 105)
    ax2.set_ylabel("Success / Explained Response (%)", fontsize=14, fontweight="bold", labelpad=8)
    ax2.set_title("B. V4 Control & Novel Prediction (Bashivan et al., 2019)", loc="left", fontsize=14.5, fontweight="bold", pad=12)
    ax2.grid(axis="y", color=PALETTE["grid"], linestyle="-", linewidth=1.0, zorder=0)
    ax2.set_axisbelow(True)
    ax2.spines["top"].set_visible(False)
    ax2.spines["right"].set_visible(False)
    ax2.axhline(100, color=PALETTE["muted"], linestyle="--", linewidth=1.2)
    ax2.text(2.42, 95.5, "100% ceiling", ha="right", fontsize=12, color=PALETTE["muted"], fontweight="bold")

    for bar, val in zip(bars_obs, c_obs):
        ax2.text(bar.get_x() + bar.get_width() / 2, val + 2.2, f"{val:.0f}%", ha="center", fontsize=14, fontweight="bold", color=PALETTE["sage"])
    for bar, val in zip(bars_ch, c_chance):
        ax2.text(bar.get_x() + bar.get_width() / 2, val + 2.2, f"{val:.0f}%", ha="center", fontsize=12.5, fontweight="bold", color=PALETTE["ochre_text"])

    ax2.legend(loc="upper right", bbox_to_anchor=(1.0, 0.91), frameon=True, facecolor=PALETTE["surface"], edgecolor=PALETTE["grid"], fontsize=12.5)

    fig.text(
        0.045, 0.032,
        "Sources: L24a Slide 38 embedded layers (median single-site V4/IT explained variance on held-out images); Slide 54 summary (3 macaques). Zero baselines preserved.",
        fontsize=12.5, color=PALETTE["muted"],
    )

    plt.subplots_adjust(left=0.13, right=0.97, top=0.80, bottom=0.14)
    fig.savefig(svg_path, format="svg", facecolor=PALETTE["background"])
    fig.savefig(png_path, format="png", dpi=100, facecolor=PALETTE["background"])
    plt.close(fig)


def lorenz_deriv(x: np.ndarray, rho: float = 28.0, sigma: float = 10.0, beta: float = 8.0 / 3.0) -> np.ndarray:
    """Lorenz ODE right-hand side (Kim et al., Eq. 1)."""
    return np.array([
        sigma * (x[1] - x[0]),
        x[0] * (rho - x[2]) - x[1],
        x[0] * x[1] - beta * x[2],
    ])


def rk4_lorenz(x0: np.ndarray, steps: int, dt: float, rho: float = 28.0) -> tuple[np.ndarray, np.ndarray]:
    """Integrate Lorenz trajectory and store RK4 increments for coupled reservoir driving."""
    xs = np.zeros((3, steps))
    ks = np.zeros((3, 3, steps))
    x = x0.copy()
    for i in range(steps):
        xs[:, i] = x
        k1 = dt * lorenz_deriv(x, rho)
        k2 = dt * lorenz_deriv(x + 0.5 * k1, rho)
        k3 = dt * lorenz_deriv(x + 0.5 * k2, rho)
        k4 = dt * lorenz_deriv(x + k3, rho)
        ks[:, 0, i], ks[:, 1, i], ks[:, 2, i] = k1, k2, k3
        x = x + (k1 + 2 * k2 + 2 * k3 + k4) / 6.0
    return xs, ks


def run_reservoir_simulations() -> dict:
    """Run reproducible RK4 quadratic reservoir simulations for translation and Hopf bifurcation."""
    dt = 0.001
    gamma = 100.0
    N = 300

    # 1. Translation extrapolation simulation (seed=42)
    rng_t = np.random.default_rng(42)
    A_tilde = rng_t.uniform(-1.0, 1.0, (N, N)) * (rng_t.random((N, N)) < 0.1)
    A = 0.95 * A_tilde / float(np.max(np.real(np.linalg.eigvals(A_tilde))))
    r_star = rng_t.choice([-1.0, 1.0], N) * rng_t.uniform(0.8, 1.0, N)
    U_diag = 1.0 - r_star**2
    V_diag = r_star**3 - r_star

    B = np.zeros((N, 3))
    for i in range(N):
        B[i, int(rng_t.integers(0, 3))] = float(rng_t.uniform(-0.004, 0.004))
    C = rng_t.uniform(-0.002, 0.002, (N, 1))

    def res_deriv(dr: np.ndarray, x: np.ndarray, c: float) -> np.ndarray:
        inp = A @ dr + B @ x + C[:, 0] * c
        return gamma * (-dr + U_diag * inp + V_diag * (inp**2))

    xs_base, ks_base = rk4_lorenz(rng_t.uniform(0, 10, 3), int(120 / dt), dt, rho=28.0)
    waste = int(20 / dt)
    D_list, X_list = [], []
    for c_val in [0.0, 1.0, 2.0, 3.0]:
        xc = xs_base + np.array([[c_val], [0.0], [0.0]])
        dr = -r_star.copy()
        drs = np.zeros((N, xs_base.shape[1]))
        for i in range(xs_base.shape[1]):
            drs[:, i] = dr
            x_cur = xc[:, i]
            k1x, k2x, k3x = ks_base[:, 0, i], ks_base[:, 1, i], ks_base[:, 2, i]
            k1 = dt * res_deriv(dr, x_cur, c_val)
            k2 = dt * res_deriv(dr + 0.5 * k1, x_cur + 0.5 * k1x, c_val)
            k3 = dt * res_deriv(dr + 0.5 * k2, x_cur + 0.5 * k2x, c_val)
            k4 = dt * res_deriv(dr + k3, x_cur + k3x, c_val)
            dr = dr + (k1 + 2 * k2 + 2 * k3 + k4) / 6.0
        D_list.append(drs[:, waste:] + r_star[:, None])
        X_list.append(xc[:, waste:])

    D_train = np.hstack(D_list)[:, ::5]
    X_train = np.hstack(X_list)[:, ::5]
    W_T, _, _, _ = np.linalg.lstsq(D_train.T, X_train.T, rcond=None)
    W_trans = W_T.T
    trans_rmse = float(np.sqrt(np.mean((W_trans @ D_train - X_train) ** 2)))
    R_trans = A + B @ W_trans
    Wr_trans = W_trans @ r_star

    def fb_trans(dr: np.ndarray, c_val: float) -> np.ndarray:
        inp = R_trans @ dr + B @ Wr_trans + C[:, 0] * c_val
        return gamma * (-dr + U_diag * inp + V_diag * (inp**2))

    trans_trajs = {}
    for c_test in [-20.0, 0.0, 20.0]:
        dr = D_list[0][:, -1] - r_star
        preds = np.zeros((3, 18000))
        for i in range(18000):
            preds[:, i] = W_trans @ (dr + r_star)
            k1 = dt * fb_trans(dr, c_test)
            k2 = dt * fb_trans(dr + 0.5 * k1, c_test)
            k3 = dt * fb_trans(dr + 0.5 * k2, c_test)
            k4 = dt * fb_trans(dr + k3, c_test)
            dr = dr + (k1 + 2 * k2 + 2 * k3 + k4) / 6.0
        trans_trajs[c_test] = preds[:, 2000:]

    # 2. Hopf bifurcation inference simulation (seed=7)
    rng_b = np.random.default_rng(7)
    Ab_tilde = rng_b.uniform(-1.0, 1.0, (N, N)) * (rng_b.random((N, N)) < 0.1)
    Ab = 0.95 * Ab_tilde / float(np.max(np.real(np.linalg.eigvals(Ab_tilde))))
    rb_star = rng_b.choice([-1.0, 1.0], N) * rng_b.uniform(0.8, 1.0, N)
    Ub_diag = 1.0 - rb_star**2
    Vb_diag = rb_star**3 - rb_star

    Bb = np.zeros((N, 3))
    for i in range(N):
        Bb[i, int(rng_b.integers(0, 3))] = float(rng_b.uniform(-0.04, 0.04))
    Cb = rng_b.uniform(-0.002, 0.002, (N, 1))

    def res_bif_deriv(dr: np.ndarray, x: np.ndarray, c: float) -> np.ndarray:
        inp = Ab @ dr + Bb @ x + Cb[:, 0] * c
        return gamma * (-dr + Ub_diag * inp + Vb_diag * (inp**2))

    Db_list, Xb_list = [], []
    b_steps = int(30 / dt)
    b_waste = int(1 / dt)
    train_b_trajs = []
    for rho, c_val in [(23.0, 0.0), (24.0, 1.0)]:
        fp = np.sqrt(8.0 / 3.0 * (rho - 1.0))
        for sgn in [1.0, -1.0]:
            x0 = np.array([sgn * fp + 2.0, sgn * fp - 2.0, (rho - 1.0) + 2.0])
            xs, ks = rk4_lorenz(x0, b_steps, dt, rho)
            if sgn > 0:
                train_b_trajs.append((rho, c_val, xs[:, b_waste:b_waste + 15000]))
            dr = -rb_star.copy()
            drs = np.zeros((N, b_steps))
            for i in range(b_steps):
                drs[:, i] = dr
                k1x, k2x, k3x = ks[:, 0, i], ks[:, 1, i], ks[:, 2, i]
                k1 = dt * res_bif_deriv(dr, xs[:, i], c_val)
                k2 = dt * res_bif_deriv(dr + 0.5 * k1, xs[:, i] + 0.5 * k1x, c_val)
                k3 = dt * res_bif_deriv(dr + 0.5 * k2, xs[:, i] + 0.5 * k2x, c_val)
                k4 = dt * res_bif_deriv(dr + k3, xs[:, i] + k3x, c_val)
                dr = dr + (k1 + 2 * k2 + 2 * k3 + k4) / 6.0
            Db_list.append(drs[:, b_waste:] + rb_star[:, None])
            Xb_list.append(xs[:, b_waste:])

    Db_train = np.hstack(Db_list)[:, ::5]
    Xb_train = np.hstack(Xb_list)[:, ::5]
    Wb_T, _, _, _ = np.linalg.lstsq(Db_train.T, Xb_train.T, rcond=None)
    W_bif = Wb_T.T
    bif_rmse = float(np.sqrt(np.mean((W_bif @ Db_train - Xb_train) ** 2)))
    R_bif = Ab + Bb @ W_bif
    Wr_bif = W_bif @ rb_star

    def fb_bif(dr: np.ndarray, c_val: float) -> np.ndarray:
        inp = R_bif @ dr + Bb @ Wr_bif + Cb[:, 0] * c_val
        return gamma * (-dr + Ub_diag * inp + Vb_diag * (inp**2))

    # Autonomous sweep: c=0 for t in [0, 5), c=4 for t in [5, 30)
    dr = Db_list[0][:, 0] - rb_star
    bif_pred = np.zeros((3, 30000))
    for i in range(30000):
        c_val = 0.0 if i < 5000 else 4.0
        bif_pred[:, i] = W_bif @ (dr + rb_star)
        k1 = dt * fb_bif(dr, c_val)
        k2 = dt * fb_bif(dr + 0.5 * k1, c_val)
        k3 = dt * fb_bif(dr + 0.5 * k2, c_val)
        k4 = dt * fb_bif(dr + k3, c_val)
        dr = dr + (k1 + 2 * k2 + 2 * k3 + k4) / 6.0

    c_grid = np.linspace(0.0, 2.5, 51)
    eig_re = []
    eig_im = []
    dr_guess = Db_list[0][:, -1] - rb_star
    for c_val in c_grid:
        sol = root(lambda u: fb_bif(u, float(c_val)), dr_guess, method="hybr")
        assert sol.success, f"Root solve failed at c={c_val}"
        dr_guess = sol.x
        inp = R_bif @ dr_guess + Bb @ Wr_bif + Cb[:, 0] * float(c_val)
        J = gamma * (-np.eye(N) + (Ub_diag[:, None] * R_bif) + 2.0 * (Vb_diag[:, None] * inp[:, None]) * R_bif)
        eigs = np.linalg.eigvals(J)
        complex_eigs = [e for e in eigs if abs(np.imag(e)) > 1e-3]
        lead = max(complex_eigs, key=lambda e: np.real(e))
        eig_re.append(float(np.real(lead)))
        eig_im.append(abs(float(np.imag(lead))))

    return {
        "trans_rmse": trans_rmse,
        "trans_wr_star": [float(v) for v in Wr_trans],
        "trans_trajs": trans_trajs,
        "bif_rmse": bif_rmse,
        "bif_wr_star": [float(v) for v in Wr_bif],
        "train_b_trajs": train_b_trajs,
        "bif_pred": bif_pred,
        "c_grid": c_grid,
        "eig_re": eig_re,
        "eig_im": eig_im,
    }


def build_figure3_reservoir(sim: dict) -> dict:
    """Build Figure 3: Constructed RK4 verification of Kim et al. (2020) reservoir extrapolation & Hopf instability."""
    svg_path = OUT_DIR / "reservoir-attractor-control-and-bifurcation.svg"
    png_path = OUT_DIR / "reservoir-attractor-control-and-bifurcation.png"

    plt.rcParams.update({
        "font.family": "sans-serif",
        "font.sans-serif": ["Helvetica Neue", "Helvetica", "Arial"],
        "svg.fonttype": "none",
        "axes.edgecolor": PALETTE["ink"],
        "axes.linewidth": 1.3,
        "text.color": PALETTE["ink"],
        "axes.labelcolor": PALETTE["ink"],
        "xtick.color": PALETTE["ink"],
        "ytick.color": PALETTE["ink"],
    })

    fig, (ax1, ax2, ax3) = plt.subplots(
        1, 3, figsize=(16, 9), dpi=100,
        gridspec_kw={"width_ratios": [1.05, 1.15, 0.95], "wspace": 0.28},
    )
    fig.patch.set_facecolor(PALETTE["background"])

    fig.text(
        0.04, 0.942,
        "Fixed Reservoirs Map Control Bias to Attractor Shifts and Hopf Instability",
        fontsize=22.5, fontweight="bold", color=PALETTE["ink"],
    )
    fig.text(
        0.04, 0.892,
        "Constructed RK4 check (N=300, gamma=100, dt=0.001) of Kim et al. (2020) Eq. 1–5, 10; not biological recordings",
        fontsize=14.5, color=PALETTE["muted"],
    )

    # Panel A: Translation Extrapolation
    ax1.set_facecolor(PALETTE["background"])
    styles = [
        (-20.0, PALETTE["terracotta"], "-", "c = -20 (extrap.)"),
        (0.0, PALETTE["blue"], "--", "c = 0 (trained)"),
        (20.0, PALETTE["sage"], "-.", "c = +20 (extrap.)"),
    ]
    means = {}
    for c_val, col, ls, lab in styles:
        tr = sim["trans_trajs"][c_val]
        means[c_val] = float(np.mean(tr[0]))
        ax1.plot(tr[0, ::4], tr[2, ::4], color=col, linestyle=ls, linewidth=1.35, alpha=0.88, label=lab)
    ax1.set_xlabel(r"Predicted $x_1'(t)$", fontsize=13.5, fontweight="bold")
    ax1.set_ylabel(r"Predicted $x_3'(t)$", fontsize=13.5, fontweight="bold")
    ax1.set_ylim(2.0, 56.0)
    ax1.set_title("A. Translation Extrapolation\n(Trained c in {0, 1, 2, 3})", loc="left", fontsize=14, fontweight="bold", pad=10)
    ax1.grid(color=PALETTE["grid"], linewidth=0.9)
    ax1.spines["top"].set_visible(False)
    ax1.spines["right"].set_visible(False)
    ax1.legend(loc="upper center", frameon=True, facecolor=PALETTE["surface"], edgecolor=PALETTE["grid"], fontsize=11.5)

    # Panel B: Pre-bifurcation training vs autonomous two-wing switching
    ax2.set_facecolor(PALETTE["background"])
    t_b = np.arange(sim["bif_pred"].shape[1]) * 0.001
    rho23_xs = sim["train_b_trajs"][0][2]
    t_tr = np.arange(rho23_xs.shape[1]) * 0.001
    ax2.plot(t_tr, rho23_xs[0] + 34.0, color=PALETTE["blue"], linestyle="--", linewidth=1.7, label=r"Train input ($\rho=23, c=0$, +34 offset)")
    ax2.plot(t_b, sim["bif_pred"][0], color=PALETTE["terracotta"], linestyle="-", linewidth=1.35, label=r"Autonomous $x_1'(t)$ (c=0 -> 4)")
    ax2.axvline(5.0, color=PALETTE["ink"], linestyle=":", linewidth=1.6)
    ax2.text(5.4, 22.5, "Step c=0 to c=4\n(post-bifurcation)", fontsize=12, fontweight="bold", color=PALETTE["ink"])
    ax2.set_xlabel("Simulation time (dimensionless)", fontsize=13.5, fontweight="bold")
    ax2.set_ylabel(r"$x_1$ Trajectory", fontsize=13.5, fontweight="bold")
    ax2.set_ylim(-23, 58)
    ax2.set_title("B. Two-Wing Switching Inference\n(Trained both wings at rho=23, 24)", loc="left", fontsize=14, fontweight="bold", pad=10)
    ax2.grid(color=PALETTE["grid"], linewidth=0.9)
    ax2.spines["top"].set_visible(False)
    ax2.spines["right"].set_visible(False)
    ax2.legend(loc="lower left", frameon=True, facecolor=PALETTE["surface"], edgecolor=PALETTE["grid"], fontsize=11)

    # Panel C: Leading Jacobian Eigenvalue Crossing Re(lambda) = 0
    ax3.set_facecolor(PALETTE["background"])
    c_grid = sim["c_grid"]
    eig_re = np.array(sim["eig_re"])
    ax3.axhline(0.0, color=PALETTE["ink"], linestyle="--", linewidth=1.4)
    ax3.plot(c_grid, eig_re, color=PALETTE["sage"], linewidth=2.5, label=r"Leading $\operatorname{Re}(\lambda_{\max})$")
    idx_c0 = 0
    idx_c1 = int(np.argmin(np.abs(c_grid - 1.0)))
    ax3.scatter([c_grid[idx_c0], c_grid[idx_c1]], [eig_re[idx_c0], eig_re[idx_c1]], s=80, color=PALETTE["blue"], edgecolor=PALETTE["ink"], zorder=5, label="Trained points (c=0, 1)")

    # Linearly interpolate exact zero crossing between last <0 and first >=0
    cross_idx = int(np.where(eig_re >= 0)[0][0])
    c0_x, c1_x = float(c_grid[cross_idx - 1]), float(c_grid[cross_idx])
    y0_x, y1_x = float(eig_re[cross_idx - 1]), float(eig_re[cross_idx])
    c_cross = c0_x - y0_x * (c1_x - c0_x) / (y1_x - y0_x)

    ax3.scatter([c_cross], [0.0], s=90, marker="D", color=PALETTE["terracotta"], edgecolor=PALETTE["ink"], zorder=6, label=f"Stability flip (c ≈ {c_cross:.2f})")
    ax3.set_xlabel("Control Parameter c", fontsize=13.5, fontweight="bold")
    ax3.set_ylabel(r"Real Part $\operatorname{Re}(\lambda_{\max})$", fontsize=13.5, fontweight="bold")
    ax3.set_title("C. Learned Stability Crossing\n(Linearized Jacobian Eq. 10)", loc="left", fontsize=14, fontweight="bold", pad=10)
    ax3.grid(color=PALETTE["grid"], linewidth=0.9)
    ax3.spines["top"].set_visible(False)
    ax3.spines["right"].set_visible(False)
    ax3.legend(loc="upper left", frameon=True, facecolor=PALETTE["surface"], edgecolor=PALETTE["grid"], fontsize=11)

    fig.text(
        0.04, 0.032,
        f"Constructed finite-window check (seeds 42 & 7): training RMSE={sim['trans_rmse']:.2e} (trans.), {sim['bif_rmse']:.2e} (bif.); Re(λ_max) crosses 0 near c={c_cross:.4f}.",
        fontsize=12.5, color=PALETTE["muted"],
    )

    plt.subplots_adjust(left=0.06, right=0.97, top=0.79, bottom=0.14)
    fig.savefig(svg_path, format="svg", facecolor=PALETTE["background"])
    fig.savefig(png_path, format="png", dpi=100, facecolor=PALETTE["background"])
    plt.close(fig)

    return {
        "translation_train_rmse": sim["trans_rmse"],
        "translation_wr_star": sim["trans_wr_star"],
        "translation_x1_means": {str(int(k)): round(v, 2) for k, v in means.items()},
        "bifurcation_train_rmse": sim["bif_rmse"],
        "bifurcation_wr_star": sim["bif_wr_star"],
        "eigenvalue_re_c0": round(float(eig_re[idx_c0]), 4),
        "eigenvalue_re_c1": round(float(eig_re[idx_c1]), 4),
        "eigenvalue_re_c170": round(float(eig_re[cross_idx - 1]), 7),
        "eigenvalue_re_c175": round(float(eig_re[cross_idx]), 7),
        "eigenvalue_crossing_c": round(c_cross, 4),
        "autonomous_c4_x1_min": round(float(np.min(sim["bif_pred"][0, 15000:])), 2),
        "autonomous_c4_x1_max": round(float(np.max(sim["bif_pred"][0, 15000:])), 2),
    }


def main() -> None:
    words_fig1 = build_figure1_architecture()
    build_figure2_benchmarks()
    sim = run_reservoir_simulations()
    sim_summary = build_figure3_reservoir(sim)

    manifest = {
        "lecture": "MIT 6.874 Deep Learning in the Life Sciences (Spring 2021) — Lecture 24: Neuroscience",
        "version": "v1 r2",
        "figures": [
            "ventral-stream-reverse-engineering-loop.png",
            "ventral-hierarchy-variance-and-control.png",
            "reservoir-attractor-control-and-bifurcation.png",
        ],
        "svg_word_counts": {
            "ventral-stream-reverse-engineering-loop": words_fig1,
        },
        "verified_math": {
            "slide38_explained_variance": {
                row[0]: {"v4": row[1], "it": row[2]} for row in SLIDE38_EXPLAINED_VARIANCE
            },
            "slide54_v4_control": {
                "super_activate_pct": 68.0,
                "super_activate_chance_pct": 1.0,
                "onehot_subpopulation_pct": 76.0,
                "onehot_chance_pct": 1.0,
                "novel_synthetic_prediction_pct": 54.0,
                "novel_prediction_chance_pct": 0.0,
                "slide58_example_n_sites": 39,
            },
            "constructed_reservoir_rk4_verification": sim_summary,
        },
        "palette": PALETTE,
    }
    (OUT_DIR / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(manifest["verified_math"], indent=2))


if __name__ == "__main__":
    main()
