File size: 9,588 Bytes
58f9a51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()