Download scripts/assemble.py from AtmosIQ/atmosiq-processed: direct link, hf CLI and curl.
- Browser
- Download file 8.97 kB
-
https://huggingface.co/datasets/AtmosIQ/atmosiq-processed/resolve/main/scripts/assemble.py
- Command line
-
hf download hf://datasets/AtmosIQ/atmosiq-processed/scripts/assemble.py
-
curl -L -o assemble.py https://huggingface.co/datasets/AtmosIQ/atmosiq-processed/resolve/main/scripts/assemble.py
8.97 kB
| r""" | |
| assemble.py -> 4-GROUP blueprint tensors (F_total=54) for AtmosIQ V1. | |
| Groups (MODEL_BLUEPRINT v1.1 §1): A satellite 18 | B meteorology 12 | C static 13 | D calendar 11. | |
| Group C is YEAR-VERSIONED (Data_Schema §2): 5 static (grid_nodes) + 4 yearly + land_use (node_features_yearly). | |
| Also builds completeness scalar + train-fold norm. | |
| Outputs to data/tensors/: groupA.npy groupB.npy groupC_static.npy groupC_yearly.npy | |
| groupC_landuse.npy year_of_day.npy years.npy calendar_num.npy grap.npy physics.npy | |
| completeness.npy targets.npy target_mask.npy edges.npz node_split.npy dates.npy norm.npz meta.json | |
| Run: python data\models\assemble.py | |
| """ | |
| from __future__ import annotations | |
| import os, json, pathlib, 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) | |
| EDGE=os.environ.get("ATMOS_EDGES","graph_edges_static_r40_k8.parquet") | |
| TARGETS=["pm2_5","pm10","no2","so2","co","o3","nh3"] | |
| NFY="node_features_yearly.parquet" | |
| # ---- GROUP MEMBERSHIP (verify vs Data_Schema §1/§2) ---- | |
| A_SAT=["s5p_no2_column","s5p_so2_column","s5p_co_column","s5p_o3_column","s5p_hcho_column", | |
| "modis_aod","viirs_aod","fire_count","frp"] # 5 S5P + 2 AOD + 2 fire = 9 | |
| A_FLAGS=["s5p_no2_column_present","s5p_co_column_present","s5p_so2_column_present","s5p_o3_column_present", | |
| "s5p_hcho_column_present","s5p_aer_ai_present","s5p_ch4_column_present","modis_aod_present","viirs_aod_present"] # 9 | |
| B_MET=["era5_temperature","era5_boundary_layer_height","era5_relative_humidity","era5_surface_pressure", | |
| "era5_cloud_cover","era5_wind_u","era5_wind_v","era5_rainfall","s5p_cloud_fraction","s5p_aer_ai", | |
| "s5p_ch4_column","u_1330ist"] # 12 | |
| C_STATIC=["elevation_m","projection_x","projection_y","distance_to_highway_km","distance_to_industry_km"] # 5 | |
| C_YEARLY=["road_density","industrial_density","population_density","ndvi_annual_mean"] # 4 | |
| import sys as _sys, pathlib as _pl | |
| _sys.path.insert(0, str(_pl.Path(__file__).resolve().parent)) | |
| from build_group_d import build as _build_group_d, COLS as GROUP_D_COLS # event calendar (festivals, stubble, monsoon, COVID, GRAP...) | |
| def calendar(dates): | |
| return _build_group_d(dates) # calendar_num [D,K], grap_stage [D] | |
| def main(): | |
| gn=pd.read_parquet(GRID); pos={n:i for i,n in enumerate(gn.node_id.astype(str))}; N=len(pos) | |
| missS=[c for c in C_STATIC if c not in gn.columns] | |
| if missS: raise SystemExit(f"grid_nodes missing static Group C: {missS}") | |
| nfy_path=OUT/NFY | |
| if not nfy_path.exists(): raise SystemExit(f"MISSING {nfy_path} — run GEE Group C pipeline first.") | |
| nfy=pd.read_parquet(nfy_path) | |
| print(f"nodes {N} | node_features_yearly {len(nfy):,} rows, years {sorted(nfy.year.unique())}") | |
| sp=pd.read_parquet(SPLIT); fmap={"train":0,"val":1,"test":2,"buffer":3} | |
| nsplit=np.full(N,3,np.uint8) | |
| for n,s in zip(sp.node_id.astype(str),sp.split): nsplit[pos[n]]=fmap.get(s,3) | |
| ed=pd.read_parquet(GRAPH/EDGE) | |
| ei=np.stack([ed.src_node.astype(str).map(pos).values,ed.dst_node.astype(str).map(pos).values]).astype(np.int64) | |
| parts=sorted((OUT/"train_ready").glob("*.parquet")) | |
| 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) | |
| print(f"days {D}") | |
| A=np.full((D,N,len(A_SAT)+len(A_FLAGS)),0.,np.float32) | |
| B=np.full((D,N,len(B_MET)),np.nan,np.float32) | |
| PH=np.full((D,N,3),0.,np.float32) # raw u_1330ist,v_1330ist,blh for physics | |
| 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] | |
| for j,c in enumerate(A_SAT): A[di,ni,j]=(pd.to_numeric(df[c],errors="coerce").fillna(0) if c in df else 0) | |
| for j,c in enumerate(A_FLAGS): A[di,ni,len(A_SAT)+j]=(pd.to_numeric(df[c],errors="coerce").fillna(0) if c in df else 0) | |
| for j,c in enumerate(B_MET): B[di,ni,j]=(pd.to_numeric(df[c],errors="coerce") if c in df else np.nan) | |
| for j,c in enumerate(TARGETS): Y[di,ni,j]=pd.to_numeric(df[c],errors="coerce") | |
| for j,c in enumerate(["u_1330ist","v_1330ist","era5_boundary_layer_height"]): | |
| if c in df: PH[di,ni,j]=pd.to_numeric(df[c],errors="coerce").fillna(0) | |
| print(f" {p.stem}",end="\r") | |
| print() | |
| # ---- Group C: static (grid_nodes) + yearly (node_features_yearly) ---- | |
| Cstat=gn.set_index("node_id").loc[gn.node_id][C_STATIC].to_numpy(np.float32) # [N,5] | |
| years=sorted(int(y) for y in nfy.year.unique()); yidx={y:i for i,y in enumerate(years)}; Ky=len(years) | |
| Cyear=np.zeros((Ky,N,len(C_YEARLY)),np.float32); LUyear=np.zeros((Ky,N),np.int64) | |
| nfy=nfy.copy(); nfy["p"]=nfy.node_id.astype(str).map(pos) | |
| nfy=nfy.dropna(subset=["p"]) | |
| pi=nfy.p.astype(int).values; yi=nfy.year.astype(int).map(yidx).values | |
| for j,c in enumerate(C_YEARLY): Cyear[yi,pi,j]=pd.to_numeric(nfy[c],errors="coerce").fillna(0).values | |
| LUyear[yi,pi]=pd.to_numeric(nfy["land_use_class"],errors="coerce").fillna(0).astype(int).values | |
| day_years=pd.to_datetime(dates).year.values | |
| year_of_day=np.array([yidx.get(int(y), yidx[min(max(int(y),years[0]),years[-1])]) for y in day_years],np.int64) | |
| Dnum,Dgrap=calendar(dates); print(f"Group D: calendar_num{Dnum.shape} grap_stage 0..{int(Dgrap.max())}") | |
| completeness=A[:,:,len(A_SAT):].mean(-1).astype(np.float32) # [D,N] | |
| # ---- normalization on TRAIN-fold ---- | |
| tr=np.where(nsplit==0)[0] | |
| def nf(X): s=X[:,tr,:].reshape(-1,X.shape[-1]); m=np.nanmean(s,0); d=np.nanstd(s,0); d[(d==0)|~np.isfinite(d)]=1; return m,d | |
| Am,Asd=nf(A[:,:,:len(A_SAT)]); Bm,Bsd=nf(B) | |
| A[:,:,:len(A_SAT)]=np.nan_to_num((A[:,:,:len(A_SAT)]-Am)/Asd); B=np.nan_to_num((B-Bm)/Bsd) | |
| Csm=np.nanmean(Cstat[tr],0); Cssd=np.nanstd(Cstat[tr],0); Cssd[(Cssd==0)|~np.isfinite(Cssd)]=1 | |
| Cstat=np.nan_to_num((Cstat-Csm)/Cssd) | |
| yt=Cyear[:,tr,:].reshape(-1,len(C_YEARLY)); Cym=np.nanmean(yt,0); Cysd=np.nanstd(yt,0); Cysd[(Cysd==0)|~np.isfinite(Cysd)]=1 | |
| Cyear=np.nan_to_num((Cyear-Cym)/Cysd) | |
| np.save(DEST/"groupA.npy",A.astype(np.float16)); np.save(DEST/"groupB.npy",B.astype(np.float16)) | |
| np.save(DEST/"groupC_static.npy",Cstat.astype(np.float16)) | |
| np.save(DEST/"groupC_yearly.npy",Cyear.astype(np.float16)); np.save(DEST/"groupC_landuse.npy",LUyear) | |
| np.save(DEST/"year_of_day.npy",year_of_day); np.save(DEST/"years.npy",np.array(years)) | |
| np.save(DEST/"calendar_num.npy",Dnum); np.save(DEST/"grap.npy",Dgrap); np.save(DEST/"physics.npy",PH.astype(np.float16)) | |
| np.save(DEST/"completeness.npy",completeness) | |
| # per-pollutant log-target standardization stats (TRAIN fold) -> level scale across pollutants | |
| yeps=1e-3; ylog=np.log(np.clip(Y,0,None)+yeps) | |
| trmask=(nsplit==0) | |
| ylm=np.zeros(7,np.float32); yls=np.ones(7,np.float32) | |
| for j in range(7): | |
| v=ylog[:,trmask,j]; v=v[~np.isnan(v)] | |
| if len(v): ylm[j]=v.mean(); yls[j]=v.std()+1e-6 | |
| print(" per-pollutant log-target mean:", np.round(ylm,2), "std:", np.round(yls,2)) | |
| mask=(~np.isnan(Y)).astype(np.uint8) | |
| np.save(DEST/"targets.npy",np.nan_to_num(Y).astype(np.float16)); np.save(DEST/"target_mask.npy",mask) | |
| 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)) | |
| np.save(DEST/"node_split.npy",nsplit); np.save(DEST/"dates.npy",np.array(dates)) | |
| np.savez(DEST/"norm.npz",Am=Am,Asd=Asd,Bm=Bm,Bsd=Bsd,Csm=Csm,Cssd=Cssd,Cym=Cym,Cysd=Cysd,y_logmean=ylm,y_logstd=yls) | |
| json.dump(dict(N=int(N),D=int(D),years=years,dimsA=int(A.shape[-1]),dimsB=int(B.shape[-1]), | |
| dimsC_static=len(C_STATIC),dimsC_yearly=len(C_YEARLY),n_landuse=int(LUyear.max())+1, | |
| dimsD_num=int(Dnum.shape[1]),n_grap=int(Dgrap.max())+1,group_d_cols=GROUP_D_COLS, | |
| A_SAT=A_SAT,A_FLAGS=A_FLAGS,B_MET=B_MET,C_STATIC=C_STATIC,C_YEARLY=C_YEARLY), | |
| open(DEST/"meta.json","w"),indent=1) | |
| print(f"assembled -> {DEST}") | |
| print(f" A{A.shape} B{B.shape} Cstatic{Cstat.shape} Cyearly{Cyear.shape} landuse<= {int(LUyear.max())} physics{PH.shape}") | |
| print(f" labeled node-days: {int((mask.sum(-1)>0).sum()):,} | set model cfg n_landuse={int(LUyear.max())+1}") | |
| if __name__=="__main__": main() |