File size: 13,586 Bytes
146b8dc | 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 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 | #!/usr/bin/env python3
# =============================================================================
# make_figures.py
# -----------------------------------------------------------------------------
# Responsible for: Turning the experiment JSON into the figures and tables that
# the logbook presents (Table 1 comparison, Figure 4 heatmap,
# Figure 7 intervention boxplots, RSES validity scatter).
# Role in project: Runs after run_experiments.py, locally, on downloaded results.
# Assumptions: Reads <results>/claim{2,3,4,5}.json. Writes PNG + CSV to <out>.
# =============================================================================
"""Figure generation for the EduMirror reproduction logbook.
Design note on presentation honesty: every figure that compares our numbers to
the paper's plots BOTH, and never rescales ours onto the paper's axis. Where we
ran at reduced scale, the caption says so. The point of these figures is to let a
reader see the ordering and the gap, not to make the reproduction look tidy.
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import matplotlib
matplotlib.use("Agg") # headless: these run in CI/jobs with no display
import matplotlib.pyplot as plt
import numpy as np
METHODS = ["EduMirror", "LLMob", "BabyAGI", "D2A", "ReAct"]
#: Paper Table 1, transcribed from arXiv:2606.07948. Used only for side-by-side
#: display -- never mixed into our computed numbers.
PAPER_TABLE1 = {
"5": {"EduMirror": 4.80, "LLMob": 4.25, "BabyAGI": 4.10, "D2A": 3.35, "ReAct": 2.35},
"15": {"EduMirror": 4.18, "LLMob": 3.60, "BabyAGI": 3.57, "D2A": 3.53, "ReAct": 2.93},
"30": {"EduMirror": 4.03, "LLMob": 3.83, "BabyAGI": 3.86, "D2A": 3.12, "ReAct": 2.41},
}
#: Consistent per-method colours across every figure. Categorical, colourblind-safe.
COLORS = {
"EduMirror": "#4C72B0",
"LLMob": "#DD8452",
"BabyAGI": "#55A868",
"D2A": "#C44E52",
"ReAct": "#8172B3",
}
def _spearman(x: list[float], y: list[float]) -> float:
"""
Spearman rank correlation between two equal-length sequences.
Args:
x: First series.
y: Second series.
Returns:
Rank correlation in [-1, 1], or NaN if either series is constant.
Why:
Claim 2's substance is an ORDERING ("EduMirror scores highest"), not the
absolute values -- which cannot transfer across a different backbone
model anyway. Rank correlation against the paper's ordering is therefore
the right statistic. We implement it directly to avoid a scipy dependency
for one function.
"""
n = len(x)
if n < 2:
return float("nan")
def rank(vals: list[float]) -> list[float]:
order = sorted(range(n), key=lambda i: vals[i])
ranks = [0.0] * n
i = 0
while i < n:
j = i
while j + 1 < n and vals[order[j + 1]] == vals[order[i]]:
j += 1
avg = (i + j) / 2 + 1 # average rank for ties
for k in range(i, j + 1):
ranks[order[k]] = avg
i = j + 1
return ranks
rx, ry = rank(x), rank(y)
mx, my = sum(rx) / n, sum(ry) / n
num = sum((a - mx) * (b - my) for a, b in zip(rx, ry))
den = (sum((a - mx) ** 2 for a in rx) * sum((b - my) ** 2 for b in ry)) ** 0.5
return num / den if den else float("nan")
def fig_claim2(results: dict, out: Path) -> dict:
"""
Grouped bar chart: our scores vs the paper's Table 1, per group size.
Args:
results: Parsed claim2.json.
out: Output directory.
Returns:
A summary dict with per-size rank correlations and orderings.
Why side-by-side rather than overlaid:
Our absolute scores come from a different judge model than GPT-4o, so the
levels are not comparable and overlaying them would invite a false
reading. What IS comparable is the ordering of methods within each panel,
which is what the claim asserts.
"""
table = results["table"]
sizes = [s for s in ("5", "15", "30") if s in table]
fig, axes = plt.subplots(1, len(sizes), figsize=(5 * len(sizes), 4.2), sharey=True)
if len(sizes) == 1:
axes = [axes]
summary = {}
for ax, size in zip(axes, sizes):
ours = [table[size].get(m) for m in METHODS]
theirs = [PAPER_TABLE1[size][m] for m in METHODS]
x = np.arange(len(METHODS))
w = 0.38
ax.bar(x - w / 2, [o if o is not None else 0 for o in ours], w,
label="This reproduction", color=[COLORS[m] for m in METHODS])
ax.bar(x + w / 2, theirs, w, label="Paper (Table 1)",
color=[COLORS[m] for m in METHODS], alpha=0.42, hatch="//")
ax.set_xticks(x)
ax.set_xticklabels(METHODS, rotation=30, ha="right")
ax.set_title(f"{size} agents")
ax.set_ylim(1, 5)
ax.grid(axis="y", alpha=0.3)
valid = [(o, t, m) for o, t, m in zip(ours, theirs, METHODS) if o is not None]
if len(valid) >= 3:
rho = _spearman([v[0] for v in valid], [v[1] for v in valid])
else:
rho = float("nan")
ranked = [m for _, m in sorted(
((o, m) for o, _, m in valid), key=lambda p: -p[0])]
summary[size] = {
"ours": {m: table[size].get(m) for m in METHODS},
"paper": PAPER_TABLE1[size],
"spearman_rho": None if rho != rho else round(rho, 3),
"our_ranking": ranked,
"paper_ranking": [m for m in sorted(METHODS, key=lambda m: -PAPER_TABLE1[size][m])],
"edumirror_is_top_ours": bool(ranked and ranked[0] == "EduMirror"),
}
axes[0].set_ylabel("Average score (1-5)")
handles = [
plt.Rectangle((0, 0), 1, 1, color="#666"),
plt.Rectangle((0, 0), 1, 1, color="#666", alpha=0.42, hatch="//"),
]
axes[-1].legend(handles, ["This reproduction", "Paper (Table 1)"], loc="upper right", fontsize=8)
fig.suptitle(
"Claim 2: kindergarten scalability -- average of Naturalness, Coherence,\n"
"Plausibility, Developmental Typicality (higher is better)",
fontsize=11,
)
fig.tight_layout()
out.mkdir(parents=True, exist_ok=True)
fig.savefig(out / "claim2_scalability.png", dpi=150)
plt.close(fig)
return summary
def fig_claim4(results: dict, out: Path) -> dict:
"""
Win-rate heatmap: cell = win rate of the COLUMN method vs the ROW method.
Args:
results: Parsed claim4.json.
out: Output directory.
Returns:
A summary dict of average win rates.
Why this orientation:
Figure 4's caption: "Each cell indicates the win rate of the column model
relative to the row model". Matching the paper's orientation matters --
transposing it would silently invert every reading.
"""
matrix = results["matrix"]
data = np.array([[matrix[r].get(c, float("nan")) for c in METHODS] for r in METHODS],
dtype=float)
fig, ax = plt.subplots(figsize=(6.4, 5.4))
im = ax.imshow(data, cmap="RdYlBu_r", vmin=0, vmax=1)
ax.set_xticks(range(len(METHODS)))
ax.set_xticklabels(METHODS, rotation=30, ha="right")
ax.set_yticks(range(len(METHODS)))
ax.set_yticklabels(METHODS)
ax.set_xlabel("Column model")
ax.set_ylabel("Row model")
for i in range(len(METHODS)):
for j in range(len(METHODS)):
v = data[i, j]
if v == v: # not NaN
ax.text(j, i, f"{v:.2f}", ha="center", va="center",
color="white" if (v < 0.28 or v > 0.72) else "black", fontsize=9)
else:
ax.text(j, i, "--", ha="center", va="center", color="#999")
fig.colorbar(im, ax=ax, label="Win rate of column vs row")
ax.set_title(f"Claim 4: pairwise win rates across {results.get('n_scenarios', '?')} scenarios")
fig.tight_layout()
out.mkdir(parents=True, exist_ok=True)
fig.savefig(out / "claim4_heatmap.png", dpi=150)
plt.close(fig)
return {"average_win_rate": results.get("average_win_rate")}
def fig_claim5(results: dict, out: Path) -> dict:
"""
Boxplot of malicious competition per intervention arm (paper Figure 7 shape).
Args:
results: Parsed claim5.json.
out: Output directory.
Returns:
The per-arm summary dict.
Why boxes + mean lines:
Figure 7's caption: "Boxes show IQRs, whiskers show min-max, and red
dashed lines indicate means". The claim is about SPREAD (interventions
produce "lower variance and narrower ranges"; the control shows "the
widest fluctuation"), so a bar chart of means would omit the very
quantity being claimed.
"""
records = results["records"]
arms = ["neglectful", "team_competition", "teacher_reminder", "pre_education"]
labels = {
"neglectful": "Control\n(Neglectful)",
"team_competition": "Team\nCompetition",
"teacher_reminder": "Teacher\nReminder",
"pre_education": "Pre-\nEducation",
}
data, present = [], []
for arm in arms:
vals = [r["malicious_competition"] for r in records
if r["arm"] == arm and r.get("valid")]
if vals:
data.append(vals)
present.append(arm)
if not data:
return {}
fig, ax = plt.subplots(figsize=(7.2, 4.6))
bp = ax.boxplot(data, tick_labels=[labels[a] for a in present], whis=(0, 100),
showmeans=True, meanline=True,
meanprops={"color": "red", "linestyle": "--", "linewidth": 1.6},
medianprops={"color": "#333"})
for patch, arm in zip(bp["boxes"], present):
patch.set_color("#C44E52" if arm == "neglectful" else "#4C72B0")
ax.set_ylabel("Malicious competition behaviours per episode")
ax.set_title("Claim 5: intervention strategies vs. extreme competition\n"
"(class monitor election; whiskers = min-max, red dashed = mean)")
ax.grid(axis="y", alpha=0.3)
fig.tight_layout()
out.mkdir(parents=True, exist_ok=True)
fig.savefig(out / "claim5_interventions.png", dpi=150)
plt.close(fig)
return results.get("summary", {})
def fig_claim3(results: dict, out: Path) -> dict:
"""
Scatter of internal need change vs. external RSES change (construct validity).
Args:
results: Parsed claim3.json.
out: Output directory.
Returns:
A summary with the correlation and n.
Why a scatter and not a bar:
The Claim 3 evidence is an association between two independently-measured
quantities (delta-Value from the internal Value System, delta-RSES from
the Surveyor's standard instrument). A scatter shows the association AND
its scatter/outliers; a summary bar would hide whether a single point
drives the correlation.
"""
records = [r for r in results["records"] if r.get("delta_rses") is not None]
if len(records) < 2:
return {"correlation": None, "n": len(records)}
xs = [r["delta_value"] for r in records]
ys = [r["delta_rses"] for r in records]
arms = sorted({r["arm"] for r in records})
arm_colors = dict(zip(arms, ["#C44E52", "#DD8452", "#55A868", "#4C72B0"]))
fig, ax = plt.subplots(figsize=(6.4, 4.8))
for arm in arms:
pts = [(r["delta_value"], r["delta_rses"]) for r in records if r["arm"] == arm]
ax.scatter([p[0] for p in pts], [p[1] for p in pts], s=60, alpha=0.8,
label=arm.replace("_", " "), color=arm_colors.get(arm))
if len(set(xs)) > 1:
coef = np.polyfit(xs, ys, 1)
xr = np.linspace(min(xs), max(xs), 50)
ax.plot(xr, np.polyval(coef, xr), "--", color="#333", alpha=0.7, linewidth=1.2)
ax.axhline(0, color="#bbb", linewidth=0.8)
ax.axvline(0, color="#bbb", linewidth=0.8)
ax.set_xlabel("Δ internal value (mean of 'self worth', 'sense of respect')")
ax.set_ylabel("Δ RSES total (external instrument, 10-40)")
ax.set_title("Claim 3: construct validity of the Individual Value System\n"
"internal state vs. LLM Surveyor's Rosenberg Self-Esteem Scale")
ax.legend(fontsize=8)
ax.grid(alpha=0.3)
fig.tight_layout()
out.mkdir(parents=True, exist_ok=True)
fig.savefig(out / "claim3_rses_validity.png", dpi=150)
plt.close(fig)
return {
"pearson": results.get("delta_value_vs_delta_rses_correlation"),
"spearman": round(_spearman(xs, ys), 3) if len(set(xs)) > 1 else None,
"n": len(records),
}
def main() -> None:
"""Generate every figure whose source JSON is present."""
p = argparse.ArgumentParser()
p.add_argument("--results", type=Path, required=True)
p.add_argument("--out", type=Path, default=Path("figures"))
args = p.parse_args()
summary = {}
for name, fn in (("claim2", fig_claim2), ("claim3", fig_claim3),
("claim4", fig_claim4), ("claim5", fig_claim5)):
path = args.results / f"{name}.json"
if not path.exists():
print(f"skip {name}: {path} not found")
continue
summary[name] = fn(json.loads(path.read_text()), args.out)
print(f"{name}: {json.dumps(summary[name], indent=2, default=str)}")
args.out.mkdir(parents=True, exist_ok=True)
(args.out / "summary.json").write_text(json.dumps(summary, indent=2, default=str))
print(f"\nwrote figures + summary.json to {args.out}")
if __name__ == "__main__":
main()
|