diff --git a/suicide_ball.toml b/suicide_ball.toml new file mode 100644 index 0000000..c078fe5 --- /dev/null +++ b/suicide_ball.toml @@ -0,0 +1,68 @@ +# Hawk–Dove phase experiment for the **suicide ball** weapon. +# +# Same rules as `ball.toml`, but the ball now kills the shooter too +# (`kills_user = true`): every hawk gets exactly one detonation, centred on +# itself, that destroys robots (both teams) *and* food inside `radius`. +# Because hawks fire the instant they see a non-kin, the geometry decides +# whether the blast is wasted or devastating: +# +# * Red (hawks) start scattered across the whole field, so one blast rarely +# catches more than the shooter's own kin by accident. +# * Blue (doves) start packed together in a nest in the middle of the food +# field, so a hawk that gets close detonates right on top of the cluster. +# +# A hawk only damages doves if it is within `radius` of them at the moment it +# first sees them, i.e. roughly when `radius > view_dist`. Sweeping +# (view_dist, weapon radius) should therefore separate: +# +# * radius ~ 0 -> pure self-harm, doves win; +# * view_dist >> radius -> hawks detonate out of range, doves win; +# * radius >~ view_dist (moderate) -> hawks trade 1-for-many, hawks win. +# +# This is the mirror image of `ball.toml`: there the *normal* ball favoured +# clustered hawks; here the *suicide* ball needs clustered *doves*. + +food_amount = 250 +view_dist = 200 +red_count = 10 +blu_count = 10 + +[weapon] +kills_user = true +type = "ball" +radius = 90 + +# Doves: a tight nest near the middle of the field (400x400 box). +[blu_spawn] +x0 = 450 +x1 = 850 +y0 = 350 +y1 = 750 + +# Hawks: scattered over the entire food field. +[red_spawn] +x0 = 200 +x1 = 1100 +y0 = 200 +y1 = 900 + +# Food: scattered over the entire field. +[food_spawn] +x0 = 200 +x1 = 1100 +y0 = 200 +y1 = 900 + +[red_policy] +aggressive = true +food = [1,0] +kin = [-0.3,0.02] +nonkin = [0.3,0.02] +none= [0.3, 0.01] + +[blu_policy] +aggressive = false +food = [1,0] +kin = [-0.3,0.02] +nonkin = [-0.3,-0.02] +none= [0.3, 0.01] diff --git a/tools/plot_suicide.py b/tools/plot_suicide.py new file mode 100644 index 0000000..22346f6 --- /dev/null +++ b/tools/plot_suicide.py @@ -0,0 +1,170 @@ +#!/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) + ax.axvspan(0, 1, color="none") # keep x starting near 0 + ymin, ymax = ax.get_ylim() + ax.fill_between([-1e9, 1e9], 0, max(ymax, 0), color=RED, alpha=0.06, zorder=0) + ax.set_ylim(ymin, ymax) + 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())