r""" tensor_prep.py -> builds ALL training tensors from train_ready (CPU, 64GB). The GPU VM then just loads these + model.py and trains (no CPU prep there). Dense layout: everything indexed by (day, node_pos). N=32,686 nodes fixed order. Outputs to data/tensors/: node_index.parquet node_id -> pos dates.npy sorted unique YYYY-MM-DD feat_cols.json ordered feature names features.npy [DAYS,N,F] float16 (z-scored on TRAIN fold, NaN->0) physics.npy [DAYS,N,3] float16 RAW u_1330ist,v_1330ist,blh (physics needs real units) targets.npy [DAYS,N,7] float16 (raw pollutant values) target_mask.npy [DAYS,N,7] uint8 (1 = observed & labeled) edges.npz ei[2,E] positions, e_hat[E], n_hat[E] node_split.npy [N] uint8 (0 train,1 val,2 test,3 buffer/none) norm.npz mean,std per feature (train fold only) Run: python data\models\tensor_prep.py """ from __future__ import annotations import os, sys, json, pathlib import numpy as np, pandas as pd OUT = pathlib.Path(os.environ.get("ATMOS_OUT","data/ingest")) GRID = pathlib.Path(os.environ.get("ATMOS_GRID","data/grid/grid_nodes.parquet")) GRAPH = pathlib.Path(os.environ.get("ATMOS_GRAPH","data/graph")) SPLIT = pathlib.Path(os.environ.get("ATMOS_SPLITS","data/splits"))/"spatial_split.parquet" DEST = pathlib.Path(os.environ.get("ATMOS_TENSORS","data/tensors")); DEST.mkdir(parents=True, exist_ok=True) TARGETS = ["pm2_5","pm10","no2","so2","co","o3","nh3"] PHYS_COLS = ["u_1330ist","v_1330ist","era5_boundary_layer_height"] META = set(["node_id","date","centroid_lat","centroid_lon","n_stations","labeled","split","block_id"]+TARGETS) EDGE_FILE = os.environ.get("ATMOS_EDGES","graph_edges_static_r40_k8.parquet") def main(): gn = pd.read_parquet(GRID) pos = {nid:i for i,nid in enumerate(gn["node_id"].astype(str))} N = len(pos); print(f"nodes: {N:,}") pd.DataFrame({"node_id":list(pos), "pos":list(pos.values())}).to_parquet(DEST/"node_index.parquet", index=False) # split -> per-node fold sp = pd.read_parquet(SPLIT); fmap = {"train":0,"val":1,"test":2,"buffer":3} nsplit = np.full(N, 3, np.uint8) for nid, s in zip(sp.node_id.astype(str), sp.split): nsplit[pos[nid]] = fmap.get(s,3) np.save(DEST/"node_split.npy", nsplit) # edges -> positions + geometry ed = pd.read_parquet(GRAPH/EDGE_FILE) ei = np.stack([ed.src_node.astype(str).map(pos).values, ed.dst_node.astype(str).map(pos).values]).astype(np.int64) np.savez(DEST/"edges.npz", ei=ei, e_hat=ed.e_hat.values.astype(np.float32), n_hat=ed.n_hat.values.astype(np.float32)) print(f"edges: {ei.shape[1]:,}") # discover feature columns + all dates from partitions parts = sorted((OUT/"train_ready").glob("*.parquet")) f0 = pd.read_parquet(parts[0]) feat_cols = [c for c in f0.columns if c not in META and pd.api.types.is_numeric_dtype(f0[c])] json.dump(feat_cols, open(DEST/"feat_cols.json","w")) F = len(feat_cols); print(f"features: {F}") dates = sorted(set().union(*[set(pd.read_parquet(p, columns=["date"]).date.astype(str)) for p in parts])) didx = {d:i for i,d in enumerate(dates)}; D = len(dates) np.save(DEST/"dates.npy", np.array(dates)) print(f"days: {D:,} -> feature array {D}x{N}x{F} float16 = {D*N*F*2/1e9:.1f} GB") # dense arrays A = np.full((D,N,F), np.nan, np.float32) # build in f32, cast at save PH = np.full((D,N,3), np.nan, np.float32) Y = np.full((D,N,7), np.nan, np.float32) for p in parts: df = pd.read_parquet(p) di = df.date.astype(str).map(didx).values ni = df.node_id.astype(str).map(pos).values ok = ~pd.isna(di) & ~pd.isna(ni) di = di[ok].astype(int); ni = ni[ok].astype(int); df = df[ok] A[di, ni, :] = df[feat_cols].to_numpy(np.float32) for j,c in enumerate(PHYS_COLS): if c in df: PH[di, ni, j] = pd.to_numeric(df[c], errors="coerce").to_numpy(np.float32) for j,c in enumerate(TARGETS): Y[di, ni, j] = pd.to_numeric(df[c], errors="coerce").to_numpy(np.float32) print(f" placed {p.stem}", end="\r") print() # normalization on TRAIN-fold node-days only (no leakage) train_nodes = np.where(nsplit==0)[0] sub = A[:, train_nodes, :].reshape(-1, F) mean = np.nanmean(sub, 0); std = np.nanstd(sub, 0); std[std==0 | ~np.isfinite(std)] = 1.0 np.savez(DEST/"norm.npz", mean=mean.astype(np.float32), std=std.astype(np.float32), feat_cols=np.array(feat_cols)) A = (A - mean) / std A = np.nan_to_num(A, nan=0.0) # NaN -> 0 (=mean); *_present flags carry missingness PH = np.nan_to_num(PH, nan=0.0) # calm/zero where missing mask = (~np.isnan(Y)).astype(np.uint8) Y = np.nan_to_num(Y, nan=0.0) np.save(DEST/"features.npy", A.astype(np.float16)) np.save(DEST/"physics.npy", PH.astype(np.float16)) np.save(DEST/"targets.npy", Y.astype(np.float16)) np.save(DEST/"target_mask.npy", mask) lab_days = int((mask.sum(2)>0).sum()) print(f"saved tensors to {DEST} | labeled node-days: {lab_days:,}") print(f" features {A.shape} physics {PH.shape} targets {Y.shape}") if __name__ == "__main__": main()