File size: 4,907 Bytes
b9d2398
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#!/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()