Download scripts/ingest_cpcb.py from AtmosIQ/atmosiq-processed: direct link, hf CLI and curl.
- Browser
- Download file 3.89 kB
-
https://huggingface.co/datasets/AtmosIQ/atmosiq-processed/resolve/main/scripts/ingest_cpcb.py
- Command line
-
hf download hf://datasets/AtmosIQ/atmosiq-processed/scripts/ingest_cpcb.py
-
curl -L -o ingest_cpcb.py https://huggingface.co/datasets/AtmosIQ/atmosiq-processed/resolve/main/scripts/ingest_cpcb.py
3.89 kB
| """ | |
| ingest_cpcb.py -> data\ingest\ (run: python data\ingest\ingest_cpcb.py) | |
| CPCB ground-truth stations -> grid-aligned SUPERVISION LABELS. | |
| Each station (lat,lon) is dropped into its 10 km cell (containment); stations | |
| in the same cell on the same day are averaged. Output: | |
| cpcb_labels_daily.parquet : node_id | date | pm2_5 pm10 no2 so2 co o3 nh3 | n_stations | centroid_lat/lon | |
| and sets grid_nodes.has_cpcb_station (the "directly_verified" calibration flag). | |
| Source: AtmosIQ/cpcb/merged_cpcb_clean.csv (HF), or pass --csv <path>. | |
| """ | |
| from __future__ import annotations | |
| import os, sys, argparse, pathlib | |
| os.environ.setdefault("HF_HUB_DISABLE_XET", "1") | |
| sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "grid")) | |
| import numpy as np, pandas as pd | |
| from grid_index import GridIndex | |
| OUT = pathlib.Path(os.environ.get("ATMOS_OUT", "data/ingest")) | |
| GRID = pathlib.Path(os.environ.get("ATMOS_GRID", "data/grid/grid_nodes.parquet")) | |
| # CPCB raw col -> model target name (blueprint P=7). Extras (no, nox_ppb) dropped. | |
| TARGETS = {"pm25":"pm2_5","pm10":"pm10","no2":"no2","so2":"so2","co":"co","o3":"o3","nh3":"nh3"} | |
| # physical caps (CPCB is ground truth; light safety only — drops sensor spikes) | |
| CAP = {"pm2_5":(0,1000),"pm10":(0,1000),"no2":(0,500),"so2":(0,300), | |
| "co":(0,50),"o3":(0,600),"nh3":(0,600)} | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--csv", default=None, help="local merged_cpcb_clean.csv (else HF download)") | |
| args = ap.parse_args() | |
| gi = GridIndex.from_parquet(str(GRID)) | |
| print(f"grid: {len(gi)} cells") | |
| if args.csv: | |
| path = args.csv | |
| else: | |
| from huggingface_hub import hf_hub_download | |
| print("downloading CPCB csv from HF...") | |
| path = hf_hub_download("AtmosIQ/cpcb", filename="merged_cpcb_clean.csv", | |
| repo_type="dataset", token=os.environ.get("HF_TOKEN")) | |
| print(f"reading {path}") | |
| df = pd.read_csv(path, usecols=["date","lat","lon"] + list(TARGETS.keys())) | |
| print(f"raw rows: {len(df):,}") | |
| # normalise date to YYYY-MM-DD (already IST calendar date) | |
| df["date"] = pd.to_datetime(df["date"], errors="coerce").dt.strftime("%Y-%m-%d") | |
| df = df.dropna(subset=["date","lat","lon"]) | |
| df = df.rename(columns=TARGETS) | |
| # station -> cell (containment) | |
| df["node_id"] = gi.assign_node_id(df["lat"].values, df["lon"].values) | |
| dropped = int(df["node_id"].isna().sum()) | |
| df = df[df["node_id"].notna()] | |
| print(f"stations mapped to grid; {dropped:,} station-days fell outside grid (dropped)") | |
| # safety clip each target (leaves NaN as NaN) | |
| for c,(lo,hi) in CAP.items(): | |
| if c in df: df[c] = df[c].clip(lo, hi) | |
| # aggregate stations sharing a cell/day -> mean target; count stations | |
| g = df.groupby(["node_id","date"]) | |
| lab = g[list(TARGETS.values())].mean() | |
| lab["n_stations"] = g["lat"].size() # station-days averaged (proxy for station count) | |
| lab = lab.reset_index().merge(gi.centroids(), on="node_id", how="left") | |
| lab.to_parquet(OUT/"cpcb_labels_daily.parquet", index=False) | |
| print(f"-> {OUT/'cpcb_labels_daily.parquet'} ({len(lab):,} labeled node-days)") | |
| print(f" unique labeled cells: {lab['node_id'].nunique():,}/{len(gi)} " | |
| f"| date range {lab['date'].min()}..{lab['date'].max()}") | |
| for c in TARGETS.values(): | |
| s = lab[c]; print(f" {c}: fill={100*s.notna().mean():.1f}% mean={s.mean():.2f}") | |
| # calibration flag: which cells ever host a station | |
| gn = pd.read_parquet(GRID) | |
| stationed = set(lab["node_id"].unique()) | |
| gn["has_cpcb_station"] = gn["node_id"].isin(stationed) | |
| gn.to_parquet(GRID, index=False) | |
| print(f" grid_nodes.has_cpcb_station set: {gn['has_cpcb_station'].sum():,} cells verified") | |
| if __name__ == "__main__": | |
| main() |