File size: 6,648 Bytes
239a1be
 
 
 
 
 
 
 
 
 
46056cb
239a1be
 
 
 
 
 
 
 
 
46056cb
 
239a1be
 
 
 
773c429
239a1be
 
773c429
239a1be
 
 
 
 
 
 
 
 
 
 
773c429
 
239a1be
 
773c429
239a1be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
773c429
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239a1be
 
 
 
 
 
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
"""Pooled out-of-fold (OOF) evaluation.

Each of the 33 samples is a test sample in exactly one of the 5 folds, so the
fold predictions can be concatenated into a single OOF set of 33 trajectories.
Per-target R2 computed on that pooled set is far more stable than averaging five
per-fold R2 values, several of which are computed on 1-3 labelled samples.
"""
from __future__ import annotations

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

import numpy as np
import pandas as pd

from .data import TARGETS, TARGET_KEYS
from .metrics import PRIMARY, _r2, regression_metrics

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


def gather(model: str, seed: int = 0, n_folds: int = 5, prefix: str = "main"):
    P, Y, M, S = [], [], [], []
    for f in range(n_folds):
        d = RUNS / f"{prefix}_{model}_f{f}_s{seed}" / "predictions.npz"
        if not d.exists():
            continue
        z = np.load(d, allow_pickle=True)
        P.append(z["pred"]); Y.append(z["true"]); M.append(z["mask"])
        S.append(np.asarray(z["sids"]))
    if not P:
        return None
    return (np.concatenate(P, 0), np.concatenate(Y, 0),
            np.concatenate(M, 0), np.concatenate(S, 0))


def pooled_table(models: List[str], seed: int = 0,
                 prefix: str = "main") -> Tuple[pd.DataFrame, pd.DataFrame]:
    rows, dec_rows = [], []
    for m in models:
        g = gather(m, seed, prefix=prefix)
        if g is None:
            continue
        P, Y, M, S = g
        pt = regression_metrics(Y.reshape(-1, len(TARGETS)),
                                P.reshape(-1, len(TARGETS)),
                                M.reshape(-1, len(TARGETS)))
        r = {"model": m, "n_samples": len(S)}
        for k in TARGET_KEYS:
            v = pt[k]
            r[k] = round(v["r2"], 3) if np.isfinite(v["r2"]) else np.nan
        prim = [pt[k]["r2"] for k in PRIMARY if np.isfinite(pt[k]["r2"])]
        r["primary_mean"] = round(float(np.mean(prim)), 3) if prim else np.nan
        r["primary_median"] = round(float(np.median(prim)), 3) if prim else np.nan
        rows.append(r)

        j = TARGET_KEYS.index("sigma")
        mm = M[:, :, j] > 0
        yv, pv = Y[:, :, j][mm], P[:, :, j][mm]
        ys, ps, lv = [], [], []
        for i in range(len(S)):
            s = M[i, :, j] > 0
            if s.sum() < 4:
                continue
            ys.append(Y[i, s, j] - Y[i, s, j].mean())
            ps.append(P[i, s, j] - P[i, s, j].mean())
            lv.append((Y[i, s, j].mean(), P[i, s, j].mean()))
        ys, ps = np.concatenate(ys), np.concatenate(ps)
        lv = np.array(lv)
        dec_rows.append({
            "model": m,
            "sigma_r2": round(_r2(yv, pv), 3),
            "shape_r2": round(_r2(ys, ps), 3),
            "level_corr": round(float(np.corrcoef(lv[:, 0], lv[:, 1])[0, 1]), 3),
            "level_mae_GPa": round(float(np.mean(np.abs(lv[:, 0] - lv[:, 1]))), 3),
            "level_bias_GPa": round(float(np.mean(lv[:, 1] - lv[:, 0])), 3),
            "peak_rel_err": round(float(np.mean([
                abs(max(P[i, M[i, :, j] > 0, j]) - max(Y[i, M[i, :, j] > 0, j]))
                / max(abs(max(Y[i, M[i, :, j] > 0, j])), 1e-6)
                for i in range(len(S)) if (M[i, :, j] > 0).sum() > 4])), 3),
        })
    return pd.DataFrame(rows), pd.DataFrame(dec_rows)


def ensemble(models: List[str], seed: int = 0, prefix: str = "main",
             prefixes: Dict[str, str] | None = None):
    """Average the normalised predictions of several runs (same fold split).

    All models see the identical test ids in the identical order, so the fold
    predictions are directly averageable; the result is inverse-transformed and
    scored exactly like a single model.
    """
    from .metrics import regression_metrics
    Ps, Ys, Ms, Ss = [], None, None, None
    for m in models:
        pref = (prefixes or {}).get(m, prefix)
        g = gather(m, seed, prefix=pref)
        if g is None:
            continue
        P, Y, M, S = g
        Ps.append(P)
        Ys, Ms, Ss = Y, M, S
    if not Ps:
        return None
    P = np.mean(Ps, 0)
    pt = regression_metrics(Ys.reshape(-1, len(TARGETS)),
                            P.reshape(-1, len(TARGETS)),
                            Ms.reshape(-1, len(TARGETS)))
    prim = [pt[k]["r2"] for k in PRIMARY if np.isfinite(pt[k]["r2"])]
    return {"model": "+".join(models), "sigma_r2": round(pt["sigma"]["r2"], 3),
            "primary_mean": round(float(np.mean(prim)), 3)}


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


def main():
    models = ["mlp", "gru", "lstm", "transformer", "mamba", "mamba2", "pimamba"]
    t, d = pooled_table(models)
    TABLES.mkdir(parents=True, exist_ok=True)
    t.to_csv(TABLES / "tab_pooled_per_target.csv", index=False)
    d.to_csv(TABLES / "tab_pooled_sigma.csv", index=False)
    ens = []
    combos = [(["pimamba", "mamba"], None),
              (["pimamba", "llama"], {"llama": "next"}),
              (["pimamba", "xlstm"], {"xlstm": "next"}),
              (["pimamba", "gdn"], {"gdn": "next"}),
              (["pimamba", "koopman"], {"koopman": "next"}),
              (["pimamba", "node"], {"node": "next"}),
              (["hymba", "mamba"], {"hymba": "next"}),
              (["hymba", "mamba", "pimamba"], {"hymba": "next"}),
              (["hymba", "llama"], {"hymba": "next", "llama": "next"})]
    for combo, pref in combos:
        r = ensemble(combo, prefixes=pref)
        if r:
            ens.append(r)
            print("ensemble", r)
    if ens:
        pd.DataFrame(ens).to_csv(TABLES / "tab_ensemble.csv", index=False)
    t2, d2 = pooled_table(NEXT, prefix="next")
    if len(t2):
        t2.to_csv(TABLES / "tab_pooled_next_per_target.csv", index=False)
        d2.to_csv(TABLES / "tab_pooled_next_sigma.csv", index=False)
        print("\n## pooled OOF (next-gen)")
        print(t2.to_string(index=False))

    V2 = ["pimamba2", "pimamba2_peak", "pimamba_peak", "pimamba2_nocouple"]
    t3, d3 = pooled_table(V2, prefix="v2")
    if len(t3):
        t3.to_csv(TABLES / "tab_pooled_v2_per_target.csv", index=False)
        d3.to_csv(TABLES / "tab_pooled_v2_sigma.csv", index=False)
        print("\n## pooled OOF (v2)")
        print(t3.to_string(index=False))
    print("## pooled OOF per-target R2")
    print(t.to_string(index=False))
    print("\n## pooled OOF stress decomposition")
    print(d.to_string(index=False))


if __name__ == "__main__":
    main()