"""Paper figures from the result files.

    python figures.py --fig 1        # figures/fig1_where_the_bits_go.{pdf,png}
    python figures.py --fig 1a-gif   # figures/fig1a_bits_counting_down.gif (website)
    python figures.py --fig S1       # figures/figS1_where_the_bits_go_map.{pdf,png}
    python figures.py --fig S2       # figures/figS2_where_the_bits_go_other_models.{pdf,png}
    python figures.py --fig 2        # figures/fig2_what_quantization_buys.{pdf,png}, _data.json, _caption.md
    python figures.py --fig S3       # the same for the sparse bench cells (figS3_...)
    python figures.py --fig 3        # figures/fig3_what_gets_quantized.{pdf,png}, _data.json, _caption.md
    python figures.py --fig 4        # figures/fig4_why_the_front_bends.{pdf,png}, _data.json, _caption.md
    python figures.py --table size   # figures/table1_size.{md,csv,json}
    python figures.py --fig FS2 --fig FS3   # the first sweep's figures 2 and 3, into figures/first_sweep/
    python figures.py --check-palette   # figures/palette_check.json (CVD simulation of the categorical slots)
    python figures.py --all          # everything; the table and figure 4 report what they wait for

Reads the per-cell sensitivity results (results/sensitivity/<problem>_n<N>_s<S>_<backend>.json,
records of kind ``cell``; only files whose two runs agreed), never refits or reruns anything.
Figure 1(a) and the GIF load the stored forrester n=32 seed 7 reference (read-only, seconds)
and predict on a grid with the study's own predictive. Deterministic: no timestamps or
random state in the outputs (PDF creation date suppressed).

Figure 1, "Where the bits go": (a) the consequence on the one-input problem, the curve and
its 95 % band against the truth at 64 bits, with the weights alpha stored at 32 bits and
with the Cholesky factor L stored at 32 bits; (b) the fewest bits per number each group
of stored quantities needs, stored as fitted and recomputed after rounding.

Figure S1, the map: stored quantity x storage format, shaded by the worst
per-output mean-shift ratio (rounding shift of the predictive mean divided by the float64
model's own error against truth, test split), worst over seeds. Hatching marks a cell where
the predictive standard deviation (median change >= 10 %) or the 95 % coverage (>= 1 point)
fails for some output in some seed. Glyphs mark cells with no measurement.

First-sweep figure 2 (FS2), "The noise floor sets the bits": (a) the fewest bits per stored number that pass
in every seed (stored mode, test split) for the weights, the factor, the inputs and the
hyperparameters, against the fitted noise variance in standardized output units, over the
heterogeneous noise-floor ladder (every ``_nf<floor>`` result present with all three seeds)
and, past a divider, HiLift (a different problem, not joined to the ladder);
(b) the first-order RMS estimate of the mean shift against the measured one for every
stored-mode cell of alpha, X and the length scales at the float formats. The fitted noise
and signal variances are read from the reference JSON's fitted hyperparameters
(results/reference/<stem>.json); fig2_data.json keeps the noise-to-signal ratio beside them.

First-sweep figure 3 (FS3), "More training points, less room for rounding": for each problem fitted at
two training-set sizes (heterogeneous dense 256/1024 and sparse 256/16384, het_tanh 1024/4096,
thermo8 256/1024), the stored-mode float32 mean-shift ratio of the weights and the inputs (X, or
Z for sparse), every seed as a dot and the worst seed joined; the caption lists every change of
the fewest tolerated bits between the sizes (summary.json).

The allocation figures (bench problems, README "Redirection", 10 November) read
results/allocation/<stem>.json (allocate.py): figure 2, bytes against the measured score
(worst of the three tests over its limit) for uniform casting and the allocation's measured
front, per problem at n = 1024, seed 7 (S3: the sparse n = 4096 cells); figure 3, bytes per
group at four passing front points (all float64, each new factor format, the last passing
point); figure 4, the saving at the last passing point against kappa of the stored float32 L
record, with the first sweep's F1 bands computed from its dense cells; table 1, bytes at
float64, best passing uniform and allocation, with resident memory of the matching synthetic
size cells. Until a bench cell exists they draw every measured allocation result and mark
the outputs as development. Figures 2 and 3 of the first sweep ("FS2", "FS3": noise floor,
training-set size) write to figures/first_sweep/. Palette: categorical slots 1-3 of the
dataviz reference palette plus #8c304c, checked with ``--check-palette`` (Machado et al.
2009 simulation, OKLab Delta E).
"""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

import numpy as np
import matplotlib
import matplotlib.lines
import matplotlib.ticker
import matplotlib.transforms

matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402
from matplotlib.colors import LinearSegmentedColormap, LogNorm  # noqa: E402
from matplotlib.patches import Rectangle  # noqa: E402

HERE = Path(__file__).resolve().parent
RESULTS = HERE / "results" / "sensitivity"
OUT = HERE / "figures"
SPLIT = "test"
THRESHOLD = 0.1          # metrics.MEAN_SHIFT_FRACTION, stated in the README before the sweep
VMIN, VMAX = 1e-4, 1e4   # colour-scale range of the mean-shift ratio; zero and smaller clip to VMIN

# --- style: palette.md (dataviz reference palette), light surface for print ---------------
SURFACE = "#ffffff"
INK = "#0b0b0b"          # primary ink
INK2 = "#52514e"         # secondary ink
MUTED = "#898781"        # muted (axis, notes)
NEUTRAL = "#eceae4"      # fill of cells with no measurement (between gridline and midpoint gray)
RULE = "#c3c2b7"         # baseline / axis
# Sequential blue ramp (palette.md steps). The pass side (< 0.1) uses the light steps
# 100-250, the fail side the dark steps 450-700: the lightness jump between 250 and 450
# is the threshold, visible in every cell and in the colour bar.
PASS_STEPS = ["#cde2fb", "#b7d3f6", "#9ec5f4", "#86b6ef"]                      # 100,150,200,250
FAIL_STEPS = ["#2a78d6", "#256abf", "#1c5cab", "#184f95", "#104281", "#0d366b"]  # 450..700
DARK_FROM = FAIL_STEPS[0]

FORMATS = ["f32", "bf16", "f16", "e4m3", "int8", "int8_row", "int8_mode", "int4_g"]
FORMAT_LABEL = {"f32": "float32", "bf16": "bfloat16", "f16": "float16", "e4m3": "float8 E4M3",
                "int8": "int8 tensor", "int8_row": "int8 row", "int8_mode": "int8 output",
                "int4_g": "int4 group"}
BIT_GROUPS = [("32", ["f32"]), ("16", ["bf16", "f16"]), ("8", ["e4m3", "int8", "int8_row", "int8_mode"]),
              ("4", ["int4_g"])]

# Rows: (group label, [(quantity, parameterization, row label), ...]); rows absent from a
# model are dropped, rows absent from one mode are drawn as a note in that panel.
def row_groups(kind, raw):
    hyp = [("lengthscales", "natural", "length scales")]
    if raw:
        hyp.append(("lengthscales", "raw", "length scales, raw"))
    hyp.append(("outputscale", "natural", "signal variance"))
    if raw:
        hyp.append(("outputscale", "raw", "signal variance, raw"))
    hyp.append(("noise", "natural", "noise variance"))
    if raw:
        hyp.append(("noise", "raw", "noise variance, raw"))
    hyp.append(("constant", "natural", "constant mean"))
    if kind == "sparse":
        inputs = ("inputs", [("X", "natural", "training inputs X"), ("Z", "natural", "inducing inputs Z")])
        post = ("posterior weights and factors", [("alpha", "natural", "weights α"),
                                                  ("L", "natural", "factor L of Kᵤᵤ"),
                                                  ("LB", "natural", "factor Lʙ"),
                                                  ("Kinv", "natural", "explicit inverse")])
    else:
        inputs = ("training inputs", [("X", "natural", "inputs X")])
        post = ("posterior weights and factor", [("alpha", "natural", "weights α"),
                                                 ("L", "natural", "Cholesky factor L"),
                                                 ("Kinv", "natural", "explicit inverse K⁻¹")])
    return [("hyperparameters", hyp), inputs, post,
            ("transforms", [("input_transform", "natural", "input scaling"),
                            ("output_transform", "natural", "output scaling")])]


# --- data ---------------------------------------------------------------------------------
def _num(v):
    if isinstance(v, bool) or v is None:
        return None
    if isinstance(v, (int, float)):
        return float(v)
    if isinstance(v, str):
        s = v.strip().lower()
        return {"inf": np.inf, "+inf": np.inf, "infinity": np.inf, "-inf": -np.inf}.get(s, np.nan)
    return None


def load_model(problem, n, backend):
    """{(q, param, mode, fmt): [(seed, status, tolerance or None)]}, seeds used."""
    cells, seeds = {}, []
    for path in sorted(RESULTS.glob(f"{problem}_n{n}_s*_{backend}.json")):
        r = json.loads(path.read_text(encoding="utf-8"))
        if r.get("failed") or not r.get("agree"):
            continue
        seed = int(path.stem.split("_")[-2][1:])
        seeds.append(seed)
        for rec in r.get("records", []):
            if rec.get("record") != "cell":
                continue
            tol = None
            if rec["status"] == "ok":
                sp = rec.get("splits", {}).get(SPLIT)
                tol = sp["tolerance"] if sp else None
            key = (rec["quantity"], rec["parameterization"], rec["mode"], rec["fmt"])
            cells.setdefault(key, []).append((seed, rec["status"], tol))
    return cells, sorted(seeds)


def aggregate(rows):
    """One cell over seeds: worst mean ratio and whether the variance/coverage failed anywhere.

    Precedence: not applicable (a structural property, the same in every seed) > not measured
    (any seed's float64 control missed, so the worst over the seeds is unknown) > failed (any
    seed produced a non-finite or singular result) > measured.
    """
    statuses = {st for _, st, _ in rows}
    if "not_applicable" in statuses:
        return {"state": "na"}
    if "control_failed" in statuses:
        return {"state": "not_measured"}
    if "failed" in statuses:
        return {"state": "failed"}
    tols = [t for _, _, t in rows]
    if any(t is None for t in tols):
        return {"state": "not_measured"}
    ratios = [_num(t["mean_worst_ratio"]) for t in tols]
    ratio = np.nan if any(np.isnan(r) for r in ratios) else max(ratios)
    mean_fail = any(not t["mean"] for t in tols)
    var_fail = any((not t["std"]) or (not t["coverage95"]) for t in tols)
    return {"state": "ok", "ratio": ratio, "mean_fail": mean_fail, "var_fail": var_fail,
            "pass": all(t["pass"] for t in tols)}


# --- drawing ------------------------------------------------------------------------------
def make_cmap():
    # Piecewise: [VMIN, THRESHOLD) over the pass steps, [THRESHOLD, VMAX] over the fail steps.
    norm = LogNorm(VMIN, VMAX)
    t = float(norm(THRESHOLD))
    nodes = []
    for i, c in enumerate(PASS_STEPS):
        nodes.append((t * i / (len(PASS_STEPS) - 1) * 0.999, c))
    for i, c in enumerate(FAIL_STEPS):
        nodes.append((t + (1 - t) * i / (len(FAIL_STEPS) - 1), c))
    cmap = LinearSegmentedColormap.from_list("bits", nodes, N=1024)
    return cmap, norm


def _luminance(hex_):
    rgb = np.array(matplotlib.colors.to_rgb(hex_))
    lin = np.where(rgb <= 0.04045, rgb / 12.92, ((rgb + 0.055) / 1.055) ** 2.4)
    return float(lin @ [0.2126, 0.7152, 0.0722])


GLYPH = {"failed": "✕", "not_measured": "?", "na": "–"}
GAP = 0.08  # surface gap between cells, in cell units


def draw_cell(ax, x, y, cell, cmap, norm):
    w = h = 1 - GAP
    x0, y0 = x + GAP / 2, y + GAP / 2
    if cell["state"] == "ok" and np.isnan(cell["ratio"]):
        cell = {"state": "failed"}  # a NaN mean shift is a non-finite result
    if cell["state"] != "ok":
        ax.add_patch(Rectangle((x0, y0), w, h, facecolor=NEUTRAL, edgecolor="none", linewidth=0))
        ax.text(x + 0.5, y + 0.53, GLYPH[cell["state"]], ha="center", va="center", color=INK2,
                fontsize=6.5 if cell["state"] == "failed" else 7, fontweight="bold")
        return
    r = cell["ratio"]
    fc = cmap(norm(np.clip(r, VMIN, VMAX)))
    ax.add_patch(Rectangle((x0, y0), w, h, facecolor=fc, edgecolor="none", linewidth=0))
    if cell["var_fail"]:
        dark = _luminance(matplotlib.colors.to_hex(fc)) < 0.25
        ax.add_patch(Rectangle((x0, y0), w, h, facecolor="none", edgecolor="none", linewidth=0,
                               hatch="////", hatchcolor=SURFACE if dark else INK2))


def draw_panel(ax, cells, groups, mode, cmap, norm, title, row_labels, row_h, states):
    """Draw one mode's grid. Rows go downward; group headers take their own row."""
    y = 0
    ytick = []
    for gname, items in groups:
        ytick.append((y, gname, True))
        y += 1
        for q, param, label in items:
            have = [cells.get((q, param, mode, f)) for f in FORMATS]
            if all(h is None for h in have):
                # This quantity is not rounded in this mode: one note across the row.
                note = "recomputed in float64" if q in ("alpha", "L", "LB", "Kinv") else "not part of this mode"
                ax.text(len(FORMATS) / 2, y + 0.53, note, ha="center", va="center", color=MUTED,
                        fontsize=7, style="italic")
            else:
                for j, f in enumerate(FORMATS):
                    rows = cells.get((q, param, mode, f))
                    cell = aggregate(rows) if rows else {"state": "na"}
                    states.add(cell["state"] if cell["state"] != "ok" or not np.isnan(cell["ratio"]) else "failed")
                    if cell.get("var_fail"):
                        states.add("hatch")
                    draw_cell(ax, j, y, cell, cmap, norm)
            ytick.append((y, label, False))
            y += 1
        y += 0.35  # breathing room between groups
    ax.set_xlim(-0.05, len(FORMATS) + 0.05)
    ax.set_ylim(y - 0.35, -0.05)
    ax.set_axis_off()
    if row_labels:
        # Group headers start at the figure's left margin and may run into their own empty
        # row of the grid; item labels sit right-aligned against the cells.
        left = matplotlib.transforms.blended_transform_factory(ax.figure.transFigure, ax.transData)
        for yy, lab, is_group in ytick:
            if is_group:
                ax.text(0.08 / ax.figure.get_figwidth(), yy + 0.55, lab, ha="left", va="center",
                        fontsize=7.5, fontweight="bold", color=INK, transform=left, clip_on=False)
            else:
                ax.text(-0.25, yy + 0.55, lab, ha="right", va="center", fontsize=7, color=INK2,
                        clip_on=False)
    # Column labels above: format names, vertical, then the bit groups below the grid.
    for j, f in enumerate(FORMATS):
        ax.text(j + 0.5, -0.35, FORMAT_LABEL[f], rotation=90, ha="center", va="bottom", fontsize=7,
                color=INK2, clip_on=False)
    ybot = y - 0.35 + 0.25
    j = 0
    for bits, fs in BIT_GROUPS:
        a, b = j + 0.12, j + len(fs) - 0.12
        ax.plot([a, a, b, b], [ybot, ybot + 0.25, ybot + 0.25, ybot], color=RULE, lw=0.7,
                clip_on=False, solid_capstyle="butt")
        ax.text((j + j + len(fs)) / 2, ybot + 0.45, bits, ha="center", va="top", fontsize=7,
                color=INK2, clip_on=False)
        j += len(fs)
    ax.text(len(FORMATS) / 2, ybot + 1.35, "bits stored per number", ha="center", va="top",
            fontsize=7, color=INK2, clip_on=False)
    head, sub = title
    ytitle = -(TOP - 0.03 - (0 if sub else 0.18)) / row_h
    ax.text(len(FORMATS) / 2, ytitle, head, ha="center", va="top", fontsize=8, color=INK,
            fontweight="bold", clip_on=False)
    if sub:
        ax.text(len(FORMATS) / 2, ytitle + 0.16 / row_h, sub, ha="center", va="top", fontsize=7,
                color=INK2, clip_on=False)
    return y - 0.35


def n_rows(groups):
    return sum(1 + len(items) for _, items in groups) + 0.35 * (len(groups) - 1)


def draw_legend(fig, rect, cmap, norm):
    """Colour bar with the threshold, then the hatch and glyph keys, in one strip."""
    cax = fig.add_axes(rect)
    grad = np.logspace(np.log10(VMIN), np.log10(VMAX), 512)[None, :]
    cax.imshow(grad, aspect="auto", cmap=cmap, norm=norm,
               extent=[np.log10(VMIN), np.log10(VMAX), 0, 1], interpolation="nearest")
    cax.set_xlim(np.log10(VMIN), np.log10(VMAX))
    cax.set_yticks([])
    ticks = [-4, -2, -1, 0, 2, 4]
    cax.set_xticks(ticks)
    cax.set_xticklabels(["≤ 10⁻⁴", "0.01", "0.1", "1", "100", "≥ 10⁴"], fontsize=7, color=INK2)
    cax.tick_params(axis="x", length=2, width=0.6, color=RULE, pad=1.5)
    for s in cax.spines.values():
        s.set_visible(False)
    t = np.log10(THRESHOLD)
    cax.plot([t, t], [-0.35, 1.35], color=INK, lw=1.2, clip_on=False)
    cax.text(t - 0.12, 1.45, "mean passes", ha="right", va="bottom", fontsize=7, color=INK2)
    cax.text(t + 0.12, 1.45, "mean fails", ha="left", va="bottom", fontsize=7, color=INK2)
    cax.set_xlabel("rounding shift of the predictive mean ÷ model error against truth\n"
                   "(worst output, worst seed; threshold 0.1)", fontsize=7, color=INK2, labelpad=2)
    return cax


def draw_keys(fig, x, y, dy, states):
    """Hatch and glyph keys, stacked, at figure coordinates (x, y) going down."""
    entries = [("hatch", "standard deviation or 95 % coverage fails"),
               ("failed", "rounding failed (non-finite or singular)"),
               ("not_measured", "not measured (float64 control missed)"),
               ("na", "not applicable to this quantity")]
    entries = [e for e in entries if e[0] in states]  # key only what the figure shows
    ax = fig.add_axes([x, y - 4 * dy, 0.3, 4 * dy + 0.02])
    ax.set_axis_off()
    ax.set_xlim(0, 10)
    ax.set_ylim(4.2, -0.2)
    for i, (kind, text) in enumerate(entries):
        x0, y0, w, h = 0, i + 0.1, 0.9, 0.8
        if kind == "hatch":
            ax.add_patch(Rectangle((x0, y0), w, h, facecolor=PASS_STEPS[1], edgecolor="none"))
            ax.add_patch(Rectangle((x0, y0), w, h, facecolor="none", edgecolor="none", hatch="////",
                                   hatchcolor=INK2))
        else:
            ax.add_patch(Rectangle((x0, y0), w, h, facecolor=NEUTRAL, edgecolor="none"))
            ax.text(x0 + w / 2, y0 + h / 2 + 0.03, GLYPH[kind], ha="center", va="center", fontsize=6.5 if kind == "failed" else 7,
                    fontweight="bold", color=INK2)
        ax.text(1.25, i + 0.5, text, ha="left", va="center", fontsize=7, color=INK2)
    return ax


def _style():
    plt.rcParams.update({
        "font.family": "DejaVu Sans", "font.size": 7, "hatch.linewidth": 0.6,
        "pdf.fonttype": 42, "svg.fonttype": "none", "axes.facecolor": SURFACE,
        "figure.facecolor": SURFACE, "savefig.facecolor": SURFACE,
    })


def save(fig, stem, out=None):
    out = OUT if out is None else out
    out.mkdir(parents=True, exist_ok=True)
    fig.savefig(out / f"{stem}.pdf", metadata={"CreationDate": None, "ModDate": None, "Creator": None,
                                              "Producer": None})
    fig.savefig(out / f"{stem}.png", dpi=300, metadata={"Software": None})
    plt.close(fig)
    print("wrote", out / f"{stem}.pdf", "and .png")


# --- figures ------------------------------------------------------------------------------
W = 7.0          # double column, inches
LABEL_W = 1.30   # row-label column, inches
PANEL_GAP = 0.25
TOP = 1.05       # panel title + vertical format names
BOTTOM = 0.45    # bit brackets and their label


def model_block(fig, y_top, cells, groups, cmap, norm, row_h, titles, states):
    """Two panels (stored | consistent) for one model, top at y_top inches from the top."""
    H = fig.get_figheight()
    rows = n_rows(groups)
    ph = rows * row_h
    pw = (W - LABEL_W - PANEL_GAP - 0.1) / 2
    axes = []
    for k, (mode, title) in enumerate(zip(("stored", "consistent"), titles)):
        left = LABEL_W + k * (pw + PANEL_GAP)
        ax = fig.add_axes([left / W, (H - y_top - TOP - ph) / H, pw / W, ph / H])
        draw_panel(ax, cells, groups, mode, cmap, norm, title, (k == 0), row_h, states)
        axes.append(ax)
    return TOP + ph + BOTTOM


def figS1():
    """The full quantity x format map for the main model (first draft of figure 1)."""
    cells, seeds = load_model("heterogeneous", 256, "dense")
    if not cells:
        raise SystemExit("no heterogeneous n=256 dense results under " + str(RESULTS))
    _style()
    cmap, norm = make_cmap()
    groups = row_groups("dense", raw=False)
    row_h = 0.175
    block_h = TOP + n_rows(groups) * row_h + BOTTOM
    legend_h = 0.95
    H = block_h + legend_h
    fig = plt.figure(figsize=(W, H))
    states = set()
    model_block(fig, 0.0, cells, groups, cmap, norm, row_h,
                (("Stored mode", "round one quantity, serve the rest as fitted"),
                 ("Consistent mode", "round one quantity, recompute α and L in float64")), states)
    # legend strip: colour bar on the left half, keys on the right half
    ly = (legend_h - 0.42) / H
    draw_legend(fig, [LABEL_W / W, ly, 2.55 / W, 0.11 / H], cmap, norm)
    draw_keys(fig, (LABEL_W + 2.95) / W, (legend_h - 0.12) / H, 0.14 / H, states)
    save(fig, "figS1_where_the_bits_go_map")
    return seeds


def figS2():
    """The map for every model with results, raw parameterization included."""
    models = [("heterogeneous", 256, "dense", "Heterogeneous (6 → 8), n = 256, dense exact GP"),
              ("forrester", 256, "dense", "Forrester (1 → 1), n = 256, dense exact GP"),
              ("heterogeneous", 256, "sparse", "Heterogeneous (6 → 8), n = 256, sparse GP, m = 64")]
    _style()
    cmap, norm = make_cmap()
    row_h = 0.15
    blocks = []
    for problem, n, backend, name in models:
        cells, seeds = load_model(problem, n, backend)
        if not cells:
            print(f"figS2: no results for {problem} n={n} {backend}; block skipped")
            continue
        blocks.append((cells, seeds, row_groups(backend, raw=True), name))
    if not blocks:
        raise SystemExit("figS2: no results")
    head = 0.28
    heights = [head + TOP + n_rows(g) * row_h + BOTTOM for _, _, g, _ in blocks]
    legend_h = 0.95
    H = sum(heights) + legend_h
    fig = plt.figure(figsize=(W, H))
    states = set()
    y = 0.0
    for (cells, seeds, groups, name), bh in zip(blocks, heights):
        seed_txt = ", ".join(str(s) for s in seeds)
        fig.text(0.1 / W, 1 - (y + 0.05) / H, f"{name}   (seeds {seed_txt})", ha="left", va="top",
                 fontsize=8, fontweight="bold", color=INK)
        model_block(fig, y + head, cells, groups, cmap, norm, row_h,
                    (("Stored mode", None), ("Consistent mode", None)), states)
        y += bh
    ly = (legend_h - 0.42) / H
    draw_legend(fig, [LABEL_W / W, ly, 2.55 / W, 0.11 / H], cmap, norm)
    draw_keys(fig, (LABEL_W + 2.95) / W, (legend_h - 0.12) / H, 0.14 / H, states)
    save(fig, "figS2_where_the_bits_go_other_models")
    return [b[1] for b in blocks]


# --- figure 1: the consequence (a) and the rule (b) -----------------------------------------
STORED_C = "#2a78d6"     # categorical slot 1 (blue): stored as fitted
RECOMP_C = "#eb6834"     # categorical slot 2 (orange): recomputed after rounding
TRUTH_C = "#898781"      # muted ink for the truth
FMT_BITS_NAME = {"f64": "64", "f32": "32", "f16": "16", "e4m3": "8"}
A_STEM = "forrester_n32_s7_dense"


def _forrester(x):
    return (6 * x - 2) ** 2 * np.sin(12 * x - 4)


def load_curves():
    """Reference, rounded copies and their predictions on a 400-point grid (forrester n=32, seed 7)."""
    import os
    import warnings
    if str(HERE) not in sys.path:
        sys.path.insert(0, str(HERE))
    import extract
    import predictive
    import quantize
    import reference
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        model, arrays, payload = reference.load_reference(A_STEM)
        q = extract.extract(model, train_x_reg=payload["train"]["x_reg"], train_y_reg=payload["train"]["y_reg"])
    xg = np.linspace(0.0, 1.0, 400)
    Xt, Yt = arrays["X_test"], arrays["Y_test"][:, 0]

    def run(qq, X):
        o = predictive.predict(qq, X)
        return o["mean_phys"].reshape(-1), o["var_phys"].reshape(-1)

    m0t, _ = run(q, Xt)
    err0 = float(np.sqrt(np.mean((m0t - Yt) ** 2)))
    out = {"x": xg, "truth": _forrester(xg), "err0": err0,
           "train_x": payload["train"]["x_reg"][:, 0] if "x_reg" in payload["train"] else None}
    # physical training targets: the truth at the training inputs (noise-free problem)
    out["train_y"] = _forrester(out["train_x"])
    cases = {}
    for name, fmt in [(None, "f64"), ("alpha", "f32"), ("alpha", "f16"), ("alpha", "e4m3"),
                      ("L", "f32"), ("L", "f16"), ("L", "e4m3")]:
        qq = q if name is None else quantize.round_quantity(q, name, fmt)
        m, v = run(qq, xg[:, None])
        mt, _ = run(qq, Xt)
        cases[(name, fmt)] = {"mean": m, "var": v, "neg_frac": float(np.mean(v < 0)),
                              "err_ratio": float(np.sqrt(np.mean((mt - Yt) ** 2))) / err0}
    out["cases"] = cases
    return out


def draw_curve(ax_top, ax_bot, data, case, title, big=False):
    """Top: the curve at full scale. Bottom: the same, minus the truth, zoomed in."""
    x, truth = data["x"], data["truth"]
    m, v = case["mean"], case["var"]
    sd = np.sqrt(np.clip(v, 0, None))   # negative variance is drawn as a zero-width band
    fs = 9 if big else 7
    for ax in (ax_top, ax_bot):
        ax.set_facecolor(SURFACE)
        for k in ("top", "right"):
            ax.spines[k].set_visible(False)
        for k in ("left", "bottom"):
            ax.spines[k].set_color(RULE)
            ax.spines[k].set_linewidth(0.6)
        ax.tick_params(colors=INK2, labelsize=fs, length=2, width=0.6)
        ax.set_xlim(0, 1)
    ax_top.plot(x, truth, color=TRUTH_C, lw=0.8, zorder=1)
    ax_top.fill_between(x, m - 1.96 * sd, m + 1.96 * sd, color=STORED_C, alpha=0.18, lw=0, zorder=2)
    ax_top.plot(x, m, color=STORED_C, lw=1.4, zorder=3, solid_capstyle="round")
    ax_top.plot(data["train_x"], data["train_y"], "o", ms=2.6, color=INK, mec=SURFACE, mew=0.5, zorder=4)
    ax_top.set_ylim(-12, 22)
    ax_top.set_xticklabels([])
    if np.max(np.abs(m - truth)) > 12:
        ax_top.text(0.03, 0.04, "curve leaves the chart", transform=ax_top.transAxes, fontsize=fs,
                    color=INK2, ha="left", va="bottom")
    r = m - truth
    ax_bot.axhline(0, color=TRUTH_C, lw=0.8, zorder=1)
    ax_bot.fill_between(x, r - 1.96 * sd, r + 1.96 * sd, color=STORED_C, alpha=0.18, lw=0, zorder=2)
    ax_bot.plot(x, r, color=STORED_C, lw=1.4, zorder=3, solid_capstyle="round")
    ax_bot.plot(data["train_x"], np.zeros_like(data["train_x"]), "o", ms=2.6, color=INK, mec=SURFACE,
                mew=0.5, zorder=4)
    ax_bot.set_ylim(-0.05, 0.05)
    ax_bot.set_yticks([-0.04, 0, 0.04])
    ax_bot.set_yticklabels(["−0.04", "0", "0.04"])
    ax_bot.set_xticks([0, 0.5, 1])
    ax_bot.set_xticklabels(["0", "0.5", "1"])
    ax_top.set_title(title, fontsize=fs + 0.5, color=INK, loc="left", pad=4)


def _a_titles(data):
    c = data["cases"]
    return [((None, "f64"), "everything at 64 bits:\nthe reference"),
            (("alpha", "f32"), f"weights at 32 bits: the curve is off,\n"
                               f"{c[('alpha', 'f32')]['err_ratio']:.1f}× the 64-bit error"),
            (("L", "f32"), "uncertainty factor at 32 bits:\nthe band collapses")]


def draw_bits_bars(ax):
    """Fewest bits per number that pass all three tests in every seed (heterogeneous n=256 dense)."""
    cells, seeds = load_model("heterogeneous", 256, "dense")
    if not cells:
        raise SystemExit("no heterogeneous n=256 dense results under " + str(RESULTS))

    def fewest(q, mode):
        best = 64
        for f in FORMATS:
            rows = cells.get((q, "natural", mode, f))
            if rows and all(st == "ok" and t is not None and t["pass"] for _, st, t in rows):
                best = min(best, int(BITS[f]))
        return best

    groups = [("hyperparameters", ["lengthscales", "outputscale", "constant"], True),
              ("training inputs", ["X"], True),
              ("weights α", ["alpha"], False),
              ("uncertainty factor L", ["L"], False),
              ("output scaling", ["output_transform"], False)]
    rows = []
    for label, qs, has_consistent in groups:
        stored = max(fewest(q, "stored") for q in qs)
        recomp = max(fewest(q, "consistent") for q in qs) if has_consistent else None
        rows.append((label, stored, recomp))
    bh = 0.30
    y = 0.0
    yt = []
    for label, stored, recomp in rows:
        bars = [(stored, STORED_C)] + ([(recomp, RECOMP_C)] if recomp is not None else [])
        n = len(bars)
        for i, (b, c) in enumerate(bars):
            yy = y + (i - (n - 1) / 2) * (bh + 0.10)
            ax.barh(yy, b, height=bh, color=c, lw=0)
            ax.text(b + 0.8, yy, f"{b} bits", va="center", ha="left", fontsize=7, color=INK2)
        yt.append((y, label))
        y += 0.85 + (0.30 if n == 2 else 0)
    ax.set_yticks([p for p, _ in yt])
    ax.set_yticklabels([l for _, l in yt], fontsize=7.5, color=INK)
    ax.invert_yaxis()
    ax.set_xlim(0, 72)
    ax.set_xticks([0, 8, 16, 32, 64])
    ax.tick_params(axis="x", colors=INK2, labelsize=7, length=2, width=0.6)
    ax.tick_params(axis="y", length=0, pad=4)
    ax.xaxis.grid(True, color="#e1e0d9", lw=0.5)
    ax.set_axisbelow(True)
    for k in ("top", "right", "left"):
        ax.spines[k].set_visible(False)
    ax.spines["bottom"].set_color(RULE)
    ax.spines["bottom"].set_linewidth(0.6)
    ax.set_xlabel("fewest bits per stored number that still give the right answer (float64 = 64)",
                  fontsize=7, color=INK2, labelpad=3)
    return rows, seeds


BITS = {"f64": 64, "f32": 32, "bf16": 16, "f16": 16, "e4m3": 8, "int8": 8, "int8_row": 8,
        "int8_mode": 8, "int4_g": 4}


def fig1():
    _style()
    data = load_curves()
    fig = plt.figure(figsize=(W, 5.6))
    # (a) three columns, each a full-scale curve over a zoomed difference strip
    left, right, gap = 0.62, 0.15, 0.30
    pw = (W - left - right - 2 * gap) / 3
    H = 5.6
    top_y, top_h, bot_h, vgap = 0.50, 0.95, 0.95, 0.10
    for k, (key, title) in enumerate(_a_titles(data)):
        x0 = left + k * (pw + gap)
        at = fig.add_axes([x0 / W, 1 - (top_y + top_h) / H, pw / W, top_h / H])
        ab = fig.add_axes([x0 / W, 1 - (top_y + top_h + vgap + bot_h) / H, pw / W, bot_h / H])
        draw_curve(at, ab, data, data["cases"][key], title)
        ab.set_xlabel("input x", fontsize=7, color=INK2, labelpad=1)
        if k == 0:
            at.set_ylabel("output y", fontsize=7, color=INK2)
            ab.set_ylabel("minus truth", fontsize=7, color=INK2)
        else:
            at.set_yticklabels([])
            ab.set_yticklabels([])
    fig.text(0.08 / W, 1 - 0.08 / H, "a", fontsize=10, fontweight="bold", va="top", color=INK)
    fig.text(0.30 / W, 1 - 0.09 / H, "What goes wrong: one input, 32 training points, noise-free",
             fontsize=8, va="top", color=INK)
    # key for (a), one line under the panels
    ky = top_y + top_h + vgap + bot_h + 0.40
    kx = left
    kax = fig.add_axes([kx / W, 1 - (ky + 0.08) / H, (W - kx - right) / W, 0.16 / H])
    kax.set_axis_off()
    kax.set_xlim(0, 100)
    kax.set_ylim(0, 1)
    kax.plot([0, 3], [0.5, 0.5], color=TRUTH_C, lw=0.8)
    kax.text(4, 0.5, "truth", va="center", fontsize=7, color=INK2)
    kax.plot([12, 15], [0.5, 0.5], color=STORED_C, lw=1.4)
    kax.text(16, 0.5, "prediction", va="center", fontsize=7, color=INK2)
    kax.add_patch(Rectangle((28, 0.15), 3, 0.7, color=STORED_C, alpha=0.18, lw=0))
    kax.text(32, 0.5, "95 % band", va="center", fontsize=7, color=INK2)
    kax.plot([43.5], [0.5], "o", ms=2.6, color=INK)
    kax.text(45, 0.5, "training points", va="center", fontsize=7, color=INK2)
    kax.text(62, 0.5, "lower strip: prediction minus truth, zoomed in", va="center", fontsize=7,
             color=INK2)
    # (b)
    by = ky + 0.30
    fig.text(0.08 / W, 1 - by / H, "b", fontsize=10, fontweight="bold", va="top", color=INK)
    fig.text(0.30 / W, 1 - (by + 0.01) / H,
             "How many bits each part needs: six inputs, eight outputs, 256 points, noise floor 10⁻⁶ (nearly noise-free)",
             fontsize=8, va="top", color=INK)
    b_left = 1.45
    bax = fig.add_axes([b_left / W, 0.78 / H, (W - b_left - 0.9) / W, (H - by - 0.78 - 0.50) / H])
    rows, seeds = draw_bits_bars(bax)
    # legend for (b): two swatches, top right of the bar area
    lx = b_left / W
    for i, (c, t) in enumerate([(STORED_C, "stored as fitted"), (RECOMP_C, "recomputed after rounding")]):
        yy = 1 - (by + 0.33) / H
        lxi = lx + i * 1.45 / W
        fig.patches.append(Rectangle((lxi, yy - 0.035 / H), 0.12 / W, 0.09 / H, color=c, lw=0,
                                     transform=fig.transFigure, figure=fig))
        fig.text(lxi + 0.18 / W, yy + 0.01 / H, t, fontsize=7, color=INK2, va="center")
    fig.text(b_left / W, 0.06 / H,
             "pass = mean within a tenth of the model's own error, standard deviation within 10 %,\n"
             "coverage within one point, on every output and seed",
             fontsize=7, color=INK2, va="bottom", linespacing=1.3)
    save(fig, "fig1_where_the_bits_go")
    c = data["cases"]
    print("fig1(a): 64-bit test RMSE %.3g; weights f32 error ratio %.3g; factor f32 variance negative at %.0f %% of grid"
          % (data["err0"], c[("alpha", "f32")]["err_ratio"], 100 * c[("L", "f32")]["neg_frac"]))
    print("fig1(b): seeds", seeds, "rows", rows)


def fig1a_gif():
    from PIL import Image
    _style()
    data = load_curves()
    seq = [("alpha", f) for f in ("f64", "f32", "f16", "e4m3")] + [("L", f) for f in ("f64", "f32", "f16", "e4m3")]
    frames = []
    for name, fmt in seq:
        key = (None, "f64") if fmt == "f64" else (name, fmt)
        case = data["cases"][key]
        fig = plt.figure(figsize=(6.4, 4.2), dpi=110)
        at = fig.add_axes([0.11, 0.42, 0.85, 0.40])
        ab = fig.add_axes([0.11, 0.12, 0.85, 0.24])
        what = "weights α" if name == "alpha" else "uncertainty factor L"
        draw_curve(at, ab, data, case, "", big=True)
        ab.set_xlabel("input x", fontsize=9, color=INK2)
        at.set_ylabel("output y", fontsize=9, color=INK2)
        ab.set_ylabel("minus truth", fontsize=9, color=INK2)
        fig.text(0.11, 0.955, f"{what} stored at {FMT_BITS_NAME[fmt]} bits", fontsize=16,
                 fontweight="bold", color=INK, va="top")
        if fmt == "f64":
            note = "full precision"
        elif name == "alpha":
            er = case["err_ratio"]
            note = f"error {er:,.0f}× the 64-bit model's" if er >= 100 else f"error {er:.1f}× the 64-bit model's"
        else:
            note = f"variance negative at {100 * case['neg_frac']:.0f} % of points: no band left"
        fig.text(0.11, 0.875, note, fontsize=10, color=INK2, va="top")
        fig.canvas.draw()
        img = Image.frombuffer("RGBA", fig.canvas.get_width_height(), fig.canvas.buffer_rgba()).convert("RGB")
        frames.append(img.quantize(colors=64, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE))
        plt.close(fig)
    OUT.mkdir(exist_ok=True)
    path = OUT / "fig1a_bits_counting_down.gif"
    frames[0].save(path, save_all=True, append_images=frames[1:], duration=2500, loop=0, optimize=False)
    print("wrote", path, f"{path.stat().st_size / 1e6:.2f} MB")


# --- figure 2: the noise floor sets the bits (a), the first-order rule predicts the mean shift (b)
REFS = HERE / "results" / "reference"
# Plain-words names of the study's problems, in the order captions list them.
PROBLEM_DESC = {"forrester": "a one-input synthetic problem",
                "heterogeneous": "a six-input, eight-output synthetic problem (dense at every noise floor, "
                                 "and sparse)",
                "het_tanh": "the same problem's sharpest output alone",
                "hilift": "HiLift, real data (dense at both budgets, and sparse)",
                "thermo8": "a synthetic eight-input field model with 12 modes"}
FIG2_SEEDS = (7, 19, 43)
FIG2_STEM = "fig2_noise_floor_sets_the_bits"
# Categorical slots 1-3 of palette.md in order, then a dark plum chosen by search to clear every
# pair with them (normal vision >= 15, each simulated deficiency >= 8; --check-palette): all four
# lines share panel (a), so every pair counts. palette.md's slot 4 (yellow) failed orange (13.7).
FIG2_LINES = [("alpha", ["alpha"], "weights α", "#2a78d6"),
              ("X", ["X"], "training inputs X", "#eb6834"),
              ("hyper", ["lengthscales", "outputscale", "constant"], "hyperparameters", "#1baf7a"),
              ("L", ["L"], "uncertainty factor L", "#8c304c")]
FIG2_COLOR = {k: c for k, _, _, c in FIG2_LINES}
FIG2_SCATTER = [("alpha", "alpha", "weights α"), ("X", "X", "training inputs X"),
                ("lengthscales", "hyper", "length scales")]
FLOAT_FORMATS = ["f32", "bf16", "f16", "e4m3"]
GRID_C = "#e1e0d9"


def _floor_label(floor):
    m, e = f"{float(floor):.0e}".split("e")
    sup = str.maketrans("-0123456789", "⁻⁰¹²³⁴⁵⁶⁷⁸⁹")
    return (f"{m}×" if m != "1" else "") + "10" + str(int(e)).translate(sup)


def _fig2_datasets():
    """The (a) ladder: heterogeneous n=256 dense at every noise floor with a reference or a
    result, then HiLift. Floors sort by value; 1e-6 is the protocol's default (no suffix)."""
    floors = set()
    for d in (RESULTS, REFS):
        for p in d.glob("heterogeneous_n256_s*_dense_nf*.json"):
            floors.add(p.stem.rsplit("_nf", 1)[1])
    sets = [{"key": "heterogeneous_nf1e-6", "problem": "heterogeneous", "n": 256, "suffix": "dense",
             "floor": "1e-6", "name": f"synthetic\nfloor {_floor_label('1e-6')}",
             "tag": f"synthetic,\nfloor {_floor_label('1e-6')}"}]
    for f in sorted(floors, key=float):
        sets.append({"key": f"heterogeneous_nf{f}", "problem": "heterogeneous", "n": 256,
                     "suffix": f"dense_nf{f}", "floor": f, "name": f"synthetic\nfloor {_floor_label(f)}",
                     "tag": f"floor\n{_floor_label(f)}"})
    sets.append({"key": "hilift", "problem": "hilift", "n": 1080, "suffix": "dense_shipped", "floor": "1e-6",
                 "compare_suffix": "dense",
                 "name": "HiLift\nreal data", "tag": "real data:\nHiLift"})
    for s in sets:
        s["stems"] = [f"{s['problem']}_n{s['n']}_s{seed}_{s['suffix']}" for seed in FIG2_SEEDS]
    return sets


def _load_result(stem):
    path = RESULTS / f"{stem}.json"
    if not path.exists():
        return None
    r = json.loads(path.read_text(encoding="utf-8"))
    return None if r.get("failed") or not r.get("agree") else r


def _noise_to_signal(stem):
    """Median over output modes of fitted noise variance / fitted signal variance. The noise
    variance itself is in standardized output units (outputs scaled to unit variance)."""
    ref = json.loads((REFS / f"{stem}.json").read_text(encoding="utf-8"))
    h = ref["hyperparameters"]
    noise = np.asarray(h["noise"], float)
    scale = np.asarray(h["outputscale"], float)
    with np.errstate(divide="ignore"):
        per_mode = noise / scale
    return float(np.median(per_mode)), per_mode.tolist(), noise.tolist(), scale.tolist()


def _fewest_bits(cells, quantities):
    """Worst over `quantities` of the lowest-bit format passing in every seed (summarize's rule)."""
    out = {}
    for q in quantities:
        best, best_fmt = 64, "f64"
        for f in FORMATS:
            rows = cells.get((q, f))
            if rows and len(rows) == len(FIG2_SEEDS) and all(st == "ok" and t is not None and t["pass"]
                                                             for st, t in rows):
                if BITS[f] < best:
                    best, best_fmt = BITS[f], f
        out[q] = (best, best_fmt)
    worst = max(out.values(), key=lambda v: v[0])
    return worst[0], {q: {"bits": b, "format": f} for q, (b, f) in out.items()}


def fig2_data():
    sets = _fig2_datasets()
    panel_a, pending = [], []
    for s in sets:
        results = {st: _load_result(st) for st in s["stems"]}
        refs = [st for st in s["stems"] if (REFS / f"{st}.json").exists()]
        if any(r is None for r in results.values()) or len(refs) != len(s["stems"]):
            pending.append({"data_set": s["key"], "noise_floor": s["floor"],
                            "seeds_with_results": [st for st, r in results.items() if r is not None],
                            "seeds_with_reference": refs})
            continue
        cells = {}
        for st, r in results.items():
            for rec in r["records"]:
                if (rec.get("record") != "cell" or rec["mode"] != "stored"
                        or rec["parameterization"] != "natural"):
                    continue
                t = rec["splits"].get(SPLIT, {}).get("tolerance") if rec["status"] == "ok" else None
                cells.setdefault((rec["quantity"], rec["fmt"]), []).append((rec["status"], t))
        ratios = {st: _noise_to_signal(st) for st in s["stems"]}
        point = {"data_set": s["key"], "label": s["name"].replace("\n", ", "), "tag": s["tag"],
                 "noise_floor": s["floor"],
                 "stems": s["stems"],
                 "fitted_noise_variance": float(np.median([np.median(v[2]) for v in ratios.values()])),
                 "fitted_signal_variance_range": [float(min(min(v[3]) for v in ratios.values())),
                                                  float(max(max(v[3]) for v in ratios.values()))],
                 "noise_to_signal": float(np.median([v[0] for v in ratios.values()])),
                 "noise_to_signal_per_seed": {st: {"median_over_modes": v[0], "per_mode": v[1],
                                                   "fitted_noise": v[2], "fitted_signal_variance": v[3]}
                                              for st, v in ratios.items()},
                 "bits": {}}
        for key, qs, label, _ in FIG2_LINES:
            b, detail = _fewest_bits(cells, qs)
            point["bits"][key] = {"label": label, "fewest_bits_all_seeds": b, "per_quantity": detail}
        st0 = json.loads((REFS / f"{s['stems'][0]}.json").read_text(encoding="utf-8"))["settings"]
        point["budget"] = {"restarts": st0["restarts"], "max_iter": st0["max_iter"], "name": st0.get("budget")}
        if s.get("compare_suffix"):
            # The same problem at another budget, for the caption's comparison only (not drawn).
            cstems = [f"{s['problem']}_n{s['n']}_s{seed}_{s['compare_suffix']}" for seed in FIG2_SEEDS]
            cres = {st: _load_result(st) for st in cstems}
            if all(r is not None for r in cres.values()):
                ccells = {}
                for r in cres.values():
                    for rec in r["records"]:
                        if (rec.get("record") == "cell" and rec["mode"] == "stored"
                                and rec["parameterization"] == "natural"):
                            t = rec["splits"].get(SPLIT, {}).get("tolerance") if rec["status"] == "ok" else None
                            ccells.setdefault((rec["quantity"], rec["fmt"]), []).append((rec["status"], t))
                cst = json.loads((REFS / f"{cstems[0]}.json").read_text(encoding="utf-8"))["settings"]
                point["comparison"] = {"stems": cstems,
                                       "budget": {"restarts": cst["restarts"], "max_iter": cst["max_iter"],
                                                  "name": cst.get("budget")},
                                       "bits": {k: _fewest_bits(ccells, qs)[0] for k, qs, _, _ in FIG2_LINES},
                                       "per_quantity": {k: _fewest_bits(ccells, qs)[1] for k, qs, _, _ in FIG2_LINES}}
        panel_a.append(point)

    points, std_checks = [], []
    for path in sorted(RESULTS.glob("*_n*_s*_*.json")):
        r = _load_result(path.stem)
        if r is None:
            continue
        for rec in r["records"]:
            # The factor's variance bound (README) against the measured median std change, float32,
            # dense models at the default floor 1e-6 (no _nf suffix).
            if (rec.get("record") == "cell" and rec["mode"] == "stored" and rec["quantity"] == "L"
                    and rec["fmt"] == "f32" and rec["status"] == "ok" and path.stem.endswith("_dense")
                    and not path.stem.startswith("hilift") and rec.get("first_order")):
                fo = rec["first_order"]
                bnd, msd = _num(fo["std_rel_readme"]["median"]), _num(fo["measured_std_rel"]["median"])
                if bnd and msd:
                    std_checks.append({"stem": path.stem, "bound_median": bnd, "measured_median": msd,
                                       "measured_over_bound": msd / bnd})
            if (rec.get("record") != "cell" or rec["mode"] != "stored" or rec["parameterization"] != "natural"
                    or rec["fmt"] not in FLOAT_FORMATS or rec["status"] != "ok"
                    or rec["quantity"] not in [q for q, _, _ in FIG2_SCATTER]):
                continue
            fo = rec.get("first_order")
            if not fo:
                continue
            pred, meas = _num(fo["rms"]["rms"]), _num(fo["measured_mean_shift"]["rms"])
            ok = pred is not None and meas is not None and np.isfinite(pred) and np.isfinite(meas) \
                and pred > 0 and meas > 0
            points.append({"stem": path.stem, "quantity": rec["quantity"], "fmt": rec["fmt"],
                           "predicted_rms": pred, "measured_rms": meas,
                           "readme_bound_rms": _num(fo["bound"]["rms"]),
                           "ratio": pred / meas if ok else None, "plotted": bool(ok)})
    ratios = np.array([p["ratio"] for p in points if p["plotted"]])
    plotted = [p for p in points if p["plotted"]]
    bound = np.array([p["readme_bound_rms"] / p["measured_rms"] for p in plotted])
    window = (1e-4, 1e-2)
    in_window = np.array([p["ratio"] for p in plotted if window[0] <= p["measured_rms"] <= window[1]])
    worst = min(plotted, key=lambda p: p["ratio"])

    def stats(rr):
        return {"n": int(rr.size), "median": float(np.median(rr)), "p10": float(np.percentile(rr, 10)),
                "p90": float(np.percentile(rr, 90)), "min": float(rr.min()), "max": float(rr.max()),
                "p90_factor_either_way": float(np.percentile(np.maximum(rr, 1 / rr), 90))}
    by_q = {q: stats(np.array([p["ratio"] for p in points if p["plotted"] and p["quantity"] == q]))
            for q, _, _ in FIG2_SCATTER}
    mob = np.array([c["measured_over_bound"] for c in std_checks])
    return {"split": SPLIT, "mode": "stored", "seeds": list(FIG2_SEEDS),
            "pass_rule": "mean shift < 0.1 x model error against truth, median std change < 10 %, "
                         "95 % coverage change < 1 point; every output, every seed",
            "x_axis": "fitted_noise_variance: fitted likelihood noise variance in standardized output "
                      "units (outputs scaled to unit variance before fitting), median over outputs, then "
                      "median over seeds (results/reference/<stem>.json hyperparameters.noise)",
            "noise_to_signal_source": "results/reference/<stem>.json hyperparameters: fitted noise / "
                                      "fitted outputscale per mode, median over modes; median over seeds",
            "panel_a": panel_a, "panel_a_pending": pending,
            "panel_b": {"predicted": "first_order.rms.rms: RMS first-order estimate of the mean shift, "
                                     "independent rounding errors uniform on +-u|x| (u the format's unit "
                                     "roundoff), from the sensitivity model's derivatives",
                        "measured": "first_order.measured_mean_shift.rms: RMS over test points and outputs "
                                    "of the shift of the predictive mean, standardized units",
                        "readme_bound_over_measured": {"n": int(bound.size), "min": float(bound.min()),
                                                       "median": float(np.median(bound)),
                                                       "n_below_1": int((bound < 1).sum())},
                        "measured_window": list(window),
                        "ratio_stats_in_window": stats(in_window),
                        "largest_underestimate": {k: worst[k] for k in ("stem", "quantity", "fmt",
                                                                        "predicted_rms", "measured_rms",
                                                                        "ratio")},
                        "factor_variance_bound_f32_floor_1e-6": {
                            "source": "first_order.std_rel_readme.median vs measured_std_rel.median, L at "
                                      "float32, stored mode, dense models at noise floor 1e-6",
                            "measured_over_bound_min": float(mob.min()), "measured_over_bound_max": float(mob.max()),
                            "cells": std_checks},
                        "units": "standardized output (coefficient) units, rms over test points",
                        "formats": FLOAT_FORMATS, "ratio_stats": stats(ratios), "ratio_stats_by_quantity": by_q,
                        "n_not_plotted": sum(not p["plotted"] for p in points), "points": points}}


def _spread(targets, gap):
    """Positions as close to `targets` as possible, at least `gap` apart, order kept."""
    order = np.argsort(targets, kind="stable")
    pos = np.array(targets, float)[order]
    for _ in range(200):
        moved = False
        for i in range(1, len(pos)):
            d = pos[i] - pos[i - 1]
            if d < gap - 1e-9:
                shift = (gap - d) / 2
                pos[i - 1] -= shift
                pos[i] += shift
                moved = True
        if not moved:
            break
    out = np.empty_like(pos)
    out[order] = pos
    return out


def _axes_style(ax):
    for k in ("top", "right"):
        ax.spines[k].set_visible(False)
    for k in ("left", "bottom"):
        ax.spines[k].set_color(RULE)
        ax.spines[k].set_linewidth(0.6)
    ax.tick_params(colors=INK2, labelsize=7, length=2, width=0.6)
    ax.set_axisbelow(True)


def _sup_decade(e):
    return "1" if e == 0 else "10" + str(e).translate(str.maketrans("-0123456789", "⁻⁰¹²³⁴⁵⁶⁷⁸⁹"))


FIG2_JITTER = 0.075  # decades between markers that share a setting and a bit count


def _jittered(pts, x_of):
    """log10 x per line and point: markers tied on (setting, bits) are spread horizontally,
    centred on the setting's x, so every marker stays exactly on its bit count."""
    out = {key: [] for key, _, _, _ in FIG2_LINES}
    for p in pts:
        x0 = np.log10(x_of(p))
        by_bits = {}
        for key, _, _, _ in FIG2_LINES:
            by_bits.setdefault(p["bits"][key]["fewest_bits_all_seeds"], []).append(key)
        for keys in by_bits.values():
            for j, key in enumerate(keys):
                out[key].append(x0 + (j - (len(keys) - 1) / 2) * FIG2_JITTER)
    return out


def draw_fig2a(ax, ax_h, data, decades_per_inch):
    """(a) on two axes sharing the bit scale: the synthetic noise-floor ladder (ax) and, past a
    divider, HiLift (ax_h), a different problem on real data; same x units and scale."""
    pts = data["panel_a"]
    syn = [p for p in pts if p["data_set"] != "hilift"]
    hil = [p for p in pts if p["data_set"] == "hilift"]
    fig = ax.figure
    x_of = lambda p: p["fitted_noise_variance"]  # noqa: E731
    for a in (ax, ax_h):
        _axes_style(a)
        a.set_xscale("log")
        a.set_ylim(np.log2(4) - 0.35, np.log2(64) + 0.35)
        a.set_yticks(np.log2([4, 8, 16, 32, 64]))
        a.yaxis.grid(True, color=GRID_C, lw=0.5)
        a.xaxis.set_minor_locator(matplotlib.ticker.NullLocator())
    ax.set_yticklabels(["4", "8", "16", "32", "64\nfloat64 only"], linespacing=1.0)
    ax_h.tick_params(axis="y", length=0, labelleft=False)
    ax_h.spines["left"].set_visible(False)
    w_main = ax.get_position().width * fig.get_figwidth()
    w_h = ax_h.get_position().width * fig.get_figwidth()
    ax.set_xlim(10 ** -6.45, 10 ** (-6.45 + w_main * decades_per_inch))
    decades = sorted({int(round(np.log10(x_of(p)))) for p in syn})
    ax.set_xticks([10.0 ** e for e in decades])
    ax.set_xticklabels([_sup_decade(e) for e in decades])
    handles = []
    xs = _jittered(syn, x_of)
    for key, _, label, color in FIG2_LINES:
        ys = np.log2([p["bits"][key]["fewest_bits_all_seeds"] for p in syn])
        ax.plot(10 ** np.array(xs[key]), ys, color=color, lw=0.7, ls=(0, (1, 1.6)), zorder=2, clip_on=False)
        h, = ax.plot(10 ** np.array(xs[key]), ys, ls="none", marker="o", ms=4.2, mfc=color, mec=SURFACE,
                     mew=0.6, zorder=3, label=label, clip_on=False)
        handles.append(h)
    if hil:
        c = np.log10(x_of(hil[0]))
        half = w_h * decades_per_inch / 2
        ax_h.set_xlim(10 ** (c - half), 10 ** (c + half))
        e = int(round(c))
        ax_h.set_xticks([10.0 ** e])
        ax_h.set_xticklabels([_sup_decade(e)])
        xh = _jittered(hil, x_of)
        for key, _, label, color in FIG2_LINES:
            ax_h.plot(10 ** np.array(xh[key]), np.log2([p["bits"][key]["fewest_bits_all_seeds"] for p in hil]),
                      ls="none", marker="o", ms=4.2, mfc=color, mec=SURFACE, mew=0.6, zorder=3, clip_on=False)
    # One x label centred under both axes.
    pa, ph = ax.get_position(), ax_h.get_position()
    ax.set_xlabel("fitted noise variance (outputs scaled to unit variance):\nfurther right, noisier data",
                  fontsize=7, color=INK2, labelpad=2)
    ax.xaxis.set_label_coords(((pa.x0 + ph.x1) / 2 - pa.x0) / pa.width, -0.10)
    ax.xaxis.label.set_va("top")
    ax.set_ylabel("fewest bits per stored number that pass", fontsize=7, color=INK2, labelpad=3)
    # Divider between the synthetic ladder and the real data, light and dashed.
    xd = (pa.x1 + ph.x0) / 2
    fig.add_artist(matplotlib.lines.Line2D([xd, xd], [pa.y0 - 0.02, pa.y1 + 0.13], transform=fig.transFigure,
                                           color=RULE, lw=0.7, ls=(0, (3, 2))))
    # Settings named above their x position; a label that would overlap its left neighbour moves up.
    fig.canvas.draw()
    renderer = fig.canvas.get_renderer()
    placed = []
    for a, group in ((ax, syn), (ax_h, hil)):
        top = matplotlib.transforms.blended_transform_factory(a.transData, a.transAxes)
        for p in group:
            row = 0
            while True:
                t = a.text(x_of(p), 1.03 + 0.17 * row, p["tag"], transform=top, ha="center", va="bottom",
                           fontsize=6.5, color=INK2, linespacing=1.15)
                bb = t.get_window_extent(renderer)
                if any(r == row and bb.x0 < b.x1 + 3 and bb.x1 > b.x0 - 3 for r, b in placed):
                    t.remove()
                    row += 1
                    continue
                placed.append((row, bb))
                break
    leg = ax.legend(handles=handles, loc="lower left", frameon=False, fontsize=7, handletextpad=0.3,
                    borderaxespad=0.3, labelspacing=0.35)
    for t in leg.get_texts():
        t.set_color(INK2)
    return handles


def draw_fig2b(ax, data):
    _axes_style(ax)
    pb = data["panel_b"]
    pts = [p for p in pb["points"] if p["plotted"]]
    allv = np.array([v for p in pts for v in (p["predicted_rms"], p["measured_rms"])])
    lo, hi = int(np.floor(np.log10(allv.min()))), int(np.ceil(np.log10(allv.max())))
    ax.set_xscale("log")
    ax.set_yscale("log")
    ax.set_xlim(10.0 ** lo, 10.0 ** hi)
    ax.set_ylim(10.0 ** lo, 10.0 ** hi)
    ax.set_aspect("equal", adjustable="box")
    step = 4 if hi - lo > 8 else 2
    ticks = [e for e in range(lo, hi + 1) if e % step == 0]
    for setter, labeller in ((ax.set_xticks, ax.set_xticklabels), (ax.set_yticks, ax.set_yticklabels)):
        setter([10.0 ** e for e in ticks])
        labeller([_sup_decade(e) for e in ticks])
    ax.xaxis.set_minor_locator(matplotlib.ticker.NullLocator())
    ax.yaxis.set_minor_locator(matplotlib.ticker.NullLocator())
    ax.grid(True, color=GRID_C, lw=0.5)
    diag, = ax.plot([10.0 ** lo, 10.0 ** hi], [10.0 ** lo, 10.0 ** hi], color=INK2, lw=0.8, zorder=2,
                    label="exact prediction")
    handles = []
    for q, ckey, label in FIG2_SCATTER:
        qq = [p for p in pts if p["quantity"] == q]
        h = ax.scatter([p["measured_rms"] for p in qq], [p["predicted_rms"] for p in qq], s=9,
                       color=FIG2_COLOR[ckey], edgecolors=SURFACE, linewidths=0.4, zorder=3, label=label,
                       clip_on=False)
        handles.append(h)
    ax.set_xlabel("measured shift of the mean\n(standardized units)", fontsize=7, color=INK2, labelpad=2)
    ax.set_ylabel("predicted by the first-order rule", fontsize=7, color=INK2, labelpad=2)
    st = pb["ratio_stats"]
    ax.text(0.97, 0.04, f"predicted ÷ measured,\n{st['n']} cells:\nmedian {st['median']:.1f}\n"
                        f"90th percentile {st['p90']:.1f}",
            transform=ax.transAxes, ha="right", va="bottom", fontsize=6.5, color=INK2, linespacing=1.25,
            bbox=dict(boxstyle="square,pad=0.35", facecolor=SURFACE, edgecolor=RULE, linewidth=0.5))
    leg = ax.legend(handles=handles + [diag], loc="upper left", frameon=False, fontsize=7, handletextpad=0.4,
                    handlelength=1.2,
                    borderaxespad=0.1, labelspacing=0.3, scatterpoints=1)
    for t in leg.get_texts():
        t.set_color(INK2)


def _fig2_caption(data):
    def sci(v, d=1):
        m, e = f"{v:.{d}e}".split("e")
        return (f"{m}×" if m not in ("1", "1.0") else "") + "10" + str(int(e)).translate(
            str.maketrans("-0123456789", "⁻⁰¹²³⁴⁵⁶⁷⁸⁹"))
    lines_txt = []
    for p in data["panel_a"]:
        b = p["bits"]
        where = (f"HiLift (fitted noise about {sci(p['fitted_noise_variance'])})" if p["data_set"] == "hilift"
                 else f"synthetic at floor {_floor_label(p['noise_floor'])}")
        lines_txt.append(f"{where}: weights {b['alpha']['fewest_bits_all_seeds']}, inputs "
                         f"{b['X']['fewest_bits_all_seeds']}, hyperparameters {b['hyper']['fewest_bits_all_seeds']}, "
                         f"factor {b['L']['fewest_bits_all_seeds']} bits")
    lines_txt[0] = lines_txt[0][0].upper() + lines_txt[0][1:]
    syn = [p for p in data["panel_a"] if p["data_set"] != "hilift"]
    hil = [p for p in data["panel_a"] if p["data_set"] == "hilift"]
    s_lo = min(p["fitted_signal_variance_range"][0] for p in syn)
    s_hi = max(p["fitted_signal_variance_range"][1] for p in syn)
    sig_txt = f"from {s_lo:.2g} to {s_hi:,.0f} on the synthetic problem"
    if hil:
        h_lo, h_hi = hil[0]["fitted_signal_variance_range"]
        sig_txt += f" and from {h_lo:.2g} to {h_hi:.2g} on HiLift"
    hil_budget, hil_cmp = "", ""
    if hil:
        bd_ = hil[0]["budget"]
        hil_budget = (f"the {bd_['name']} budget " if bd_.get("name") else "") + \
            f"({bd_['restarts']} restarts × {bd_['max_iter']} iterations)"
        cmp_ = hil[0].get("comparison")
        if cmp_:
            ours = {k: v["fewest_bits_all_seeds"] for k, v in hil[0]["bits"].items()}
            cb = cmp_["budget"]
            per_a = {q: v["format"] for d in hil[0]["bits"].values() for q, v in d["per_quantity"].items()}
            per_b = {q: v["format"] for d in cmp_["per_quantity"].values() for q, v in d.items()}
            diff = sorted(q for q in per_a if per_a[q] != per_b.get(q))
            low = all(min(BITS[per_a[q]], BITS[per_b[q]]) <= 8 for q in diff)
            hil_cmp = (f" The pilot's HiLift fits at the reduced budget ({cb['restarts']} restarts × "
                       f"{cb['max_iter']} iterations, `" + cmp_["stems"][0].replace("_s7_", "_s*_") + "`) give "
                       + ("the same bits for all four parts drawn" if ours == cmp_["bits"] else
                          "different bits: " + ", ".join(f"{k} {v}" for k, v in cmp_["bits"].items()))
                       + ("" if not diff else
                          ("; their formats differ only below 16 bits (" if low else "; their formats differ (")
                          + ", ".join(QUANTITY_WORDS.get(q, q) for q in diff) + ")")
                       + ".")
    pend = data["panel_a_pending"]
    pend_txt = ""
    if pend:
        names = " and ".join(_floor_label(p["noise_floor"]) for p in pend)
        pend_txt = (f" Models at noise floors {names} are being fitted and swept; they join the "
                    "figure when all three seeds have results." if len(pend) > 1 else
                    f" The model at noise floor {names} is being fitted and swept; it joins the "
                    "figure when all three seeds have results.")
    pb = data["panel_b"]
    st, sw = pb["ratio_stats"], pb["ratio_stats_in_window"]
    bd, lu = pb["readme_bound_over_measured"], pb["largest_underestimate"]
    vb = pb["factor_variance_bound_f32_floor_1e-6"]
    nmodels = len({p["stem"] for p in pb["points"]})
    probs = {p["stem"].split("_n")[0] for p in pb["points"]}
    models_txt = "; ".join(PROBLEM_DESC[k] for k in PROBLEM_DESC if k in probs)
    qname = {q: lab for q, _, lab in FIG2_SCATTER}[lu["quantity"]]
    never = "never underestimates" if bd["n_below_1"] == 0 else f"underestimates in {bd['n_below_1']} cells"
    return f"""**Figure 2. The noise floor sets the bits.** How many bits a stored part of the model needs depends on how noisy the model believes its data to be.

(a) Each point is one problem setting, fitted with three seeds (7, 19 and 43). Left of the dashed line: a synthetic problem with six inputs, eight outputs and 256 training points, fitted at the shipped budget (10 restarts × 200 iterations), where the smallest noise the fit may assume (the noise floor) is raised from 10⁻⁶ to 10⁻²; the fits put the noise at the floor, so each column sits at its floor. Right of the dashed line: HiLift, real data with nine inputs, three outputs and 1,080 training points, fitted at {hil_budget}, whose fitted noise is far above its floor of 10⁻⁶.{hil_cmp} It is a different problem and is not joined to the synthetic settings. The horizontal axis is the fitted noise variance with every output scaled to unit variance (the median over the outputs, then over the seeds), on a log scale: further right means noisier data. The fitted signal variance ranges {sig_txt}; the noise-to-signal ratio, which sets the conditioning κ ≈ s²/σ², is given per output and seed in `fig2_data.json`. The vertical axis is the fewest bits per stored number that still pass on every output and every seed, when only that part is rounded and the rest is served as fitted. Only 64, 32, 16, 8 and 4 bits were tested; the dotted lines only guide the eye. "64, float64 only" means nothing below float64 passed, not a measured need for 64 bits. Markers that share a value are set side by side, each exactly on its bit count. A part passes when rounding moves the predicted mean by less than a tenth of the model's own error against the truth, moves the median predicted standard deviation by less than 10 %, and moves the 95 % coverage by less than one point, on the held-out test points. The hyperparameter markers are the worst of the length scales, the signal variance and the constant mean. {'; '.join(lines_txt)}.{pend_txt} The protocol predicted, before these runs, that the tolerated bits fall as the noise rises (README, amendment of 8 November).

(b) For every model in the study ({nmodels} fits: {models_txt}), each point is one stored part (weights, inputs, or length scales in natural units) rounded to one floating-point format (float32, bfloat16, float16 or float8 E4M3), stored mode, test points. Horizontal, measured: the root mean square, over the test points and the outputs, of how far the rounding moved the predicted mean, in units of the output's standard deviation. Vertical, predicted: the first-order rule's root-mean-square estimate of the same shift, from the sensitivity model's derivatives at the fitted model's own numbers, assuming independent rounding errors spread uniformly over ±u|x| (u the format's unit roundoff; README, Sensitivity model, paragraph added 8 November). Points on the line are predicted exactly. Over {st['n']} cells the estimate is a median {st['median']:.1f} times the measurement, with 80 % of cells between {st['p10']:.2g} and {st['p90']:.2g} times. Where the pass threshold falls, at measured shifts between 10⁻⁴ and 10⁻² standardized units ({sw['n']} cells), the median is {sw['median']:.1f} and 80 % lie between {sw['p10']:.2g} and {sw['p90']:.2g}. The README's pre-registered worst-case bound, which is the tested form, {never} over the same {bd['n']} cells (bound ÷ measured: minimum {bd['min']:.2f}, median {bd['median']:.3g}). The estimate's largest underestimate, a factor of {1 / lu['ratio']:.0f}, is at a measured shift of about {sci(lu['measured_rms'], 0)} standardized units ({qname} at {FORMAT_LABEL[lu['fmt']]} in {lu['stem']}, whose weights are very large), far outside the regime of a first-order rule. The rule covers the mean only: the factor L's variance bound is not validated, and at noise floor 10⁻⁶ it understates the change of the standard deviation under float32 by {vb['measured_over_bound_min']:.1f} to {vb['measured_over_bound_max']:.0f} times. Integer formats are left out: they round to a grid set by the largest value, so a small length scale can round to zero, and that is not a small perturbation the rule can describe.
"""


def fig2():
    _style()
    data = fig2_data()
    if not data["panel_a"]:
        raise SystemExit("fig2: no complete data sets for panel (a)")
    H = 2.92
    fig = plt.figure(figsize=(W, H))
    # (a): the synthetic ladder, a gap for the divider, then HiLift at the same x scale.
    a_left, a_main, a_gap, a_hil, a_bot, a_h = 0.80, 2.55, 0.24, 0.50, 0.50, 1.78
    ax_a = fig.add_axes([a_left / W, a_bot / H, a_main / W, a_h / H])
    ax_h = fig.add_axes([(a_left + a_main + a_gap) / W, a_bot / H, a_hil / W, a_h / H])
    b_left, b_w = 5.20, 1.70
    ax_b = fig.add_axes([b_left / W, a_bot / H, b_w / W, a_h / H])
    draw_fig2a(ax_a, ax_h, data, decades_per_inch=4.9 / a_main)
    draw_fig2b(ax_b, data)
    fig.text(0.08 / W, 1 - 0.06 / H, "a", fontsize=10, fontweight="bold", va="top", color=INK)
    fig.text(0.28 / W, 1 - 0.07 / H, "The noise floor sets the bits", fontsize=8, va="top", color=INK)
    fig.text((b_left - 0.62) / W, 1 - 0.06 / H, "b", fontsize=10, fontweight="bold", va="top", color=INK)
    fig.text((b_left - 0.42) / W, 1 - 0.07 / H, "The first-order rule predicts\nthe mean shift", fontsize=8,
             va="top", color=INK, linespacing=1.15)
    save(fig, FIG2_STEM, FIRST)
    (FIRST / "fig2_data.json").write_text(json.dumps(data, indent=1, ensure_ascii=False) + "\n",
                                        encoding="utf-8", newline="\n")
    (FIRST / "fig2_caption.md").write_text(_fig2_caption(data), encoding="utf-8", newline="\n")
    for p in data["panel_a"]:
        print("fig2(a):", p["label"], "noise %.3g, noise/signal %.2g" % (p["fitted_noise_variance"],
                                                                       p["noise_to_signal"]),
              {k: v["fewest_bits_all_seeds"] for k, v in p["bits"].items()})
    for p in data["panel_a_pending"]:
        print("fig2(a) pending:", p)
    pb = data["panel_b"]
    print("fig2(b): ratio", {k: round(v, 3) for k, v in pb["ratio_stats"].items()},
          "not plotted", pb["n_not_plotted"])
    print("fig2(b): measured in", pb["measured_window"],
          {k: round(v, 3) for k, v in pb["ratio_stats_in_window"].items()})
    print("fig2(b): README bound / measured", pb["readme_bound_over_measured"])
    print("fig2(b): largest underestimate", pb["largest_underestimate"])
    vb = pb["factor_variance_bound_f32_floor_1e-6"]
    print("fig2(b): L f32 measured std change / README bound at floor 1e-6: %.3g to %.3g"
          % (vb["measured_over_bound_min"], vb["measured_over_bound_max"]))


# --- figure 3: more training points, more harm from the same rounding ------------------------
FIG3_STEM = "fig3_more_points_less_room"
SUMMARY = RESULTS / "summary.json"
# (problem, backend, the two training-set sizes, panel title); the same problem's dense and
# sparse models sit side by side.
FIG3_PAIRS = [("heterogeneous", "dense", (256, 1024), "six inputs, eight outputs,\ndense"),
              ("heterogeneous", "sparse", (256, 16384), "the same problem, sparse"),
              ("het_tanh", "dense", (1024, 4096), "its sharpest output\nalone, dense"),
              ("thermo8", "dense", (256, 1024), "a field with 12 modes,\ndense")]
# Colours follow figure 2: weights blue, inputs orange.
FIG3_LINES = [("alpha", "weights α", FIG2_COLOR["alpha"]), ("inputs", "training inputs", FIG2_COLOR["X"]),
              ("lengthscales", "length scales", FIG2_COLOR["hyper"])]
QUANTITY_WORDS = {"alpha": "weights", "L": "factor L", "LB": "second factor Lʙ", "Kinv": "explicit inverse",
                  "X": "training inputs", "Z": "inducing inputs", "lengthscales": "length scales",
                  "outputscale": "signal variance", "noise": "noise variance", "constant": "constant mean",
                  "input_transform": "input scaling", "output_transform": "output scaling",
                  "basis": "field basis", "mean_field": "mean field"}


def _tolerated(summary, key):
    """{quantity: (bits, format)} in the stored mode, natural units, every seed (summarize.py's rule)."""
    out = {}
    for k, v in summary["tolerated"].get(key, {}).items():
        q, param, mode = k.split("|")
        if param == "natural" and mode == "stored":
            f = v["tolerates"] or "f64"
            out[q] = (BITS[f], f)
    return out


def fig3_data():
    summary = json.loads(SUMMARY.read_text(encoding="utf-8"))
    pairs, pending = [], []
    for problem, backend, ns, title in FIG3_PAIRS:
        sizes = []
        for n in ns:
            stems = [f"{problem}_n{n}_s{s}_{backend}" for s in FIG2_SEEDS]
            res = {st: _load_result(st) for st in stems}
            if any(r is None for r in res.values()):
                pending.append({"problem": problem, "backend": backend, "n": n,
                                "missing": [st for st, r in res.items() if r is None]})
                continue
            q_in = "Z" if backend == "sparse" else "X"
            per = {"alpha": {}, "inputs": {}, "lengthscales": {}}
            for st, r in res.items():
                for rec in r["records"]:
                    if (rec.get("record") != "cell" or rec["mode"] != "stored" or rec["fmt"] != "f32"
                            or rec["parameterization"] != "natural"
                            or rec["quantity"] not in ("alpha", q_in, "lengthscales")
                            or rec["status"] != "ok"):
                        continue
                    t = rec["splits"][SPLIT]["tolerance"]
                    fo = rec.get("first_order") or {}
                    key = "inputs" if rec["quantity"] == q_in else rec["quantity"]
                    per[key][st] = {"mean_shift_over_tenth_error": None,
                                    "mean_worst_ratio": _num(t["mean_worst_ratio"]), "pass": bool(t["pass"]),
                                    "mean_shift_rms": _num(fo.get("measured_mean_shift", {}).get("rms"))}
            ref = json.loads((REFS / f"{stems[0]}.json").read_text(encoding="utf-8"))
            errs = [json.loads((REFS / f"{st}.json").read_text(encoding="utf-8"))["metrics"][SPLIT]["standardized_rmse"]
                    for st in stems]
            sizes.append({"n": n, "stems": stems, "inputs_quantity": q_in,
                          "model_error_test_srmse": {st: e for st, e in zip(stems, errs)},
                          "model_error_median": float(np.median(errs)),
                          "n_inducing": ref.get("n_inducing") if backend == "sparse" else None,
                          "f32": per, "tolerated_bits": {q: {"bits": b, "format": f} for q, (b, f) in
                                                         _tolerated(summary, f"{problem}_n{n}_{backend}").items()}})
            for v in per.values():
                for s in v.values():
                    del s["mean_shift_over_tenth_error"]
        if len(sizes) != 2:
            continue
        a, b = sizes
        growth = {"model_error": {"median": [a["model_error_median"], b["model_error_median"]],
                                  "factor": b["model_error_median"] / a["model_error_median"]}}
        for key in ("alpha", "inputs", "lengthscales"):
            wa = max(s["mean_worst_ratio"] for s in a["f32"][key].values())
            wb = max(s["mean_worst_ratio"] for s in b["f32"][key].values())
            sa = float(np.median([s["mean_shift_rms"] for s in a["f32"][key].values()]))
            sb = float(np.median([s["mean_shift_rms"] for s in b["f32"][key].values()]))
            growth[key] = {"worst_ratio": [wa, wb], "ratio_growth": wb / wa,
                           "median_shift_rms": [sa, sb], "shift_growth": sb / sa,
                           "pass": [all(s["pass"] for s in a["f32"][key].values()),
                                    all(s["pass"] for s in b["f32"][key].values())]}
        changes = []
        ta, tb = a["tolerated_bits"], b["tolerated_bits"]
        for q in ta:
            if q in tb and ta[q]["bits"] != tb[q]["bits"]:
                changes.append({"quantity": q, "bits": [ta[q]["bits"], tb[q]["bits"]],
                                "formats": [ta[q]["format"], tb[q]["format"]]})
        pairs.append({"problem": problem, "backend": backend, "title": title.replace("\n", " "),
                      "title_lines": title,
                      "sizes": sizes, "growth": growth, "bit_changes": changes,
                      "quantities_compared": sorted(set(ta) & set(tb))})
    return {"split": SPLIT, "mode": "stored", "format": "f32", "seeds": list(FIG2_SEEDS),
            "y": "mean_worst_ratio: rounding shift of the predictive mean / the float64 model's own error "
                 "against truth, worst output; per seed, the line through the worst seed",
            "pass_line": THRESHOLD, "pairs": pairs, "pending": pending}


def fig3():
    _style()
    data = fig3_data()
    pairs = data["pairs"]
    if not pairs:
        raise SystemExit(f"fig3: waiting for sweep results; missing {data['pending']}")
    vals = [s["mean_worst_ratio"] for p in pairs for z in p["sizes"] for v in z["f32"].values()
            for s in v.values()] + [THRESHOLD]
    lo, hi = int(np.floor(np.log10(min(vals)))), int(np.ceil(np.log10(max(vals))))
    H = 2.75
    fig = plt.figure(figsize=(W, H))
    left, right, gap, bot, top = 0.80, 0.10, 0.22, 0.50, 0.62
    pw = (W - left - right - gap * (len(pairs) - 1)) / len(pairs)
    for i, p in enumerate(pairs):
        ax = fig.add_axes([(left + i * (pw + gap)) / W, bot / H, pw / W, (H - bot - top) / H])
        _axes_style(ax)
        ax.set_xscale("log", base=2)
        ax.set_yscale("log")
        ns = [z["n"] for z in p["sizes"]]
        span = np.log2(ns[1] / ns[0])
        ax.set_xlim(2 ** (np.log2(ns[0]) - 0.32 * span), 2 ** (np.log2(ns[1]) + 0.32 * span))
        ax.set_xticks(ns)
        ax.set_xticklabels([f"{n:,}" for n in ns])
        ax.xaxis.set_minor_locator(matplotlib.ticker.NullLocator())
        ax.set_ylim(10.0 ** lo, 10.0 ** hi)
        step = 2 if hi - lo > 6 else 1
        ax.set_yticks([10.0 ** e for e in range(lo, hi + 1) if e % step == 0])
        ax.yaxis.set_minor_locator(matplotlib.ticker.NullLocator())
        ax.yaxis.grid(True, color=GRID_C, lw=0.5)
        if i == 0:
            ax.set_yticklabels([_sup_decade(e) for e in range(lo, hi + 1) if e % step == 0])
            ax.set_ylabel("rounding shift of the mean at 32 bits\n÷ the model's own error", fontsize=7,
                          color=INK2, labelpad=3)
        else:
            ax.tick_params(axis="y", labelleft=False)
        ax.axhline(THRESHOLD, color=INK2, lw=0.8, ls=(0, (4, 2)), zorder=1)
        if i == 0:
            ax.text(ax.get_xlim()[0] * 1.05, THRESHOLD * 1.3, "the mean passes below this line", fontsize=6.5, color=INK2,
                    ha="left", va="bottom")
        for key, label, color in FIG3_LINES:
            worst = [max(s["mean_worst_ratio"] for s in z["f32"][key].values()) for z in p["sizes"]]
            ax.plot(ns, worst, color=color, lw=1.2, zorder=2, solid_capstyle="round")
            for n, z in zip(ns, p["sizes"]):
                ys = [s["mean_worst_ratio"] for s in z["f32"][key].values()]
                ax.plot([n] * len(ys), ys, ls="none", marker="o", ms=3.4, mfc=color, mec=SURFACE, mew=0.5,
                        zorder=3, clip_on=False)
        if i == len(pairs) - 1:   # direct labels once, where the lines are far apart
            for key, label, color in FIG3_LINES:
                y1 = max(s["mean_worst_ratio"] for s in p["sizes"][1]["f32"][key].values())
                y0 = max(s["mean_worst_ratio"] for s in p["sizes"][0]["f32"][key].values())
                above = y1 >= y0
                ax.text(np.sqrt(ns[0] * ns[1]), np.sqrt(y0 * y1) * (2.6 if key == "alpha" else 1 / 2.6),
                        label, fontsize=6.5, color=INK2, ha="center",
                        va="bottom" if key == "alpha" else "top")
        sub = ""
        if p["backend"] == "sparse":
            m = [z["n_inducing"] for z in p["sizes"]]
            sub = f"\n({m[0]} and {m[1]} inducing points)" if m[0] != m[1] else f"\n({m[0]} inducing points)"
        ax.set_title(p["title_lines"] + sub, fontsize=7, color=INK, loc="left", pad=4, linespacing=1.15)
    fig.text((left + (W - left - right) / 2) / W, 0.06 / H, "training points (log scale)", ha="center",
             va="bottom", fontsize=7, color=INK2)
    fig.text(0.08 / W, 1 - 0.06 / H, "More training points, less room for rounding", fontsize=8,
             va="top", color=INK)
    save(fig, FIG3_STEM, FIRST)
    (FIRST / "fig3_data.json").write_text(json.dumps(data, indent=1, ensure_ascii=False) + "\n",
                                        encoding="utf-8", newline="\n")
    (FIRST / "fig3_caption.md").write_text(_fig3_caption(data), encoding="utf-8", newline="\n")
    for p in pairs:
        print("fig3:", p["problem"], p["backend"], [z["n"] for z in p["sizes"]],
              {k: (round(g["ratio_growth"], 2), round(g["shift_growth"], 2), g["pass"]) for k, g in p["growth"].items()
               if k != "model_error"}, "model error x%.2g" % p["growth"]["model_error"]["factor"],
              "bit changes", p["bit_changes"])
    for q in data["pending"]:
        print("fig3 pending:", q)


def _n(v):
    """A ratio in words: thousands separators from 100 up, two significant digits below."""
    return f"{v:,.0f}" if v >= 100 else f"{v:.2g}"


def _fig3_caption(data):
    pairs = data["pairs"]
    parts = ("alpha", "inputs", "lengthscales")
    up = all(p["growth"][k]["ratio_growth"] > 1 for p in pairs for k in parts)
    err_down = all(p["growth"]["model_error"]["factor"] < 1 for p in pairs)
    slower = all(p["growth"][k]["shift_growth"] > p["growth"]["model_error"]["factor"]
                 for p in pairs for k in parts)
    if up and err_down and slower:
        first = ("With more training points, the same 32-bit rounding takes a larger share of the model's own "
                 "error and leaves less room under the pass line, mostly because the error shrinks while the "
                 "shift the rounding causes does not shrink as fast.")
    else:
        first = ("How the share of the model's own error taken by 32-bit storage of the weights, the inputs and "
                 "the length scales changes with the number of training points.")
    first = "**Figure 3. More training points, less room for rounding.** " + first

    def word(p, k):
        return {"alpha": "weights", "lengthscales": "length scales"}.get(k) or \
            QUANTITY_WORDS[p["sizes"][0]["inputs_quantity"]]
    rows, shift_rows = [], []
    for p in pairs:
        ns = [z["n"] for z in p["sizes"]]
        me = p["growth"]["model_error"]
        rows.append(f"{p['title']}, n = {ns[0]:,} → {ns[1]:,}: model error {me['median'][0]:.2g} → "
                    f"{me['median'][1]:.2g}; " + ", ".join(
                        f"{word(p, k)} {_n(p['growth'][k]['worst_ratio'][0])} → {_n(p['growth'][k]['worst_ratio'][1])}"
                        for k in parts))
        shift_rows.append(f"{p['title']}: model error × {me['factor']:.2g}; shift of " + ", ".join(
            f"{word(p, k)} × {p['growth'][k]['shift_growth']:.2g}" for k in parts))
    changes = []
    for p in pairs:
        ns = [z["n"] for z in p["sizes"]]
        for c in p["bit_changes"]:
            changes.append(f"{QUANTITY_WORDS.get(c['quantity'], c['quantity'])} in {p['title']} "
                           f"({FORMAT_LABEL.get(c['formats'][0], c['formats'][0])} at n = {ns[0]:,}, "
                           f"{FORMAT_LABEL.get(c['formats'][1], c['formats'][1])} at n = {ns[1]:,})"
                           .replace("f64", "float64 only"))
    ch_txt = ("The fewest bits that pass changed between the two sizes only for " + "; ".join(changes) + "."
              if changes else "The fewest bits that pass did not change between the two sizes for any stored part.")
    cross = [f"{word(p, k)} in {p['title']}" for p in pairs for k in parts
             if p["growth"][k]["pass"][0] and not p["growth"][k]["pass"][1]]
    cross_txt = (" A line that crosses the pass line between the sizes is a part that stops passing at 32 bits: "
                 + "; ".join(cross) + "." if cross else "")
    fell = [f"{word(p, k)} in {p['title']}" for p in pairs for k in parts if p["growth"][k]["shift_growth"] < 1]
    fell_txt = (" The shift itself even falls for " + "; ".join(fell) + "." if fell else "")
    flat = [p for p in pairs if p["growth"]["model_error"]["factor"] > 0.8]
    if flat:
        fell_txt += (" The exception to the shrinking yardstick: in " + "; ".join(
            f"{p['title']} the model error hardly changes (× {p['growth']['model_error']['factor']:.2g})"
            for p in flat) + ", and the ratio rises because the shift itself grows.")
    sparse = [p for p in pairs if p["backend"] == "sparse"]
    sp_txt = ""
    if sparse:
        m = [z["n_inducing"] for z in sparse[0]["sizes"]]
        if m[0] != m[1]:
            sp_txt = (f" The sparse models also differ in their inducing points ({m[0]} at the smaller size, "
                      f"{m[1]} at the larger, as fitted), so their weights and inducing inputs change with both; "
                      "their recomputed (consistent) mode missed its float64 control at the larger size and is "
                      "not used here.")
    seeds = ", ".join(str(s) for s in data["seeds"])
    return f"""{first}

Each panel is one problem fitted at two training-set sizes, three seeds each ({seeds}); the dense and sparse models of the six-input problem are side by side. Each dot is one seed; the line joins the worst seed at each size, which is what the pass rule uses. The vertical axis is how far storing one part at 32 bits (float32), with everything else served as fitted, moves the predicted mean on the held-out test points, divided by the 64-bit model's own error against the truth (the worst output), on a log scale. Below the dashed line at {THRESHOLD} the mean passes; the standard deviation and coverage tests are not drawn here, but they count in the fewest-bits comparison below, which covers every stored part. Weights are the posterior weights α; training inputs are X for the dense models and the inducing inputs Z for the sparse ones; length scales are in natural units. Model error is the reference's test standardized RMSE, median over seeds; the ratios are the worst seed, smaller → larger size: {'; '.join(rows)}.

The ratio rises because its yardstick, the model's own error, shrinks as the model sees more data, while the rounding shift (median over seeds of its root-mean-square, standardized output units; the field model in coefficient units) shrinks less or grows: {'; '.join(shift_rows)}.{fell_txt} {ch_txt}{cross_txt}{sp_txt} Fewest bits use summarize.py's rule (every output, every seed, all three tests) from `results/sensitivity/summary.json`; every number here is in `fig3_data.json`, read from `results/sensitivity/<problem>_n<N>_s<seed>_<backend>.json` and `results/reference/<stem>.json`.
"""


# --- the allocation front: figures 2, 3, 4 and table 1 (bench problems, 10 November) ---------
ALLOC = HERE / "results" / "allocation"
SIZE_DIR = HERE / "results" / "size"
FIRST = OUT / "first_sweep"          # the first sweep's figures, kept for the supplement
BENCH = ["forrester", "branin", "ishigami", "hartmann6", "borehole"]
BENCH_N, BENCH_SPARSE_N, BENCH_SEED = 1024, 4096, 7
FIG2_WITH_SPARSE = ["hartmann6"]   # sparse models drawn in figure 2 beside their dense model
PROBLEM_NAME = {"forrester": "Forrester, 1 input", "branin": "Branin, 2 inputs", "ishigami": "Ishigami, 3 inputs",
                "hartmann6": "Hartmann 6, 6 inputs", "borehole": "borehole, 8 inputs",
                "heterogeneous": "synthetic, 6 inputs, 8 outputs", "het_tanh": "synthetic sharp output",
                "hilift": "HiLift, real data", "thermo8": "synthetic field"}
UNIFORM_NAME = {"f64": "float64", "f32": "float32", "bf16": "bfloat16", "f16": "float16", "e4m3": "float8"}
GROUP_NAME = {"hyper": "hyperparameters", "inputs": "inputs", "alpha": "weights", "factor": "factor",
              "output": "output transform", "input": "input transform"}
# Figure 3's four bar segments: colour follows figure 2 of the first sweep (weights blue, inputs
# orange, hyperparameters aqua, factor plum); the transforms ride with the hyperparameters.
BAR_GROUPS = [("factor", ["factor"], "uncertainty factor", "#8c304c"),
              ("alpha", ["alpha"], "weights", "#2a78d6"),
              ("inputs", ["inputs"], "inputs", "#eb6834"),
              ("small", ["hyper", "output", "input"], "hyperparameters and transforms", "#1baf7a")]
BASE_C = INK2            # uniform casting: the baseline, in secondary ink
FRONT_C = "#2a78d6"      # the allocation's measured front: categorical slot 1
SPARSE_C = "#eb6834"     # figure 4: sparse models, slot 2 (dense take slot 1)


def _stem_parts(stem):
    """problem, n, seed, backend, tag from <problem>_n<N>_s<S>_<backend>[_tag]."""
    parts = stem.split("_")
    i = next(k for k, s in enumerate(parts) if k > 0 and s.startswith("n") and s[1:].isdigit())
    return ("_".join(parts[:i]), int(parts[i][1:]), int(parts[i + 1][1:]), parts[i + 2],
            "_".join(parts[i + 3:]))


def load_allocations():
    """{stem: result} for every measured allocation result whose two runs agreed."""
    out = {}
    for p in sorted(ALLOC.glob("*.json")):
        if p.name == "fronts.json" or p.name.endswith(".predicted.json"):
            continue
        r = json.loads(p.read_text(encoding="utf-8"))
        rep = r.get("report") or {}
        if r.get("measured") and rep.get("runs_agree"):
            out[p.stem] = r
    return out


def front_cells(allocs, sparse=False):
    """The panels: bench problems at the paper's size and seed 7; when none exists yet, every
    measured cell (development mode, marked in the outputs)."""
    n, kind = (BENCH_SPARSE_N, "sparse") if sparse else (BENCH_N, "dense")
    stems = []
    for p in BENCH:
        st = f"{p}_n{n}_s{BENCH_SEED}_{kind}"
        if st in allocs:
            stems.append(st)
        elif not sparse:
            # A problem not fitted at the paper's size (forrester stops at n = 256): its largest n.
            alt = sorted((_stem_parts(x)[1], x) for x in allocs
                         if _stem_parts(x)[0] == p and _stem_parts(x)[2] == BENCH_SEED
                         and _stem_parts(x)[3] == kind and not _stem_parts(x)[4])
            if alt:
                stems.append(alt[-1][1])
    if any(_stem_parts(st)[1] == n for st in stems) or sparse:
        return stems, False
    return sorted(allocs), True


def _score_floor(scores):
    pos = [s for s in scores if 0 < s < np.inf]
    return 10.0 ** (np.floor(np.log10(min(pos))) - 1) if pos else 1e-6


def _seed_range(allocs, stem, key):
    """Range over the seeds present of report[key] for this cell's problem, size and backend."""
    prob, n, _, kind, tag = _stem_parts(stem)
    vals = [r["report"][key] for st, r in allocs.items()
            if _stem_parts(st)[:2] == (prob, n) and _stem_parts(st)[3:] == (kind, tag) and r["report"].get(key)]
    return (min(vals), max(vals), len(vals)) if vals else None


def front_data(stems, allocs):
    cells = []
    for st in stems:
        r = allocs[st]
        m, rep = r["measured"], r["report"]
        uni = sorted([{"format": p["assignment"]["factor"].split("/")[0], "bytes": p["bytes"],
                       "score": _num(p["score"]), "pass": p["pass"]} for p in m["uniform"] if p.get("status") == "ok"],
                     key=lambda p: (-p["bytes"], p["score"]))
        front = sorted([{"bytes": p["bytes"], "score": _num(p["score"]), "pass": p["pass"],
                         "assignment": p["assignment"]}
                        for p in m["front"] if p.get("status") == "ok"], key=lambda p: -p["bytes"])
        not_drawn = [{"format": p["assignment"]["factor"].split("/")[0], "status": p.get("status")}
                     for p in m["uniform"] if p.get("status") != "ok"]
        cells.append({"stem": st, "uniform_not_drawn": not_drawn, "kind": r["kind"], "n_train": r["n_train"], "n_outputs": r["n_outputs"],
                      "bytes_f64": r["bytes_f64"], "uniform": uni, "front": front,
                      "last_pass": rep["allocation_last_pass"], "uniform_best_pass": rep["uniform_best_pass"],
                      "saving_vs_f64": rep["saving_vs_f64"], "saving_vs_uniform": rep["saving_vs_uniform"],
                      "seed_range_saving_vs_uniform": _seed_range(allocs, st, "saving_vs_uniform"),
                      "seed_range_saving_vs_f64": _seed_range(allocs, st, "saving_vs_f64"),
                      "order": rep.get("order")})
    return cells


def _log_axes(ax):
    _axes_style(ax)
    ax.set_xscale("log")
    ax.set_yscale("log")
    ax.xaxis.set_minor_locator(matplotlib.ticker.NullLocator())
    ax.yaxis.set_minor_locator(matplotlib.ticker.NullLocator())
    ax.grid(True, color=GRID_C, lw=0.5)


def _bytes_label(v, _=None):
    for unit, k in (("GB", 1e9), ("MB", 1e6), ("kB", 1e3)):
        if v >= k:
            return f"{v / k:g} {unit}"
    return f"{v:g} B"


def draw_front(ax, c, floor, first):
    """One panel of figure 2: uniform casting as the baseline line, the allocation's front on it."""
    _log_axes(ax)
    top = ax.figure._fig_top  # noqa: SLF001  non-finite scores are drawn at the top, labelled
    clip = lambda s: top if not np.isfinite(s) else max(s, floor)  # noqa: E731
    ub = c["uniform"]
    ax.plot([p["bytes"] for p in ub], [clip(p["score"]) for p in ub], color=BASE_C, lw=0.8, zorder=2)
    ax.plot([p["bytes"] for p in ub], [clip(p["score"]) for p in ub], ls="none", marker="o", ms=3.6, mfc=SURFACE,
            mec=BASE_C, mew=0.9, zorder=3)
    seen = set()
    for p in ub:
        b = p["bytes"]
        same = [q for q in ub if q["bytes"] == b]   # two formats with the same bytes: higher score above
        dy = 3 if len(same) == 1 or p["score"] >= max(q["score"] for q in same) else -9
        seen.add(b)
        ax.annotate(UNIFORM_NAME.get(p["format"], p["format"]) + ("" if np.isfinite(p["score"]) else ", no finite score"),
                    (b, clip(p["score"])), xytext=(-3 if p["format"] == "f64" else 3, 6 if p["format"] == "f64" else dy),
                    textcoords="offset points", fontsize=6, color=INK2, va="bottom", ha="right" if p["format"] == "f64" else "left")
    fr = c["front"]
    ax.plot([p["bytes"] for p in fr], [clip(p["score"]) for p in fr], ls="none", marker="o", ms=3.2,
            mfc=FRONT_C, mec=SURFACE, mew=0.4, zorder=4)
    lp = c["last_pass"]
    lps = next((p["score"] for p in fr if p["bytes"] == lp["bytes"]), None)
    if lps is not None:
        ax.plot([lp["bytes"]], [clip(lps)], ls="none", marker="o", ms=7.5, mfc="none", mec=FRONT_C, mew=1.1,
                zorder=5)
    ax.axhline(1.0, color=INK2, lw=0.8, ls=(0, (4, 2)), zorder=1)
    if False:   # the pass limit is named in the key
        ax.text(0.02, 1.0, "pass limit", transform=matplotlib.transforms.blended_transform_factory(ax.transAxes,
                ax.transData), fontsize=6, color=INK2, va="bottom", ha="left")
    ub_best = c["uniform_best_pass"]
    sv = c["saving_vs_uniform"]
    svt = f"{sv:.3g}" if sv >= 1.1 else f"{sv:.4g}"
    lpb = _bytes_label(float(f"{lp['bytes']:.3g}"))
    # The note goes in the lower-left corner unless a point sits there, else the upper right.
    allx = [q["bytes"] for q in ub + fr]
    xmid = np.sqrt(min(allx) * max(allx))
    busy = any(q["bytes"] < xmid and clip(q["score"]) < 1 for q in ub + fr)
    ax.text(0.97 if busy else 0.03, 0.97 if busy else 0.04,
            f"last passing: {lpb},\n" + (f"{svt}× smaller than " if sv >= 1.0005 else "the same size as ")
            + UNIFORM_NAME.get(ub_best['format'], ub_best['format']),
            transform=ax.transAxes, ha="right" if busy else "left", va="top" if busy else "bottom", fontsize=6,
            color=INK2, linespacing=1.2)
    ax.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(_bytes_label))
    ax.xaxis.set_major_locator(matplotlib.ticker.LogLocator(base=10, numticks=4))


def fig_front(sparse=False):
    allocs = load_allocations()
    stems, dev = front_cells(allocs, sparse)
    if not dev and not sparse:
        # The main figure also carries the sparse model whose groups need different formats
        # (Hartmann 6 at n = 4096), right after its dense model.
        for prob in FIG2_WITH_SPARSE:
            st = f"{prob}_n{BENCH_SPARSE_N}_s{BENCH_SEED}_sparse"
            dense = [x for x in stems if _stem_parts(x)[0] == prob]
            if st in allocs and dense:
                stems.insert(stems.index(dense[0]) + 1, st)
    if sparse and not dev:
        # The supplement: every sparse model not in figure 2 at seed 7, and those in it at every seed.
        stems = [x for x in stems if _stem_parts(x)[0] not in FIG2_WITH_SPARSE] + sorted(
            (x for x in allocs if _stem_parts(x)[0] in FIG2_WITH_SPARSE and _stem_parts(x)[1] == BENCH_SPARSE_N
             and _stem_parts(x)[3] == "sparse"), key=lambda x: _stem_parts(x)[2])
    stem_name = "figS3_what_quantization_buys_sparse" if sparse else "fig2_what_quantization_buys"
    if not stems:
        raise SystemExit(f"{stem_name}: waiting for allocation results "
                         f"({'sparse n = 4096' if sparse else 'n = 1024'} bench cells) in {ALLOC}")
    _style()
    data = {"development": dev, "cells": front_data(stems, allocs)}
    scores = [p["score"] for c in data["cells"] for p in c["uniform"] + c["front"]]
    floor = _score_floor(scores)
    hi = 10.0 ** (np.ceil(np.log10(max(max(s for s in scores if np.isfinite(s)), 10))) + 1.5)
    data["score_top_drawn_as_infinite"] = hi / 100
    k = len(stems)
    ncol = min(k, 3)
    nrow = int(np.ceil(k / ncol))
    pw, ph, gx, gy, left, top, bot = 1.85, 1.65, 0.30, 0.75, 0.75, 0.55, 0.55
    H = top + nrow * ph + (nrow - 1) * gy + bot
    fig = plt.figure(figsize=(W, H))
    fig._fig_top = data["score_top_drawn_as_infinite"]
    for i, c in enumerate(data["cells"]):
        r_, c_ = divmod(i, ncol)
        ax = fig.add_axes([(left + c_ * (pw + gx)) / W, (H - top - (r_ + 1) * ph - r_ * gy) / H, pw / W, ph / H])
        draw_front(ax, c, floor, i == 0)
        ax.set_ylim(floor / 2, hi)
        e0, e1 = int(round(np.log10(floor))), int(np.floor(np.log10(hi)))
        step = 3 if e1 - e0 > 9 else 2
        ax.set_yticks([floor] + [10.0 ** e for e in range(e0 + 2, e1 + 1) if e % step == 0])
        ax.yaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(
            lambda v, _: "0" if v <= floor * 1.01 else _sup_decade(int(round(np.log10(v))))))
        prob, n, seed, kind, tag = _stem_parts(c["stem"])
        ax.set_title(f"{PROBLEM_NAME.get(prob, prob)}, n = {n:,}" + (" sparse" if kind == "sparse" else "")
                     + (f", seed {seed}" if sparse else ""),
                     fontsize=7, color=INK, loc="left", pad=3)
        if c_ == 0:
            ax.set_ylabel("worst of the three tests\n(1 = pass limit)", fontsize=7, color=INK2)
        if r_ == nrow - 1 or i + ncol >= k:
            ax.set_xlabel("bytes stored", fontsize=7, color=INK2)
    # key, one line: the two series and the ring
    kx = fig.add_axes([left / W, (H - 0.42) / H, (W - left - 0.2) / W, 0.14 / H])
    kx.set_axis_off()
    kx.set_xlim(0, 100)
    kx.set_ylim(0, 1)
    kx.plot([0, 3], [0.5, 0.5], color=BASE_C, lw=0.8)
    kx.plot([1.5], [0.5], marker="o", ms=3.6, mfc=SURFACE, mec=BASE_C, mew=0.9)
    kx.text(4, 0.5, "every part at one format", fontsize=7, color=INK2, va="center")
    kx.plot([30], [0.5], marker="o", ms=3.2, mfc=FRONT_C, mec=SURFACE)
    kx.text(31.5, 0.5, "per-part allocation", fontsize=7, color=INK2, va="center")
    kx.plot([60], [0.5], marker="o", ms=7.5, mfc="none", mec=FRONT_C, mew=1.1)
    kx.text(61.5, 0.5, "its last passing point", fontsize=7, color=INK2, va="center")
    kx.plot([84, 87], [0.5, 0.5], color=INK2, lw=0.8, ls=(0, (4, 2)))
    kx.text(88, 0.5, "pass limit", fontsize=7, color=INK2, va="center")
    fig.text(0.08 / W, 1 - 0.06 / H, ("What quantization buys" + (", sparse models" if sparse else "")
                                      + ("   [DEVELOPMENT CELLS, not the paper's problems]" if dev else "")),
             fontsize=8, va="top", color=INK)
    save(fig, stem_name)
    data["score_floor_drawn_as_zero"] = floor
    (OUT / f"{stem_name.split('_')[0]}_data.json").write_text(json.dumps(data, indent=1, ensure_ascii=False) + "\n",
                                                              encoding="utf-8", newline="\n")
    (OUT / f"{stem_name.split('_')[0]}_caption.md").write_text(_front_caption(data, sparse), encoding="utf-8",
                                                               newline="\n")
    for c in data["cells"]:
        print(f"{stem_name}: {c['stem']} f64 {c['bytes_f64']} best uniform {c['uniform_best_pass']} "
              f"last pass {c['last_pass']['bytes']} vs uniform x{c['saving_vs_uniform']:.3g} vs f64 x{c['saving_vs_f64']:.3g}")


def _sci(v, up=None):
    """Three significant digits as a×10ⁿ. A bound rounds outward so it contains every value it
    summarises: ``up=True`` for a "passes up to" bound (ceiling), ``up=False`` for a "fails from"
    bound (floor); ``None`` rounds to nearest (medians). A mantissa of exactly X.00 prints as X.0."""
    e = int(np.floor(np.log10(v)))
    m = v / 10.0 ** e
    if up is None:
        m = round(m, 2)
    else:
        m = (np.ceil if up else np.floor)(round(m * 100, 6)) / 100
    if m >= 10:
        m, e = m / 10, e + 1
    txt = f"{m:.2f}"
    if txt.endswith(".00"):
        txt = txt[:-1]
    sup = str.maketrans("-0123456789", "⁻⁰¹²³⁴⁵⁶⁷⁸⁹")
    return f"{txt}×10" + str(e).translate(sup)


def _rng(vals, fmt="{:.2g}"):
    """'a–b' over the values, or one value when they print the same."""
    lo, hi = fmt.format(min(vals)), fmt.format(max(vals))
    return lo if lo == hi else f"{lo}–{hi}"


def _front_caption(data, sparse):
    cells = data["cells"]
    big = [c for c in cells if c["uniform_best_pass"]["format"] != "f64"]
    small = [c for c in cells if c["uniform_best_pass"]["format"] == "f64"]
    nm = lambda c: (PROBLEM_NAME.get(_stem_parts(c["stem"])[0], c["stem"]).split(",")[0]  # noqa: E731
                    + (f" seed {_stem_parts(c['stem'])[2]}" if sparse else ""))
    parts = []
    if small:
        pct = [100 * (1 - 1 / c["saving_vs_f64"]) for c in small]
        parts.append(f"where no uniform format below float64 passes ({', '.join(nm(c) for c in small)}), the "
                     f"allocation removes {_rng(pct, '{:.2g}')} % of the bytes")
    for fmt in sorted({c["uniform_best_pass"]["format"] for c in big}, key=lambda f: -BITS[f]):
        cs = [c for c in big if c["uniform_best_pass"]["format"] == fmt]
        sv = [c["saving_vs_uniform"] for c in cs]
        parts.append(f"where uniform {UNIFORM_NAME.get(fmt, fmt)} already passes ({', '.join(nm(c) for c in cs)}, "
                     f"{_rng([c['bytes_f64'] / c['uniform_best_pass']['bytes'] for c in cs])} times smaller than "
                     "float64), the allocation is "
                     + (f"{_rng(sv)} times smaller again" if max(sv) >= 1.01 else "smaller by under 1 %"))
    lead = ("Choosing the format part by part buys little over the best uniform format: "
            if max(c["saving_vs_uniform"] for c in cells) < 1.1 else "Choosing the format part by part: ")
    first = lead + "; ".join(parts) + "."
    gain = [c for c in big if c["saving_vs_uniform"] >= 1.01]
    match = [c for c in big if c["saving_vs_uniform"] < 1.01]
    mixed = all(len({v.split("/")[0] for v in c["last_pass"]["assignment"].values()}) > 1 for c in gain)
    if not sparse and gain and mixed:
        kind = lambda c: f"{nm(c)} {'sparse' if c['kind'] == 'sparse' else 'dense'}"  # noqa: E731
        bits = []
        if small:
            bits.append(f"{len(small)} models stay within "
                        f"{max(100 * (1 - 1 / c['saving_vs_f64']) for c in small):.1g} % of float64")
        for c in match:
            bits.append(f"{kind(c)} shrinks {c['bytes_f64'] / c['uniform_best_pass']['bytes']:.2g} times at uniform "
                        f"{UNIFORM_NAME[c['uniform_best_pass']['format']]} and the allocation matches it")
        for c in gain:
            bits.append(f"{kind(c)} shrinks {c['saving_vs_f64']:.2g} times, {c['saving_vs_uniform']:.3g} times below "
                        f"the best uniform cast ({UNIFORM_NAME[c['uniform_best_pass']['format']]}), because its "
                        "groups need different formats")
        first = ("The allocation finds the best uniform format and gains beyond it only where groups need "
                 "different formats: " + "; ".join(bits) + ".")
    title = "Figure S3. What quantization buys, sparse models." if sparse else "Figure 2. What quantization buys."
    dev = (" **Development cells, not the paper's problems: redraw when the bench cells land.**"
           if data["development"] else "")
    rows = []
    for c in cells:
        rr = c["seed_range_saving_vs_uniform"]
        seeds = (f"; over {rr[2]} seeds {_rng([rr[0], rr[1]], '{:.3g}')}×" if rr and rr[2] > 1 else "")
        lp = c["last_pass"]
        carriers = ", ".join(f"{GROUP_NAME[g]} {v}" for g, v in lp["assignment"].items())
        rows.append(f"{c['stem']}: float64 {c['bytes_f64']:,} bytes, best passing uniform "
                    f"{UNIFORM_NAME.get(c['uniform_best_pass']['format'])} {c['uniform_best_pass']['bytes']:,}, "
                    f"last passing allocation {lp['bytes']:,} ({c['saving_vs_uniform']:.3g}× the uniform, "
                    f"{c['saving_vs_f64']:.3g}× float64{seeds}; {carriers})")
    order = [f"{c['stem']} {c['order']['kendall_tau_b']:.2f}" for c in cells if c.get("order")]
    nd = [f"{UNIFORM_NAME.get(u['format'], u['format'])} in {c['stem']} ({u['status']})"
          for c in cells for u in c["uniform_not_drawn"]]
    inf_ = [f"{UNIFORM_NAME.get(u['format'], u['format'])} in {c['stem']}"
            for c in cells for u in c["uniform"] if not np.isfinite(u["score"])]
    extra = ((" Uniform casts with no finite score, drawn at the top of the panel: " + "; ".join(inf_) + ".")
             if inf_ else "") + ((" Uniform casts not drawn because the rounded model could not be served: "
                                  + "; ".join(nd) + ".") if nd else "")
    small_n = [c["stem"] for c in cells if c["kind"] == ("sparse" if sparse else "dense")
               and _stem_parts(c["stem"])[1] != (BENCH_SPARSE_N if sparse else BENCH_N)]
    if small_n:
        extra += (f" Not fitted at n = {BENCH_SPARSE_N if sparse else BENCH_N:,}, so drawn at its largest size: "
                  + ", ".join(small_n) + ".")
    return f"""**{title}** {first}{dev}

Each panel is one fitted model ({'its seed in the title' if sparse else f'seed {BENCH_SEED}'}). Horizontal: the bytes the prediction reads, on a log scale (the factor counted as a triangle). Vertical: the measured score of the rounded model on the held-out test points, the worst of the three tests divided by its limit (mean shift ÷ 0.1 of the model's own error, median change of the predicted standard deviation ÷ 10 %, change of the 95 % coverage ÷ one point), so a point passes below the dashed line at 1; "0" marks a score of exactly zero (the rounding changed nothing), drawn at {_sup_decade(int(round(np.log10(data['score_floor_drawn_as_zero']))))}. Grey: every stored part cast to one format, joined from float64 to float8 (bfloat16 and float16 take the same bytes). Blue: the assignments the allocation search predicted on its front, each rounded all at once and measured; the ring is the cheapest that passes. The note in each panel gives the bytes at the ring and how many times smaller that is than the best uniform format that passes. Every point is a measurement in two fresh processes that agreed bit for bit. Per cell: {'; '.join(rows)}. Rank agreement of the predicted with the measured score over the front's points (Kendall's τ-b): {', '.join(order)}.{extra} Every number is in `{'figS3' if sparse else 'fig2'}_data.json`, read from `results/allocation/<stem>.json`.
"""


def _pick_four(front):
    """Four passing points of the measured front: all float64, the first point at each new format of the
    factor (its steps carry the bytes), and the last passing point; filled, where fewer, by points
    spaced evenly in log bytes; where more, the last factor steps are kept."""
    ok = sorted([p for p in front if p["pass"]], key=lambda p: -p["bytes"])
    if len(ok) <= 4:
        return ok
    picks, seen = [0], {ok[0]["assignment"].get("factor")}
    for i, p in enumerate(ok):
        f = p["assignment"].get("factor")
        if f not in seen:
            seen.add(f)
            picks.append(i)
    last = len(ok) - 1
    steps = [i for i in picks[1:] if i != last][-2:]
    picks = sorted({0, last, *steps})
    lb = np.log10([p["bytes"] for p in ok])
    while len(picks) < 4:
        gaps = [(lb[picks[k]] - lb[picks[k + 1]], k) for k in range(len(picks) - 1)]
        g, k = max(gaps)
        target = (lb[picks[k]] + lb[picks[k + 1]]) / 2
        cand = [i for i in range(picks[k] + 1, picks[k + 1])]
        if not cand:
            cand = [i for i in range(1, last) if i not in picks]
            if not cand:
                break
        picks = sorted(set(picks) | {min(cand, key=lambda i: (abs(lb[i] - target), i))})
    return [ok[i] for i in picks]


def fig_composition():
    allocs = load_allocations()
    stems, dev = front_cells(allocs)
    if not stems:
        raise SystemExit(f"fig3: waiting for allocation results in {ALLOC}")
    cells = front_data(stems, allocs)
    # Two problems: the largest and the smallest saving against the best uniform format.
    cells.sort(key=lambda c: (-c["saving_vs_f64"], c["stem"]))
    chosen = [cells[0]] + ([cells[-1]] if len(cells) > 1 else [])
    _style()
    group_bytes = {st: allocs[st]["group_option_bytes"] for st in stems}
    panels = []
    for c in chosen:
        gb = group_bytes[c["stem"]]
        bars = []
        for p in _pick_four(c["front"]):
            seg = {}
            for key, groups, _, _ in BAR_GROUPS:
                seg[key] = sum(gb[g][p["assignment"][g]] for g in groups if g in p["assignment"])
            bars.append({"bytes": p["bytes"], "score": p["score"], "assignment": p["assignment"], "segments": seg})
        panels.append({"stem": c["stem"], "bars": bars, "saving_vs_uniform": c["saving_vs_uniform"]})
    H = 0.65 + len(panels) * 1.45
    fig = plt.figure(figsize=(W, H))
    left, right = 1.0, 2.8
    for i, pn in enumerate(panels):
        y0 = H - 0.6 - (i + 1) * 1.15 - i * 0.3
        ax = fig.add_axes([left / W, y0 / H, (W - left - right) / W, 1.0 / H])
        _axes_style(ax)
        ax.spines["left"].set_visible(False)
        ax.xaxis.grid(True, color=GRID_C, lw=0.5)
        nb = len(pn["bars"])
        xmax = max(b["bytes"] for b in pn["bars"])
        for j, b in enumerate(pn["bars"]):
            x = 0
            for key, groups, label, color in BAR_GROUPS:
                w = b["segments"][key]
                ax.barh(j, w, left=x, height=0.62, color=color, lw=0, zorder=2)
                fm = "/".join(sorted({b["assignment"][g].split("/")[0] for g in groups if g in b["assignment"]}))
                if w > 0.12 * xmax:
                    ax.text(x + w / 2, j, UNIFORM_NAME.get(fm, fm), ha="center", va="center", fontsize=6,
                            color=SURFACE if key in ("factor", "alpha") else INK)
                x += w
            def fmt_(g):
                f = b["assignment"][g]
                return (UNIFORM_NAME.get(f.split("/")[0], f.split("/")[0])
                        + (" (recomputed)" if f.endswith("consistent") else ""))
            tr = sorted({fmt_(g) for g in ("output", "input") if g in b["assignment"]})
            txt = (", ".join(f"{GROUP_NAME[g]} {fmt_(g)}" for g in ("alpha", "inputs") if g in b["assignment"])
                   + "\n" + ", ".join(([f"hyperparameters {fmt_('hyper')}"] if "hyper" in b["assignment"] else [])
                                      + ([f"transforms {'/'.join(tr)}"] if tr else [])))
            ax.text(xmax * 1.03, j, txt, va="center", fontsize=5.6, color=INK2, clip_on=False, linespacing=1.15)
        ax.set_yticks(range(nb))
        ax.set_yticklabels(["all float64" if j == 0 else ("last passing" if j == nb - 1 else f"front point {j + 1}")
                            for j in range(nb)], fontsize=6.5, color=INK2)
        ax.tick_params(axis="y", length=0)
        ax.invert_yaxis()
        ax.set_xlim(0, xmax * 1.02)
        ax.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(lambda v, _: _bytes_label(v) if v > 0 else "0"))
        prob, n, *_ = _stem_parts(pn["stem"])
        ax.set_title(f"{PROBLEM_NAME.get(prob, prob)}, n = {n:,}", fontsize=7, color=INK, loc="left", pad=3)
        if i == len(panels) - 1:
            ax.set_xlabel("bytes stored", fontsize=7, color=INK2)
    kx = fig.add_axes([left / W, (H - 0.42) / H, (W - left - 0.2) / W, 0.14 / H])
    kx.set_axis_off()
    kx.set_xlim(0, 100)
    kx.set_ylim(0, 1)
    x = 0
    for key, _, label, color in BAR_GROUPS:
        kx.add_patch(Rectangle((x, 0.2), 1.8, 0.6, color=color, lw=0))
        kx.text(x + 2.4, 0.5, label, fontsize=7, color=INK2, va="center")
        x += 6 + 1.25 * len(label)
    fig.text(0.08 / W, 1 - 0.06 / H, "What gets quantized along the front"
             + ("   [DEVELOPMENT CELLS]" if dev else ""), fontsize=8, va="top", color=INK)
    save(fig, "fig3_what_gets_quantized")
    data = {"development": dev, "panels": panels}
    (OUT / "fig3_data.json").write_text(json.dumps(data, indent=1, ensure_ascii=False) + "\n", encoding="utf-8",
                                        newline="\n")
    nm = [PROBLEM_NAME.get(_stem_parts(p["stem"])[0]) for p in panels]
    facs = [p["bars"][-1]["assignment"].get("factor", "").split("/")[0] for p in panels]
    shares = [p["bars"][0]["segments"]["factor"] / p["bars"][0]["bytes"] for p in panels]
    other = [max(abs(sum(v for k_, v in a["segments"].items() if k_ != "factor")
                         - sum(v for k_, v in b["segments"].items() if k_ != "factor")) / a["bytes"]
                     for a, b in zip(pn["bars"], pn["bars"][1:])) if len(pn["bars"]) > 1 else 0.0
             for pn in panels]
    steps = []
    for pn, n_ in zip(panels, nm):
        fs = []
        for b_ in pn["bars"]:
            f = UNIFORM_NAME.get(b_["assignment"].get("factor", "").split("/")[0], "?")
            if not fs or fs[-1] != f:
                fs.append(f)
        steps.append(f"{' → '.join(fs)} for {n_}")
    cap = (f"**Figure 3. What gets quantized along the front.** Only the uncertainty factor's bits matter for "
           f"size: it holds {_rng([100 * x for x in shares], '{:.0f}')} % of the bytes at float64, each step of its "
           f"format moves the whole model, and every other group together changes the bytes by under "
           f"{max(100 * max(other), 0.1):.1g} % between the points shown. The factor's formats along the front: "
           + "; ".join(steps) + "."
           + (" **Development cells: redraw when the bench cells land.**" if dev else "")
           + "\n\nTwo dense models of figure 2: the largest dense saving against float64 and the smallest. "
           "Each bar is one measured point of the allocation's front that passes all three tests, from all float64 "
           "(top) to the cheapest passing point (bottom); between them the first point at each new format of the factor, "
           "filled where needed by a point spaced evenly in log bytes. Bar "
           "length is the bytes the prediction reads; segments are the uncertainty factor, the weights, the inputs, "
           "and the hyperparameters with the transforms together (too small to see). The format of a wide segment is "
           "written in it; the formats of every group are listed at the right, '(recomputed)' where the posterior "
           "was recomputed in float64 after rounding. Every number is in `fig3_data.json`, read from "
           "`results/allocation/<stem>.json` (`measured.front`, `group_option_bytes`).\n")
    (OUT / "fig3_caption.md").write_text(cap, encoding="utf-8", newline="\n")
    for p in panels:
        print("fig3:", p["stem"], [(b["bytes"], b["segments"]) for b in p["bars"]])


def _kappa(stem):
    """Worst over outputs of first_order.kappa on the stored float32 L record (the factor's matrix);
    for a sparse model, the consistent_control record's kappa of K_uu."""
    r = _load_result(stem)
    if r is None:
        return None
    for rec in r["records"]:
        if (rec.get("record") == "cell" and rec["quantity"] == "L" and rec["mode"] == "stored"
                and rec["fmt"] == "f32" and (rec.get("first_order") or {}).get("kappa") is not None):
            k = rec["first_order"]["kappa"]
            return float(max(k)) if isinstance(k, list) else float(k)
    # A sparse model's L record carries no first-order block: its kappa is the sweep's control
    # record's, the worst over outputs of cond(L)^2 of the inducing covariance K_uu.
    for rec in r["records"]:
        if rec.get("record") == "consistent_control" and rec.get("kappa") is not None:
            return float(rec["kappa"])
    return None


def _first_sweep(stem):
    """The 48 cells of the 9-10 November sweep (forrester at n = 32 and 256 belongs to both sets)."""
    prob, n, *_ = _stem_parts(stem)
    return prob in ("heterogeneous", "het_tanh", "hilift", "thermo8") or (prob == "forrester" and n in (32, 256))


def _f1_thresholds():
    """From the first sweep's dense cells: the largest kappa where the quantity passes float32 in
    the stored mode and the smallest where it fails, for alpha and for L (memo F1)."""
    out = {}
    for q in ("alpha", "L"):
        ok, bad = [], []
        for path in sorted(RESULTS.glob("*_dense*.json")):
            if not _first_sweep(path.stem):
                continue
            r = _load_result(path.stem)
            if r is None:
                continue
            k = _kappa(path.stem)
            for rec in r["records"]:
                if (rec.get("record") == "cell" and rec["quantity"] == q and rec["mode"] == "stored"
                        and rec["fmt"] == "f32" and rec["status"] == "ok" and k is not None):
                    (ok if rec["splits"][SPLIT]["tolerance"]["pass"] else bad).append(k)
        if ok and bad:
            out[q] = {"largest_pass": max(ok), "smallest_fail": min(bad), "n_pass": len(ok), "n_fail": len(bad)}
    return out


def fig_kappa():
    allocs = load_allocations()
    pts = []
    for st, r in allocs.items():
        k = _kappa(st)
        if k is None:
            continue
        prob, n, seed, kind, tag = _stem_parts(st)
        pts.append({"stem": st, "kappa": k, "saving_vs_f64": r["report"]["saving_vs_f64"], "kind": kind,
                    "bench": prob in BENCH})
    if not pts:
        raise SystemExit(f"fig4: waiting for allocation results with a sweep record in {ALLOC}")
    thr = _f1_thresholds()
    _style()
    H = 2.6
    fig = plt.figure(figsize=(W * 0.62, H))
    ax = fig.add_axes([0.85 / (W * 0.62), 0.5 / H, (W * 0.62 - 1.05) / (W * 0.62), (H - 0.85) / H])
    _log_axes(ax)
    for q, ls, label in (("alpha", (0, (4, 2)), "weights pass float32 left of this band"),
                         ("L", (0, (1, 1.5)), "factor passes float32 left of this band")):
        if q in thr:
            ax.axvspan(thr[q]["largest_pass"], thr[q]["smallest_fail"], color=NEUTRAL, lw=0, zorder=0)
    for kind, color in (("dense", FRONT_C), ("sparse", SPARSE_C)):
        for bench in (True, False):
            sel = [p for p in pts if p["kind"] == kind and p["bench"] == bench]
            if sel:
                ax.plot([p["kappa"] for p in sel], [p["saving_vs_f64"] for p in sel], ls="none", marker="o", ms=4.2,
                        mfc=color if bench else SURFACE, mec=color, mew=0.9, zorder=3, clip_on=False)
    ax.set_xlabel("conditioning κ of the training covariance (worst output)", fontsize=7, color=INK2)
    ax.set_ylabel("saving at the last passing point\n(bytes at float64 ÷ bytes)", fontsize=7, color=INK2)
    ax.yaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(lambda v, _: f"{v:g}×"))
    ax.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(lambda v, _: _sup_decade(int(round(np.log10(v))))))
    lo = min(p["saving_vs_f64"] for p in pts)
    ax.set_ylim(min(0.9, lo * 0.9), max(5, max(p["saving_vs_f64"] for p in pts) * 1.3))
    yt = [1, 2, 4, 8]
    ax.set_yticks([v for v in yt if ax.get_ylim()[0] <= v <= ax.get_ylim()[1]])
    xs = [p["kappa"] for p in pts] + [v for t in thr.values() for v in (t["largest_pass"], t["smallest_fail"])]
    ax.set_xlim(10 ** (np.floor(np.log10(min(xs))) - 0.3), 10 ** (np.ceil(np.log10(max(xs))) + 0.3))
    ax.xaxis.set_major_locator(matplotlib.ticker.LogLocator(base=10, numticks=7))
    for q, name, side in (("alpha", "weights", "left"), ("L", "factor", "right")):
        if q in thr:   # the weights' label left of its band, the factor's right of its band
            x = thr[q]["largest_pass"] / 1.3 if side == "left" else thr[q]["smallest_fail"] * 1.3
            ax.text(x, ax.get_ylim()[1] * 0.97, f"{name}: float32 passes\nleft of this band, fails right",
                    ha="right" if side == "left" else "left", va="top", fontsize=6, color=INK2, linespacing=1.1)
    kinds = sorted({p["kind"] for p in pts})
    benches = sorted({p["bench"] for p in pts})
    entries = [(c, True, f"{k}, this study") for k, c in (("dense", FRONT_C), ("sparse", SPARSE_C))
               if k in kinds and True in benches] + \
              [(c, False, f"{k}, earlier sweep") for k, c in (("dense", FRONT_C), ("sparse", SPARSE_C))
               if any(p["kind"] == k and not p["bench"] for p in pts)]
    if len(entries) >= 2:
        hs = [matplotlib.lines.Line2D([], [], ls="none", marker="o", ms=4.2, mfc=c if b else SURFACE, mec=c, mew=0.9)
              for c, b, _ in entries]
        leg = ax.legend(hs, [t for _, _, t in entries], loc="lower left", frameon=False, fontsize=6.5,
                        handletextpad=0.3, borderaxespad=0.3)
        for t in leg.get_texts():
            t.set_color(INK2)
    fig.text(0.06 / (W * 0.62), 1 - 0.06 / H, "Why the front bends where it does", fontsize=8, va="top", color=INK)
    save(fig, "fig4_why_the_front_bends")
    data = {"points": sorted(pts, key=lambda p: p["stem"]), "f1_thresholds_first_sweep": thr}
    (OUT / "fig4_data.json").write_text(json.dumps(data, indent=1, ensure_ascii=False) + "\n", encoding="utf-8",
                                        newline="\n")
    big = [p for p in pts if p["saving_vs_f64"] >= 1.5]
    small = [p for p in pts if p["saving_vs_f64"] < 1.5]
    kb = max((p["kappa"] for p in big), default=None)
    ks = min((p["kappa"] for p in small), default=None)
    if big and small and kb < ks:
        first = (f"The saving comes only from well-conditioned models: every model with κ ≤ {_sci(kb, up=True)} "
                 f"shrinks {_rng([p['saving_vs_f64'] for p in big], '{:.3g}')} times, every model with κ ≥ "
                 f"{_sci(ks, up=False)} by "
                 f"{_rng([p['saving_vs_f64'] for p in small], '{:.3g}')} times, and no model lies between.")
    else:
        first = "How the saving at the last passing point depends on the conditioning of the training covariance."
    thr_txt = "; ".join(f"{'the weights pass' if q == 'alpha' else 'the factor passes'} float32 up to "
                        f"κ = {_sci(t['largest_pass'], up=True)} ({t['n_pass']} cell-seeds) and "
                        f"{'fail' if q == 'alpha' else 'fails'} from {_sci(t['smallest_fail'], up=False)} ({t['n_fail']})"
                        for q, t in thr.items())
    # How kappa moves with n on each paper problem (dense, default floor): medians over seeds.
    rises = []
    for prob in BENCH:
        byn = {}
        for p_ in pts:
            pr, n_, _, kind, tag = _stem_parts(p_["stem"])
            if pr == prob and kind == "dense" and not tag:
                byn.setdefault(n_, []).append(p_["kappa"])
        ns = sorted(byn)
        if len(ns) > 1:
            med = [float(np.median(byn[n_])) for n_ in ns]
            rises.append((prob, ns, med, all(b > a for a, b in zip(med, med[1:]))))
    n_txt = ""
    if rises:
        up = [r for r in rises if r[3]]
        n_txt = (" κ rises with the training-set size on " + ("every paper problem" if len(up) == len(rises) else
                 ", ".join(PROBLEM_NAME[r[0]].split(",")[0] for r in up)) + " (median over seeds; "
                 + "; ".join(f"{PROBLEM_NAME[r[0]].split(',')[0]} " + " → ".join(_sci(m) for m in r[2])
                             + f" at n = {', '.join(str(n_) for n_ in r[1])}" for r in rises)
                 + "), so the same function moves left to right as it gets more data.")
    cap = (f"**Figure 4. Why the front bends where it does.** {first}\n\nEach point is one fitted model with a "
           "measured allocation front: blue a dense model, orange a sparse one; filled markers are this study's "
           "five functions, hollow ones the earlier sweep's models. "
           "Horizontal: the 2-norm condition number of the factored training covariance K + σ²I (for a sparse model, "
           "of the inducing covariance), worst output, from the sweep's stored float32 factor record "
           "(`first_order.kappa`; for a sparse model, whose factor record has none, the sweep's control record, `consistent_control.kappa`). Vertical: bytes at float64 divided by bytes at the cheapest passing point of the "
           f"measured front. The grey bands are where the first sweep's dense models change from passing to failing "
           f"float32 when only that part is rounded: {thr_txt}. No first-sweep model lies inside a band, so the "
           f"boundary is not located more closely.{n_txt} Every number is in `fig4_data.json`.\n")
    (OUT / "fig4_caption.md").write_text(cap, encoding="utf-8", newline="\n")
    for p in pts:
        print("fig4:", p["stem"], f"kappa {p['kappa']:.3g} saving x{p['saving_vs_f64']:.3g}")
    print("fig4: F1 thresholds", thr)


def _resident(cell_id):
    """(CPU peak private bytes over baseline through the first prediction, CUDA peak bytes over the
    allocator baseline) of a synthetic size cell, or None where the cell is missing."""
    out = {}
    for dev in ("cpu", "cuda"):
        p = SIZE_DIR / f"{cell_id}_{dev}.json"
        if not p.exists():
            out[dev] = None
            continue
        c = json.loads(p.read_text(encoding="utf-8"))
        serve = [s for s in (c.get("serve") or []) if s.get("status") == "ok"]
        if c.get("status") != "ok" or not serve:
            out[dev] = None
            continue
        s = serve[0]
        if dev == "cpu":
            out[dev] = s["peak_private_over_baseline"].get("predict")
        else:
            cu = s.get("cuda") or {}
            out[dev] = (max(cu[k]["max_allocated"] for k in ("to_cuda", "predict") if k in cu)
                        - cu["baseline_allocated"]) if cu else None
    return out


def table_size():
    allocs = load_allocations()
    dense, dev = front_cells(allocs)
    sparse, _ = front_cells(allocs, sparse=True)
    stems = dense + sparse
    if not stems:
        raise SystemExit(f"table 1: waiting for allocation results in {ALLOC}")
    rows = []
    for st in stems:
        r = allocs[st]
        rep = r["report"]
        prob, n, seed, kind, tag = _stem_parts(st)
        ids = ({"float64": f"sparse_n{n}_m256_r1_d6_float64", "float32": f"sparse_n{n}_m256_r1_d6_float32"}
               if kind == "sparse" else
               {"float64": f"dense_n{n}_r1_d6_float64", "float32": f"dense_n{n}_r1_d6_float32"})
        rows.append({"stem": st, "problem": prob, "n": n, "kind": kind, "outputs": r["n_outputs"],
                     "bytes_f64": rep["bytes_f64"], "uniform_best_pass": rep["uniform_best_pass"],
                     "allocation_last_pass_bytes": rep["allocation_last_pass"]["bytes"],
                     "allocation_assignment": rep["allocation_last_pass"]["assignment"],
                     "saving_vs_uniform": rep["saving_vs_uniform"], "saving_vs_f64": rep["saving_vs_f64"],
                     "size_cells": ids, "resident": {dt: _resident(cid) for dt, cid in ids.items()}})
    fb = lambda v: "—" if v is None else _bytes_label(float(f"{v:.3g}"))  # noqa: E731
    head = ["model", "n", "f64", "best uniform", "alloc.", "gain", "res. f64 CPU", "res. f64 GPU",
            "res. f32 CPU", "res. f32 GPU"]
    md = ["**Table 1. How big a model is.** Bytes the prediction reads at float64, at the best uniform format "
          "that passes all three tests, and at the allocation's cheapest passing point; and the memory a serving "
          "process adds through its first prediction for a synthetic model of the same shape (one output, six "
          "inputs)." + (" **Development cells: redraw when the bench cells land.**" if dev else ""), "",
          "| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
    csv = ["stem,n,kind,outputs,bytes_f64,uniform_best_format,uniform_best_bytes,allocation_bytes,saving_vs_uniform,"
           "saving_vs_f64,resident_f64_cpu,resident_f64_cuda,resident_f32_cpu,resident_f32_cuda,size_cell_f64,"
           "size_cell_f32"]
    for r in rows:
        ub = r["uniform_best_pass"]
        res = r["resident"]
        md.append("| " + " | ".join([
            f"{PROBLEM_NAME.get(r['problem'], r['problem']).split(',')[0]}{', sparse' if r['kind'] == 'sparse' else ''}",
            f"{r['n']:,}", fb(r["bytes_f64"]), f"{UNIFORM_NAME.get(ub['format'], ub['format'])}, {fb(ub['bytes'])}",
            fb(r["allocation_last_pass_bytes"]), f"{r['saving_vs_uniform']:.3g}×",
            fb(res['float64']['cpu']), fb(res['float64']['cuda']),
            fb(res['float32']['cpu']), fb(res['float32']['cuda'])]) + " |")
        csv.append(",".join("" if v is None else str(v) for v in [
            r["stem"], r["n"], r["kind"], r["outputs"], r["bytes_f64"], ub["format"], ub["bytes"],
            r["allocation_last_pass_bytes"], r["saving_vs_uniform"], r["saving_vs_f64"],
            res["float64"]["cpu"], res["float64"]["cuda"], res["float32"]["cpu"], res["float32"]["cuda"],
            r["size_cells"]["float64"], r["size_cells"]["float32"]]))
    md += ["", "Columns: f64, bytes at float64; best uniform, the cheapest uniform format that passes, and its "
               "bytes; alloc., bytes at the allocation's cheapest passing point; gain, best uniform ÷ alloc.; "
               "res., resident memory of a float64 or float32 model on the CPU or GPU. Units are decimal (1 kB = 1000 bytes), three significant digits. Bytes stored count the factor as a "
               "triangle (`results/allocation/<stem>.json`, `report`). Resident memory is measured on synthetic "
               "models of the same n (and m = 256 for the sparse ones) with one output and six inputs, built in "
               "float64 or float32 (`results/size/<cell>_<cpu|cuda>.json`, cell names in `table1_size.csv`): on "
               "the CPU the peak committed private memory over the process baseline, on the GPU the peak CUDA "
               "allocation over the allocator's baseline, both through the first prediction; the product holds "
               "the dense factor as a full square, so resident memory is not the stored bytes. "
               + ("'—': that size cell is not measured. " if any('—' in r for r in md if r.startswith('| ')) else '')
               + "Every number is in `table1_size.json`."]
    (OUT / "table1_size.md").write_text("\n".join(md) + "\n", encoding="utf-8", newline="\n")
    (OUT / "table1_size.csv").write_text("\n".join(csv) + "\n", encoding="utf-8", newline="\n")
    (OUT / "table1_size.json").write_text(json.dumps({"development": dev, "rows": rows}, indent=1,
                                                     ensure_ascii=False) + "\n", encoding="utf-8", newline="\n")
    print("wrote", OUT / "table1_size.md", ".csv and .json:", len(rows), "rows")


# --- palette check -----------------------------------------------------------------------------
# Machado, Oliveira and Fernandes (2009) full-severity simulation matrices, linear RGB.
CVD = {"protanopia": [[0.152286, 1.052583, -0.204868], [0.114503, 0.786281, 0.099216],
                      [-0.003882, -0.048116, 1.051998]],
       "deuteranopia": [[0.367322, 0.860646, -0.227968], [0.280085, 0.672501, 0.047413],
                        [-0.011820, 0.042940, 0.968881]],
       "tritanopia": [[1.255528, -0.076749, -0.178779], [-0.078411, 0.930809, 0.147602],
                      [0.004733, 0.691367, 0.303900]]}
CATEGORICAL = ["#2a78d6", "#eb6834", "#1baf7a", "#8c304c"]   # every figure, this order (see FIG2_LINES)


def _oklab(lin):
    m1 = np.array([[0.4122214708, 0.5363325363, 0.0514459929], [0.2119034982, 0.6806995451, 0.1073969566],
                   [0.0883024619, 0.2817188376, 0.6299787005]])
    m2 = np.array([[0.2104542553, 0.7936177850, -0.0040720468], [1.9779984951, -2.4285922050, 0.4505937099],
                   [0.0259040371, 0.7827717662, -0.8086757660]])
    return m2 @ np.cbrt(m1 @ lin)


def palette_check():
    def lin(h):
        rgb = np.array(matplotlib.colors.to_rgb(h))
        return np.where(rgb <= 0.04045, rgb / 12.92, ((rgb + 0.055) / 1.055) ** 2.4)
    out = {"palette": CATEGORICAL, "method": "Machado et al. 2009 severity 1.0 in linear sRGB, "
                                             "Delta E in OKLab x 100", "pairs": []}
    for i in range(len(CATEGORICAL)):
        for j in range(i + 1, len(CATEGORICAL)):
            a, b = lin(CATEGORICAL[i]), lin(CATEGORICAL[j])
            row = {"pair": [CATEGORICAL[i], CATEGORICAL[j]], "adjacent": j == i + 1,
                   "normal": float(100 * np.linalg.norm(_oklab(a) - _oklab(b)))}
            for k, m in CVD.items():
                m = np.array(m)
                row[k] = float(100 * np.linalg.norm(_oklab(np.clip(m @ a, 0, 1)) - _oklab(np.clip(m @ b, 0, 1))))
            row["passes_15_normal_8_cvd"] = bool(row["normal"] >= 15 and
                                                 min(row[k] for k in CVD) >= 8)
            out["pairs"].append(row)
    OUT.mkdir(exist_ok=True)
    (OUT / "palette_check.json").write_text(json.dumps(out, indent=1) + "\n", encoding="utf-8", newline="\n")
    for r in out["pairs"]:
        print("palette:", r["pair"], "adjacent" if r["adjacent"] else "        ",
              " ".join(f"{k} {r[k]:.1f}" for k in ("normal", "protanopia", "deuteranopia", "tritanopia")))


# Figures 1, S1 and S2 need only the sweep; "FS2"/"FS3" are the first sweep's figures 2 and 3
# (figures/first_sweep/); the allocation figures and the table wait for results/allocation/.
FIGS = {"1": fig1, "1a-gif": fig1a_gif, "S1": figS1, "S2": figS2, "FS2": fig2, "FS3": fig3}
ALLOC_FIGS = {"2": fig_front, "S3": lambda: fig_front(sparse=True), "3": fig_composition, "4": fig_kappa}


def main():
    sys.stdout.reconfigure(encoding="utf-8")
    p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    p.add_argument("--fig", choices=sorted(FIGS) + sorted(ALLOC_FIGS), action="append", default=[])
    p.add_argument("--table", choices=["size"], action="append", default=[])
    p.add_argument("--check-palette", action="store_true")
    p.add_argument("--all", action="store_true")
    a = p.parse_args()
    if not (a.all or a.fig or a.table or a.check_palette):
        p.error("give --fig, --table, --check-palette or --all")
    for k in (sorted(FIGS) if a.all else [f for f in a.fig if f in FIGS]):
        FIGS[k]()
    if a.all or a.check_palette:
        palette_check()
    later = [(k, ALLOC_FIGS[k]) for k in (sorted(ALLOC_FIGS) if a.all else [f for f in a.fig if f in ALLOC_FIGS])]
    if a.all or "size" in a.table:
        later.append(("table size", table_size))
    for name, fn in later:
        if a.all:
            try:
                fn()
            except SystemExit as e:   # a figure waiting for its data is reported, not fatal, under --all
                print(f"{name}: not drawn: {e}")
        else:
            fn()
    return 0


if __name__ == "__main__":
    sys.exit(main())
