# /// script # requires-python = ">=3.12" # dependencies = [ # "matplotlib==3.10.7", # "numpy==2.3.4", # "pyarrow==21.0.0", # "zstandard==0.25.0", # ] # /// """Make the figures of the dataset card from this release's own data and records. uv run figures/make_figures.py # from the dataset root; writes figures/*.png Inputs: data/connectome-v1/ (neurons.parquet, manifest.json, matrix-full.tar.zst) and records/ (results/*.json, results/culling-equivalence.md). The numbers of the gate null test are quoted from records/validation-log.md (entry *Validation of the recalibrated rule*, 2026-11-04), which is text only. """ from __future__ import annotations import io import json import re import tarfile from pathlib import Path import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt # noqa: E402 import numpy as np # noqa: E402 import pyarrow.parquet as pq # noqa: E402 import zstandard # noqa: E402 ROOT = Path(__file__).resolve().parents[1] DATA = ROOT / "data" / "connectome-v1" RES = ROOT / "records" / "results" OUT = ROOT / "figures" DPI = 200 # figures are laid out at 100 px per inch, so this is 2x # Palette (validated: first three categorical slots, all pairs, light surface) SURFACE = "#fcfcfb" INK = "#0b0b0b" INK2 = "#52514e" MUTED = "#898781" GRID = "#e1e0d9" AXIS = "#c3c2b7" BLUE, ORANGE, AQUA = "#2a78d6", "#eb6834", "#1baf7a" # blue, orange, aqua OTHER = "#b9b8b1" EXC, INH = "#2a78d6", "#e34948" # diverging pair: blue <-> red GOOD, CRIT = "#0ca30c", "#d03b3b" # status: pass / fail (always with a text label) plt.rcParams.update({ "figure.facecolor": SURFACE, "axes.facecolor": SURFACE, "savefig.facecolor": SURFACE, "font.family": "sans-serif", "font.size": 10, "text.color": INK, "axes.edgecolor": AXIS, "axes.linewidth": 0.8, "axes.labelcolor": INK2, "axes.titlesize": 11, "axes.titleweight": "bold", "axes.titlelocation": "left", "axes.spines.top": False, "axes.spines.right": False, "axes.grid": True, "axes.axisbelow": True, "grid.color": GRID, "grid.linewidth": 0.6, "xtick.color": MUTED, "ytick.color": MUTED, "xtick.labelcolor": INK2, "ytick.labelcolor": INK2, "legend.frameon": False, "lines.linewidth": 2, }) def save(fig: plt.Figure, name: str) -> None: fig.savefig(OUT / name, dpi=DPI, bbox_inches="tight", pad_inches=0.15) plt.close(fig) print("wrote", OUT / name) # ----------------------------------------------------------------------------- neurons REGION = [ # (label, colour, superclass prefixes); intrinsic, sensory and motor alike ("Optic lobe", BLUE, ("ol_", "visual_")), ("Central brain", ORANGE, ("cb_",)), ("Ventral nerve cord", AQUA, ("vnc_",)), ] def fig_neurons() -> None: t = pq.read_table(DATA / "neurons.parquet", columns=["superclass", "x", "y", "z"]) sc = np.array([s or "" for s in t["superclass"].to_pylist()]) x, y, z = (t[c].to_numpy(zero_copy_only=False) for c in "xyz") ok = np.isfinite(x) group = np.full(len(sc), -1) for g, (_, _, prefixes) in enumerate(REGION): for prefix in prefixes: group[np.char.startswith(sc, prefix)] = g n_other = int(np.sum(ok & (group == -1))) xr = np.nanmax(x) - np.nanmin(x) zr = np.nanmax(z) - np.nanmin(z) fig, axes = plt.subplots(1, 2, figsize=(12.5, 5.0), gridspec_kw={"width_ratios": [xr, zr]}) views = [("Front view (x, y)", x, y), ("Side view (z, y)", z, y)] for ax, (title, h, v) in zip(axes, views, strict=True): for g, (_, colour, _) in enumerate(REGION): m = ok & (group == g) ax.scatter(h[m], v[m], s=0.25, c=colour, alpha=0.35, lw=0, rasterized=True) m = ok & (group == -1) # the small group goes on top, so it stays visible ax.scatter(h[m], v[m], s=0.8, c="#5f5e5a", alpha=0.6, lw=0, rasterized=True) ax.set_aspect("equal") ax.invert_yaxis() # y grows ventrally in the source volume ax.set_title(title) ax.set_xlabel("voxels (8 nm)") ax.grid(False) ax.tick_params(labelsize=8) axes[0].set_ylabel("y, voxels (8 nm)") handles = [plt.Line2D([], [], ls="", marker="o", ms=7, color=c, label=f"{lbl} ({int(np.sum(ok & (group == g))):,})") for g, (lbl, c, _) in enumerate(REGION)] handles.append(plt.Line2D([], [], ls="", marker="o", ms=7, color="#5f5e5a", label=f"Ascending, descending, efferent, unlabelled ({n_other:,})")) fig.legend(handles=handles, loc="lower center", ncol=4, fontsize=9, bbox_to_anchor=(0.5, -0.02), handletextpad=0.2, columnspacing=1.2) fig.suptitle(f"MaleCNS v1.0: {int(ok.sum()):,} traced neurons with a position, by superclass", x=0.01, ha="left", fontsize=12, fontweight="bold") fig.text(0.01, 0.905, "Soma position, else 'to soma' location, else the synapse-weighted " "mean of partner positions. 496 neurons have no position.", fontsize=9, color=INK2) fig.subplots_adjust(top=0.82, bottom=0.2, left=0.07, right=0.99, wspace=0.1) save(fig, "neurons.png") # ----------------------------------------------------------------------------- matrix def load_full() -> dict[str, np.ndarray]: raw = (DATA / "matrix-full.tar.zst").read_bytes() tar_bytes = zstandard.ZstdDecompressor().decompress(raw, max_output_size=1 << 32) arrays = {} with tarfile.open(fileobj=io.BytesIO(tar_bytes)) as tar: for member in tar.getmembers(): f = tar.extractfile(member) assert f is not None arrays[member.name.removesuffix(".npy")] = np.load(io.BytesIO(f.read())) return arrays def int_log_hist(values: np.ndarray, top: int, n: int = 60) -> tuple[np.ndarray, np.ndarray]: """Histogram of positive integers in log-spaced integer bins [a, b): bin centres (geometric mean of the integers a..b-1) and counts per integer value.""" edges = np.unique(np.round(np.logspace(0, np.log10(top + 1), n)).astype(int)) h, e = np.histogram(values, bins=edges) centre = np.sqrt(e[:-1] * (e[1:] - 1)) dens = h / np.diff(e) keep = dens > 0 return centre[keep], dens[keep] def fig_connectivity() -> None: a = load_full() w = a["weights"].astype(np.int32) n_syn = np.abs(w) out_deg = np.diff(a["indptr"]) in_deg = np.bincount(a["indices"], minlength=len(out_deg)) exc, inh = w > 0, w < 0 fig, axes = plt.subplots(1, 2, figsize=(11, 4.4)) ax = axes[0] top = int(n_syn.max()) for mask, colour, label in ((exc, EXC, "excitatory (ACh)"), (inh, INH, "inhibitory (GABA, Glu, His)")): ax.plot(*int_log_hist(n_syn[mask], top), color=colour, label=label) ax.set_xscale("log") ax.set_yscale("log") ax.set_xlabel("synapses per edge") ax.set_ylabel("edges per synapse-count value") ax.set_title("Edge weights, full matrix") ax.legend(fontsize=9, loc="upper right") e_share = exc.sum() / len(w) s_share = n_syn[exc].sum() / n_syn.sum() ax.text(0.0, -0.2, f"{len(w) / 1e6:.2f} M edges, {n_syn.sum() / 1e6:.1f} M synapses " "(sign-0 senders omitted)\n" f"excitatory: {e_share:.1%} of edges, {s_share:.1%} of synapses\n" f"{np.mean(n_syn == 1):.1%} of edges are a single synapse; max {top:,}", transform=ax.transAxes, fontsize=8.5, color=INK2, va="top") ax = axes[1] top = int(max(out_deg.max(), in_deg.max())) for deg, colour, label in ((out_deg, BLUE, "out-degree (postsynaptic partners)"), (in_deg, ORANGE, "in-degree (presynaptic partners)")): ax.plot(*int_log_hist(deg[deg > 0], top, 45), color=colour, label=label) ax.set_xscale("log") ax.set_yscale("log") ax.set_xlabel("partners per neuron") ax.set_ylabel("neurons per degree value") ax.set_title("Degree distributions, full matrix") ax.legend(fontsize=9, loc="lower left") ax.text(0.0, -0.2, f"median out-degree {int(np.median(out_deg))}, in-degree {int(np.median(in_deg))}\n" f"{int(np.sum(out_deg == 0)):,} neurons have no outgoing edge in the matrix " "(4,143 of them are sign 0)", transform=ax.transAxes, fontsize=8.5, color=INK2, va="top") fig.subplots_adjust(wspace=0.25) save(fig, "connectivity.png") # ----------------------------------------------------------------------------- culling def fig_culling() -> None: man = json.loads((DATA / "manifest.json").read_text()) variants = ["full", "min2", "min3", "min5", "min10"] edges = [man["variants"][v]["edge_fraction"] * 100 for v in variants] syn = [man["variants"][v]["synapse_fraction"] * 100 for v in variants] md = (RES / "culling-equivalence.md").read_text() checks = {} for v, r, rn, lat, ln, same, sn in re.findall( r"^\| (min\d+) \| (\d+)/(\d+) \| (\d+)/(\d+) \| (\d+)/(\d+) \|", md, re.M): checks[v] = (int(r) + int(lat) + int(same), int(rn) + int(ln) + int(sn)) fig, axes = plt.subplots(1, 2, figsize=(11, 4.2), gridspec_kw={"width_ratios": [1.15, 1]}) ax = axes[0] xi = np.arange(len(variants)) bw = 0.38 for off, vals, colour, label in ((-bw / 2, edges, BLUE, "edges kept"), (bw / 2, syn, ORANGE, "synapses kept")): bars = ax.bar(xi + off, vals, bw - 0.03, color=colour, label=label) for b, v, val in zip(bars, variants, vals, strict=True): if v != "full": # full is 100% by definition ax.text(b.get_x() + b.get_width() / 2, val + 1.5, f"{val:.0f}%", ha="center", fontsize=8, color=INK2) ax.set_xticks(xi, [f"{v}\n(≥{man['variants'][v]['min_synapses']} syn)" for v in variants]) ax.set_ylim(0, 112) ax.set_ylabel("% of the full matrix") ax.set_title("What each culled variant keeps") ax.legend(fontsize=9, loc="upper right", ncol=2, bbox_to_anchor=(1, 1.02)) ax.grid(axis="x", visible=False) ax = axes[1] culled = variants[1:] failed = [checks[v][1] - checks[v][0] for v in culled] yi = np.arange(len(culled))[::-1] ax.barh(yi, failed, 0.55, color=CRIT) for y, v, f in zip(yi, culled, failed, strict=True): ax.text(f + 0.6, y, f"{f} of {checks[v][1]} checks fail · ✘ FAIL", va="center", fontsize=9, color=INK) ax.set_yticks(yi, culled) ax.set_xlim(0, 62) ax.set_xlabel("failed checks (rates, latencies, chain verdicts); a pass needs 0") ax.set_title("Pruning equivalence to full (pre-registered)") ax.grid(axis="y", visible=False) fig.subplots_adjust(wspace=0.3) save(fig, "culling.png") # ----------------------------------------------------------------------------- chains CHAINS = [("LC4", "DNp01", "escape", "FAIL: activity after the stimulus"), ("LC16", "MDN", "back away", "FAIL: readout too weak, not specific"), ("LC9", "DNp09", "approach", "PASS")] READOUT_COLOUR = {"DNp01": BLUE, "MDN": ORANGE, "DNp09": AQUA} RATES = [25, 50, 100, 150, 200] def readout_rates(cond: dict, readout: str) -> np.ndarray: """Per trial 0-29: spikes in [0, 300) ms over all bodies / 0.3 s / bodies. The rate definition of the chain tests (records/preregistration.md).""" trials = cond["trials"] counts = np.asarray(cond["counts"][readout], dtype=float) # trial x body rows = [i for i, t in enumerate(trials) if t < 30] return counts[rows].sum(axis=1) / 0.3 / counts.shape[1] def fig_chains() -> None: conds = json.loads((RES / "chain-tests-trials.json").read_text())["conditions"] fig, axes = plt.subplots(1, 3, figsize=(12.5, 4.2)) for ax, (src, intended, name, verdict) in zip(axes, CHAINS, strict=True): ends, upper = {}, 0.0 for r, colour in READOUT_COLOUR.items(): m, se = [], [] for rate in RATES: x = readout_rates(conds[f"{src}/{rate}Hz"], r) m.append(x.mean()) se.append(x.std(ddof=1) / np.sqrt(len(x))) m, se = np.array(m), np.array(se) lw = 2.4 if r == intended else 1.4 ax.fill_between(RATES, m - 1.96 * se, m + 1.96 * se, color=colour, alpha=0.15, lw=0) ax.plot(RATES, m, color=colour, lw=lw, marker="o", ms=4.5, label=r + (" (intended)" if r == intended else "")) ends[r] = m[-1] upper = max(upper, float(np.max(m + 1.96 * se))) # direct-label line ends, skipping labels that would collide (the legend has all) span = max(ends.values()) or 1.0 last = None for r in sorted(ends, key=lambda k: (ends[k], k != intended)): if last is not None and ends[r] - last < 0.08 * span: continue ax.annotate(r, (RATES[-1], ends[r]), xytext=(5, 0), textcoords="offset points", va="center", fontsize=8.5, color=INK2, fontweight="bold" if r == intended else "normal") last = ends[r] ax.set_ylim(bottom=-0.04 * span, top=max(1.12 * span, 1.03 * upper)) colour = GOOD if verdict.startswith("PASS") else CRIT ax.set_title(f"{src} → {intended} ({name})") ax.text(0.02, 0.97, ("✔ " if colour == GOOD else "✘ ") + verdict, transform=ax.transAxes, va="top", fontsize=9, color=colour, fontweight="bold") ax.set_xticks(RATES) ax.set_xlim(15, 235) ax.set_xlabel("input rate (Hz), right-side source neurons") axes[0].set_ylabel("readout rate (Hz), mean over 30 trials") axes[1].text(0.02, 0.88, "note: own y scale", transform=axes[1].transAxes, fontsize=8.5, color=INK2, va="top") handles = [plt.Line2D([], [], color=c, marker="o", ms=4.5, label=r) for r, c in READOUT_COLOUR.items()] fig.legend(handles=handles, loc="upper right", ncol=3, fontsize=9, bbox_to_anchor=(0.995, 1.06)) fig.suptitle("Chain tests on MaleCNS (pre-registered): readout rates in the stimulus window", x=0.01, ha="left", y=1.04, fontsize=12, fontweight="bold") fig.text(0.01, -0.1, "Readout rate: spikes in [0, 300) ms per body, 30 trials (seeds 0-29). " "Bands: 95% interval of the mean. LC4, and LC16's pre-registered alternative " "LC16 + LPLC1 + LPLC2 (not shown), both fail\nthe post-stimulus criterion " "because of one self-sustaining loop of 49 VNC-side neurons that strong " "giant-fiber (DNp01) drive switches on (records/validation-log.md).", fontsize=8.5, color=INK2) fig.subplots_adjust(wspace=0.22) save(fig, "chains.png") # ----------------------------------------------------------------------------- gate def fig_gate() -> None: # records/validation-log.md (recalibrated-rule validation): 200 null replicates of the full # 17-condition gate on our engine only (fake "Brian2" and fake "ours" drawn from the # same engine), and 50 replicates per deliberately broken engine. null = [("Original\npre-registered rule", 184, 200, (87, 95), ORANGE), ("Recalibrated rule\n(permutation tests,\nBonferroni)", 9, 200, (2.4, 8.3), BLUE)] # failing condition checks per gate, recalibrated rule: (min, median, max); 50/50 failed detect = [("refractory-input bug", 24, 28, 31), ("w_syn × 1.05", 15, 20, 25)] fig, axes = plt.subplots(1, 2, figsize=(11.5, 3.8), gridspec_kw={"width_ratios": [1.1, 1]}) ax = axes[0] y = np.arange(len(null))[::-1] for yi, (_, k, n, (lo, hi), colour) in zip(y, null, strict=True): p = 100 * k / n ax.barh(yi, p, 0.5, color=colour) ax.plot([lo, hi], [yi, yi], color=INK, lw=1.2) for edge in (lo, hi): ax.plot([edge, edge], [yi - 0.08, yi + 0.08], color=INK, lw=1.2) if p > 50: ax.text(lo - 2, yi, f"{p:.0f}% ({k}/{n})", va="center", ha="right", fontsize=9.5, color="#ffffff", fontweight="bold") else: ax.text(hi + 2, yi, f"{p:.1f}% ({k}/{n}; 95% CI {lo}–{hi}%)", va="center", fontsize=9.5, color=INK) ax.axvline(5, color=INK2, lw=1) ax.text(6, 1.42, "5% target", fontsize=8.5, color=INK2, va="center") ax.set_yticks(y, [n[0] for n in null]) ax.set_xlim(0, 100) ax.set_ylim(-0.5, 1.55) ax.set_xlabel("% of replicates with ≥ 1 false fail (200 replicates)") ax.set_title("False alarms: a correct engine judged against itself") ax.grid(axis="y", visible=False) ax = axes[1] yi = np.arange(len(detect))[::-1] for y_, (_, lo, med, hi) in zip(yi, detect, strict=True): ax.plot([lo, hi], [y_, y_], color=BLUE, lw=6, solid_capstyle="round", alpha=0.45) ax.plot([med], [y_], "o", ms=9, color=BLUE, mec=SURFACE, mew=2) ax.text(hi + 1.2, y_, f"median {med} (range {lo}–{hi}) of 68\n50/50 gates fail", va="center", fontsize=9, color=INK) ax.axvline(1, color=INK2, lw=1) ax.text(1.6, 1.42, "1 failing check fails the gate", fontsize=8.5, color=INK2, va="center") ax.set_yticks(yi, [d[0] for d in detect]) ax.set_xlim(0, 52) ax.set_ylim(-0.5, 1.55) ax.set_xlabel("failing condition checks per gate, recalibrated rule") ax.set_title("Detection: deliberately broken engines") ax.grid(axis="y", visible=False) fig.suptitle("Engine-check gate calibration on our engine alone (exploratory; " "records/validation-log.md)", x=0.01, ha="left", y=1.04, fontsize=12, fontweight="bold") fig.text(0.01, -0.1, "The original rule also failed 50/50 gates for both broken engines. " "The recorded engine-check verdict stays FAIL under the original rule; " "the recalibrated rule's results are exploratory only.", fontsize=8.5, color=INK2) fig.subplots_adjust(wspace=0.55) save(fig, "gate_calibration.png") # ----------------------------------------------------------------------------- speed def fig_speed() -> None: def table(name: str) -> dict[tuple[str, float], float]: d = json.loads((RES / name).read_text()) return {(r["stimulus"], r["rate"]): r["median_per_sim_s"] for r in d["results"]} plain, vec = table("speed-plain-rerun-2.json"), table("speed-vec.json") keys = [k for k in vec if k in plain] stim_order = ["LC4", "LC16", "LC9", "LC16+LPLC1+LPLC2"] keys.sort(key=lambda k: (stim_order.index(k[0]), k[1])) labels = [f"{s.replace('+', ' + ')}, {r:g} Hz" for s, r in keys] yi = np.arange(len(keys))[::-1] bh = 0.38 fig, ax = plt.subplots(figsize=(10, 6.2)) ax.barh(yi + bh / 2, [plain[k] for k in keys], bh - 0.05, color=OTHER, label="plain kernel") ax.barh(yi - bh / 2, [vec[k] for k in keys], bh - 0.05, color=BLUE, label="vec kernel (default)") for y, k in zip(yi, keys, strict=True): ax.text(plain[k] + 0.08, y + bh / 2, f"{plain[k]:.2f}", va="center", fontsize=8, color=INK2) ax.text(vec[k] + 0.08, y - bh / 2, f"{vec[k]:.2f} ({plain[k] / vec[k]:.1f}× faster)", va="center", fontsize=8, color=INK, zorder=3, bbox={"boxstyle": "square,pad=0.1", "fc": SURFACE, "ec": "none"}) ax.axvline(1.0, color=INK2, lw=1, zorder=2) ax.text(1.03, len(keys) - 0.35, "real time", fontsize=8.5, color=INK2) ax.set_yticks(yi, labels) ax.set_xlabel("wall seconds per simulated second (median of 5; one core; lower is faster)") ax.set_title("Speed on the dev container (provisional, not a gated result)", pad=28) ax.legend(fontsize=9, loc="lower left", ncol=2, bbox_to_anchor=(0, 1.0)) ax.grid(axis="y", visible=False) ax.set_xlim(0, max(plain.values()) * 1.15) fig.text(0.01, -0.02, "Whole MaleCNS, full matrix (165,122 neurons, 24.5 M edges), float32. " "Paired runs on a shared 4-vCPU Xeon @ 2.80 GHz (records speed-vec.json, " "speed-plain-rerun-2.json). The vec kernel is bit-identical to plain on all " "1,520 chain-test trials.", fontsize=8.5, color=INK2, wrap=True) save(fig, "speed.png") if __name__ == "__main__": OUT.mkdir(exist_ok=True) fig_neurons() fig_connectivity() fig_culling() fig_chains() fig_gate() fig_speed()