#!/usr/bin/env python3 """Paper figures from the locked result files (no model is run, no number is typed in by hand). /home/jovyan/lamlvh/ML-Porosity/.venv/bin/python scripts/22_paper_figures.py ... scripts/22_paper_figures.py --outputs outputs --out paper/figures Reads only outputs/m34/report.json, outputs/m5/errors/report.json, outputs/m5/synthetic/report.json and outputs/m5/synthetic/settings_t{2,3}.csv. Writes t4_modes.pdf, taxonomy.pdf, leakage.pdf, planted.pdf and figures_provenance.md. Before anything is drawn, every plotted quantity that docs/plan.md (Sec. 1.6-1.9) states is compared with the stated value; any difference larger than the tolerance stops the script with exit code 2. Needs matplotlib (the Volve-DIA .venv has none); the ML-Porosity interpreter has it. Output is deterministic: PDF creation dates are removed and hash salts fixed. """ from __future__ import annotations import argparse import csv import hashlib import json import os import sys from pathlib import Path import numpy as np os.environ.setdefault("SOURCE_DATE_EPOCH", "0") import matplotlib # noqa: E402 matplotlib.use("pdf") import matplotlib.pyplot as plt # noqa: E402 ROOT = Path(__file__).resolve().parents[1] MM = 1 / 25.4 SINGLE, DOUBLE = 85 * MM, 170 * MM DEEPSEEK = "vai-deepseek-v4-1-flash" REPS = (0, 1, 2) TOL = 0.002 # Okabe-Ito (colour-blind-safe); every colour is paired with a marker, line style or hatch. OI = {"black": "#000000", "orange": "#E69F00", "sky": "#56B4E9", "green": "#009E73", "yellow": "#F0E442", "blue": "#0072B2", "vermillion": "#D55E00", "purple": "#CC79A7", "grey": "#999999"} # T4 modes, top to bottom: (mode, modality, label, group) T4_MODES = [("zero_shot", "xml", "Zero-shot", "none"), ("few_shot", "xml", "Few-shot", "none"), ("rag", "xml", "RAG (XML)", "text"), ("c4", "xml", "C4 XML", "text"), ("c4", "html", "C4 HTML", "text"), ("c4", "ocr", "C4 OCR", "text"), ("tool_only", "xml", "Tool-only", "tool"), ("agent", "xml", "Agent", "tool")] GROUPS = {"none": ("No report context", OI["orange"], "s"), "text": ("Text retrieval", OI["blue"], "o"), "tool": ("Tools over XML tables", OI["green"], "D")} # Error classes in protocol v4 order; the last one merges two classes that are below 0.03 in every mode. CLASSES = [("correct", "Correct", OI["green"], ""), ("abstained", "Abstention", "#DDDDDD", ""), ("wrong_wellbore", "Wrong wellbore", OI["vermillion"], "//"), ("evidence_missed", "Wrong report cited", OI["orange"], "\\\\"), ("wrong_with_evidence", "Right report, wrong value", OI["sky"], ".."), ("failed", "Call failure", OI["purple"], "xx"), (("no_citation", "answered_unanswerable"), "No citation or answered unanswerable", OI["yellow"], "--")] # Values stated in docs/plan.md, used only to check the files; plotted values are always read from the files. PLAN_T4 = {("zero_shot", "xml"): 0.071, ("few_shot", "xml"): 0.151, ("rag", "xml"): 0.148, ("c4", "xml"): 0.151, ("c4", "html"): 0.177, ("c4", "ocr"): 0.181, ("tool_only", "xml"): 0.712, ("agent", "xml"): 0.618} PLAN_TAXONOMY = { # plan Sec. 1.7: correct, abstained, wrong_wellbore, evidence_missed, wrong_with_evidence, failed ("c4", "xml"): (0.151, 0.678, 0.095, 0.026, 0.047, 0), ("c4", "html"): (0.177, 0.535, 0.190, 0.025, 0.072, 0), ("c4", "ocr"): (0.181, 0.580, 0.137, 0.026, 0.074, 0), ("rag", "xml"): (0.148, 0.638, 0.110, 0.030, 0.066, 0), ("zero_shot", "xml"): (0.071, 0.891, 0.026, 0.012, 0, 0), ("few_shot", "xml"): (0.151, 0.739, 0.079, 0.009, 0, 0), ("tool_only", "xml"): (0.712, 0.083, 0.049, 0.008, 0.144, 0.004), ("agent", "xml"): (0.618, 0.129, 0.026, 0.014, 0.146, 0.064)} PLAN_LEAK = { # plan Sec. 1.6 / 1.7, quantities on the primary subset ("all", XML) "t2_tfidf_masked": (0.463, TOL), "t2_tfidf_unmasked": (0.995, TOL), "t2_tfidf_delta": (0.531, TOL), "t2_distilbert_masked_seeds": ((0.579, 0.596, 0.603), TOL), "t2_distilbert_delta_seeds": ((0.291, 0.283, 0.266), TOL), "t2_majority_masked": (0.183, TOL), # majority AP is the prevalence; plan Sec. 1.9 states pi = 0.183 "t3_tfidf_masked": (0.1225, 0.0002), "t3_tfidf_unmasked": (0.1273, 0.0002), "t3_tfidf_delta": (0.0048, 0.0002), "t3_distilbert_masked_mean": (0.121, TOL), "t3_majority": (0.114, TOL)} PLAN_POOLED = { # plan Sec. 1.6 final paragraph: these equal means over subsets all + without_sidetrack (see notes) ("masked", "well", "majority"): 0.179, ("masked", "well", "lexicon"): 0.249, ("masked", "well", "tfidf_logistic"): 0.461, ("masked", "well", "distilbert"): 0.597, ("masked", "well", "vai_deepseek_zero_shot"): 0.405, ("masked", "well", "qwen_zero_shot"): 0.261, ("masked", "wellbore", "distilbert"): 0.619, ("masked", "wellbore", "tfidf_logistic"): 0.484, ("unmasked", "well", "tfidf_logistic"): 0.994, ("unmasked", "well", "distilbert"): 0.869} PLAN_T2_CURVE = {0.0: 0.182, 0.1: 0.201, 0.25: 0.258, 0.5: 0.363, 0.75: 0.440, 1.0: 0.521} PLAN_T3_CURVE = {0.0: (0.118, 0.115), 0.25: (0.119, 0.139), 0.5: (0.131, 0.176), 1.0: (0.191, 0.283), 2.0: (0.379, 0.489)} PLAN_PLANTED = {"t2_pi": (0.183, TOL), "t2_real": (0.463, TOL), "c_eff": (0.82, 0.005), "c_lo": (0.78, 0.005), "c_hi": (0.84, 0.005), "t3_pi": (0.114, TOL), "t3_real": (0.150, TOL), "s_eff": (0.66, 0.005), "s_lo": (0.55, 0.005), "s_hi": (0.72, 0.005)} class Checks: def __init__(self): self.rows, self.failed = [], [] def __call__(self, name, value, expected, tol=TOL): ok = abs(value - expected) <= tol + 1e-12 self.rows.append((name, value, expected, tol, ok)) if not ok: self.failed.append(f"{name}: file {value:.6f}, plan {expected}, |diff| {abs(value - expected):.6f} > {tol}") def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()[:16] def read_csv(path): with open(path, newline="") as fh: return list(csv.DictReader(fh)) def pick(rows, **kw): return [r for r in rows if all(r.get(k) == v for k, v in kw.items())] def one(rows, what): if len(rows) != 1: raise SystemExit(f"Expected one row for {what}, found {len(rows)}") return rows[0] # ---------------------------------------------------------------- data def t4_data(m34, check): out = [] for mode, modality, label, group in T4_MODES: reps = [] for seed in REPS: r = one(pick(m34["qa"], model=DEEPSEEK, mode=mode, modality=modality, seed=seed, subset="well", average="macro_families"), f"T4 {mode} {modality} rep {seed}") m = r["metrics"]["correct"] reps.append((m["estimate"], m["ci"][0], m["ci"][1], r["n"])) mean = float(np.mean([x[0] for x in reps])) check(f"T4 {mode}/{modality} mean of 3 reps", mean, PLAN_T4[(mode, modality)]) out.append({"mode": mode, "modality": modality, "label": label, "group": group, "reps": reps, "mean": mean}) return out def taxonomy_data(err, check): out = [] for mode, modality, label, _ in T4_MODES: r = one(pick(err["taxonomy_macro"], model=DEEPSEEK, mode=mode, modality=modality, family="macro"), f"taxonomy {mode} {modality}") if r["seeds"] != len(REPS): raise SystemExit(f"taxonomy {mode} {modality}: {r['seeds']} repetitions, expected {len(REPS)}") shares = [sum(r[k] for k in key) if isinstance(key, tuple) else r[key] for key, *_ in CLASSES] if abs(sum(shares) - 1) > 1e-6: raise SystemExit(f"taxonomy {mode} {modality}: shares sum to {sum(shares)}") for (key, *_), share, plan in zip(CLASSES[:6], shares[:6], PLAN_TAXONOMY[(mode, modality)]): check(f"taxonomy {mode}/{modality} {key}", share, plan) out.append({"label": label, "mode": mode, "modality": modality, "shares": shares, "n": r["n"]}) return out def ap_row(m34, task, mode, split, method, seed, subset="all", modality="xml"): r = one(pick(m34["classification"], task=task, definition="b", mode=mode, split=split, method=method, modality=modality, seed=seed, subset=subset), f"{task} {mode} {split} {method} seed {seed}") m = r["metrics"]["pr_auc_ap"] return m["estimate"], m["ci"][0], m["ci"][1] def contrast_row(m34, task, method, seed): r = one(pick(m34["classification_contrasts"], task=task, definition="b", method=method, seed=seed, contrast="unmasked_minus_masked", subset="all", metric="pr_auc_ap"), f"{task} {method} seed {seed} unmasked-masked") return r["estimate"], r["ci"][0], r["ci"][1] def leakage_data(m34, check): d = {} for task in ("t2", "t3"): t = {"tfidf": {}, "distilbert": {}} for mode in ("masked", "unmasked"): t["tfidf"][mode] = [ap_row(m34, task, mode, "well", "tfidf_logistic", -1)] t["distilbert"][mode] = [ap_row(m34, task, mode, "well", "distilbert", s) for s in REPS] t["tfidf"]["delta"] = [contrast_row(m34, task, "tfidf_logistic", -1)] t["distilbert"]["delta"] = [contrast_row(m34, task, "distilbert", s) for s in REPS] t["majority"] = ap_row(m34, task, "masked", "well", "majority", -1) if task == "t2": t["lexicon"] = ap_row(m34, task, "masked", "well", "lexicon", -1) d[task] = t t2, t3 = d["t2"], d["t3"] check("T2(b) TF-IDF masked AP", t2["tfidf"]["masked"][0][0], *PLAN_LEAK["t2_tfidf_masked"]) check("T2(b) TF-IDF unmasked AP", t2["tfidf"]["unmasked"][0][0], *PLAN_LEAK["t2_tfidf_unmasked"]) check("T2(b) TF-IDF unmasked-masked", t2["tfidf"]["delta"][0][0], *PLAN_LEAK["t2_tfidf_delta"]) for s, (row, plan) in enumerate(zip(t2["distilbert"]["masked"], PLAN_LEAK["t2_distilbert_masked_seeds"][0])): check(f"T2(b) DistilBERT masked AP seed {s}", row[0], plan) for s, (row, plan) in enumerate(zip(t2["distilbert"]["delta"], PLAN_LEAK["t2_distilbert_delta_seeds"][0])): check(f"T2(b) DistilBERT unmasked-masked seed {s}", row[0], plan) check("T2(b) majority masked AP (= prevalence)", t2["majority"][0], *PLAN_LEAK["t2_majority_masked"]) check("T3(b) TF-IDF masked AP", t3["tfidf"]["masked"][0][0], *PLAN_LEAK["t3_tfidf_masked"]) check("T3(b) TF-IDF unmasked AP", t3["tfidf"]["unmasked"][0][0], *PLAN_LEAK["t3_tfidf_unmasked"]) check("T3(b) TF-IDF unmasked-masked", t3["tfidf"]["delta"][0][0], *PLAN_LEAK["t3_tfidf_delta"]) check("T3(b) DistilBERT masked AP mean", float(np.mean([r[0] for r in t3["distilbert"]["masked"]])), *PLAN_LEAK["t3_distilbert_masked_mean"]) check("T3(b) majority AP (= prevalence)", t3["majority"][0], *PLAN_LEAK["t3_majority"]) return d def pooled_plan_check(m34, check): """The plan Sec. 1.6 summary values are means over subsets all + without_sidetrack (and XML + OCR for TF-IDF). They are checked here so the origin of each stated value is reproducible; they are not plotted.""" out = [] for (mode, split, method), plan in PLAN_POOLED.items(): rows = [r for r in pick(m34["classification"], task="t2", definition="b", mode=mode, split=split, method=method) if r["subset"] in ("all", "without_sidetrack") and (r.get("metrics") or {}).get("pr_auc_ap", {}).get("estimate") is not None] pooled = float(np.mean([r["metrics"]["pr_auc_ap"]["estimate"] for r in rows])) primary = float(np.mean([r["metrics"]["pr_auc_ap"]["estimate"] for r in rows if r["subset"] == "all" and r["modality"] == "xml"])) check(f"plan pooled T2(b) {mode}/{split}/{method}", pooled, plan) out.append((mode, split, method, plan, pooled, primary, len(rows))) return out def planted_data(outputs, syn, check): t2 = [r for r in read_csv(outputs / "m5/synthetic/settings_t2.csv") if float(r["f"]) == 0.02] t3 = read_csv(outputs / "m5/synthetic/settings_t3.csv") t2 = sorted(({k: float(v) for k, v in r.items()} for r in t2), key=lambda r: r["c"]) t3 = sorted(({k: float(v) for k, v in r.items()} for r in t3), key=lambda r: r["s"]) for r in t2: check(f"planted T2 f=0.02 c={r['c']} mean AP", r["ap_mean"], PLAN_T2_CURVE[r["c"]]) for r in t3: check(f"planted T3 s={r['s']} mean AP", r["ap_mean"], PLAN_T3_CURVE[r["s"]][0]) check(f"planted T3 s={r['s']} oracle AP", r["oracle_ap_mean"], PLAN_T3_CURVE[r["s"]][1]) cue = syn["t2_cues"]["effective_cue_rate"] if cue["f"] != 0.02: raise SystemExit("effective cue rate is not reported for f = 0.02") c_ref, s_ref = cue["reference_report"], syn["t3_hazard"]["effective_strength"]["reference_report"] p = {"t2_pi": syn["design"]["t2_pi"], "t2_real": syn["references"]["t2"]["ap"], "c_eff": c_ref["value"], "c_lo": c_ref["seed_range"][0], "c_hi": c_ref["seed_range"][1], "t3_pi": syn["design"]["t3_pi"], "t3_real": syn["references"]["t3"]["ap"], "s_eff": s_ref["value"], "s_lo": s_ref["seed_range"][0], "s_hi": s_ref["seed_range"][1]} for k, v in p.items(): check(f"planted {k}", v, *PLAN_PLANTED[k]) if not syn["t2_cues"]["null_checks"]["f=0.02"]["null_check_passed"]: raise SystemExit("protocol v6 null check for f = 0.02 did not pass; the curve must not be drawn as valid") return t2, t3, p # ---------------------------------------------------------------- drawing def style(): plt.rcParams.update({ "font.family": "DejaVu Sans", "font.size": 7, "axes.labelsize": 7, "axes.titlesize": 7, "xtick.labelsize": 6.5, "ytick.labelsize": 6.5, "legend.fontsize": 6.5, "axes.linewidth": 0.6, "xtick.major.width": 0.6, "ytick.major.width": 0.6, "lines.linewidth": 1.0, "hatch.linewidth": 0.5, "axes.spines.top": False, "axes.spines.right": False, "pdf.fonttype": 42, "ps.fonttype": 42, "svg.hashsalt": "volve-dia", "figure.facecolor": "white", "axes.facecolor": "white", "savefig.facecolor": "white", "legend.frameon": False}) def minus(text): return text.replace("-", "\u2212") def panel_tags(*axes): for ax, tag in zip(axes, "abcdef"): ax.set_title(f"({tag})", loc="left", fontsize=8, fontweight="bold") def save(fig, path): fig.savefig(path, format="pdf", metadata={"CreationDate": None, "ModDate": None, "Producer": None, "Creator": "scripts/22_paper_figures.py"}) plt.close(fig) def fig_t4(data, path): fig, ax = plt.subplots(figsize=(SINGLE, 72 * MM), layout="constrained") n = len(data) for i, row in enumerate(data): y = n - 1 - i name, colour, marker = GROUPS[row["group"]] for k, (est, lo, hi, _) in enumerate(row["reps"]): yy = y + (k - 1) * 0.22 ax.plot([lo, hi], [yy, yy], color=colour, lw=0.8, solid_capstyle="butt") ax.plot(est, yy, marker=marker, ms=3.2, color=colour, mec="white", mew=0.3, ls="none") ax.plot([row["mean"]] * 2, [y - 0.38, y + 0.38], color=OI["black"], lw=1.3) right = max(r[2] for r in row["reps"]) ax.text(right + 0.015, y, f"{row['mean']:.3f}", va="center", ha="left", fontsize=6.5) ax.set_yticks(range(n), [r["label"] for r in reversed(data)]) ax.set_xlim(0, 0.9) ax.set_ylim(-0.6, n - 0.4) ax.set_xlabel("Macro-family accuracy (fraction correct)") ax.xaxis.grid(True, color="#E5E5E5", lw=0.5) ax.set_axisbelow(True) handles = [plt.Line2D([], [], color=c, marker=m, ms=3.2, lw=0.8, label=lab) for lab, c, m in GROUPS.values()] handles.append(plt.Line2D([], [], color=OI["black"], lw=1.3, label="Mean of 3 repetitions")) fig.legend(handles=handles, loc="outside upper center", ncol=2, handlelength=1.6, columnspacing=1.0) save(fig, path) def luminance(hex_colour): r, g, b = (int(hex_colour[i:i + 2], 16) / 255 for i in (1, 3, 5)) return 0.2126 * r + 0.7152 * g + 0.0722 * b def fig_taxonomy(data, path): fig, ax = plt.subplots(figsize=(DOUBLE, 70 * MM), layout="constrained") n = len(data) for i, row in enumerate(data): y, left = n - 1 - i, 0.0 for (_, _, colour, hatch), share in zip(CLASSES, row["shares"]): ax.barh(y, share, left=left, height=0.7, color=colour, hatch=hatch, edgecolor="#333333", lw=0.4) if share >= 0.06: txt = "white" if luminance(colour) < 0.35 else "black" ax.text(left + share / 2, y, f"{share:.2f}", ha="center", va="center", fontsize=6, color=txt, bbox=None if txt == "white" else {"boxstyle": "square,pad=0.08", "fc": colour, "lw": 0}) left += share ax.set_yticks(range(n), [r["label"] for r in reversed(data)]) ax.set_xlim(0, 1) ax.set_ylim(-0.6, n - 0.4) ax.set_xlabel("Share of predictions, macro average over question families (mean of 3 repetitions)") handles = [matplotlib.patches.Patch(facecolor=c, hatch=h, edgecolor="#333333", lw=0.4, label=lab) for _, lab, c, h in CLASSES] fig.legend(handles=handles, loc="outside upper center", ncol=4, handlelength=1.8, columnspacing=1.2) save(fig, path) def _leak_panel(ax, t, ymax, reference, ref_label, dec): methods = [("tfidf", "TF-IDF + logistic"), ("distilbert", "DistilBERT")] conds = [("masked", "Codes masked", "white", "////"), ("unmasked", "Codes shown", OI["blue"], "")] width = 0.36 for j, (key, _) in enumerate(methods): for k, (mode, _, colour, hatch) in enumerate(conds): rows = t[key][mode] x = j + (k - 0.5) * width ax.bar(x, np.mean([r[0] for r in rows]), width=width * 0.92, color=colour, hatch=hatch, edgecolor=OI["blue"], lw=0.7) offs = np.linspace(-0.09, 0.09, len(rows)) if len(rows) > 1 else [0.0] for off, (est, lo, hi) in zip(offs, rows): ax.errorbar(x + off, est, yerr=[[est - lo], [hi - est]], fmt="o", ms=2.4, color=OI["black"], mfc=OI["yellow"] if mode == "unmasked" else "white", mew=0.6, elinewidth=0.6, capsize=1.2) deltas = t[key]["delta"] top = max(r[2] for m in ("masked", "unmasked") for r in t[key][m]) if len(deltas) == 1: est, lo, hi = deltas[0] text = minus(f"Δ {est:+.{dec}f}\n({lo:.{dec}f} to {hi:.{dec}f})") else: excl = sum(lo > 0 or hi < 0 for _, lo, hi in deltas) ests = [d[0] for d in deltas] text = minus(f"Δ {min(ests):+.{dec}f} to {max(ests):+.{dec}f}\n" f"(CI excludes 0: {excl}/{len(deltas)} seeds)") ax.text(j, top + ymax * 0.03, text, ha="center", va="bottom", fontsize=6) for value, label, ls in zip(reference, ref_label, ("--", ":")): ax.axhline(value, color=OI["vermillion"], ls=ls, lw=0.9, zorder=0.5) ax.text(1.42, value, f"{label} {value:.3f}", ha="left", va="bottom", fontsize=6, color=OI["vermillion"]) ax.set_xticks(range(len(methods)), [m[1] for m in methods]) ax.set_xlim(-0.55, 2.15) ax.set_ylim(0, ymax) handles = [matplotlib.patches.Patch(facecolor=c, hatch=h, edgecolor=OI["blue"], lw=0.7, label=lab) for _, lab, c, h in conds] return handles def fig_leakage(d, path): fig, (a, b) = plt.subplots(1, 2, figsize=(DOUBLE, 68 * MM), layout="constrained", gridspec_kw={"width_ratios": [1, 1]}) handles = _leak_panel(a, d["t2"], 1.18, [d["t2"]["majority"][0], d["t2"]["lexicon"][0]], ["Majority", "Lexicon"], 3) _leak_panel(b, d["t3"], 0.30, [d["t3"]["majority"][0]], ["Majority (π)"], 4) a.set_ylabel("Average precision, T2(b) activity") b.set_ylabel("Average precision, T3(b) depth cell") panel_tags(a, b) handles.append(plt.Line2D([], [], color=OI["black"], marker="o", mfc="white", ms=2.4, lw=0.6, label="Run or seed with 95% well-cluster bootstrap CI")) fig.legend(handles=handles, loc="outside upper center", ncol=3, handlelength=1.8) save(fig, path) def _curve(ax, x, mean, lo, hi, colour, marker, ls, label): ax.fill_between(x, lo, hi, color=colour, alpha=0.18, lw=0) ax.plot(x, mean, color=colour, marker=marker, ms=3.2, ls=ls, label=label) def fig_planted(t2, t3, p, path): fig, (a, b) = plt.subplots(1, 2, figsize=(DOUBLE, 62 * MM), layout="constrained") c = [r["c"] for r in t2] _curve(a, c, [r["ap_mean"] for r in t2], [r["ap_min"] for r in t2], [r["ap_max"] for r in t2], OI["blue"], "o", "-", "TF-IDF on planted labels (mean, seed range)") a.axhline(p["t2_pi"], color=OI["grey"], ls="--", lw=0.9, label=f"Prevalence π = {p['t2_pi']:.3f}") a.axhline(p["t2_real"], color=OI["vermillion"], ls=":", lw=1.0, label=f"Real masked TF-IDF AP = {p['t2_real']:.3f}") a.axvspan(p["c_lo"], p["c_hi"], color=OI["vermillion"], alpha=0.12, lw=0) a.axvline(p["c_eff"], color=OI["vermillion"], lw=0.8) a.annotate(f"c ≈ {p['c_eff']:.2f}\n({p['c_lo']:.2f} to {p['c_hi']:.2f})", (p["c_eff"], p["t2_real"]), xytext=(p["c_eff"] - 0.17, p["t2_real"] - 0.17), fontsize=6, ha="center", arrowprops={"arrowstyle": "-", "lw": 0.5, "color": OI["vermillion"]}) a.set_xlabel("Cue fraction c of planted rows (decoy rate f = 0.02)") a.set_ylabel("Average precision (leave-one-well-out)") a.set_xlim(-0.03, 1.03) a.set_ylim(0, 0.75) a.legend(loc="upper left", handlelength=1.8) s = [r["s"] for r in t3] _curve(b, s, [r["ap_mean"] for r in t3], [r["ap_min"] for r in t3], [r["ap_max"] for r in t3], OI["blue"], "o", "-", "Depth neighbour forecast (k = 10, other wells)") _curve(b, s, [r["oracle_ap_mean"] for r in t3], [r["oracle_ap_min"] for r in t3], [r["oracle_ap_max"] for r in t3], OI["orange"], "s", "--", "Oracle (true hazard)") b.axhline(p["t3_pi"], color=OI["grey"], ls="--", lw=0.9, label=f"Prevalence π = {p['t3_pi']:.3f}") b.axhline(p["t3_real"], color=OI["vermillion"], ls=":", lw=1.0, label=f"Real depth-forecast AP = {p['t3_real']:.3f}") b.axvspan(p["s_lo"], p["s_hi"], color=OI["vermillion"], alpha=0.12, lw=0) b.axvline(p["s_eff"], color=OI["vermillion"], lw=0.8) b.annotate(f"s ≈ {p['s_eff']:.2f}\n({p['s_lo']:.2f} to {p['s_hi']:.2f})", (p["s_eff"], p["t3_real"]), xytext=(p["s_eff"] + 0.8, p["t3_real"] - 0.12), fontsize=6, ha="center", arrowprops={"arrowstyle": "-", "lw": 0.5, "color": OI["vermillion"]}) b.set_xlabel("Signal strength s (log-odds per SD of measured depth)") b.set_ylabel("Average precision (leave-one-well-out)") b.set_xlim(-0.05, 2.05) b.set_ylim(0, 0.75) b.legend(loc="upper left", handlelength=1.8) panel_tags(a, b) save(fig, path) # ---------------------------------------------------------------- provenance def provenance(path, inputs, t4, tax, leak, pooled, t2, t3, p, checks): f3 = "{:.3f}".format lines = ["# Figure provenance", "", "Written by `scripts/22_paper_figures.py`; do not edit by hand. Every plotted value is read from the " "files below (sha256, first 16 hex). Checks against `docs/plan.md`: " f"{sum(r[4] for r in checks.rows)}/{len(checks.rows)} within tolerance.", "", "| Input | sha256 |", "| --- | --- |"] lines += [f"| `{k}` | `{v}` |" for k, v in inputs.items()] lines += ["", "## t4_modes.pdf", "", f"Source: `outputs/m34/report.json` key `qa`, model `{DEEPSEEK}`, subset `well`, average " "`macro_families`, metric `correct`; one point and 95% well-cluster bootstrap CI per repetition " "(0, 1, 2); black tick = mean of the three estimates.", "", "| Mode | n | Rep 0 | Rep 1 | Rep 2 | Mean |", "| --- | ---: | ---: | ---: | ---: | ---: |"] for r in t4: reps = " | ".join(f"{e:.3f} ({lo:.3f}-{hi:.3f})" for e, lo, hi, _ in r["reps"]) lines.append(f"| {r['label']} | {r['reps'][0][3]} | {reps} | {f3(r['mean'])} |") lines += ["", "## taxonomy.pdf", "", f"Source: `outputs/m5/errors/report.json` key `taxonomy_macro`, model `{DEEPSEEK}`, family `macro` " "(macro over question families, mean of 3 repetitions, protocol v4 classes). The last segment merges " "`no_citation` and `answered_unanswerable`.", "", "| Mode | n | " + " | ".join(c[1] for c in CLASSES) + " |", "| --- | ---: |" + " ---: |" * len(CLASSES)] for r in tax: lines.append(f"| {r['label']} | {int(r['n'])} | " + " | ".join(f3(s) for s in r["shares"]) + " |") lines += ["", "## leakage.pdf", "", "Source: `outputs/m34/report.json` keys `classification` (AP, `definition` b, `split` well, " "`modality` xml, `subset` all) and `classification_contrasts` (`unmasked_minus_masked`, subset all, " "paired 95% well-cluster bootstrap CI). Bars: TF-IDF single run, DistilBERT mean of seeds 0-2.", "", "| Task | Method | Masked AP (CI) | Unmasked AP (CI) | Unmasked - masked (CI) |", "| --- | --- | --- | --- | --- |"] for task in ("t2", "t3"): dec = 3 if task == "t2" else 4 for key, name in (("tfidf", "TF-IDF"), ("distilbert", "DistilBERT")): cells = [] for part in ("masked", "unmasked", "delta"): runs = leak[task][key][part] cells.append("; ".join(f"{e:.{dec}f} ({lo:.{dec}f} to {hi:.{dec}f})" for e, lo, hi in runs)) lines.append(f"| {task.upper()}(b) | {name} | " + " | ".join(cells) + " |") lines += ["", f"Reference lines (masked, by well, subset all): T2(b) majority {leak['t2']['majority'][0]:.4f}, " f"lexicon {leak['t2']['lexicon'][0]:.4f}; T3(b) majority {leak['t3']['majority'][0]:.4f}.", "", "**Discrepancy with plan Sec. 1.6 (final paragraph).** The values stated there equal the mean over the " "subsets `all` and `without_sidetrack` (and over XML and OCR for TF-IDF), not the primary subset `all`. " "The figure plots `all` (XML), the subset behind the earlier TF-IDF statement in plan Sec. 1.6, the " "DistilBERT deltas in Sec. 1.7 and the protocol v6 reference AP (`references.t2.source`).", "", "| Mode / split / method | Plan value | Pooled mean (= plan) | Primary `all`, XML | Rows pooled |", "| --- | ---: | ---: | ---: | ---: |"] lines += [f"| {m}/{s}/{meth} | {plan:.3f} | {pv:.4f} | {pr:.4f} | {n} |" for m, s, meth, plan, pv, pr, n in pooled] lines += ["", "## planted.pdf", "", "Sources: `outputs/m5/synthetic/settings_t2.csv` (rows f = 0.02; f = 0.10 is not drawn because its " "protocol v6 null check failed), `outputs/m5/synthetic/settings_t3.csv`, and " "`outputs/m5/synthetic/report.json` (`design.t2_pi`, `design.t3_pi`, `references.t2.ap`, " "`references.t3.ap`, `t2_cues.effective_cue_rate.reference_report`, " "`t3_hazard.effective_strength.reference_report`). Lines: mean over 5 seeds; bands: seed min-max.", "", "| c | mean AP | min | max |", "| ---: | ---: | ---: | ---: |"] lines += [f"| {r['c']:g} | {r['ap_mean']:.4f} | {r['ap_min']:.4f} | {r['ap_max']:.4f} |" for r in t2] lines += ["", "| s | depth AP mean | min | max | oracle AP mean | min | max |", "| ---: | ---: | ---: | ---: | ---: | ---: | ---: |"] lines += [f"| {r['s']:g} | {r['ap_mean']:.4f} | {r['ap_min']:.4f} | {r['ap_max']:.4f} | " f"{r['oracle_ap_mean']:.4f} | {r['oracle_ap_min']:.4f} | {r['oracle_ap_max']:.4f} |" for r in t3] lines += ["", f"T2: prevalence {p['t2_pi']:.3f}, real masked TF-IDF AP {p['t2_real']:.4f}, effective cue fraction " f"{p['c_eff']:.3f} (seed range {p['c_lo']:.3f} to {p['c_hi']:.3f}). T3: prevalence {p['t3_pi']:.4f}, " f"real depth-forecast AP {p['t3_real']:.4f}, effective strength {p['s_eff']:.3f} (seed range " f"{p['s_lo']:.3f} to {p['s_hi']:.3f}).", "", "## Checks against docs/plan.md", "", "| Quantity | File | Plan | Tolerance | OK |", "| --- | ---: | ---: | ---: | --- |"] lines += [f"| {n} | {v:.4f} | {e} | {t} | {'yes' if ok else 'NO'} |" for n, v, e, t, ok in checks.rows] Path(path).write_text("\n".join(lines) + "\n") def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("--outputs", type=Path, default=ROOT / "outputs", help="result directory (read only)") ap.add_argument("--out", type=Path, default=ROOT / "paper/figures", help="figure directory") args = ap.parse_args(argv) files = {"m34": args.outputs / "m34/report.json", "errors": args.outputs / "m5/errors/report.json", "synthetic": args.outputs / "m5/synthetic/report.json"} m34, err, syn = (json.loads(files[k].read_text()) for k in ("m34", "errors", "synthetic")) if not m34["g2_v2"]["passed"]: raise SystemExit("outputs/m34/report.json: g2_v2 has not passed") checks = Checks() t4 = t4_data(m34, checks) tax = taxonomy_data(err, checks) leak = leakage_data(m34, checks) pooled = pooled_plan_check(m34, checks) t2, t3, p = planted_data(args.outputs, syn, checks) if checks.failed: print("Result files contradict docs/plan.md; no figure written:", file=sys.stderr) for line in checks.failed: print(" " + line, file=sys.stderr) return 2 args.out.mkdir(parents=True, exist_ok=True) style() fig_t4(t4, args.out / "t4_modes.pdf") fig_taxonomy(tax, args.out / "taxonomy.pdf") fig_leakage(leak, args.out / "leakage.pdf") fig_planted(t2, t3, p, args.out / "planted.pdf") inputs = {str(f.relative_to(args.outputs.parent)) if f.is_relative_to(args.outputs.parent) else str(f): sha(f) for f in [*files.values(), args.outputs / "m5/synthetic/settings_t2.csv", args.outputs / "m5/synthetic/settings_t3.csv"]} provenance(args.out / "figures_provenance.md", inputs, t4, tax, leak, pooled, t2, t3, p, checks) print(f"{len(checks.rows)} checks passed; wrote 4 figures and figures_provenance.md to {args.out}") print("NOTE: these plan Sec. 1.6 T2(b) summary values are means over subsets all + without_sidetrack; the " "figure plots subset all (see figures_provenance.md):") for mode, split, method, plan, pv, pr, _ in pooled: print(f" {mode}/{split}/{method}: plan {plan:.3f} = pooled {pv:.4f}; primary all/xml {pr:.4f}") return 0 if __name__ == "__main__": sys.exit(main())