grite-corpus / scripts /plot_coordination.py
dipankarsarkar's picture
Publish grite-corpus from ds-hf
b9d2398 verified
Raw
History Blame Contribute Delete
4.91 kB
#!/usr/bin/env python3
"""Regenerate the C1 coordination figures/tables from raw experiment CSVs.
Consumes the output of ../grite/scripts/run_experiments.sh (coordination.csv) and writes
PDFs into ../figures plus a LaTeX-ready summary table. Pure stdlib + matplotlib; no seaborn.
Usage:
python plot_coordination.py --raw _raw --out ../figures
"""
import argparse
import csv
import statistics
from collections import defaultdict
from pathlib import Path
ARMS = ["no-coord", "locks-only", "locks-plus-state"]
ARM_LABEL = {
"no-coord": "No coordination",
"locks-only": "Locks only",
"locks-plus-state": "Locks + shared state",
}
def load(raw_dir: Path):
rows = []
with open(raw_dir / "coordination.csv", newline="") as f:
for r in csv.DictReader(f):
rows.append(r)
return rows
def aggregate(rows):
"""-> agg[arm][n] = {metric: (mean, ci95)} over seeds."""
buckets = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
for r in rows:
arm, n = r["arm"], int(r["n_agents"])
buckets[arm][n]["dup"].append(float(r["duplicate_work_rate"]))
buckets[arm][n]["conf"].append(float(r["conflicting_edits"]))
buckets[arm][n]["good"].append(float(r["goodput"]))
buckets[arm][n]["deny"].append(float(r["lock_denials"]))
def stat(xs):
m = statistics.fmean(xs)
if len(xs) > 1:
sd = statistics.pstdev(xs)
ci = 1.96 * sd / (len(xs) ** 0.5)
else:
ci = 0.0
return m, ci
agg = defaultdict(lambda: defaultdict(dict))
for arm, ns in buckets.items():
for n, metrics in ns.items():
for k, xs in metrics.items():
agg[arm][n][k] = stat(xs)
return agg
def plot(agg, out_dir: Path):
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
out_dir.mkdir(parents=True, exist_ok=True)
ns_all = sorted({n for arm in agg for n in agg[arm]})
# Figure 1: duplicate-work rate vs N, per arm.
fig, ax = plt.subplots(figsize=(4.2, 3.0))
for arm in ARMS:
if arm not in agg:
continue
ns = sorted(agg[arm])
ys = [agg[arm][n]["dup"][0] for n in ns]
es = [agg[arm][n]["dup"][1] for n in ns]
ax.errorbar(ns, ys, yerr=es, marker="o", capsize=3, label=ARM_LABEL[arm])
ax.set_xscale("log", base=2)
ax.set_xticks(ns_all)
ax.set_xticklabels(ns_all)
ax.set_xlabel("Concurrent agents $N$")
ax.set_ylabel("Duplicate-work rate")
ax.set_ylim(-0.02, 1.0)
ax.legend(fontsize=7)
ax.grid(True, alpha=0.3)
fig.tight_layout()
fig.savefig(out_dir / "duplicate_work.pdf")
plt.close(fig)
# Figure 2 (money figure): coordination overhead (lock denials, proxy) vs duplicate-work
# AVOIDED relative to no-coord. One point per (arm, N): the Pareto trade-off.
fig, ax = plt.subplots(figsize=(4.2, 3.0))
for arm in ARMS:
if arm not in agg or arm == "no-coord":
continue
xs, ys = [], []
for n in sorted(agg[arm]):
base = agg["no-coord"][n]["dup"][0]
avoided = base - agg[arm][n]["dup"][0]
overhead = agg[arm][n]["deny"][0] # lock-wait/denial events as overhead proxy
xs.append(overhead)
ys.append(avoided)
ax.plot(xs, ys, marker="s", label=ARM_LABEL[arm])
ax.set_xlabel("Coordination overhead (lock denials)")
ax.set_ylabel("Duplicate work avoided vs. no-coord")
ax.legend(fontsize=7)
ax.grid(True, alpha=0.3)
fig.tight_layout()
fig.savefig(out_dir / "pareto.pdf")
plt.close(fig)
print(f"[plot_coordination] wrote {out_dir}/duplicate_work.pdf, {out_dir}/pareto.pdf")
def write_table(agg, out_dir: Path):
"""Emit a LaTeX booktabs summary at the largest N."""
n = max({n for arm in agg for n in agg[arm]})
lines = [
"% auto-generated by plot_coordination.py -- do not edit",
"\\begin{tabular}{lrrr}",
"\\toprule",
f"Arm ($N={n}$) & Dup-work rate & Conflicting edits & Goodput \\\\",
"\\midrule",
]
for arm in ARMS:
if arm not in agg or n not in agg[arm]:
continue
d = agg[arm][n]
lines.append(
f"{ARM_LABEL[arm]} & {d['dup'][0]:.2f} & {d['conf'][0]:.0f} & {d['good'][0]:.2f} \\\\"
)
lines += ["\\bottomrule", "\\end{tabular}"]
(out_dir / "coordination_table.tex").write_text("\n".join(lines) + "\n")
print(f"[plot_coordination] wrote {out_dir}/coordination_table.tex")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--raw", default="_raw", type=Path)
ap.add_argument("--out", default=Path("../figures"), type=Path)
args = ap.parse_args()
rows = load(args.raw)
agg = aggregate(rows)
plot(agg, args.out)
write_table(agg, args.out)
if __name__ == "__main__":
main()