AtmosIQ commited on
Commit
093c656
·
verified ·
1 Parent(s): 0aa48cc

Upload scripts/tensor_prep.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/tensor_prep.py +100 -0
scripts/tensor_prep.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ tensor_prep.py -> builds ALL training tensors from train_ready (CPU, 64GB).
3
+ The GPU VM then just loads these + model.py and trains (no CPU prep there).
4
+
5
+ Dense layout: everything indexed by (day, node_pos). N=32,686 nodes fixed order.
6
+ Outputs to data/tensors/:
7
+ node_index.parquet node_id -> pos
8
+ dates.npy sorted unique YYYY-MM-DD
9
+ feat_cols.json ordered feature names
10
+ features.npy [DAYS,N,F] float16 (z-scored on TRAIN fold, NaN->0)
11
+ physics.npy [DAYS,N,3] float16 RAW u_1330ist,v_1330ist,blh (physics needs real units)
12
+ targets.npy [DAYS,N,7] float16 (raw pollutant values)
13
+ target_mask.npy [DAYS,N,7] uint8 (1 = observed & labeled)
14
+ edges.npz ei[2,E] positions, e_hat[E], n_hat[E]
15
+ node_split.npy [N] uint8 (0 train,1 val,2 test,3 buffer/none)
16
+ norm.npz mean,std per feature (train fold only)
17
+
18
+ Run: python data\models\tensor_prep.py
19
+ """
20
+ from __future__ import annotations
21
+ import os, sys, json, pathlib
22
+ import numpy as np, pandas as pd
23
+
24
+ OUT = pathlib.Path(os.environ.get("ATMOS_OUT","data/ingest"))
25
+ GRID = pathlib.Path(os.environ.get("ATMOS_GRID","data/grid/grid_nodes.parquet"))
26
+ GRAPH = pathlib.Path(os.environ.get("ATMOS_GRAPH","data/graph"))
27
+ SPLIT = pathlib.Path(os.environ.get("ATMOS_SPLITS","data/splits"))/"spatial_split.parquet"
28
+ DEST = pathlib.Path(os.environ.get("ATMOS_TENSORS","data/tensors")); DEST.mkdir(parents=True, exist_ok=True)
29
+ TARGETS = ["pm2_5","pm10","no2","so2","co","o3","nh3"]
30
+ PHYS_COLS = ["u_1330ist","v_1330ist","era5_boundary_layer_height"]
31
+ META = set(["node_id","date","centroid_lat","centroid_lon","n_stations","labeled","split","block_id"]+TARGETS)
32
+ EDGE_FILE = os.environ.get("ATMOS_EDGES","graph_edges_static_r40_k8.parquet")
33
+
34
+ def main():
35
+ gn = pd.read_parquet(GRID)
36
+ pos = {nid:i for i,nid in enumerate(gn["node_id"].astype(str))}
37
+ N = len(pos); print(f"nodes: {N:,}")
38
+ pd.DataFrame({"node_id":list(pos), "pos":list(pos.values())}).to_parquet(DEST/"node_index.parquet", index=False)
39
+
40
+ # split -> per-node fold
41
+ sp = pd.read_parquet(SPLIT); fmap = {"train":0,"val":1,"test":2,"buffer":3}
42
+ nsplit = np.full(N, 3, np.uint8)
43
+ for nid, s in zip(sp.node_id.astype(str), sp.split): nsplit[pos[nid]] = fmap.get(s,3)
44
+ np.save(DEST/"node_split.npy", nsplit)
45
+
46
+ # edges -> positions + geometry
47
+ ed = pd.read_parquet(GRAPH/EDGE_FILE)
48
+ ei = np.stack([ed.src_node.astype(str).map(pos).values, ed.dst_node.astype(str).map(pos).values]).astype(np.int64)
49
+ 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))
50
+ print(f"edges: {ei.shape[1]:,}")
51
+
52
+ # discover feature columns + all dates from partitions
53
+ parts = sorted((OUT/"train_ready").glob("*.parquet"))
54
+ f0 = pd.read_parquet(parts[0])
55
+ feat_cols = [c for c in f0.columns if c not in META and pd.api.types.is_numeric_dtype(f0[c])]
56
+ json.dump(feat_cols, open(DEST/"feat_cols.json","w"))
57
+ F = len(feat_cols); print(f"features: {F}")
58
+ dates = sorted(set().union(*[set(pd.read_parquet(p, columns=["date"]).date.astype(str)) for p in parts]))
59
+ didx = {d:i for i,d in enumerate(dates)}; D = len(dates)
60
+ np.save(DEST/"dates.npy", np.array(dates))
61
+ print(f"days: {D:,} -> feature array {D}x{N}x{F} float16 = {D*N*F*2/1e9:.1f} GB")
62
+
63
+ # dense arrays
64
+ A = np.full((D,N,F), np.nan, np.float32) # build in f32, cast at save
65
+ PH = np.full((D,N,3), np.nan, np.float32)
66
+ Y = np.full((D,N,7), np.nan, np.float32)
67
+ for p in parts:
68
+ df = pd.read_parquet(p)
69
+ di = df.date.astype(str).map(didx).values
70
+ ni = df.node_id.astype(str).map(pos).values
71
+ ok = ~pd.isna(di) & ~pd.isna(ni)
72
+ di = di[ok].astype(int); ni = ni[ok].astype(int); df = df[ok]
73
+ A[di, ni, :] = df[feat_cols].to_numpy(np.float32)
74
+ for j,c in enumerate(PHYS_COLS):
75
+ if c in df: PH[di, ni, j] = pd.to_numeric(df[c], errors="coerce").to_numpy(np.float32)
76
+ for j,c in enumerate(TARGETS):
77
+ Y[di, ni, j] = pd.to_numeric(df[c], errors="coerce").to_numpy(np.float32)
78
+ print(f" placed {p.stem}", end="\r")
79
+ print()
80
+
81
+ # normalization on TRAIN-fold node-days only (no leakage)
82
+ train_nodes = np.where(nsplit==0)[0]
83
+ sub = A[:, train_nodes, :].reshape(-1, F)
84
+ mean = np.nanmean(sub, 0); std = np.nanstd(sub, 0); std[std==0 | ~np.isfinite(std)] = 1.0
85
+ np.savez(DEST/"norm.npz", mean=mean.astype(np.float32), std=std.astype(np.float32), feat_cols=np.array(feat_cols))
86
+ A = (A - mean) / std
87
+ A = np.nan_to_num(A, nan=0.0) # NaN -> 0 (=mean); *_present flags carry missingness
88
+ PH = np.nan_to_num(PH, nan=0.0) # calm/zero where missing
89
+ mask = (~np.isnan(Y)).astype(np.uint8)
90
+ Y = np.nan_to_num(Y, nan=0.0)
91
+
92
+ np.save(DEST/"features.npy", A.astype(np.float16))
93
+ np.save(DEST/"physics.npy", PH.astype(np.float16))
94
+ np.save(DEST/"targets.npy", Y.astype(np.float16))
95
+ np.save(DEST/"target_mask.npy", mask)
96
+ lab_days = int((mask.sum(2)>0).sum())
97
+ print(f"saved tensors to {DEST} | labeled node-days: {lab_days:,}")
98
+ print(f" features {A.shape} physics {PH.shape} targets {Y.shape}")
99
+
100
+ if __name__ == "__main__": main()