#!/usr/bin/env python3 """Compare a suicide-ball sweep (`kills_user = true`) against a free-ball control (`kills_user = false`) over the same (view_dist, radius) grid. Renders two panels: 1. the winner phase diagram for the suicide ball, with the estimated phase boundary (mean RED-BLU food-share difference == 0) overlaid; 2. cuts of the mean difference against weapon radius at a few view_dist values, suicide (solid) vs free (dashed). The shaded band above zero is where the weapon *benefits the hawks*; the radius -> 0 edge of the suicide curves is the "pure self-harm" control. Example ------- python3 tools/plot_suicide.py sweep_out/suicide/results.jsonl \ sweep_out/free/results.jsonl -o sweep_out/suicide_phase.png """ from __future__ import annotations import argparse import json from pathlib import Path import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import TwoSlopeNorm from matplotlib.lines import Line2D RED = "#d62728" BLU = "#1f77b4" TIE = "#9e9e9e" def load(path: Path) -> dict: rows = [] with path.open() as f: for line in f: line = line.strip() if line: rows.append(json.loads(line)) return { "vd": np.array([float(r["view_dist"]) for r in rows]), "rad": np.array([float(r["weapon_radius"]) for r in rows]), "diff": np.array([float(r["mean_diff"]) for r in rows]), "sigma": np.array([float(r["sigma"]) for r in rows]), "n": np.array([float(r["n"]) for r in rows]), "winner": [r["winner"] for r in rows], "stopped": [r["stopped"] for r in rows], } def outcome(winner: str, stopped: str) -> str: return "tie" if stopped != "sigma" else winner def marker_sizes(n: np.ndarray, lo: float = 18.0, hi: float = 260.0) -> np.ndarray: if n.max() <= n.min(): return np.full_like(n, (lo + hi) / 2) scaled = (n - n.min()) / (n.max() - n.min()) return lo + scaled * (hi - lo) def cut_curve(d: dict, vd: float) -> tuple[np.ndarray, np.ndarray]: """Mean difference as a function of radius at `view_dist == vd`.""" m = np.isclose(d["vd"], vd) order = np.argsort(d["rad"][m]) return d["rad"][m][order], d["diff"][m][order] def main() -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("suicide", type=Path, help="results.jsonl with kills_user = true") ap.add_argument("free", type=Path, nargs="?", help="optional results.jsonl with kills_user = false") ap.add_argument("-o", "--out", type=Path, default=Path("sweep_out/suicide_phase.png")) ap.add_argument("--cuts", default="75,150,225,300", help="comma-separated view_dist values for the cut panel") ap.add_argument("--title", default="Suicide ball (kills_user = true): hawks vs doves") ap.add_argument("--dpi", type=int, default=180) args = ap.parse_args() s = load(args.suicide) f = load(args.free) if args.free else None cuts = [float(x) for x in args.cuts.split(",") if x.strip()] if f is None: fig, axes = plt.subplots(1, 2, figsize=(15, 6.2)) else: fig, axes = plt.subplots(1, 3, figsize=(20, 6.2)) # ---- Panel 1: suicide-ball winner phase diagram ---------------------- # ax = axes[0] labels = [outcome(w, st) for w, st in zip(s["winner"], s["stopped"])] colors = [{"red": RED, "blu": BLU, "tie": TIE}[l] for l in labels] ax.scatter(s["vd"], s["rad"], s=marker_sizes(s["n"]), c=colors, marker="s", edgecolors="black", linewidths=0.6, alpha=0.9, zorder=3) try: ax.tricontour(s["vd"], s["rad"], s["diff"], levels=[0.0], colors="black", linewidths=2.0, zorder=4) except Exception: pass ax.set_title("Suicide ball: winner (marker size ∝ seeds)") ax.set_xlabel("view_dist") ax.set_ylabel("weapon radius") ax.set_axisbelow(True) ax.grid(alpha=0.25) ax.legend(handles=[ Line2D([], [], marker="s", linestyle="", color=RED, markersize=11, label="red (hawk) wins"), Line2D([], [], marker="s", linestyle="", color=BLU, markersize=11, label="blue (dove) wins"), Line2D([], [], marker="s", linestyle="", color=TIE, markersize=11, label="undecided (hit cap)"), Line2D([], [], color="black", linewidth=2, label="boundary: mean diff = 0"), ], loc="best", framealpha=0.9) # ---- Panel 2: continuous field --------------------------------------- # ax = axes[1] vmax = max(abs(s["diff"]).max(), 1e-6) norm = TwoSlopeNorm(vmin=-vmax, vcenter=0.0, vmax=vmax) sc = ax.scatter(s["vd"], s["rad"], s=marker_sizes(s["n"]), c=s["diff"], cmap="coolwarm", norm=norm, marker="s", edgecolors="black", linewidths=0.6, zorder=3) try: ax.tricontour(s["vd"], s["rad"], s["diff"], levels=[0.0], colors="black", linewidths=2.0, zorder=4) except Exception: pass cb = fig.colorbar(sc, ax=ax, fraction=0.046, pad=0.04) cb.set_label("mean RED-BLU food-share difference") ax.set_title("Mean difference (suicide ball)") ax.set_xlabel("view_dist") ax.set_axisbelow(True) ax.grid(alpha=0.25) # ---- Panel 3: radius cuts, suicide vs free --------------------------- # if f is not None: ax = axes[2] cmap = plt.get_cmap("viridis") for k, vd in enumerate(cuts): c = cmap(k / max(len(cuts) - 1, 1)) rad, diff = cut_curve(s, vd) if len(rad): ax.plot(rad, diff, color=c, linewidth=2.0, label=f"suicide vd={vd:g}") rad, diff = cut_curve(f, vd) if len(rad): ax.plot(rad, diff, color=c, linewidth=1.4, linestyle="--", label=f"free vd={vd:g}") ax.axhline(0.0, color="black", linewidth=1.2) ymin, ymax = ax.get_ylim() ax.axhspan(0.0, max(ymax, 0.0), color=RED, alpha=0.06, zorder=0) ax.set_ylim(ymin, ymax) ax.set_xlim(0, s["rad"].max()) ax.set_xlabel("weapon radius") ax.set_ylabel("mean RED-BLU food-share difference") ax.set_title("Radius cuts (solid: suicide, dashed: free)") ax.set_axisbelow(True) ax.grid(alpha=0.25) ax.legend(fontsize=8, loc="best", framealpha=0.9) fig.suptitle(args.title, fontsize=13) fig.tight_layout(rect=(0, 0, 1, 0.96)) args.out.parent.mkdir(parents=True, exist_ok=True) fig.savefig(args.out, dpi=args.dpi) print(f"wrote {args.out}") return 0 if __name__ == "__main__": raise SystemExit(main())