YJT / Script /analysis /plot_prediction_agreement_results.py
JX-Lab's picture
Add files using upload-large-folder tool
58f9a51 verified
Raw History Blame Contribute Delete
9.59 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Generate manuscript figures and summaries for Sections 3.4 and 3.5."""
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
ROOT = Path(__file__).resolve().parents[2]
ANALYSIS_DIR = ROOT / "Analysis" / "label_free_common"
FIGURE_DIR = ROOT / "论文" / "figures" / "3_4"
METHOD_LABELS = {
"Chem": "化学结构",
"Text1": "功效-主治文本",
"Text2": "名称文本对照",
"KG": "知识图谱",
}
PRIMARY_METHODS = ("Chem", "Text1", "KG")
ALL_METHODS = ("Chem", "Text1", "Text2", "KG")
LABELS = (
("Mu(Pungent)", "木(辛)"),
("Huo(Salty)", "火(咸)"),
("Tu(Sweet)", "土(甘)"),
("Jin(Sour)", "金(酸)"),
("Shui(Bitter)", "水(苦)"),
)
METHOD_COLORS = {
"Chem": "#287271",
"Text1": "#D97A54",
"KG": "#616B7A",
}
DEGREE_COLORS = {
1: "#B7BDC5",
2: "#4C78A8",
3: "#E49B3F",
4: "#A33A3A",
}
def configure_plotting():
plt.rcParams.update({
"font.family": "sans-serif",
"font.sans-serif": ["Noto Sans CJK SC", "Droid Sans Fallback"],
"axes.unicode_minus": False,
"font.size": 10,
"axes.titlesize": 12,
"axes.labelsize": 10,
"xtick.labelsize": 9,
"ytick.labelsize": 9,
"pdf.fonttype": 42,
"ps.fonttype": 42,
})
def load_results():
candidates = pd.read_csv(
ANALYSIS_DIR / "candidate_predictions.csv", encoding="utf-8-sig"
)
pairs = pd.read_csv(
ANALYSIS_DIR / "agreement_pairs.csv", encoding="utf-8-sig"
)
if len(candidates) != 570:
raise ValueError(f"Expected 570 common candidates, found {len(candidates)}")
return candidates, pairs
def build_primary_distribution(candidates):
rows = []
for method in PRIMARY_METHODS:
counts = candidates[f"{method}_label"].value_counts()
for internal_label, display_label in LABELS:
count = int(counts.get(internal_label, 0))
rows.append({
"method": method,
"method_name": METHOD_LABELS[method],
"label": internal_label,
"label_name": display_label,
"candidate_count": count,
"percentage": count / len(candidates) * 100,
})
result = pd.DataFrame(rows)
result.to_csv(
ANALYSIS_DIR / "primary_method_label_distribution.csv",
index=False,
encoding="utf-8-sig",
)
return result
def plot_primary_distribution(distribution):
fig, ax = plt.subplots(figsize=(9.2, 5.4))
x = np.arange(len(LABELS))
width = 0.24
for index, method in enumerate(PRIMARY_METHODS):
method_data = (
distribution.loc[distribution["method"] == method]
.set_index("label")
.reindex([label for label, _ in LABELS])
)
bars = ax.bar(
x + (index - 1) * width,
method_data["candidate_count"],
width,
label=METHOD_LABELS[method],
color=METHOD_COLORS[method],
edgecolor="white",
linewidth=0.6,
)
ax.bar_label(bars, padding=2, fontsize=8)
ax.set_xticks(x, [display for _, display in LABELS])
ax.set_ylabel("候选中药数(味)")
ax.set_xlabel("药精属性")
ax.set_ylim(0, 215)
ax.grid(axis="y", color="#D9DDE2", linewidth=0.7, alpha=0.8)
ax.set_axisbelow(True)
ax.spines[["top", "right"]].set_visible(False)
ax.legend(frameon=False, ncol=3, loc="upper center")
fig.tight_layout()
for suffix in ("png", "pdf"):
fig.savefig(
FIGURE_DIR / f"图1_三种主方法五类药精预测分布.{suffix}",
dpi=300,
bbox_inches="tight",
)
plt.close(fig)
def parse_methods(value):
return tuple(method for method in ALL_METHODS if method in value.split("+"))
def build_exact_intersections(pairs):
exact = (
pairs.groupby("methods", as_index=False)
.size()
.rename(columns={"size": "intersection_size"})
)
exact["members"] = exact["methods"].map(parse_methods)
exact["degree"] = exact["members"].map(len)
exact["method_names"] = exact["members"].map(
lambda methods: "+".join(METHOD_LABELS[method] for method in methods)
)
exact = exact.sort_values(
["degree", "intersection_size", "methods"],
ascending=[False, False, True],
).reset_index(drop=True)
exact.drop(columns="members").to_csv(
ANALYSIS_DIR / "exact_method_intersections.csv",
index=False,
encoding="utf-8-sig",
)
return exact
def plot_upset(exact):
configure_plotting()
n_intersections = len(exact)
x = np.arange(n_intersections)
fig = plt.figure(figsize=(12.2, 7.0))
grid = fig.add_gridspec(
2,
2,
width_ratios=[2.3, 9.7],
height_ratios=[4.6, 2.4],
hspace=0.05,
wspace=0.05,
)
ax_sizes = fig.add_subplot(grid[1, 0])
ax_bars = fig.add_subplot(grid[0, 1])
ax_matrix = fig.add_subplot(grid[1, 1], sharex=ax_bars)
colors = [DEGREE_COLORS[degree] for degree in exact["degree"]]
bars = ax_bars.bar(x, exact["intersection_size"], color=colors, width=0.72)
ax_bars.bar_label(bars, padding=2, fontsize=7.5, rotation=90)
ax_bars.set_ylabel("严格交集大小(中药-标签配对数)")
ax_bars.set_ylim(0, max(exact["intersection_size"]) * 1.22)
ax_bars.grid(axis="y", color="#D9DDE2", linewidth=0.7, alpha=0.8)
ax_bars.set_axisbelow(True)
ax_bars.spines[["top", "right"]].set_visible(False)
ax_bars.tick_params(axis="x", bottom=False, labelbottom=False)
row_positions = np.arange(len(ALL_METHODS))[::-1]
for row_index, method in enumerate(ALL_METHODS):
y = row_positions[row_index]
ax_matrix.scatter(
x,
np.full(n_intersections, y),
s=25,
color="#D4D7DB",
zorder=1,
)
for column_index, members in enumerate(exact["members"]):
if method in members:
ax_matrix.scatter(
column_index, y, s=34, color="#202428", zorder=3
)
for column_index, members in enumerate(exact["members"]):
member_rows = [
row_positions[index]
for index, method in enumerate(ALL_METHODS)
if method in members
]
if len(member_rows) > 1:
ax_matrix.plot(
[column_index, column_index],
[min(member_rows), max(member_rows)],
color="#202428",
linewidth=1.5,
zorder=2,
)
ax_matrix.set_yticks(row_positions, [""] * len(ALL_METHODS))
ax_matrix.set_ylim(-0.6, len(ALL_METHODS) - 0.4)
ax_matrix.set_xlim(-0.6, n_intersections - 0.4)
ax_matrix.set_xlabel("精确方法组合(按支持方法数及交集大小排序)")
ax_matrix.spines[["top", "right", "left"]].set_visible(False)
ax_matrix.tick_params(axis="x", bottom=False, labelbottom=False)
ax_matrix.tick_params(axis="y", length=0)
for y in row_positions[::2]:
ax_matrix.axhspan(y - 0.5, y + 0.5, color="#F4F5F6", zorder=0)
set_sizes = [570] * len(ALL_METHODS)
ax_sizes.barh(row_positions, set_sizes, color="#6E7781", height=0.58)
for y, size in zip(row_positions, set_sizes):
ax_sizes.text(
size / 2,
y,
str(size),
va="center",
ha="center",
color="white",
fontweight="bold",
)
ax_sizes.set_yticks(row_positions, [METHOD_LABELS[m] for m in ALL_METHODS])
ax_sizes.invert_xaxis()
ax_sizes.set_xlabel("集合大小")
ax_sizes.set_xlim(650, 0)
ax_sizes.spines[["top", "right", "left"]].set_visible(False)
ax_sizes.tick_params(axis="y", length=0)
FIGURE_DIR.mkdir(parents=True, exist_ok=True)
for suffix in ("png", "pdf"):
fig.savefig(
FIGURE_DIR / f"图2_不同方法预测结果严格交集UpSet图.{suffix}",
dpi=300,
bbox_inches="tight",
)
plt.close(fig)
def write_high_agreement_summaries(candidates):
label_names = dict(LABELS)
high = candidates.loc[candidates["max_support_count"] >= 3].copy()
high["label_name"] = high["consensus_label"].map(label_names)
high_summary = (
high.groupby(["max_support_count", "consensus_label", "label_name"])
.size()
.rename("candidate_count")
.reset_index()
)
high_summary.to_csv(
ANALYSIS_DIR / "high_agreement_summary.csv",
index=False,
encoding="utf-8-sig",
)
four = candidates.loc[candidates["max_support_count"] == 4].copy()
four["label_name"] = four["consensus_label"].map(label_names)
four[["herb", "consensus_label", "label_name"]].to_csv(
ANALYSIS_DIR / "four_method_consensus_candidates.csv",
index=False,
encoding="utf-8-sig",
)
def main():
configure_plotting()
FIGURE_DIR.mkdir(parents=True, exist_ok=True)
candidates, pairs = load_results()
distribution = build_primary_distribution(candidates)
plot_primary_distribution(distribution)
exact = build_exact_intersections(pairs)
plot_upset(exact)
write_high_agreement_summaries(candidates)
print(f"Figures saved to: {FIGURE_DIR}")
print(f"Summary tables saved to: {ANALYSIS_DIR}")
if __name__ == "__main__":
main()