hypoagent-gbm / scripts /make_figures.py
eduzrh's picture
Sync manuscript, figures and tables after consistency pass (part 2)
45edb2a verified
Raw History Blame Contribute Delete
20.5 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Generate publication-ready figures from the experiment tables."""
from __future__ import annotations
import json
import re
import sys
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.patches import FancyArrowPatch, FancyBboxPatch
from matplotlib import font_manager
from decimal import Decimal, ROUND_HALF_UP
ROOT = Path(__file__).resolve().parents[1]
TABLES = ROOT / "results" / "tables"
FIG_DIR = ROOT / "paper" / "figures"
FIG_DIR.mkdir(parents=True, exist_ok=True)
# Prefer an installed CJK font; fall back to DejaVu Sans for English-only runs.
for candidate in ["Noto Sans CJK SC", "Noto Serif CJK SC", "WenQuanYi Zen Hei", "SimHei"]:
if font_manager.findfont(candidate, fallback_to_default=False):
plt.rcParams["font.sans-serif"] = [candidate, "DejaVu Sans"]
break
plt.rcParams["axes.unicode_minus"] = False
plt.rcParams["font.size"] = 9
plt.rcParams["axes.spines.top"] = False
plt.rcParams["axes.spines.right"] = False
COLORS = {
"direct": "#8C8C8C",
"cot": "#C49A6C",
"rag": "#4E79A7",
"multi_agent": "#59A14F",
"hypoagent": "#D62728",
"hypoagent_no_gap": "#F28E2B",
"hypoagent_no_cards": "#4C9F70",
"hypoagent_no_debate": "#76B7B2",
"hypoagent_no_trace": "#B07AA1",
}
LABELS = {
"direct": "Direct",
"cot": "CoT",
"rag": "RAG",
"multi_agent": "Multi-agent",
"hypoagent": "HypoAgent-Bio",
"hypoagent_no_gap": "去掉空白挖掘与候选选择",
"hypoagent_no_cards": "去掉蛋白注释条目",
"hypoagent_no_debate": "去掉角色审查",
"hypoagent_no_trace": "去掉证据标注",
}
# The manuscript reports five criteria as primary; 实用性 is kept in the
# released CSV tables but is not plotted.
CRITERIA = ["创新性", "可行性", "数据支持", "理论基础", "整体评价"]
def fmt2(value: float) -> str:
"""Fixed two decimals with half-up rounding, so figures match the tables."""
return str(Decimal(str(value)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
def save(fig, name: str) -> None:
for ext in ("png", "pdf"):
path = FIG_DIR / f"{name}.{ext}"
fig.savefig(path, dpi=300, bbox_inches="tight", facecolor="white")
plt.close(fig)
print(f" wrote {name}.png/.pdf")
def fig_framework() -> None:
fig, ax = plt.subplots(figsize=(7.2, 5.0))
ax.set_xlim(0, 10)
ax.set_ylim(0.75, 6.72)
ax.axis("off")
def box(x, y, w, h, text, fc="#FFFFFF", fs=7.3, bold=False):
ax.add_patch(FancyBboxPatch((x, y), w, h, boxstyle="round,pad=0.05,rounding_size=0.10",
linewidth=0.9, edgecolor="#333333", facecolor=fc, zorder=2))
ax.text(x + w / 2, y + h / 2, text, ha="center", va="center", fontsize=fs,
fontweight="bold" if bold else "normal", zorder=3, linespacing=1.35)
def arrow(p1, p2, ls="-", color="#555555"):
ax.add_patch(FancyArrowPatch(p1, p2, arrowstyle="-|>", mutation_scale=8,
linewidth=0.9, color=color, linestyle=ls, zorder=1))
# top band: input -> retrieval -> evidence pack <- frozen KB
box(0.10, 5.95, 1.75, 0.62, "研究问题\nGBM/TMZ 耐药", fc="#EEF3FA")
box(2.10, 5.95, 2.20, 0.62, "证据检索\nBM25+主题/实体匹配", fc="#E8F3EA", bold=True)
box(4.55, 5.95, 1.85, 0.62, "证据材料\n[E1…E8]+[K1…K2]", fc="#FFF6E5")
box(6.75, 5.95, 3.15, 0.62, "固定文献库:161 篇摘要 + 6 个注释条目", fc="#F2EAF7", fs=6.9)
arrow((1.85, 6.26), (2.10, 6.26))
arrow((4.30, 6.26), (4.55, 6.26))
arrow((6.75, 6.26), (6.40, 6.26), ls="--", color="#999999")
# left column: gap mining -> divergence -> domain review
box(0.10, 4.55, 2.85, 0.80, "① 研究空白挖掘\nG1–G3:矛盾/未答/未共现", fc="#FDEBEC", bold=True)
box(0.10, 3.35, 2.85, 0.80, "② 候选假设生成\n每个空白1个 + 不明显联系", fc="#FDEBEC")
box(0.10, 2.15, 2.85, 0.80, "③ 多角色审查\n生信/蛋白语言模型 · 药理/转化\n方法学", fc="#FFFFFF")
# middle column: tournament -> convergence -> verification/repair
box(3.55, 4.55, 2.95, 0.80, "④ 候选选择(加权评分)\n创新35% · 证据35% · 可行30%", fc="#EEF3FA", bold=True)
box(3.55, 3.35, 2.95, 0.80, "⑤ 收敛写作\n最多1条无证据推测", fc="#EEF3FA")
box(3.55, 2.15, 2.95, 0.80, "⑥ 规则校验与修改\n标题/编号/证据表/数值阈值", fc="#FFF6E5")
box(7.10, 3.35, 2.80, 2.00, "⑦ 结构化假设与核查\n\n7个部分 + 证据对照表\n\n引用有效率 · 未标注来源比例\n结构完整率 · 可逐条核对", fc="#E8F3EA", bold=True)
arrow((1.52, 5.95), (1.52, 5.35))
arrow((1.52, 4.55), (1.52, 4.15))
arrow((1.52, 3.35), (1.52, 2.95))
# ③ -> ④ (elbow)
ax.plot([2.95, 3.20], [2.55, 2.55], color="#555555", lw=0.9)
ax.plot([3.20, 3.20], [2.55, 4.95], color="#555555", lw=0.9)
arrow((3.20, 4.95), (3.55, 4.95))
arrow((5.02, 4.55), (5.02, 4.15))
arrow((5.02, 3.35), (5.02, 2.95))
# ⑥ -> ⑦
ax.plot([6.50, 6.80], [2.55, 2.55], color="#555555", lw=0.9)
ax.plot([6.80, 6.80], [2.55, 4.35], color="#555555", lw=0.9)
arrow((6.80, 4.35), (7.10, 4.35))
ax.add_patch(FancyBboxPatch((0.10, 0.85), 9.80, 0.62, boxstyle="round,pad=0.05,rounding_size=0.10",
linewidth=0.9, edgecolor="#333333", facecolor="#F4F4F4", zorder=2))
ax.text(5.0, 1.16, "证据编号 [E1]~[E8]、[K1]~[K2]:每条机制主张与所引文献逐条对应,可按编号回查原文",
ha="center", va="center", fontsize=6.9, zorder=3)
save(fig, "fig1_framework")
def fig_kb() -> None:
docs = [json.loads(line) for line in (ROOT / "data" / "kb" / "documents.jsonl").open(encoding="utf-8")]
manifest = json.loads((ROOT / "data" / "kb" / "manifest.json").read_text(encoding="utf-8"))
theme_labels = {
"mgmt": "MGMT与DNA修复", "dna_damage": "DNA损伤", "tme": "肿瘤微环境", "singlecell": "单细胞",
"candidate": "候选分子", "combination": "联合治疗", "biomarker": "生物标志物", "plm": "蛋白语言模型",
}
themes = manifest.get("themes", {})
names = [theme_labels.get(k, k) for k in themes]
vals = list(themes.values())
years = [int(d["year"]) for d in docs if str(d.get("year", "")).isdigit()]
fig, axes = plt.subplots(1, 2, figsize=(7.2, 2.7), gridspec_kw={"width_ratios": [1.15, 1]})
ax = axes[0]
order = np.argsort(vals)
ax.barh([names[i] for i in order], [vals[i] for i in order], color="#4E79A7", alpha=0.85)
ax.set_xlabel("文献数")
ax.set_title("(a) 文献库主题分布", fontsize=9.5, fontweight="bold")
for i, v in enumerate([vals[j] for j in order]):
ax.text(v + 0.4, i, str(v), va="center", fontsize=7.5)
ax.set_xlim(0, max(vals) + 5)
ax = axes[1]
bins = np.arange(min(years) - 0.5, max(years) + 1.5, 2)
ax.hist(years, bins=bins, color="#59A14F", alpha=0.85, edgecolor="white")
ax.set_xlabel("发表年份")
ax.set_ylabel("文献数")
ax.set_title("(b) 文献年份分布", fontsize=9.5, fontweight="bold")
fig.tight_layout()
save(fig, "fig2_kb")
def fig_radar(group: str = "main", methods: list[str] | None = None) -> None:
"""Compact quality profile as an annotated heatmap.
A radar chart at 4-5 cm width is hard to read once printed; a heatmap keeps
the same information legible and makes the per-criterion winner obvious.
"""
df = pd.read_csv(TABLES / f"{group}_summary.csv")
methods = methods or [m for m in ["direct", "cot", "multi_agent", "hypoagent"]
if m in set(df["method"])]
matrix = np.array([[float(df[df["method"] == m].iloc[0][f"{c}_mean"]) for c in CRITERIA]
for m in methods])
fig, ax = plt.subplots(figsize=(6.4, 2.5))
im = ax.imshow(matrix, cmap="RdYlGn", vmin=2.5, vmax=4.5, aspect="auto")
ax.set_xticks(range(len(CRITERIA)))
ax.set_xticklabels(CRITERIA, fontsize=8)
ax.set_yticks(range(len(methods)))
ax.set_yticklabels([LABELS[m] for m in methods], fontsize=8)
ax.tick_params(length=0)
for spine in ax.spines.values():
spine.set_visible(False)
for i in range(len(methods)):
for j in range(len(CRITERIA)):
value = matrix[i, j]
ax.text(j, i, fmt2(value), ha="center", va="center", fontsize=8,
color="#111111" if 3.0 <= value <= 4.2 else "white")
if value == matrix[:, j].max():
ax.add_patch(plt.Rectangle((j - 0.5, i - 0.5), 1, 1, fill=False,
edgecolor="#111111", linewidth=1.8))
cbar = fig.colorbar(im, ax=ax, fraction=0.035, pad=0.02)
cbar.ax.tick_params(labelsize=7)
cbar.set_label("评分", fontsize=7)
fig.tight_layout()
save(fig, f"fig3_radar_{group}")
def fig_main() -> None:
df = pd.read_csv(TABLES / "main_summary.csv")
methods = [m for m in ["direct", "cot", "multi_agent", "hypoagent"] if m in set(df["method"])]
fig, axes = plt.subplots(1, 2, figsize=(7.4, 3.2), gridspec_kw={"width_ratios": [1.55, 1]})
ax = axes[0]
x = np.arange(len(CRITERIA))
width = 0.19
for i, method in enumerate(methods):
row = df[df["method"] == method].iloc[0]
means = [float(row[f"{c}_mean"]) for c in CRITERIA]
stds = [float(row[f"{c}_std"]) if not pd.isna(row[f"{c}_std"]) else 0 for c in CRITERIA]
n = max(1, int(row["n"]))
sem = [s / np.sqrt(n) for s in stds]
off = (i - (len(methods) - 1) / 2) * width
ax.bar(x + off, means, width, yerr=sem, capsize=2, label=LABELS[method],
color=COLORS[method], alpha=0.9, error_kw={"linewidth": 0.7})
ax.set_xticks(x)
ax.set_xticklabels(CRITERIA, fontsize=8)
ax.set_ylim(1, 5)
ax.set_ylabel("评分(1~5)")
ax.set_title("(a) LLM 评审质量", fontsize=9.5, fontweight="bold")
ax.legend(fontsize=6.5, ncol=2, frameon=False, loc="upper center", bbox_to_anchor=(0.5, -0.18))
ax = axes[1]
metrics = [("citation_validity", "引用有效率"), ("unsupported_claim_rate", "未标注来源比例")]
x = np.arange(len(metrics))
for i, method in enumerate(methods):
row = df[df["method"] == method].iloc[0]
vals = []
for key, _ in metrics:
v = row.get(key)
vals.append(np.nan if pd.isna(v) else float(v))
off = (i - (len(methods) - 1) / 2) * width
ax.bar(x + off, vals, width, label=LABELS[method], color=COLORS[method], alpha=0.9)
for xi, v in zip(x + off, vals):
if np.isnan(v):
ax.text(xi, 0.02, "—", ha="center", va="bottom", fontsize=6.6, color=COLORS[method])
elif v == 0:
ax.text(xi, 0.02, "0", ha="center", va="bottom", fontsize=5.8, color=COLORS[method])
ax.set_xticks(x)
ax.set_xticklabels(["引用\n有效率", "未标注\n来源比例"], fontsize=7.2, linespacing=1.2)
ax.set_xlim(-0.55, 1.55)
ax.set_ylim(0, 1.08)
ax.set_ylabel("比例")
ax.set_title("(b) 核查指标", fontsize=9.5, fontweight="bold")
fig.tight_layout()
save(fig, "fig4_main")
def fig_ablation() -> None:
"""Score panel plus an explicit delta panel for the ablation variants."""
path = TABLES / "ablation_summary.csv"
if not path.exists():
print(" skip ablation figure (no table yet)")
return
df = pd.read_csv(path)
sig_path = TABLES / "ablation_significance.csv"
sig = pd.read_csv(sig_path) if sig_path.exists() else None
variants = [(m, LABELS[m]) for m in ["hypoagent", "hypoagent_no_gap", "hypoagent_no_cards",
"hypoagent_no_debate"] if m in set(df["method"])]
criteria = [("理论基础", "#4E79A7"), ("整体评价", "#D62728")]
fig, axes = plt.subplots(1, 2, figsize=(7.2, 2.9), gridspec_kw={"width_ratios": [1.35, 1]})
ax = axes[0]
y = np.arange(len(variants))[::-1]
h = 0.34
for k, (crit, color) in enumerate(criteria):
vals = [float(df[df["method"] == m].iloc[0][f"{crit}_mean"]) for m, _ in variants]
ax.barh(y + (0.5 - k) * h, vals, h, color=color, alpha=0.9, label=crit)
for yi, v in zip(y + (0.5 - k) * h, vals):
ax.text(v + 0.03, yi, fmt2(v), va="center", ha="left", fontsize=6.5)
ax.set_yticks(y)
ax.set_yticklabels([lab for _, lab in variants], fontsize=7.2)
ax.set_xlim(0, 4.35)
ax.set_xlabel("评分(1~5)", fontsize=7.5)
ax.legend(fontsize=7, frameon=False, ncol=2, loc="upper center", bbox_to_anchor=(0.5, -0.19))
ax.set_title("(a) 各版本的理论基础与整体评价", fontsize=9, fontweight="bold")
ax = axes[1]
short = {"hypoagent_no_gap": "空白挖掘与候选选择", "hypoagent_no_cards": "蛋白注释条目",
"hypoagent_no_debate": "角色审查"}
full = float(df[df["method"] == "hypoagent"].iloc[0]["整体评价_mean"])
names, deltas, ps = [], [], []
for m in ["hypoagent_no_gap", "hypoagent_no_cards", "hypoagent_no_debate"]:
if m not in set(df["method"]):
continue
d = float(df[df["method"] == m].iloc[0]["整体评价_mean"]) - full
p = np.nan
if sig is not None:
hit = sig[(sig["baseline"] == m) & (sig["criterion"] == "整体评价")]
if len(hit):
p = float(hit["p_wilcoxon"].iloc[0])
names.append(short[m])
deltas.append(d)
ps.append(p)
y = np.arange(len(names))[::-1]
ax.barh(y, deltas, 0.5, color="#8C8C8C", alpha=0.9)
for yi, d, p in zip(y, deltas, ps):
lab = f"{d:.2f}(p={p:.3f})".replace("-", "−")
ax.text(d - 0.015, yi, lab, va="center", ha="right", fontsize=6.5)
ax.axvline(0, color="#333333", linewidth=0.8)
ax.set_yticks(y)
ax.set_yticklabels(names, fontsize=7.5)
ax.set_xlim(-0.62, 0.03)
ax.set_xticks([-0.6, -0.4, -0.2, 0.0])
ax.set_xticklabels(["−0.6", "−0.4", "−0.2", "0.0"])
ax.set_xlabel("整体评价相对完整框架的变化", fontsize=7.5)
ax.set_title("(b) 去掉模块后的整体评价变化", fontsize=9, fontweight="bold")
fig.tight_layout()
save(fig, "fig5_ablation")
def fig_case(qid: str = "Q18") -> None:
"""Claim-evidence mapping of the structured hypothesis.
Claim labels are taken from the mechanism chain (the binding table uses
placeholder names such as 主张一), so the figure shows what each claim
actually states.
"""
rec = json.loads((ROOT / "results" / "generations" / qid / "hypoagent.json").read_text(encoding="utf-8"))
text = rec["final_output"]
# Mechanism chain: numbered statements.
claims: list[str] = []
in_chain = False
for line in text.splitlines():
s = line.strip()
if s.startswith("## 机制链"):
in_chain = True
continue
if in_chain and s.startswith("## "):
break
m = re.match(r"^(\d+)[.、]\s*(.+)$", s)
if in_chain and m:
claims.append(m.group(2))
# Binding table: evidence IDs and strength per claim, in the same order.
rows = []
in_table = False
for line in text.splitlines():
s = line.strip()
if s.startswith("## 证据绑定表"):
in_table = True
continue
if in_table and s.startswith("## "):
break
if in_table and s.startswith("|"):
cells = [c.strip() for c in s.strip("|").split("|")]
if len(cells) >= 4 and cells[0] not in {"主张", "---"} and not set(cells[0]) <= {"-", ":"}:
rows.append(cells[:4])
if not rows:
print(" skip case figure (no binding table)")
return
if len(claims) != len(rows):
claims = [r[0] for r in rows]
# Evidence order: mean position of the citing claims, so arrows stay short.
pos: dict[str, list[int]] = {}
for i, (_, ev, _, _) in enumerate(rows):
for eid in re.findall(r"[EK]\d+", ev):
pos.setdefault(eid, []).append(i)
order = sorted(pos, key=lambda e: (sum(pos[e]) / len(pos[e]), int(e[1:])))
strength_color = {"强": "#2E7D32", "中": "#EF6C00", "弱": "#757575", "无": "#C62828"}
fig, ax = plt.subplots(figsize=(7.4, 4.2))
ax.set_xlim(0, 10)
n_c, n_e = len(rows), len(order)
ax.set_ylim(-0.55, max(n_c, n_e) + 1.0)
ax.axis("off")
c_y = np.linspace(max(n_c, n_e) - 0.2, 0.8, n_c)
e_bottom = 1.7 if n_c > n_e else 0.8
e_y = np.linspace(max(n_c, n_e) - 0.2, e_bottom, n_e) if n_e > 1 else np.array([max(n_c, n_e) / 2])
e_pos = {eid: (7.3, y) for eid, y in zip(order, e_y)}
for i, (_, ev, strength, _) in enumerate(rows):
body = re.sub(r"\[(?:E\d+[,\s]*)+\]|\[无直接证据\]", "", claims[i]).strip(" ;;,,")
body = re.sub(r"\s+", " ", body)
body = body.replace("MGMT− 亚群", "MGMT启动子甲基化亚群").replace("MGMT- 亚群", "MGMT启动子甲基化亚群")
lines, rest = [], body
while rest and len(lines) < 3:
acc, cut = 0.0, len(rest)
for k, ch in enumerate(rest):
acc += 0.5 if ord(ch) < 128 else 1.0
if acc > 26:
cut = k
break
if cut >= len(rest):
lines.append(rest)
rest = ""
break
best = max(rest.rfind(sep, 14, cut + 1) for sep in ",;:、")
if best > 0:
cut = best + 1
elif cut > 0 and rest[cut - 1].isascii() and rest[cut].isascii() \
and rest[cut - 1].isalnum() and rest[cut].isalnum():
sp = rest.rfind(" ", 16, cut)
if sp > 0:
cut = sp + 1
lines.append(rest[:cut].strip())
rest = rest[cut:].lstrip()
if rest:
lines[-1] = lines[-1].rstrip(",;:、") + "…"
label = "\n".join(lines)
ax.text(3.62, c_y[i], label, ha="right", va="center", fontsize=6.5, linespacing=1.28, clip_on=False)
ax.add_patch(FancyBboxPatch((3.69, c_y[i] - 0.15), 0.11, 0.30, boxstyle="round,pad=0.01",
facecolor="#FDEBEC", edgecolor="#D62728", linewidth=0.8))
ids = re.findall(r"[EK]\d+", ev)
color = strength_color.get(strength[:1] if strength else "无", "#757575")
if not ids:
ax.plot([3.80, 7.15], [c_y[i], c_y[i]], color="#C62828", linestyle=":", linewidth=1.0)
ax.text(5.3, c_y[i] + 0.14, "无直接证据", ha="center", va="bottom", fontsize=6.2,
color="#C62828", bbox={"facecolor": "white", "edgecolor": "none", "pad": 0.8})
for eid in ids:
if eid not in e_pos:
continue
ax.annotate("", xy=(7.25, e_pos[eid][1]), xytext=(3.82, c_y[i]),
arrowprops={"arrowstyle": "-|>", "color": color, "lw": 1.0, "alpha": 0.8})
for eid, (x, y) in e_pos.items():
ax.add_patch(FancyBboxPatch((7.3, y - 0.15), 0.5, 0.30, boxstyle="round,pad=0.01",
facecolor="#FFF6E5", edgecolor="#B08D57", linewidth=0.8))
ax.text(7.55, y, eid, ha="center", va="center", fontsize=7.2, fontweight="bold")
doc_id = rec["retrieval"]["doc_ids"][int(eid[1:]) - 1] if eid.startswith("E") and eid[1:].isdigit() else eid
ax.text(7.90, y, doc_id.replace("PMID:", "PMID "), ha="left", va="center", fontsize=6.4, color="#555555")
ax.text(1.7, max(n_c, n_e) + 0.35, "机制主张", ha="center", fontsize=9, fontweight="bold")
ax.text(7.8, max(n_c, n_e) + 0.35, "证据", ha="center", fontsize=9, fontweight="bold")
ax.text(5.0, -0.45, "绿=强支持 橙=中支持 灰=弱支持 红点线=无直接证据", ha="center", fontsize=6.8, color="#555555")
save(fig, "fig6_case")
def main() -> int:
print("Generating figures ...")
fig_framework()
fig_kb()
fig_radar("main")
fig_main()
fig_ablation()
fig_case()
manifest = sorted(p.name for p in FIG_DIR.glob("*.png"))
(FIG_DIR / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"Done: {len(manifest)} PNG files in {FIG_DIR}")
return 0
if __name__ == "__main__":
raise SystemExit(main())