r""" calibrate_u1.py — U-1 mandatory calibration gate (Architecture §7, ADR-015). PICP@50/80/95 per pollutant (h0, spatial-held-out), MC-sampled from the predicted log-Student-t (N=500, ADR-015), STRATIFIED by window-completeness (pass = within-stratum). Coverage checked in standardized-log space (invariant under monotone back-transform). Pre-registered pass bar: |PICP - nominal| <= 5 points in every stratum with n>=200. Run: python data/models_v3/calibrate_u1.py --tensors data/tensors --ckpt data/atmosiq_v3_lp_final.pt """ from __future__ import annotations import json, argparse, pathlib, sys import numpy as np, torch sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from model import AtmosIQNet from dataset_v3 import AtmosDataV3 POLL = ["pm2_5", "pm10", "no2", "so2", "co", "o3", "nh3"] LEVELS = [0.50, 0.80, 0.95] STRATA = [(0.0, 0.33, "low-comp "), (0.33, 0.66, "mid-comp "), (0.66, 1.01, "high-comp")] def stride(days, k): if not k or k >= len(days): return list(days) s = max(1, len(days) // k) return list(days)[::s][:k] def main(): ap = argparse.ArgumentParser() ap.add_argument("--tensors", default="data/tensors") ap.add_argument("--ckpt", default="data/atmosiq_v3_lp_final.pt") ap.add_argument("--window", type=int, default=7) ap.add_argument("--days", type=int, default=200) ap.add_argument("--mc", type=int, default=500) ap.add_argument("--seed", type=int, default=42) a = ap.parse_args() torch.manual_seed(a.seed) dev = "cuda" if torch.cuda.is_available() else "cpu"; print("device:", 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") ylm = torch.tensor(nz["y_logmean"]).float().to(dev) yls = torch.tensor(nz["y_logstd"]).float().to(dev) print(f"loaded {a.ckpt}") days = stride(data.target_days(2), a.days) te = (data.split == 2).to(dev) print(f"U-1 over {len(days)} season-balanced test days, MC={a.mc}") hits = np.zeros((7, len(LEVELS), len(STRATA))); ns = np.zeros((7, len(STRATA))) hitn = np.zeros((7, len(LEVELS), len(STRATA))) w80s = np.zeros((7, len(STRATA))) qs = [] for p in LEVELS: qs += [(1 - p) / 2, 1 - (1 - p) / 2] qs_t = torch.tensor(qs, device=dev) with torch.no_grad(): for t in days: b = data.full_window(t) out = net(b["groups_t"], b["ei"], b["e_hat"], b["n_hat"], b["wu"], b["wv"], b["blh"], b["comp"]) mu = out["mu"][:, 0, :] sigma = torch.nn.functional.softplus(out["log_sigma"][:, 0, :]) + 1e-3 nu = out["nu"].clamp(2.05, 100.0).view(1, -1).expand_as(mu) dist = torch.distributions.StudentT(df=nu, loc=mu, scale=sigma) smp = dist.sample((a.mc,)) Q = torch.quantile(smp, qs_t, dim=0) yl = (torch.log(b["y"][:, 0, :].clamp_min(0) + 1e-3) - ylm.view(1, -1)) / yls.view(1, -1) m = (b["m"][:, 0, :] > 0) & te.unsqueeze(-1) comp = b["comp"] for si, (lo, hi, _) in enumerate(STRATA): sm = (comp >= lo) & (comp < hi) mm = m & sm.unsqueeze(-1) for j in range(7): idx = mm[:, j] n = int(idx.sum()) if n == 0: continue ns[j, si] += n y = yl[idx, j] for li in range(len(LEVELS)): loq = Q[2 * li, idx, j]; hiq = Q[2 * li + 1, idx, j] hits[j, li, si] += float(((y >= loq) & (y <= hiq)).sum()) hitn[j, li, si] += n w80s[j, si] += float((Q[3, idx, j] - Q[2, idx, j]).sum()) print("\n===== U-1 — PICP per pollutant × completeness stratum (h0, std-log space) =====") print(f"{'pollutant':8} {'stratum':10} {'n':>8} {'PICP50':>8} {'PICP80':>8} {'PICP95':>8} {'width80':>8} verdict") overall_pass = True for j, pn in enumerate(POLL): for si, (_, _, sname) in enumerate(STRATA): n = int(ns[j, si]) if n == 0: print(f"{pn:8} {sname:10} {'0':>8} (empty stratum)"); continue pic = [hits[j, li, si] / max(hitn[j, li, si], 1) for li in range(len(LEVELS))] w80 = w80s[j, si] / n if n >= 200: ok = all(abs(pic[li] - LEVELS[li]) <= 0.05 for li in range(len(LEVELS))) verdict = "PASS" if ok else "MISCAL" if not ok: overall_pass = False else: verdict = "n<200 (info)" print(f"{pn:8} {sname:10} {n:>8} {pic[0]:>8.3f} {pic[1]:>8.3f} {pic[2]:>8.3f} {w80:>8.3f} {verdict}") print(f"\nU-1 overall (all strata n>=200 within ±5pts): {'PASS' if overall_pass else 'FAIL'}") print("NOTE: deliverable was selected on val_mse (TP-7) — sigma/nu were never selection criteria,") print("so miscalibration here is expected-possible and honest; fix path = sigma/nu-only recalibration") print("(head log_sigma/log_nu params) on val fold, mu frozen. Never tune on this test output.") if __name__ == "__main__": main()