File size: 17,108 Bytes
0c88e5a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 | """
run_ingest.py — AtmosIQ Phase-2 orchestrator (checkpointed, never-skip build).
GUARANTEE: no file is EVER skipped. Every source is resumable and asserts
100% file completeness before writing its output. If a download can't be
recovered after retries, the run STOPS (raises) — it never drops data.
Feeding modes:
--local DIR : process files already on disk (use `hf download` for whole repos)
(default) : stream each file from HF to scratch, process, delete (for MODIS)
Env: ATMOS_OUT, ATMOS_GRID, ATMOS_SCRATCH, HF_TOKEN
Commands: <source...> | --local DIR | --merge | --check | --no-merge | --force
"""
from __future__ import annotations
import os, sys, glob, math, pathlib, fnmatch, time
os.environ.setdefault("HF_HUB_DISABLE_XET", "1") # avoid Xet CAS 401 churn
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "grid"))
import numpy as np
import pandas as pd
import pyarrow as pa, pyarrow.parquet as pq
from aggregation import SPECS, ingest, _to_date, _clean, _select_nearest_ist
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"))
SCRATCH = pathlib.Path(os.environ.get("ATMOS_SCRATCH", "scratch"))
CHUNK = 500_000
OUT.mkdir(parents=True, exist_ok=True); SCRATCH.mkdir(parents=True, exist_ok=True)
CKPT = OUT / ".ckpt"; CKPT.mkdir(exist_ok=True)
REG = {
"s5p_no2": ("Atmos_Pollutants_Particles","data/NO2/*.csv","s5p_no2","stream"),
"s5p_so2": ("Atmos_Pollutants_Particles","data/SO2/*.csv","s5p_so2","stream"),
"s5p_co": ("Atmos_Pollutants_Particles","data/CO/*.csv","s5p_co","stream"),
"s5p_o3": ("Atmos_Pollutants_Particles","data/O3/*.csv","s5p_o3","stream"),
"s5p_hcho": ("Atmos_Pollutants_Particles","data/HCHO/*.csv","s5p_hcho","stream"),
"s5p_aer_ai":("Atmos_Pollutants_Particles","data/AER_AI/*.csv","s5p_aer_ai","stream"),
"s5p_ch4": ("Atmos_Pollutants_Particles","data/CH4/*.csv","s5p_ch4","stream"),
"s5p_cloud":("Atmos_Pollutants_Particles","data/CLOUD/*.csv","s5p_cloud","stream"),
"modis": ("Atmos_MODIS_AOD","data/*.csv","modis","stream"),
"viirs": ("Atmos_VIIRS_AOD","data/*.csv","viirs","stream"),
"era5_daily": ("Atmos_ERA5_Meteorology","data/*.csv","era5_daily","centroid"),
"era5_wind_1330": ("Atmos_ERA5_Meteorology","data/*.csv","era5_wind_1330","centroid"),
"firms": ("Atmos_FIRMS_Fire","data/*.csv","firms","stream"),
"dem": ("Atmos_DEM_Copernicus","*.tif",None,"dem"),
}
HF_ORG = "AtmosIQ"
def hf_list(repo, subpath):
from huggingface_hub import HfApi
api = HfApi(token=os.environ.get("HF_TOKEN"))
return [f for f in api.list_repo_files(f"{HF_ORG}/{repo}", repo_type="dataset")
if fnmatch.fnmatch(f, subpath)]
def local_files(root, repo, subpath):
return sorted(glob.glob(str(pathlib.Path(root) / repo / subpath)))
def _dl_retry(repo, f, tries=10):
"""Download one file with exp backoff. NEVER skips: raises after `tries`
so the run STOPS rather than dropping data."""
from huggingface_hub import hf_hub_download
for a in range(tries):
try:
return hf_hub_download(f"{HF_ORG}/{repo}", filename=f, repo_type="dataset",
local_dir=str(SCRATCH), token=os.environ.get("HF_TOKEN"))
except Exception as e:
if a == tries - 1:
raise RuntimeError(f"STOP: {f} failed after {tries} tries ({type(e).__name__}). "
f"Nothing skipped — fix & re-run to resume.") from e
w = min(120, 3 * 2 ** a); print(f" retry {a+1}/{tries} {f} in {w}s"); time.sleep(w)
# ---- checkpoint helpers (resume without loss) ------------------------------
def _ckpt_load(name):
ck = CKPT / f"{name}.ckpt.parquet" # new atomic single-file format
if ck.exists():
t = pq.read_table(ck); done = set(t.schema.metadata[b"done"].decode().splitlines())
return done, t.to_pandas().set_index(["node_id", "date"])
man = CKPT / f"{name}.manifest.txt"; acc = CKPT / f"{name}.acc.parquet" # backward-compat resume
if man.exists() and acc.exists():
return set(man.read_text().splitlines()), pd.read_parquet(acc).set_index(["node_id", "date"])
return set(), None
def _ckpt_save(name, done, accdf):
"""ONE atomic parquet: accumulator + done-list in metadata. Crash-safe — the
file is either fully the old checkpoint or fully the new one, never partial,
so done and accumulator can never drift (no double-count on resume)."""
ck = CKPT / f"{name}.ckpt.parquet"
t = pa.Table.from_pandas(accdf.reset_index(), preserve_index=False)
md = dict(t.schema.metadata or {}); md[b"done"] = ("\n".join(sorted(done))).encode()
t = t.replace_schema_metadata(md)
tmp = ck.with_suffix(".tmp"); pq.write_table(t, tmp); os.replace(tmp, ck)
_WORKER_GI = None
def _process_one(args):
"""Worker: one file -> partial groupby (sum_<col> + n_obs). If `repo` is set,
the worker DOWNLOADS the file (with retry) to scratch, processes, deletes —
enabling parallel HF streaming. Each worker lazy-loads its GridIndex once
(Windows spawn-safe)."""
path, speckey, grid_path, repo, scratch = args
import os, time, pandas as pd, pathlib
from aggregation import SPECS, _to_date, _clean
from grid_index import GridIndex
global _WORKER_GI
if _WORKER_GI is None:
_WORKER_GI = GridIndex.from_parquet(grid_path)
spec = SPECS[speckey]; gi = _WORKER_GI
local = path
if repo is not None: # HF: download this file with retry
from huggingface_hub import hf_hub_download
for a in range(10):
try:
local = hf_hub_download(f"AtmosIQ/{repo}", filename=path, repo_type="dataset",
local_dir=scratch, token=os.environ.get("HF_TOKEN")); break
except Exception as e:
if a == 9: raise RuntimeError(f"STOP: {path} failed after 10 tries ({type(e).__name__})") from e
time.sleep(min(120, 3 * 2 ** a))
try:
reader = [pd.read_parquet(local)] if str(local).endswith(".parquet") else pd.read_csv(local, chunksize=500_000)
acc = None
for chunk in reader:
df = _clean(_to_date(chunk, spec), spec)
if not len(df): continue
df["node_id"] = gi.assign_node_id(df[spec.lat_col].values, df[spec.lon_col].values)
df = df[df["node_id"].notna()]
if not len(df): continue
g = df.groupby(["node_id","date"])
part = g[spec.value_cols].sum().add_prefix("sum_"); part["n_obs"] = g.size()
acc = part if acc is None else acc.add(part, fill_value=0)
finally:
if repo is not None:
try: os.remove(local)
except OSError: pass
return pathlib.Path(path).name, acc
# ---- streaming containment (checkpointed, never-skip) ----------------------
class StreamAgg:
def __init__(self, cols, acc=None): self.cols=cols; self.acc=acc
def push(self, part): self.acc = part if self.acc is None else self.acc.add(part, fill_value=0)
def finalize(self, agg):
df=self.acc.reset_index()
if agg=="mean":
for c in self.cols: df[c]=df["sum_"+c]/df["n_obs"]
df=df.drop(columns=["sum_"+c for c in self.cols])
elif agg=="count":
for c in self.cols: df[c]=df["sum_"+c]/df["n_obs"]; df=df.drop(columns=["sum_"+c])
df=df.rename(columns={"n_obs":"count"})
return df
def run_stream(repo, files, use_hf, root, gi, spec):
done, acc0 = _ckpt_load(spec.name)
agg = StreamAgg(spec.value_cols, acc0)
total = len(files); n = len(done)
JOBS = int(os.environ.get("ATMOS_JOBS", "1"))
BATCH = int(os.environ.get("ATMOS_BATCH", str(max(JOBS * 4, 32)))) # files per batch
if JOBS > 1: # parallel, BATCH-WISE (predictable, clean state each batch)
from multiprocessing import Pool
gp = str(GRID.resolve())
todo = [f for f in files if pathlib.Path(f).name not in done]
# process in fixed batches: download+process a batch in parallel, then
# checkpoint ONCE, then next batch. Nothing races beyond one batch.
for bstart in range(0, len(todo), BATCH):
batch = todo[bstart:bstart + BATCH]
if use_hf:
tasks = [(f, spec.name, gp, repo, str(SCRATCH)) for f in batch]
else:
tasks = [(f, spec.name, gp, None, None) for f in batch]
with Pool(min(JOBS, len(batch))) as pool: # fresh pool per batch = clean workers
for name, part in pool.imap_unordered(_process_one, tasks, chunksize=1):
if part is not None: agg.push(part)
done.add(name); n += 1
print(f" [{spec.name}] {n}/{total}", end="\r")
_ckpt_save(spec.name, done, agg.acc) # checkpoint after each COMPLETE batch
if len(done) != total:
raise RuntimeError(f"[{spec.name}] INCOMPLETE {len(done)}/{total}; refusing to write.")
out = agg.finalize(spec.agg).rename(columns=spec.rename)
return out.merge(gi.centroids(), on="node_id", how="left")
for f in files:
name = pathlib.Path(f).name
if name in done: # already processed in a prior run — resume, NOT a skip
continue
path = _dl_retry(repo, f) if use_hf else f
try:
reader = [pd.read_parquet(path)] if str(path).endswith(".parquet") else pd.read_csv(path, chunksize=CHUNK)
for chunk in reader:
df = _clean(_to_date(chunk, spec), spec)
if not len(df): continue
df["node_id"] = gi.assign_node_id(df[spec.lat_col].values, df[spec.lon_col].values)
df = df[df["node_id"].notna()]
if not len(df): continue
g = df.groupby(["node_id","date"])
part = g[spec.value_cols].sum().add_prefix("sum_"); part["n_obs"]=g.size()
agg.push(part)
finally:
if use_hf:
try: os.remove(path)
except OSError: pass
done.add(name); n += 1
if n % 50 == 0: _ckpt_save(spec.name, done, agg.acc)
print(f" [{spec.name}] {n}/{total}", end="\r")
_ckpt_save(spec.name, done, agg.acc)
if len(done) != total: # completeness gate — never finish partial
raise RuntimeError(f"[{spec.name}] INCOMPLETE {len(done)}/{total}; refusing to write. Re-run to resume.")
out = agg.finalize(spec.agg).rename(columns=spec.rename)
return out.merge(gi.centroids(), on="node_id", how="left")
def run_centroid(repo, files, use_hf, root, gi, spec):
frames=[]; total=len(files)
for i,f in enumerate(files):
path=_dl_retry(repo,f) if use_hf else f
try:
df=pd.read_parquet(path) if str(path).endswith(".parquet") else pd.read_csv(path)
frames.append(ingest(df,gi,spec))
finally:
if use_hf:
try: os.remove(path)
except OSError: pass
print(f" [{spec.name}] {i+1}/{total}", end="\r")
if len(frames)!=total:
raise RuntimeError(f"[{spec.name}] INCOMPLETE {len(frames)}/{total}; refusing to write.")
return pd.concat(frames, ignore_index=True)
def run_dem(gi, use_hf, root):
import rasterio
nodes=gi.centroids().copy(); nodes["elevation_m"]=np.nan
nodes["tlat"]=np.floor(nodes.centroid_lat).astype(int); nodes["tlon"]=np.floor(nodes.centroid_lon).astype(int)
def tile(tlat,tlon):
ns="N" if tlat>=0 else "S"; ew="E" if tlon>=0 else "W"
fn=f"Copernicus_DSM_COG_10_{ns}{abs(tlat):02d}_00_{ew}{abs(tlon):03d}_00_DEM.tif"
if use_hf:
from huggingface_hub import hf_hub_download
try: return hf_hub_download(f"{HF_ORG}/Atmos_DEM_Copernicus",filename=fn,repo_type="dataset",
local_dir=str(SCRATCH),token=os.environ.get("HF_TOKEN"))
except Exception: return None
p=pathlib.Path(root)/"Atmos_DEM_Copernicus"/fn; return str(p) if p.exists() else None
for (tlat,tlon),grp in nodes.groupby(["tlat","tlon"]):
p=tile(tlat,tlon)
if not p: continue
with rasterio.open(p) as src:
vals=[v[0] for v in src.sample(list(zip(grp.centroid_lon,grp.centroid_lat)))]
nd=src.nodata; vals=[np.nan if (nd is not None and v==nd) else float(v) for v in vals]
nodes.loc[grp.index,"elevation_m"]=vals
if use_hf:
try: os.remove(p)
except OSError: pass
return nodes[["node_id","elevation_m"]]
def merge_master(gi):
daily=[d for d in sorted(OUT.glob("*_daily.parquet"))]
if not daily: print(" no *_daily.parquet"); return
master=None
for d in daily:
df=pd.read_parquet(d); vc=[c for c in df.columns if c not in ("node_id","date","centroid_lat","centroid_lon","n_obs")]
df=df[["node_id","date"]+vc]; master=df if master is None else master.merge(df,on=["node_id","date"],how="outer")
master=master.merge(gi.centroids(),on="node_id",how="left"); master["_ym"]=master["date"].str.slice(0,7)
mdir=OUT/"node_observations_daily"; mdir.mkdir(exist_ok=True)
for ym,part in master.groupby("_ym"): part.drop(columns="_ym").to_parquet(mdir/f"{ym}.parquet",index=False)
print(f" master: {len(master):,} node-days, {master.shape[1]-1} cols, {master['_ym'].nunique()} partitions -> {mdir}")
dem=OUT/"dem_static.parquet"
if dem.exists():
gn=pd.read_parquet(GRID).drop(columns=["elevation_m"],errors="ignore").merge(pd.read_parquet(dem),on="node_id",how="left")
gn.to_parquet(GRID,index=False); print(" grid_nodes.elevation_m filled")
SANE={"s5p_no2_column":(-0.002,0.002),"s5p_so2_column":(-0.02,0.02),"s5p_co_column":(0,0.1),
"s5p_o3_column":(0,0.25),"s5p_hcho_column":(-0.005,0.02),"s5p_aer_ai":(-30,35),
"s5p_ch4_column":(1300,2400),"s5p_cloud_fraction":(0,1),"modis_aod":(0,5),"viirs_aod":(0,5),
"era5_temperature":(230,325),"era5_boundary_layer_height":(0,5000),"u_1330ist":(-30,30),
"v_1330ist":(-30,30),"fire_count":(0,1e6),"elevation_m":(-50,8850)}
def check():
print("=== range check ===")
for d in sorted(OUT.glob("*_daily.parquet")):
df=pd.read_parquet(d); print(f"\n{d.name}: {len(df):,} rows")
for c in df.columns:
if c not in SANE: continue
s=df[c]; lo,hi=SANE[c]; bad=((s<lo)|(s>hi)).sum()
print(f" {c}: min={s.min():.4g} max={s.max():.4g} null%={100*s.isna().mean():.1f}{' ⚠OUT-OF-RANGE' if bad else ''}")
def main(argv):
if "--check" in argv: check(); return
use_hf = "--local" not in argv
root = argv[argv.index("--local")+1] if "--local" in argv else None
gi = GridIndex.from_parquet(str(GRID))
print(f"grid: {len(gi)} cells | mode: {'HF-stream' if use_hf else 'local:'+str(root)}")
if "--merge" in argv: merge_master(gi); return
skip={"--local","--merge","--check","--no-merge","--force",root}
only=[a for a in argv if a not in skip and not a.startswith("--")]
for key,(repo,subpath,speckey,kind) in REG.items():
if only and key not in only: continue
outp=OUT/("dem_static.parquet" if kind=="dem" else f"{key}_daily.parquet")
if outp.exists() and "--force" not in argv: print(f" skip {key} (exists)"); continue
if "--force" in argv: # forced redo: wipe stale checkpoint so it starts clean
for suf in (".manifest.txt",".acc.parquet",".ckpt.parquet"):
fp=CKPT/f"{key}{suf}"
if fp.exists(): fp.unlink()
if kind=="dem":
print(f" {key} [dem]"); out=run_dem(gi,use_hf,root)
else:
files=hf_list(repo,subpath) if use_hf else local_files(root,repo,subpath)
if not files: print(f" ! {key}: 0 files ({repo}/{subpath})"); continue
print(f" {key}: {len(files)} files [{kind}]")
out=run_stream(repo,files,use_hf,root,gi,SPECS[speckey]) if kind=="stream" \
else run_centroid(repo,files,use_hf,root,gi,SPECS[speckey])
out.to_parquet(outp,index=False); print(f"\n -> {outp} ({len(out):,} rows)")
# clear this source's checkpoint once its final output is safely written
for suf in (".manifest.txt",".acc.parquet",".ckpt.parquet"):
fp=CKPT/f"{key}{suf}"
if fp.exists(): fp.unlink()
if "--no-merge" not in argv: merge_master(gi)
print("done.")
if __name__=="__main__": main(sys.argv[1:]) |