"""Render analysis CSVs into LaTeX tables and PDF figures for the paper. python src/analysis/make_paper_assets.py --run-id RUN [--results-dir results] [--paper-dir ../paper] Outputs into /generated/: tab_regret_by_topology.tex parse-conditional regret [95% CI] and failure rate per topology x family (primary outcome) tab_consistency.tex TCI_seed / TCI_para per topology x family tab_degradation.tex GDS (parse-conditional) per class x topology tab_latency_cost.tex latency percentiles, LPI, tokens, delta cost tab_per_model.tex per-model regret, failure rate, latency fig_regret_vs_scale.pdf regret vs log params per topology fig_pareto.pdf regret vs tokens scatter """ from __future__ import annotations import argparse import json import os import numpy as np import pandas as pd import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt # noqa: E402 def fmt_ci(m, lo, hi): if not np.isfinite(m): return "-" return f"{m:.2f} [{lo:.2f}, {hi:.2f}]" def write_table(path, body, caption, label, wide=True): env = "table*" if wide else "table" with open(path, "w") as f: f.write(f"\\begin{{{env}}}[t]\n\\caption{{{caption}}}\n" f"\\label{{{label}}}\n\\centering\n\\small\n" + body + f"\\end{{{env}}}\n") def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--run-id", required=True) ap.add_argument("--results-dir", default="results") ap.add_argument("--paper-dir", default="../paper") args = ap.parse_args() adir = os.path.join(args.results_dir, args.run_id, "analysis") gdir = os.path.join(args.paper_dir, "generated") os.makedirs(gdir, exist_ok=True) s = pd.read_csv(os.path.join(adir, "summary.csv")) fams = ["menu", "layout", "klm", "intervention"] topos = ["single", "chain", "critique", "debate", "hierarchical"] # -------- primary regret table: parse-conditional with CIs + fail rate lines = ["\\begin{tabular}{l" + "c" * len(fams) + "}", "\\toprule", "Topology & " + " & ".join(fams) + " \\\\", "\\midrule"] for topo in topos: cells = [] for fam in fams: g = s[(s.topology == topo) & (s.family == fam)] m = g["regret_parsed"].mean() lo = g["regret_parsed_lo"].mean() hi = g["regret_parsed_hi"].mean() pf = 100 * g["parse_fail_rate"].mean() cells.append(f"{fmt_ci(m, lo, hi)} ({pf:.0f}\\%)") lines.append(f"{topo} & " + " & ".join(cells) + " \\\\") lines += ["\\bottomrule", "\\end{tabular}"] write_table(os.path.join(gdir, "tab_regret_by_topology.tex"), "\n".join(lines) + "\n", "Parse-conditional normalized regret (F1), mean over models " "[95\\% percentile bootstrap interval of the per-cell mean], " "with budget-exhaustion or format failure rate in " "parentheses, by topology and task family.", "tab:regret") # -------- consistency table per topology x family t = pd.read_csv(os.path.join(adir, "tci.csv")) piv_s = t.pivot_table(index="topology", columns="family", values="tci_seed").reindex(topos)[fams] piv_p = t.pivot_table(index="topology", columns="family", values="tci_para").reindex(topos)[fams] lines = ["\\begin{tabular}{l" + "cc" * len(fams) + "}", "\\toprule", " & " + " & ".join(f"\\multicolumn{{2}}{{c}}{{{f}}}" for f in fams) + " \\\\", "Topology & " + " & ".join(["seed & para"] * len(fams)) + " \\\\", "\\midrule"] for topo in topos: cells = [] for fam in fams: cells += [f"{piv_s.loc[topo, fam]:.2f}", f"{piv_p.loc[topo, fam]:.2f}"] lines.append(f"{topo} & " + " & ".join(cells) + " \\\\") lines += ["\\bottomrule", "\\end{tabular}"] write_table(os.path.join(gdir, "tab_consistency.tex"), "\n".join(lines) + "\n", "Temporal Consistency Index under seed replication (F3) and " "paraphrase (F2) by topology and family. The intervention " "family is near ceiling for all topologies.", "tab:consistency") # -------- degradation table (parse-conditional GDS) g = pd.read_csv(os.path.join(adir, "gds.csv")) piv = (g.groupby(["condition", "topology"])["gds_parsed"].mean() .unstack("topology").reindex(columns=topos).round(2)) body = piv.to_latex(na_rep="-", float_format="%.2f") write_table(os.path.join(gdir, "tab_degradation.tex"), body, "Degradation slope (F7) on the parse-conditional scale: " "change in normalized regret under perturbation relative to " "intact replication cells, by class and topology. The " "single-topology corruption and dropout cells are noise-floor " "references: single has no inter-agent messages to corrupt " "and no agent to drop.", "tab:degradation") # -------- latency and cost l = pd.read_csv(os.path.join(adir, "lpi.csv")) k = pd.read_csv(os.path.join(adir, "kappa.csv")) piv = l.groupby("topology")[["latency_p50_s", "latency_p95_s", "lpi_p95_over_p50", "mean_tokens"]].mean() dt = k.groupby("topology")["delta_tokens"].mean() piv["extra_tokens_vs_single"] = dt piv = piv.reindex(topos).round(2) body = piv.to_latex(na_rep="-", float_format="%.2f") write_table(os.path.join(gdir, "tab_latency_cost.tex"), body, "Latency percentiles and predictability (F6; LPI is the mean " "over models of each model's p95/p50 ratio) and token cost " "(F8) by topology. No topology produced a positive mean " "regret reduction over single, so cost per unit improvement " "is not defined at the pool level.", "tab:latency") # -------- per-model table pm = s.groupby("model")[["regret_parsed", "parse_fail_rate", "mean_latency_s"]].mean().round(3) body = pm.to_latex(float_format="%.3f") write_table(os.path.join(gdir, "tab_per_model.tex"), body, "Per-model parse-conditional regret, failure rate, and mean " "decision latency, averaged over topologies and families.", "tab:permodel", wide=False) # -------- figures fig, ax = plt.subplots(figsize=(5, 3.4)) for topo, gg in s.groupby("topology"): ax.scatter(gg["mean_tokens"], gg["regret_parsed"], label=topo, s=18, alpha=0.7) ax.set_xlabel("mean tokens per decision") ax.set_ylabel("parse-conditional normalized regret") ax.set_xscale("log") ax.legend(fontsize=7) fig.tight_layout() fig.savefig(os.path.join(gdir, "fig_pareto.pdf")) with open(os.path.join(args.results_dir, args.run_id, "manifest.json")) as f: manifest = json.load(f) params = {m["id"]: m.get("params_b") for m in manifest["models"]} s["params_b"] = s["model"].map(params) ss = s.dropna(subset=["params_b"]) if not ss.empty: fig, ax = plt.subplots(figsize=(5, 3.4)) for topo, gg in ss.groupby("topology"): m = gg.groupby("params_b")["regret_parsed"].mean() ax.plot(m.index, m.values, marker="o", ms=3, label=topo) ax.set_xscale("log") ax.set_xlabel("model parameters (B)") ax.set_ylabel("parse-conditional normalized regret") ax.legend(fontsize=7) fig.tight_layout() fig.savefig(os.path.join(gdir, "fig_regret_vs_scale.pdf")) print(f"[info] paper assets written to {gdir}") if __name__ == "__main__": main()