File size: 13,976 Bytes
239a1be
 
 
 
 
 
 
 
 
46056cb
239a1be
 
 
 
 
 
 
 
46056cb
 
239a1be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46056cb
 
 
 
 
 
239a1be
46056cb
239a1be
46056cb
 
 
 
 
 
239a1be
 
 
 
 
 
46056cb
 
 
 
 
 
 
 
 
 
773c429
 
 
 
 
 
 
 
 
46056cb
 
 
 
 
239a1be
 
 
 
773c429
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239a1be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46056cb
 
 
 
 
239a1be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
773c429
 
 
 
239a1be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
773c429
 
 
 
 
 
 
 
 
 
 
239a1be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46056cb
 
 
 
 
773c429
 
239a1be
 
 
 
 
 
 
 
 
 
 
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
"""Generate the result tables / figures / RESULTS.md from ``results/``.

Run after the experiment suites have finished::

    python -m pimamba.report
"""
from __future__ import annotations

import json
import os
from pathlib import Path
from typing import Dict, List

import numpy as np
import pandas as pd

from . import analysis as A

ROOT = Path(os.environ.get("PIMAMBA_ROOT")
            or Path(__file__).resolve().parents[2])
RUNS = ROOT / "results" / "runs"
TABLES = ROOT / "results" / "tables"
FIGS = ROOT / "results" / "figures"

MAIN_ORDER = ["mlp", "gru", "lstm", "transformer", "mamba", "mamba2", "pimamba"]
COLS = ["sigma_r2", "sigma_shape_r2", "sigma_level_corr", "macro_r2_primary",
        "rho_total_r2", "twin_r2", "xi_FCC_r2", "peak_rel_err"]


def _pm(df: pd.DataFrame, key: str, col: str, nd: int = 3) -> str:
    g = df[df[key[0]] == key[1]][col]
    if not len(g):
        return "n/a"
    return A.fmt_pm(float(g.mean()), float(g.std()) if len(g) > 1 else float("nan"), nd)


def _maybe_csv(path: Path) -> "pd.DataFrame | None":
    if path.exists():
        return pd.read_csv(path)
    return None


def table_main(df: pd.DataFrame) -> pd.DataFrame:
    """Per-fold mean+-sd *and* pooled out-of-fold metrics side by side."""
    sub = df[df.suite == "main"].copy()
    ps = _maybe_csv(TABLES / "tab_pooled_sigma.csv")
    pt = _maybe_csv(TABLES / "tab_pooled_per_target.csv")
    if ps is not None:
        ps = ps.set_index("model")
    if pt is not None:
        pt = pt.set_index("model")
    rows = []
    for m in MAIN_ORDER:
        g = sub[sub.model == m]
        if not len(g):
            continue
        r = {"model": A.MODEL_LABEL[m], "n": len(g)}
        r["应力 R²(逐折)"] = A.fmt_pm(float(g.sigma_r2.mean()), float(g.sigma_r2.std()))
        r["形状 R²(逐折)"] = A.fmt_pm(float(g.sigma_shape_r2.mean()),
                                     float(g.sigma_shape_r2.std()))
        if ps is not None and m in ps.index:
            r["池化应力 R²"] = f"{float(ps.loc[m, 'sigma_r2']):.3f}"
            r["池化形状 R²"] = f"{float(ps.loc[m, 'shape_r2']):.3f}"
        if pt is not None and m in pt.index:
            r["池化主指标 R²"] = f"{float(pt.loc[m, 'primary_mean']):.3f}"
        r["水平相关"] = A.fmt_pm(float(g.sigma_level_corr.mean()),
                               float(g.sigma_level_corr.std()))
        # rare targets (twin: 6/33 labelled) have a meaningless per-fold R2 --
        # a fold can contain a single labelled sample.  Report pooled OOF.
        if pt is not None and m in pt.index:
            r["池化总位错 R²"] = f"{float(pt.loc[m, 'rho_total']):.3f}"
            r["池化孪晶 R²"] = f"{float(pt.loc[m, 'twin']):.3f}"
            r["池化FCC R²"] = f"{float(pt.loc[m, 'xi_FCC']):.3f}"
        else:
            r["总位错 R²"] = A.fmt_pm(float(g.rho_total_r2.mean()),
                                   float(g.rho_total_r2.std()))
        r["峰值相对误差"] = f"{g.peak_rel_err.mean():.3f}"
        r["曲线 RMSE/GPa"] = A.fmt_pm(float(g.curve_rmse.mean()), float(g.curve_rmse.std()))
        r["逐折宏平均 R²"] = A.fmt_pm(float(g.macro_r2_primary.mean()),
                                   float(g.macro_r2_primary.std()))
        r["参数量"] = f"{int(g.n_params.mean()):,}"
        rows.append(r)
    return pd.DataFrame(rows)


NEXT_ORDER = ["llama", "xlstm", "gdn", "hymba", "koopman", "node", "rssm",
              "flow", "pimamba2"]


def table_next(df: pd.DataFrame) -> pd.DataFrame:
    """Next-generation backbones: per-fold + pooled OOF, sorted by R2."""
    sub = df[df.suite == "next"].copy()
    if not len(sub):
        return pd.DataFrame()
    ps = _maybe_csv(TABLES / "tab_pooled_next_sigma.csv")
    pt = _maybe_csv(TABLES / "tab_pooled_next_per_target.csv")
    if ps is not None:
        ps = ps.set_index("model")
    if pt is not None:
        pt = pt.set_index("model")
    rows = []
    order = sub.groupby("model").sigma_r2.mean().sort_values(ascending=False).index
    for m in order:
        g = sub[sub.model == m]
        r = {"模型": A.MODEL_LABEL.get(m, m), "n": len(g),
             "应力 R²(逐折)": A.fmt_pm(float(g.sigma_r2.mean()),
                                    float(g.sigma_r2.std())),
             "形状 R²(逐折)": A.fmt_pm(float(g.sigma_shape_r2.mean()),
                                    float(g.sigma_shape_r2.std()))}
        if ps is not None and m in ps.index:
            r["池化应力"] = f"{float(ps.loc[m, 'sigma_r2']):.3f}"
            r["池化形状"] = f"{float(ps.loc[m, 'shape_r2']):.3f}"
        if pt is not None and m in pt.index:
            r["池化主指标"] = f"{float(pt.loc[m, 'primary_mean']):.3f}"
        r["峰值误差"] = f"{g.peak_rel_err.mean():.3f}"
        r["参数量"] = f"{int(g.n_params.mean()):,}"
        r["耗时/run(s)"] = f"{g.wall_time_s.mean():.0f}"
        rows.append(r)
    return pd.DataFrame(rows)


def table_v2(df: pd.DataFrame) -> pd.DataFrame:
    """PI-Mamba v2 variants (Taylor coupling + peak loss)."""
    sub = df[df.suite == "v2"].copy()
    if not len(sub):
        return pd.DataFrame()
    ps = _maybe_csv(TABLES / "tab_pooled_v2_sigma.csv")
    pt = _maybe_csv(TABLES / "tab_pooled_v2_per_target.csv")
    if ps is not None:
        ps = ps.set_index("model")
    if pt is not None:
        pt = pt.set_index("model")
    rows = []
    # reference = the main-suite PI-Mamba, so every variant is comparable to the
    # baseline it is meant to improve (the v2 suite has no "pimamba" row).
    bm = df[(df.suite == "main") & (df.model == "pimamba")].sigma_r2
    base = float(bm.mean()) if len(bm) else float(sub.sigma_r2.max())
    order = sub.groupby("variant").sigma_r2.mean().sort_values(ascending=False).index
    for v in order:
        g = sub[sub.variant == v]
        r = {"变体": v, "n": len(g),
             "应力 R²(逐折)": A.fmt_pm(float(g.sigma_r2.mean()),
                                    float(g.sigma_r2.std())),
             "形状 R²(逐折)": f"{g.sigma_shape_r2.mean():.3f}"}
        if ps is not None and v in ps.index:
            r["池化应力"] = f"{float(ps.loc[v, 'sigma_r2']):.3f}"
            r["池化形状"] = f"{float(ps.loc[v, 'shape_r2']):.3f}"
        if pt is not None and v in pt.index:
            r["池化主指标"] = f"{float(pt.loc[v, 'primary_mean']):.3f}"
        r["峰值误差"] = f"{g.peak_rel_err.mean():.3f}"
        r["ΔR²(vs PI-Mamba)"] = f"{g.sigma_r2.mean() - base:+.3f}"
        rows.append(r)
    return pd.DataFrame(rows)


def table_loao(df: pd.DataFrame) -> pd.DataFrame:
    sub = df[df.suite == "loao"].copy()
    if not len(sub):
        return pd.DataFrame()
    rows = []
    for al, g in sub.groupby("holdout"):
        r = {"留出合金体系": al, "n": len(g)}
        for m in ["mlp", "gru", "mamba", "pimamba"]:
            gg = g[g.model == m]
            r[A.MODEL_LABEL[m]] = (f"{gg.sigma_r2.mean():.3f}"
                                   if len(gg) else "n/a")
        rows.append(r)
    rows.append({"留出合金体系": "**平均**", "n": len(sub),
                 **{A.MODEL_LABEL[m]: f"{sub[sub.model == m].sigma_r2.mean():.3f}"
                    for m in ["mlp", "gru", "mamba", "pimamba"]}})
    return pd.DataFrame(rows)


def table_ablation(df: pd.DataFrame) -> pd.DataFrame:
    sub = df[df.suite == "ablation"].copy()
    if not len(sub):
        return pd.DataFrame()
    rows = []
    base = sub[sub.variant == "pimamba"].sigma_r2.mean()
    order = sub.groupby("variant").sigma_r2.mean().sort_values(ascending=False).index
    for v in order:
        g = sub[sub.variant == v]
        rows.append({
            "变体": A.MODEL_LABEL.get(v, v), "n": len(g),
            "应力 R²": A.fmt_pm(float(g.sigma_r2.mean()), float(g.sigma_r2.std())),
            "形状 R²": A.fmt_pm(float(g.sigma_shape_r2.mean()),
                                float(g.sigma_shape_r2.std())),
            "总位错 R²": f"{g.rho_total_r2.mean():.3f}",
            "ΔR²(应力)": f"{g.sigma_r2.mean() - base:+.3f}",
        })
    return pd.DataFrame(rows)


def table_dataeff(df: pd.DataFrame) -> pd.DataFrame:
    sub = df[df.suite == "dataeff"].copy()
    if not len(sub):
        return pd.DataFrame()
    def _frac(v):
        f = float(str(v).split("@")[-1])
        return f / 100.0 if f > 1.0 else f

    sub["frac"] = sub.variant.map(_frac)
    rows = []
    for m, g in sub.groupby("model"):
        r = {"模型": A.MODEL_LABEL.get(m, m)}
        for fr, gg in sorted(g.groupby("frac")):
            r[f"{int(fr*100)}%"] = f"{gg.sigma_r2.mean():.3f}"
        r["n_train@100%"] = int(g[g.frac == 1.0].n_train.mean()) if len(g[g.frac == 1.0]) else np.nan
        rows.append(r)
    return pd.DataFrame(rows)


def table_per_target(tag: str) -> pd.DataFrame:
    m = json.loads((RUNS / tag / "metrics.json").read_text())
    rows = []
    for k, v in m["per_target"].items():
        if v["n"] == 0:
            continue
        rows.append({"目标": k, "组": v["group"], "n": v["n"],
                     "R²": round(v["r2"], 3) if np.isfinite(v["r2"]) else "nan",
                     "R²(log)": round(v["r2_log"], 3) if np.isfinite(v.get("r2_log", np.nan)) else "–",
                     "nMAE": round(v["nmae"], 3) if np.isfinite(v["nmae"]) else "nan",
                     "σ_y": f"{v['y_std']:.3g}", "单位": v["unit"]})
    return pd.DataFrame(rows)


def rebuild_summary():
    """Reconstruct ``results/summary.csv`` from the individual run folders.

    Safety net: the orchestrator only flushes the summary at the end of a suite,
    so a crash would otherwise lose the table.
    """
    from .run_experiments import _row
    rows = []
    for d in sorted(RUNS.iterdir()):
        mp = d / "metrics.json"
        if not mp.exists():
            continue
        res = json.loads(mp.read_text())
        res["tag"] = d.name
        n = d.name
        if n.startswith("main_"):
            suite, var = "main", res["config"]["model"]
        elif n.startswith("abl_"):
            suite, var = "ablation", "_".join(n.split("_")[1:-2])
        elif n.startswith("loao_"):
            suite, var = "loao", res["config"]["model"]
        elif n.startswith("de_"):
            frac = int(n.split("_")[2]) / 100.0
            suite, var = "dataeff", f'{res["config"]["model"]}@{frac:.2f}'
        elif n.startswith("next_"):
            suite, var = "next", res["config"]["model"]
        elif n.startswith("v2_"):
            suite, var = "v2", "_".join(n.split("_")[1:-2])
        else:
            continue
        try:
            rows.append(_row(res, suite, var, res["config"].get("fold", -1),
                             res["config"].get("seed", 0)))
        except Exception as e:  # noqa: BLE001
            print("skip", n, e)
    if rows:
        df = pd.DataFrame(rows).drop_duplicates(subset=["tag"], keep="last")
        (ROOT / "results" / "summary.csv").parent.mkdir(parents=True, exist_ok=True)
        df.to_csv(ROOT / "results" / "summary.csv", index=False)
        print(f"rebuilt summary.csv: {len(df)} rows")


def main():
    import sys
    if "--rebuild" in sys.argv:
        rebuild_summary()
    TABLES.mkdir(parents=True, exist_ok=True)
    FIGS.mkdir(parents=True, exist_ok=True)
    df = A.load_summary()
    out: Dict[str, str] = {}

    tm = table_main(df)
    if len(tm):
        tm.to_csv(TABLES / "tab_main.csv", index=False)
        out["main"] = A.markdown_table(tm, list(tm.columns))
        A.fig_model_comparison(df)

    tn = table_next(df)
    if len(tn):
        tn.to_csv(TABLES / "tab_next.csv", index=False)
        out["next"] = A.markdown_table(tn, list(tn.columns))
        A.fig_next(df)

    tv = table_v2(df)
    if len(tv):
        tv.to_csv(TABLES / "tab_v2.csv", index=False)
        out["v2"] = A.markdown_table(tv, list(tv.columns))

    tl = table_loao(df)
    if len(tl):
        tl.to_csv(TABLES / "tab_loao.csv", index=False)
        out["loao"] = A.markdown_table(tl, list(tl.columns))

    ta = table_ablation(df)
    if len(ta):
        ta.to_csv(TABLES / "tab_ablation.csv", index=False)
        out["ablation"] = A.markdown_table(ta, list(ta.columns))
        A.fig_ablation(df)

    td = table_dataeff(df)
    if len(td):
        td.to_csv(TABLES / "tab_dataeff.csv", index=False)
        out["dataeff"] = A.markdown_table(td, list(td.columns))
        A.fig_dataeff(df)

    best = df[(df.suite == "main") & (df.model == "pimamba")].sort_values(
        "sigma_r2", ascending=False)
    if len(best):
        tag = str(best.iloc[0]["tag"])
        if (RUNS / tag / "predictions.npz").exists():
            A.fig_curves(tag)
            out["curve_tag"] = tag
        tp = table_per_target(tag)
        tp.to_csv(TABLES / "tab_per_target.csv", index=False)
        out["per_target"] = A.markdown_table(tp, list(tp.columns))
        out["per_target_tag"] = tag

    lines = ["# 自动生成的结果汇总", "",
             "> 口径说明:`(逐折)` 为 5 折 × 2 种子的 mean ± sd;`池化` 为把 5 折测试预测\n"
             "> 拼成 33 个样本后统一计算的 out-of-fold 指标(更稳定,报告 §6 主用)。\n"
             "> `逐折宏平均 R²` 仍包含 `rho_perfect` / `rho_112_111` 等退化目标,\n"
             "> 数值大幅为负属正常,不可与池化主指标直接比较。", ""]
    for k, title in [("main", "主对比"), ("next", "新一代架构(2024–2026)"),
                     ("v2", "PI-Mamba v2 改进"), ("loao", "跨合金(LOAO)"),
                     ("ablation", "消融"), ("dataeff", "数据效率")]:
        if k in out:
            lines += [f"## {title}", "", out[k], ""]
    if "per_target" in out:
        lines += [f"## 逐目标指标({out['per_target_tag']})", "", out["per_target"], ""]
    (ROOT / "results" / "RESULTS.md").write_text("\n".join(lines), encoding="utf-8")
    print("\n".join(lines))


if __name__ == "__main__":
    main()