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

from __future__ import annotations

import json
import math
import struct
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

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": "#5A554E",
    "grid": "#DDD5C7",
    "blue": "#356482",
    "terracotta": "#B5493A",
    "sage": "#4B6B46",
    "ochre": "#A87919",
    "ochre_text": "#7A560E",
}

# Single source of truth for Slide 21 / ICML Table 1 benchmarks
SEMI_SYNTH_DATA = [
    ("SSM PK-PD", 55.34, 0.03, 39.84, 0.02, PALETTE["blue"], "o", "-", (0.0, 1.4), (0.0, 0.0)),
    ("SSM PK-PD (w/o TExp)", 58.39, 0.05, 38.93, 0.01, PALETTE["sage"], "s", "--", (0.0, -1.7), (0.0, -1.4)),
    ("SSM Linear", 58.57, 0.06, 53.84, 0.02, PALETTE["ochre_text"], "^", "-.", (0.0, 0.0), (0.0, 1.4)),
    ("SSM MOE", 60.98, 0.04, 51.57, 0.03, PALETTE["terracotta"], "D", ":", (0.0, -0.5), (0.0, 0.4)),
    ("SSM NL", 69.04, 0.11, 44.75, 0.02, PALETTE["ink"], "v", "-", (0.0, 0.5), (0.0, 0.0)),
    ("SSM Attn.Hist.", 76.94, 0.02, 73.80, 0.03, PALETTE["muted"], "P", "--", (0.0, 0.0), (0.0, 0.0)),
]

MMRF_MODELS = [
    ("SSM Linear", 7, 74.22, PALETTE["ochre_text"], "^", (3.5, 4.0), "left"),
    ("SSM Attn.Hist.", 17, 105.04, PALETTE["muted"], "P", (3.5, -1.0), "left"),
    ("SSM PK-PD", 23, 61.54, PALETTE["blue"], "o", (-3.5, 5.0), "center"),
    ("SSM NL", 51, 79.10, PALETTE["ink"], "v", (0.0, 5.8), "center"),
    ("SSM MOE", 77, 73.44, PALETTE["terracotta"], "D", (-3.5, -5.8), "center"),
]

MMRF_PAIRWISE = {
    "vs_Linear": {"fraction_lower_nelbo": 0.796, "sd": 0.400, "gt_10nat_nll_counts": [158, 6]},
    "vs_NL": {"fraction_lower_nelbo": 0.760, "sd": 0.426, "gt_10nat_nll_counts": [130, 12]},
    "vs_MOE": {"fraction_lower_nelbo": 0.714, "sd": 0.450, "gt_10nat_nll_counts": [94, 8]},
    "vs_AttnHist": {"fraction_lower_nelbo": 0.934, "sd": 0.247, "gt_10nat_nll_counts": [272, 0]},
}


def arrow_polygon(
    tip_x: float,
    tip_y: float,
    dx: float,
    dy: float,
    length: float = 16.0,
    half_w: float = 7.0,
) -> str:
    """Return explicit SVG <polygon> points for an arrowhead at (tip_x, tip_y)."""
    norm = math.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 = "#4B5558",
    width: float = 3.5,
    dashed: bool = False,
) -> str:
    """Draw a straight line ending with an explicit <polygon> arrowhead at (x2, y2)."""
    dx, dy = x2 - x1, y2 - y1
    norm = math.hypot(dx, dy)
    ux, uy = dx / norm, dy / norm
    lx2, ly2 = x2 - 12.0 * ux, y2 - 12.0 * uy
    dash_attr = ' stroke-dasharray="10,7"' 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 box(
    x: float,
    y: float,
    w: float,
    h: float,
    title: str,
    subtitle: str = "",
    fill: str = "#F3EEE3",
    stroke: str = "#5A554E",
    title_color: str = "#1F2A2E",
    sub_color: str = "#3E3A34",
    title_size: int = 30,
    sub_size: int = 23,
    rx: int = 14,
) -> str:
    """Render a centered rounded SVG box with larger feed-legible typography."""
    cx = x + w / 2.0
    parts = [
        f'<rect x="{x:.1f}" y="{y:.1f}" width="{w:.1f}" height="{h:.1f}" rx="{rx}" '
        f'fill="{fill}" stroke="{stroke}" stroke-width="2.8" />'
    ]
    if subtitle:
        ty = y + h * 0.43
        sy = y + h * 0.76
        parts.append(
            f'<text x="{cx:.1f}" y="{ty:.1f}" text-anchor="middle" font-size="{title_size}" '
            f'font-weight="700" fill="{title_color}">{title}</text>'
        )
        parts.append(
            f'<text x="{cx:.1f}" y="{sy:.1f}" text-anchor="middle" font-size="{sub_size}" '
            f'fill="{sub_color}">{subtitle}</text>'
        )
    else:
        ty = y + h * 0.56
        parts.append(
            f'<text x="{cx:.1f}" y="{ty:.1f}" text-anchor="middle" font-size="{title_size}" '
            f'font-weight="700" fill="{title_color}">{title}</text>'
        )
    return "\n    ".join(parts)


def fig_pkpd_architecture() -> str:
    """Figure 1 (Lead Cover): SVG diagram of PK-PD^Neural transition with all required input paths."""
    parts = [
        # Outer transition module frame
        '<rect x="395" y="160" width="855" height="545" rx="22" fill="#F6F1E7" stroke="#356482" stroke-width="2.8" stroke-dasharray="10,7" />',
        '<text x="422" y="202" font-size="27" font-weight="700" fill="#23475E">PK-PD<tspan baseline-shift="super" font-size="18">Neural</tspan> Transition μ<tspan baseline-shift="sub" font-size="18">θ</tspan>(Z<tspan baseline-shift="sub" font-size="18">t-1</tspan>, U<tspan baseline-shift="sub" font-size="18">t-1</tspan>, B)</text>',

        # Left inputs
        box(68, 208, 265, 118, 'State Z<tspan baseline-shift="sub" font-size="20">t-1</tspan>', "Patient proxy", "#EBF1F5", "#356482", "#1F2A2E", "#23475E", 30, 22),
        box(68, 380, 265, 126, 'Regimen U<tspan baseline-shift="sub" font-size="20">t-1</tspan>', "Drugs, line, clocks", "#FAECE9", "#B5493A", "#7A2D22", "#52322D", 30, 22),
        box(68, 560, 265, 118, "Baseline B", "RNA, demographics", "#ECF2EB", "#4B6B46", "#2E472B", "#364635", 30, 22),

        # Input arrows: Z_{t-1} -> g1, g2, g3; U_{t-1} -> g1, g2, g3; B -> g1, g3
        draw_arrow(333, 267, 435, 275, "#356482", 3.2),
        draw_arrow(333, 282, 435, 422, "#356482", 2.8),
        draw_arrow(333, 294, 435, 578, "#356482", 2.6),

        draw_arrow(333, 426, 435, 295, "#B5493A", 2.8),
        draw_arrow(333, 443, 435, 443, "#B5493A", 3.2),
        draw_arrow(333, 460, 435, 595, "#B5493A", 2.8),

        draw_arrow(333, 602, 435, 315, "#4B6B46", 2.6),
        draw_arrow(333, 619, 435, 615, "#4B6B46", 3.2),

        # Three mechanism functions (larger text for 360px legibility)
        box(440, 226, 336, 118, 'g<tspan baseline-shift="sub" font-size="20">1</tspan>: Baseline', "Z ⊙ tanh(b + W[U, B])", "#EBF1F5", "#356482", "#1F2A2E", "#23475E", 28, 22),
        box(440, 384, 336, 118, 'g<tspan baseline-shift="sub" font-size="20">2</tspan>: Log-Cell Kill', "Gradual relapse via lc", "#FAECE9", "#B5493A", "#7A2D22", "#52322D", 28, 22),
        box(440, 542, 336, 118, 'g<tspan baseline-shift="sub" font-size="20">3</tspan>: Treatment Exp.', "Piecewise sigmoid via γ<tspan baseline-shift='sub' font-size='16'>l</tspan>", "#F7EFE0", "#A87919", "#694B0B", "#5A4517", 28, 22),

        # Arrows from g1, g2, g3 into Soft Attention
        draw_arrow(776, 285, 858, 404, "#356482", 3.2),
        draw_arrow(776, 443, 858, 443, "#B5493A", 3.2),
        draw_arrow(776, 601, 858, 482, "#7A560E", 3.2),

        # Attention selector box
        box(864, 354, 240, 178, "Soft Attention", 'Query Z<tspan baseline-shift="sub" font-size="18">t-1</tspan> | α<tspan baseline-shift="sub" font-size="18">i</tspan>', "#F3EEE3", "#5A554E", "#1F2A2E", "#3E3A34", 29, 23),

        # Query path from Z_{t-1} along top
        '<path d="M 200 208 L 200 124 L 984 124 L 984 341" fill="none" stroke="#356482" stroke-width="3.0" stroke-dasharray="9,6" />',
        f'<polygon points="{arrow_polygon(984, 353, 0, 1)}" fill="#356482" />',
        '<text x="592" y="112" text-anchor="middle" font-size="23" font-weight="700" fill="#23475E">Query Z<tspan baseline-shift="sub" font-size="16">t-1</tspan> weights mechanisms</text>',

        # Residual skip path routed cleanly from Z_{t-1} left edge along bottom to + node
        '<path d="M 68 267 L 34 267 L 34 756 L 1175 756 L 1175 484" fill="none" stroke="#356482" stroke-width="3.2" />',
        f'<polygon points="{arrow_polygon(1175, 472, 0, -1)}" fill="#356482" />',
        '<text x="690" y="742" text-anchor="middle" font-size="23" font-weight="700" fill="#23475E">Residual skip Z<tspan baseline-shift="sub" font-size="16">t-1</tspan> (Slide 18)</text>',

        # Addition node
        draw_arrow(1104, 443, 1142, 443, "#1F2A2E", 3.4),
        '<circle cx="1175" cy="443" r="29" fill="#FAF6EE" stroke="#1F2A2E" stroke-width="3.2" />',
        '<text x="1175" y="454" text-anchor="middle" font-size="36" font-weight="700" fill="#1F2A2E">+</text>',

        # Right outputs Z_t and X_t
        draw_arrow(1204, 443, 1300, 443, "#356482", 3.5),
        box(1306, 384, 228, 118, 'Next State Z<tspan baseline-shift="sub" font-size="20">t</tspan>', 'N(μ<tspan baseline-shift="sub" font-size="16">θ</tspan>, Σ<tspan baseline-shift="sub" font-size="16">θ</tspan>)', "#EBF1F5", "#356482", "#1F2A2E", "#23475E", 29, 22),
        draw_arrow(1420, 502, 1420, 566, "#4B6B46", 3.5),
        box(1306, 572, 228, 118, 'Labs X<tspan baseline-shift="sub" font-size="20">t</tspan>', "Missing X dropped", "#ECF2EB", "#4B6B46", "#2E472B", "#364635", 29, 22),

        '<text x="68" y="848" font-size="22" fill="#5A554E">MIT 6.874 Lecture 23 (Krishnan, Slides 14–18; Hussain et al., ICML 2021)</text>',
    ]
    return f"""<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 900" width="1600" height="900">
  <rect width="1600" height="900" fill="#FAF6EE" />
  <g font-family="{FONT}">
    <text x="68" y="72" font-size="40" font-weight="700" fill="#1F2A2E">Pharmacodynamic Attention Steers Latent State Across Treatment Lines</text>
    {"".join(parts)}
  </g>
</svg>
"""


def count_svg_words(svg_str: str) -> int:
    root = ET.fromstring(svg_str)
    texts = [
        " ".join("".join(el.itertext()).split())
        for el in root.iter()
        if el.tag.endswith("}text") or el.tag == "text"
    ]
    return sum(len(t.split()) for t in texts)


def rasterize_svg(svg_str: str, png_path: Path) -> None:
    html = f"""<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<style>
* {{ margin: 0; padding: 0; border: 0; box-sizing: border-box; }}
html, body {{ width: 1600px; height: 900px; overflow: hidden; background: #FAF6EE; }}
svg {{ display: block; width: 1600px; height: 900px; }}
</style>
</head>
<body>{svg_str}</body>
</html>
"""
    with tempfile.TemporaryDirectory(dir="/tmp") as tmp:
        html_path = Path(tmp) / "fig.html"
        prof_dir = Path(tmp) / "profile"
        prof_dir.mkdir()
        html_path.write_text(html, encoding="utf-8")
        subprocess.run(
            [
                CHROME,
                "--headless=new",
                "--no-sandbox",
                "--disable-gpu",
                "--hide-scrollbars",
                f"--user-data-dir={prof_dir}",
                "--force-device-scale-factor=1",
                "--window-size=1600,900",
                f"--screenshot={png_path}",
                f"file://{html_path}",
            ],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )


def png_dimensions(png_path: Path) -> tuple[int, int]:
    data = png_path.read_bytes()
    assert data[:8] == b"\x89PNG\r\n\x1a\n", f"Not PNG: {png_path}"
    return struct.unpack(">II", data[16:24])


def style_axes(ax: plt.Axes) -> None:
    ax.set_facecolor(PALETTE["background"])
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.spines["left"].set_color(PALETTE["muted"])
    ax.spines["bottom"].set_color(PALETTE["muted"])
    ax.spines["left"].set_linewidth(1.5)
    ax.spines["bottom"].set_linewidth(1.5)
    ax.tick_params(colors=PALETTE["ink"], labelsize=15)
    ax.grid(axis="y", color=PALETTE["grid"], linestyle="-", linewidth=1.0, alpha=0.8)
    ax.set_axisbelow(True)


def fig_sample_complexity_and_params() -> None:
    """Figure 2: Slide 21 semi-synthetic sample scaling & ML-MMRF parameter efficiency."""
    plt.rcParams.update({
        "font.family": "sans-serif",
        "font.sans-serif": ["Helvetica Neue", "Helvetica", "Arial", "DejaVu Sans"],
        "axes.edgecolor": PALETTE["muted"],
    })
    fig, (ax1, ax2) = plt.subplots(
        1, 2, figsize=(16, 9), dpi=100, facecolor=PALETTE["background"],
        gridspec_kw={"width_ratios": [1.05, 1.0], "wspace": 0.28},
    )
    fig.subplots_adjust(left=0.075, right=0.96, top=0.80, bottom=0.14)

    # Panel 1: Semi-synthetic NELBO (mean +/- SD) at N=100 vs N=1,000 (Slide 21)
    style_axes(ax1)
    xs = np.array([0.0, 1.0])
    for name, y100, sd100, y1k, sd1k, col, mk, ls, (dx_r, dy_r), (dx_l, dy_l) in SEMI_SYNTH_DATA:
        ax1.errorbar(
            xs, [y100, y1k], yerr=[sd100, sd1k],
            color=col, marker=mk, linestyle=ls, linewidth=2.8, markersize=10,
            capsize=5, label=name, zorder=4,
        )
        ax1.annotate(
            f"{name} ({y1k:.2f})",
            xy=(1.0, y1k), xytext=(1.06 + dx_r, y1k + dy_r),
            fontsize=14, fontweight="bold" if "PK-PD" in name else "normal",
            color=col, va="center",
        )
        ax1.annotate(
            f"{y100:.2f}",
            xy=(0.0, y100), xytext=(-0.06 + dx_l, y100 + dy_l),
            fontsize=13.5, color=col, ha="right", va="center", fontweight="bold" if name == "SSM PK-PD" else "normal",
        )

    ax1.set_xticks([0.0, 1.0])
    ax1.set_xticklabels(["N = 100 samples", "N = 1,000 samples"], fontsize=16, fontweight="bold")
    ax1.set_xlim(-0.30, 1.88)
    ax1.set_ylim(33, 82)
    ax1.set_ylabel("Test NELBO (nats, lower is better)", fontsize=16, fontweight="bold", color=PALETTE["ink"])
    ax1.set_title("Semi-Synthetic Sample Complexity (SD ≤ 0.11)", fontsize=19, fontweight="bold", color=PALETTE["ink"], pad=14)

    # Panel 2: Real Multiple Myeloma (ML-MMRF, N=282 test) Parameter Count vs Test NELBO
    style_axes(ax2)
    for name, params_k, nelbo, col, mk, (dx, dy), ha in MMRF_MODELS:
        ms = 230 if name == "SSM PK-PD" else 145
        ax2.scatter(
            [params_k], [nelbo], s=ms, color=col, marker=mk,
            edgecolors=PALETTE["ink"], linewidths=1.5, zorder=5,
        )
        ax2.annotate(
            f"{name}\n({params_k}K, {nelbo:.2f})",
            xy=(params_k, nelbo),
            xytext=(params_k + dx, nelbo + dy),
            fontsize=14.5, fontweight="bold" if name == "SSM PK-PD" else "normal",
            color=col, ha=ha, va="center",
        )

    ax2.axhline(61.54, color=PALETTE["blue"], linestyle=":", linewidth=1.6, alpha=0.8)
    ax2.annotate(
        ">10-nat NLL gain in 130/282 vs NL\nand 94/282 vs MOE (N=282 test)",
        xy=(23.8, 60.6), xytext=(32, 52.5),
        arrowprops={"arrowstyle": "->", "color": PALETTE["blue"], "lw": 2.0},
        fontsize=14, fontweight="bold", color=PALETTE["blue"],
        bbox={"boxstyle": "round,pad=0.35", "fc": "#EBF1F5", "ec": PALETTE["blue"], "lw": 1.4},
    )
    ax2.set_xlim(0, 88)
    ax2.set_ylim(47, 113)
    ax2.set_xlabel("Model Parameters (thousands)", fontsize=16, fontweight="bold", color=PALETTE["ink"])
    ax2.set_ylabel("Test NELBO (nats, lower is better)", fontsize=16, fontweight="bold", color=PALETTE["ink"])
    ax2.set_title("Multiple Myeloma (ML-MMRF) Size vs. Error", fontsize=19, fontweight="bold", color=PALETTE["ink"], pad=14)

    fig.suptitle(
        "Pharmacodynamic Structure Cuts Small-Sample Error and Beats Larger MLPs",
        x=0.075, y=0.94, ha="left", fontsize=27, fontweight="bold", color=PALETTE["ink"],
    )
    fig.text(
        0.075, 0.88,
        "Lecture-reported test NELBO on semi-synthetic trajectories (left; SD ≤ 0.11 within markers) and 282 ML-MMRF patients (right)",
        fontsize=15.5, color=PALETTE["muted"],
    )
    fig.text(
        0.075, 0.035,
        "Source: MIT 6.874 Lecture 23 (Slide 21); N = 282 test count & >10-nat NLL threshold from Hussain et al. (ICML 2021, Table 1).",
        fontsize=14, color=PALETTE["muted"],
    )

    for ext in ("png", "svg"):
        fig.savefig(OUT_DIR / f"sample-complexity-and-parameter-efficiency.{ext}", facecolor=PALETTE["background"])
    plt.close(fig)


def fig_clocks_and_drug_response() -> None:
    """Figure 3: Constructed illustration of global/local clocks and g2/g3 dynamics."""
    plt.rcParams.update({
        "font.family": "sans-serif",
        "font.sans-serif": ["Helvetica Neue", "Helvetica", "Arial", "DejaVu Sans"],
    })
    fig, (ax1, ax2) = plt.subplots(
        1, 2, figsize=(16, 9), dpi=100, facecolor=PALETTE["background"],
        gridspec_kw={"width_ratios": [1.0, 1.0], "wspace": 0.25},
    )
    fig.subplots_adjust(left=0.075, right=0.96, top=0.80, bottom=0.15)

    # Panel 1: Constructed 18-step therapy sequence -> gc vs lc
    style_axes(ax1)
    t = np.arange(0, 18)
    gc = t.copy()
    p_t = np.array([0]*6 + [6]*6 + [12]*6)
    lc = t - p_t

    ax1.axvspan(-0.5, 5.5, color="#EBF1F5", alpha=0.55, zorder=0)
    ax1.axvspan(5.5, 11.5, color="#F3EEE3", alpha=0.85, zorder=0)
    ax1.axvspan(11.5, 17.5, color="#FAECE9", alpha=0.55, zorder=0)
    ax1.text(2.5, 13.8, "Line 1", ha="center", fontsize=15.5, fontweight="bold", color=PALETTE["blue"])
    ax1.text(8.5, 13.8, "Line 2", ha="center", fontsize=15.5, fontweight="bold", color=PALETTE["muted"])
    ax1.text(14.5, 18.2, "Line 3+", ha="center", fontsize=15.5, fontweight="bold", color=PALETTE["terracotta"])

    ax1.plot(t, gc, marker="o", linestyle="-", linewidth=2.8, markersize=8, color=PALETTE["blue"], label="Global clock gc = t")
    ax1.step(t, lc, where="mid", linestyle="--", linewidth=2.8, color=PALETTE["terracotta"], label=r"Local clock $lc = t - p_t$")
    ax1.scatter(t, lc, marker="s", s=65, color=PALETTE["terracotta"], zorder=5)

    for reset_t, text_y in ((6, 4.2), (12, 5.2)):
        ax1.axvline(reset_t - 0.5, color=PALETTE["muted"], linestyle=":", linewidth=1.8, zorder=2)
        ax1.annotate(
            "Reset lc = 0", xy=(reset_t, 0.45), xytext=(reset_t + 0.65, text_y),
            arrowprops={"arrowstyle": "->", "color": PALETTE["terracotta"], "lw": 1.8},
            fontsize=14, fontweight="bold", color=PALETTE["terracotta"],
        )

    ax1.set_xlim(-0.5, 17.5)
    ax1.set_ylim(-0.8, 19.6)
    ax1.set_xticks([0, 3, 6, 9, 12, 15, 17])
    ax1.set_xlabel("Visit Index t (Constructed 18-step schedule)", fontsize=16, fontweight="bold", color=PALETTE["ink"])
    ax1.set_ylabel("Clock Value (steps)", fontsize=16, fontweight="bold", color=PALETTE["ink"])
    ax1.set_title("Global Clock vs. Local Clock Reset", fontsize=19, fontweight="bold", color=PALETTE["ink"], pad=14)
    leg1 = ax1.legend(loc="upper left", frameon=True, framealpha=1.0, facecolor=PALETTE["background"], edgecolor=PALETTE["grid"], fontsize=14)
    leg1.set_zorder(10)

    # Panel 2: Constructed g2/Z multiplier and discontinuous g3 (printed ICML Eq. 6)
    style_axes(ax2)
    gamma_l, a1, a2, a3 = 4.0, 1.0, 1.8, 1.2
    a0_printed = a1 / (1.0 + math.exp(-a3 * gamma_l / 2.0))

    lc_left = np.linspace(0.0, gamma_l, 140, endpoint=False)
    lc_right = np.linspace(gamma_l, 10.0, 200)
    lc_all = np.linspace(0.0, 10.0, 300)

    z_val, rho, beta, delta = 1.5, 0.15, 0.80, 0.45
    g2_mult = 1.0 - rho * math.log(z_val ** 2) - beta * np.exp(-delta * lc_all)

    g3_left = a1 / (1.0 + np.exp(-a2 * (lc_left - gamma_l / 2.0)))
    g3_right = a0_printed / (1.0 + np.exp(a3 * (lc_right - 1.5 * gamma_l)))

    # Draw the two piecewise g3 branches separately so no line connects across the jump
    ax2.plot(lc_left, g3_left, color=PALETTE["sage"], linestyle="-", linewidth=3.2, label=r"$g_3$ Treatment Exp. ($b_0=b_l=0,\ \gamma_l=4$)")
    ax2.plot(lc_right, g3_right, color=PALETTE["sage"], linestyle="-", linewidth=3.2)
    ax2.plot(lc_all, g2_mult, color=PALETTE["ochre_text"], linestyle="--", linewidth=3.2, label=r"$g_2 / Z$ multiplier ($Z=1.5,\ \delta=0.45$)")
    ax2.axhline(0.0, color=PALETTE["muted"], linewidth=1.2)
    ax2.axvline(gamma_l, color=PALETTE["blue"], linestyle=":", linewidth=2.2)

    g3_left_limit = a1 / (1.0 + math.exp(-a2 * (gamma_l - gamma_l / 2.0)))
    g3_right_val = a0_printed / (1.0 + math.exp(a3 * (gamma_l - 1.5 * gamma_l)))
    # Open circle at excluded left limit (4, 0.973), filled circle at achieved right value (4, 0.841)
    ax2.scatter([gamma_l], [g3_left_limit], facecolor=PALETTE["background"], edgecolor=PALETTE["sage"], linewidth=2.4, s=95, zorder=6)
    ax2.scatter([gamma_l], [g3_right_val], facecolor=PALETTE["sage"], edgecolor=PALETTE["sage"], s=95, zorder=6)

    ax2.annotate(
        f"Left limit {g3_left_limit:.3f} (open)\njumps to {g3_right_val:.3f} (filled) at $\\gamma_l=4$",
        xy=(gamma_l + 0.06, g3_left_limit), xytext=(4.45, 0.95),
        arrowprops={"arrowstyle": "->", "color": PALETTE["sage"], "lw": 1.8},
        fontsize=13.5, fontweight="bold", color=PALETTE["sage"],
    )
    ax2.annotate(
        r"Initial $g_2/Z = 0.078$" + "\n" + r"($g_2 = 0.118$ for $Z=1.5$)",
        xy=(0.06, float(g2_mult[1])), xytext=(0.22, 0.95),
        arrowprops={"arrowstyle": "->", "color": PALETTE["ochre_text"], "lw": 1.8},
        fontsize=13.5, fontweight="bold", color=PALETTE["ochre_text"],
    )

    ax2.set_xlim(0.0, 10.0)
    ax2.set_ylim(-0.06, 1.30)
    ax2.set_xlabel("Local Clock lc (steps in current line of therapy)", fontsize=16, fontweight="bold", color=PALETTE["ink"])
    ax2.set_ylabel("Dimensionless Mechanism Response", fontsize=16, fontweight="bold", color=PALETTE["ink"])
    ax2.set_title(r"Constructed $g_2/Z$ and $g_3$ vs. Local Clock", fontsize=19, fontweight="bold", color=PALETTE["ink"], pad=14)
    leg2 = ax2.legend(loc="upper right", frameon=True, framealpha=1.0, facecolor=PALETTE["background"], edgecolor=PALETTE["grid"], fontsize=13.5)
    leg2.set_zorder(10)

    fig.suptitle(
        "Local Clocks Reset Drug-Response Trajectories at Each Therapy Transition",
        x=0.075, y=0.94, ha="left", fontsize=27, fontweight="bold", color=PALETTE["ink"],
    )
    fig.text(
        0.075, 0.88,
        r"Constructed mathematical illustration of Slide 14 clock resets (left) and Slide 17 $g_2/Z$ and $g_3$ formulas (right; not cohort data)",
        fontsize=15.5, color=PALETTE["muted"],
    )
    fig.text(
        0.075, 0.035,
        r"Constructed parameters: $g_2/Z$ uses $Z=1.5,\ \rho=0.15,\ \beta=0.80,\ \delta=0.45$; $g_3$ uses $b_0=b_l=0,\ \alpha_1=1.0,\ \alpha_2=1.8,\ \alpha_3=1.2,\ \gamma_l=4.0$.",
        fontsize=14, color=PALETTE["muted"],
    )

    for ext in ("png", "svg"):
        fig.savefig(OUT_DIR / f"clocks-and-drug-response-dynamics.{ext}", facecolor=PALETTE["background"])
    plt.close(fig)


def compute_verified_math() -> dict:
    """Compute and verify all lecture-reported comparisons and constructed examples from single-source constants."""
    emr_pct = {2008: 9.4, 2009: 12.2, 2010: 15.6, 2011: 27.6, 2012: 44.4, 2013: 59.4, 2014: 75.5, 2015: 83.8}

    synth_n100 = {row[0]: {"mean": row[1], "sd": row[2]} for row in SEMI_SYNTH_DATA}
    synth_n1000 = {row[0]: {"mean": row[3], "sd": row[4]} for row in SEMI_SYNTH_DATA}

    mmrf_nelbo = {row[0]: row[2] for row in MMRF_MODELS}
    mmrf_params_k = {row[0]: row[1] for row in MMRF_MODELS}
    mmrf_deltas = {k: round(v - mmrf_nelbo["SSM PK-PD"], 2) for k, v in mmrf_nelbo.items() if k != "SSM PK-PD"}

    # Constructed 1D scalar check (freely chosen illustrative parameters)
    z_prev = 1.5
    lc_val = 2.0
    g1_val = z_prev * math.tanh(0.25)
    g2_mult_lc0 = 1.0 - 0.15 * math.log(z_prev ** 2) - 0.80 * math.exp(0.0)
    g2_at_lc0 = z_prev * g2_mult_lc0
    g2_mult_lc2 = 1.0 - 0.15 * math.log(z_prev ** 2) - 0.80 * math.exp(-0.45 * lc_val)
    g2_at_lc2 = z_prev * g2_mult_lc2

    gamma_l, a1, a2, a3, b0, bl = 4.0, 1.0, 1.8, 1.2, 0.0, 0.0
    d2 = 1.0 + math.exp(-a2 * gamma_l / 2.0)
    d3 = 1.0 + math.exp(-a3 * gamma_l / 2.0)
    a0_printed = (a1 + 2 * b0 - bl) / d3
    a0_continuous = d3 * (b0 - bl + a1 / d2)

    g3_at_lc2 = b0 + a1 / (1.0 + math.exp(-a2 * (2.0 - gamma_l / 2.0)))
    g3_at_lc4_left = b0 + a1 / d2
    g3_at_lc4_right_printed = bl + a0_printed / d3
    g3_at_lc4_right_continuous = bl + a0_continuous / d3
    g3_at_lc8_printed = bl + a0_printed / (1.0 + math.exp(a3 * (8.0 - 1.5 * gamma_l)))

    # Manually supplied Slide 18 attention weights (0.4, 0.3, 0.3) and residual Z_{t-1}
    attn_weights = [0.4, 0.3, 0.3]
    intervention_effect = attn_weights[0] * g1_val + attn_weights[1] * g2_at_lc2 + attn_weights[2] * g3_at_lc2
    z_next_mean = z_prev + intervention_effect

    return {
        "slide03_us_hospital_emr_pct": emr_pct,
        "slide21_semi_synthetic_nelbo": {"N100": synth_n100, "N1000": synth_n1000},
        "slide21_mmrf_nelbo_and_params_k": {
            "cohort_size_slide19": 1143,
            "test_patients_icml_table1": 282,
            "nelbo": mmrf_nelbo,
            "nelbo_improvement_over_baselines": mmrf_deltas,
            "params_k": mmrf_params_k,
            "pairwise": MMRF_PAIRWISE,
        },
        "constructed_pkpd_scalar_check": {
            "z_prev": z_prev,
            "lc": lc_val,
            "g1": round(g1_val, 4),
            "g2_multiplier_lc0": round(g2_mult_lc0, 5),
            "g2_lc0": round(g2_at_lc0, 5),
            "g2_multiplier_lc2": round(g2_mult_lc2, 4),
            "g2_lc2": round(g2_at_lc2, 4),
            "a0_printed_icml_p5": round(a0_printed, 5),
            "a0_exact_continuity": round(a0_continuous, 5),
            "g3_at_lc2": round(g3_at_lc2, 4),
            "g3_at_lc4_left_limit": round(g3_at_lc4_left, 5),
            "g3_at_lc4_right_printed": round(g3_at_lc4_right_printed, 5),
            "g3_at_lc4_right_continuous": round(g3_at_lc4_right_continuous, 5),
            "g3_at_lc8_printed": round(g3_at_lc8_printed, 4),
            "manual_attn_weights_slide18": attn_weights,
            "intervention_effect": round(intervention_effect, 4),
            "z_next_mean_with_residual": round(z_next_mean, 4),
        },
    }


def main() -> None:
    svg_name = "pkpd-ssm-transition-architecture"
    svg_str = fig_pkpd_architecture()
    words = count_svg_words(svg_str)
    svg_path = OUT_DIR / f"{svg_name}.svg"
    png_path = OUT_DIR / f"{svg_name}.png"
    svg_path.write_text(svg_str, encoding="utf-8")
    rasterize_svg(svg_str, png_path)
    w, h = png_dimensions(png_path)
    assert (w, h) == (1600, 900), f"{svg_name} unexpected PNG size {w}x{h}"
    print(f"{svg_name}: words={words} size={w}x{h}")

    fig_sample_complexity_and_params()
    fig_clocks_and_drug_response()

    for name in ("sample-complexity-and-parameter-efficiency", "clocks-and-drug-response-dynamics"):
        p = OUT_DIR / f"{name}.png"
        mw, mh = png_dimensions(p)
        assert (mw, mh) == (1600, 900), f"{name} unexpected PNG size {mw}x{mh}"
        print(f"{name}: size={mw}x{mh}")

    manifest = {
        "lecture": "MIT 6.874 Deep Learning in the Life Sciences (Spring 2021) — Lecture 23: EHRs and Data Mining (Disease Progression Modeling)",
        "version": "v1 r2",
        "figures": [
            "pkpd-ssm-transition-architecture.png",
            "sample-complexity-and-parameter-efficiency.png",
            "clocks-and-drug-response-dynamics.png",
        ],
        "svg_word_counts": {svg_name: words},
        "verified_math": compute_verified_math(),
        "palette": PALETTE,
    }
    (OUT_DIR / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()
