File size: 9,638 Bytes
7215ff1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
r"""
evaluate_v3.py — AtmosIQ v3 evaluation. Fresh file; never imports old models/ code.

Reports (spatial-held-out test nodes, full-graph forward, de-standardized to concentration):
  1. Per-pollutant R2/RMSE/MAE at ALL horizons 0-3 (blueprint §10 primary + forecast).
  2. HONEST XGBoost tag: 'BEAT' only if R2 > xgb AND R2 > 0. Negative-vs-negative is not a win.
  3. Reasoning ablations on identical days: no_graph (edges removed), no_physics (flat edge
     bias), no_temporal (window collapsed to 1 day). graph_gain = full - no_graph.
  4. ORPHAN eval: test nodes' satellite+static [MASK]ed -> gap-fill from neighbors only.
     This is the T-2 ungauged-cell deployment story measured directly.
  5. alpha_self per GAT layer (mean self-attention share; ~1.0 = graph unused).

PRE-REGISTERED SUCCESS CRITERIA (fixed before the run; no after-the-fact rationalizing):
  S1  graph_gain > +0.03 on pm2_5 AND pm10, and graph_gain > 0 on >=5/7 pollutants
  S2  orphan-eval pm2_5 R2 > 0 (graph carries real signal to blind nodes)
  S3  mean alpha_self < 0.9 on the full graph

Run: python data/models_v3/evaluate_v3.py --tensors data/tensors --ckpt data/ckpt_v3/atmosiq_v3_best.pt
"""
from __future__ import annotations
import os, sys, json, argparse, pathlib
import numpy as np, torch
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import model as MODEL
from model import AtmosIQNet
from dataset_v3 import AtmosDataV3

POLL = ["pm2_5", "pm10", "no2", "so2", "co", "o3", "nh3"]


def load(a, dev):
    meta = json.load(open(pathlib.Path(a.tensors) / "meta.json"))
    data = AtmosDataV3(a.tensors, window=a.window, device=dev)
    cfg = {"calendar_num_dim": meta["dimsD_num"],
           "n_recon_channels": 9 + meta["dimsB"] + meta["dimsC_static"] + meta["dimsC_yearly"],
           "categorical": {"land_use_class": 4, "grap_stage": 3,
                           "n_landuse": meta["n_landuse"], "n_grap": meta["n_grap"]}}
    net = AtmosIQNet(cfg).to(dev)
    net.load_state_dict(torch.load(a.ckpt, map_location=dev)); net.eval()
    nz = np.load(pathlib.Path(a.tensors) / "norm.npz")
    assert "y_logmean" in nz, "norm.npz missing y_logmean/y_logstd — refusing to evaluate without de-standardization"
    ylm = torch.tensor(nz["y_logmean"]).float().to(dev)
    yls = torch.tensor(nz["y_logstd"]).float().to(dev)
    return meta, data, net, ylm, yls


def predict(net, b, ylm, yls, gm=None, mode="full"):
    ei, eh, nh = b["ei"], b["e_hat"], b["n_hat"]
    wu, wv, blh = b["wu"], b["wv"], b["blh"]
    groups_t = b["groups_t"]
    if mode == "no_graph":
        ei = torch.zeros(2, 0, dtype=torch.long, device=ei.device)
        eh = torch.zeros(0, device=eh.device); nh = torch.zeros(0, device=nh.device)
    if mode == "no_temporal":
        groups_t = groups_t[-1:]
        wu, wv, blh = wu[-1:], wv[-1:], blh[-1:]
        gm = gm[-1:] if gm is not None else None
    orig = MODEL.phys_log_bias
    if mode == "no_physics":
        MODEL.phys_log_bias = lambda *ar, **kw: torch.zeros_like(ar[4])   # ar[4] = e_hat -> [E]
    try:
        out = net(groups_t, ei, eh, nh, wu, wv, blh, b["comp"], gm)
    finally:
        MODEL.phys_log_bias = orig
    mu = out["mu"] * yls.view(1, 1, -1) + ylm.view(1, 1, -1)              # de-standardize
    return (torch.exp(mu.clamp(max=12)) - 1e-3).clamp_min(0)             # invert log(y+eps)


def collect(data, net, ylm, yls, days, mode="full", orphan=False):
    te = (data.split == 2)
    Ys = {p: {h: [] for h in range(4)} for p in POLL}
    Ps = {p: {h: [] for h in range(4)} for p in POLL}
    with torch.no_grad():
        for t in days:
            b = data.full_window(t)
            gm = None
            if orphan:
                o = te.float().to(b["comp"].device)
                gm = [{"satellite": o, "static": o} for _ in b["groups_t"]]
            pred = predict(net, b, ylm, yls, gm, mode)
            m = b["m"] * te.float().view(-1, 1, 1).to(pred.device)
            y = b["y"]
            for j, p in enumerate(POLL):
                for h in range(4):
                    mm = m[:, h, j] > 0
                    if mm.any():
                        Ys[p][h].append(y[mm, h, j].cpu()); Ps[p][h].append(pred[mm, h, j].cpu())
    return Ys, Ps


def r2_table(Ys, Ps, horizons=(0,)):
    out = {}
    for p in POLL:
        out[p] = {}
        for h in horizons:
            if not Ys[p][h]:
                out[p][h] = None; continue
            y = torch.cat(Ys[p][h]).numpy(); pr = torch.cat(Ps[p][h]).numpy()
            pr = np.nan_to_num(pr, nan=float(np.mean(y)))
            ss = ((y - pr) ** 2).sum(); st = ((y - y.mean()) ** 2).sum() + 1e-9
            out[p][h] = (1 - ss / st, float(np.sqrt(((y - pr) ** 2).mean())),
                         float(np.abs(y - pr).mean()), len(y))
    return out


def attn_stats(net, b):
    """Mean alpha_self per GAT layer on a real full-graph window (replicates model.encode)."""
    with torch.no_grad():
        T = len(b["groups_t"]); N = b["groups_t"][0]["satellite"].shape[0]
        H = torch.cat([net.assemble(g) for g in b["groups_t"]], 0)
        src, dst = b["ei"][0], b["ei"][1]
        offs = (torch.arange(T, device=src.device) * N).view(T, 1)
        ei_b = torch.stack([(src.unsqueeze(0) + offs).reshape(-1),
                            (dst.unsqueeze(0) + offs).reshape(-1)])
        lb = torch.cat([MODEL.phys_log_bias(b["wu"][t], b["wv"][t], b["blh"][t],
                                            src, b["e_hat"], b["n_hat"]) for t in range(T)])
        stats = []
        for g in net.gats:
            H, att = g(H, ei_b, lb, return_attn=True)
            stats.append(float(att["alpha_self"].mean()))
    return stats


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--tensors", default="data/tensors")
    ap.add_argument("--ckpt", default="data/ckpt_v3/atmosiq_v3_best.pt")
    ap.add_argument("--window", type=int, default=7)
    ap.add_argument("--refs", default="data/models/refs.json")
    ap.add_argument("--test_days", type=int, default=0, help="0 = all test days for the main table")
    ap.add_argument("--abl_days", type=int, default=250, help="days for ablation/orphan arms")
    a = ap.parse_args()
    dev = "cuda" if torch.cuda.is_available() else "cpu"; print("device:", dev)
    meta, data, net, ylm, yls = load(a, dev)
    print(f"loaded {a.ckpt} ({sum(p.numel() for p in net.parameters()):,} params)")
    days = data.target_days(2)
    if a.test_days:                     # P0-1: season-balanced stride, not first-K
        s = max(1, len(days) // a.test_days)
        days = days[::s][:a.test_days]
    refs = json.load(open(a.refs)) if os.path.exists(a.refs) else {}
    print(f"test days: {len(days)} | held-out test nodes: {int((data.split == 2).sum())}")

    # 1) full model, all horizons
    Ys, Ps = collect(data, net, ylm, yls, days)
    tab = r2_table(Ys, Ps, horizons=(0, 1, 2, 3))
    print("\n===== v3 — SPATIAL-HELD-OUT (full model, concentration units) =====")
    print(f"{'pollutant':8} {'h':>2} {'n':>7} {'R2':>8} {'RMSE':>8} {'MAE':>8}   vs XGBoost (h0)")
    for p in POLL:
        for h in range(4):
            r = tab[p][h]
            if r is None: continue
            r2, rmse, mae, n = r
            cmpi = ""
            if h == 0:
                xg = refs.get(p, {}).get("xgboost")
                if xg is not None:
                    tag = "BEAT" if (r2 > xg and r2 > 0) else (">=xgb but R2<0" if r2 > xg else "below")
                    cmpi = f"xgb {xg:+.2f}  {tag}"
            print(f"{p:8} {h:>2} {n:>7} {r2:>+8.3f} {rmse:>8.2f} {mae:>8.2f}   {cmpi}")

    # 2-3) reasoning ablations on identical day subset
    abl_days = days[:a.abl_days]
    print(f"\n===== reasoning ablations ({len(abl_days)} test days, horizon 0) =====")
    arms = {}
    for mode in ["full", "no_graph", "no_physics", "no_temporal"]:
        Ys2, Ps2 = collect(data, net, ylm, yls, abl_days, mode=mode)
        arms[mode] = r2_table(Ys2, Ps2)
    print(f"{'pollutant':8} {'full':>8} {'no_graph':>9} {'no_phys':>9} {'no_temp':>9} {'graph_gain':>11}")
    gains = {}
    for p in POLL:
        row = [(arms[m][p][0][0] if arms[m][p][0] else float("nan"))
               for m in ["full", "no_graph", "no_physics", "no_temporal"]]
        gains[p] = row[0] - row[1]
        print(f"{p:8} {row[0]:>+8.3f} {row[1]:>+9.3f} {row[2]:>+9.3f} {row[3]:>+9.3f} {gains[p]:>+11.3f}")

    # 4) orphan eval — the T-2 deployment measurement
    Yo, Po = collect(data, net, ylm, yls, abl_days, orphan=True)
    otab = r2_table(Yo, Po)
    print("\n===== ORPHAN eval (test nodes satellite+static MASKED -> neighbors only) =====")
    for p in POLL:
        if otab[p][0] and arms["full"][p][0]:
            print(f"  {p:8} orphan R2={otab[p][0][0]:+.3f}   (full={arms['full'][p][0][0]:+.3f})")

    # 5) attention distribution
    st = attn_stats(net, data.full_window(days[0]))
    print(f"\nalpha_self per GAT layer (full graph): {['%.3f' % s for s in st]}   (~1.0 = graph unused)")

    # verdict against pre-registered criteria
    ok1 = (gains.get("pm2_5", 0) > 0.03 and gains.get("pm10", 0) > 0.03
           and sum(1 for g in gains.values() if g > 0) >= 5)
    ok2 = bool(otab["pm2_5"][0] and otab["pm2_5"][0][0] > 0)
    ok3 = (sum(st) / len(st) < 0.9)
    print("\n===== PRE-REGISTERED CRITERIA =====")
    print(f"  S1 graph_gain (pm2_5&pm10 > +0.03, >=5/7 positive): {'PASS' if ok1 else 'FAIL'}")
    print(f"  S2 orphan pm2_5 R2 > 0:                             {'PASS' if ok2 else 'FAIL'}")
    print(f"  S3 mean alpha_self < 0.9:                           {'PASS' if ok3 else 'FAIL'}")


if __name__ == "__main__":
    main()