#!/usr/bin/env python3
"""Causal-vs-pair comparison plot + per-fire trace browser. Data only.
python3 make_causal_browser.py --out causal_browser.html
"""
from __future__ import annotations
import argparse
import base64
import html
import io
import json
import re
import time
from collections import defaultdict
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
HERE = Path(__file__).resolve().parent
plt.rcParams.update({"figure.facecolor": "#0f1115", "axes.facecolor": "#141822",
"axes.edgecolor": "#2a2f3a", "text.color": "#e6e6e6",
"axes.labelcolor": "#e6e6e6", "xtick.color": "#c8d0dc",
"ytick.color": "#9aa4b2", "font.size": 11})
GREEN, BLUE = "#7ee08a", "#8ab4ff"
def jl(name):
try:
return [json.loads(l) for l in (HERE / "data" / name).read_text().splitlines() if l.strip()]
except OSError:
return []
def jload(name):
try:
return json.loads((HERE / "data" / name).read_text())
except OSError:
return None
def compute() -> dict:
noise = jload("noise_floor.json")
floor = noise["global_rel_floor_p95"]
pr = jload("pr_results.json")
cf = jl("counterfactual_runs.jsonl")
scored = [s for s in jl("eval_scored.jsonl")
if (s.get("grading") or {}).get("graded")]
g = {s["state_id"]: s for s in scored}
best: dict[str, tuple] = {}
for s in scored:
c, lb, v = s["competition"], s["grading"]["is_lower_better"], s["grading"]["score"]
if c not in best or (v < best[c][0]) == lb:
best[c] = (v, lb)
measured = [r for r in cf if r.get("outcome") == "measured"]
for r in measured:
r["rel"] = r["improvement"] / max(abs(r.get("score_before") or 1e-9), 1e-9)
r["verdict"] = ("improved" if r["rel"] > floor
else "harmed" if r["rel"] < -floor else "within_noise")
improved = [r for r in measured if r["verdict"] == "improved"]
tested = {r["state_id"] for r in measured}
den = [sid for sid in tested if sid in g
and abs(g[sid]["grading"]["score"] - best[g[sid]["competition"]][0])
/ max(abs(best[g[sid]["competition"]][0]), 1e-9) > floor]
num = {r["state_id"] for r in improved} & set(den)
fam = (pr or {}).get("by_family", {}).get("conceptual", {})
return {
"floor": floor,
"pair_precision": fam.get("precision"),
"pair_recall": fam.get("recall"),
"causal_precision": len(improved) / len(measured) if measured else None,
"causal_recall": len(num) / len(den) if den else None,
"causal_recall_def": (f"states with ≥1 above-noise-improving fire "
f"({len(num)}) / tested states with above-noise "
f"gap to best ({len(den)})"),
"causal_precision_def": (f"fires improving above noise ({len(improved)}) "
f"/ tested fires ({len(measured)})"),
"measured": measured,
}
def fig_comparison(m) -> str:
fig, ax = plt.subplots(figsize=(7.2, 3.8))
groups = ["precision", "recall"]
pair_vals = [m["pair_precision"], m["pair_recall"]]
causal_vals = [m["causal_precision"], m["causal_recall"]]
x = range(len(groups))
w = 0.34
b1 = ax.bar([i - w / 2 for i in x], pair_vals, w, color=BLUE,
label="weak-vs-strong (pair annotation)")
b2 = ax.bar([i + w / 2 for i in x], causal_vals, w, color=GREEN,
label="causal (patch-and-rerun)")
for bars in (b1, b2):
for b in bars:
ax.text(b.get_x() + b.get_width() / 2, b.get_height() + 0.008,
f"{b.get_height():.3f}", ha="center", fontsize=10)
ax.set_xticks(list(x)); ax.set_xticklabels(groups)
ax.set_ylim(0, 0.62)
ax.legend(frameon=False, loc="upper left")
ax.set_title("Precision and recall under the two ground-truth standards "
"(held-out competitions)")
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=135, bbox_inches="tight")
plt.close(fig)
return base64.b64encode(buf.getvalue()).decode()
def rubric_meta() -> dict:
"""id-suffix -> (title, pattern, patch) from the written rubric files."""
out = {}
for path in sorted((HERE / "out" / "conceptual").glob("*.md")):
text = path.read_text()
title = re.search(r"### P1 — (.+)", text)
pattern = re.search(r"\*\*Pattern\*\*:\s*(.+)", text)
out[path.stem] = {
"title": title.group(1) if title else path.stem,
"pattern": pattern.group(1) if pattern else "",
}
return out
def trace_cards(m) -> str:
lib = {}
for row in jl("conceptual_applicable.jsonl"):
lib[row["id"]] = row
meta = rubric_meta()
dec = {(d["rubric_id"], d["state_id"]): d for d in jl("pr_decisions.jsonl")
if d.get("fires")}
order = {"improved": 0, "harmed": 1, "within_noise": 2}
cards = []
for r in sorted(m["measured"], key=lambda r: (order[r["verdict"]], -abs(r["rel"]))):
rid = r["rubric_id"]
cand = lib.get(rid.rsplit("__", 1)[-1], {})
info = meta.get(rid, {})
d = dec.get((rid, r["state_id"]), {})
v = r["verdict"]
badge = {"improved": "g", "harmed": "r", "within_noise": "y"}[v]
cards.append(f"""
{v.replace('_', ' ')}
{r['rel']:+.3%}
{html.escape(info.get('title', rid))}
{html.escape(r['competition'])}