edumirror-repro-code / experiments /make_figures.py
ygoldi's picture
Upload folder using huggingface_hub
146b8dc verified
Raw
History Blame Contribute Delete
13.6 kB
#!/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()