File size: 9,921 Bytes
463c895
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

aggregation.py  ->  data/ingest/



Phase 2 ingestion, LOCKED to the real HuggingFace schemas (audit 2026-07).

raw source (CSV/parquet) -> grid-aligned table:

    node_id | date | <value cols> | n_obs | centroid_lat | centroid_lon



Audit-driven fixes baked in:

  - per-source MISSING SENTINELS (VIIRS -999, S5P 9.969e36) -> NaN before aggregating

  - per-source lat/lon column names (MODIS/VIIRS use lat/lon)

  - timestamp -> date derivation (S5P/ERA5 use time_utc)

  - ERA5 hourly -> daily collapse, + a separate 13:30-IST wind spec

  - nonneg filter (MODIS uncertainty had 67 negative rows)

"""
from __future__ import annotations
import sys, pathlib
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "grid"))

import numpy as np
import pandas as pd
from dataclasses import dataclass, field
from scipy.spatial import cKDTree
from pyproj import Transformer
from grid_index import GridIndex

S5P_FILL_VALUE = 9.969209968386869e+36
IST_OFFSET_H = 5.5   # UTC -> IST


@dataclass
class SourceSpec:
    name: str
    mode: str                          # "containment" | "centroid"
    value_cols: list
    lat_col: str = "latitude"
    lon_col: str = "longitude"
    date_col: str | None = "date"      # used if timestamp_col is None
    timestamp_col: str | None = None   # if set, date derived from this (UTC)
    agg: str = "mean"                  # mean|median|max|min|sum|count
    sentinels: list = field(default_factory=list)   # values -> NaN (e.g. -999)
    qa_col: str | None = None
    qa_min: float | None = None
    nonneg_cols: list = field(default_factory=list) # drop rows where these < 0
    ist_target_h: float | None = None   # select row nearest this IST hour (13.5 = 13:30)
    pre_daily_mean: bool = False       # collapse (lat,lon,date) before centroid sample
    max_sample_km: float | None = None
    rename: dict = field(default_factory=dict)


def _to_date(df: pd.DataFrame, spec: SourceSpec) -> pd.DataFrame:
    df = df.copy()
    if spec.timestamp_col is not None:
        ts = pd.to_datetime(df[spec.timestamp_col], utc=True, errors="coerce")
        ist = ts + pd.Timedelta(hours=IST_OFFSET_H)
        df["date"] = ist.dt.strftime("%Y-%m-%d")
        df["_ist_h"] = ist.dt.hour + ist.dt.minute / 60.0   # fractional IST hour
    else:
        df["date"] = pd.to_datetime(df[spec.date_col], errors="coerce").dt.strftime("%Y-%m-%d")
    return df.dropna(subset=["date"])


def _select_nearest_ist(df: pd.DataFrame, spec: SourceSpec) -> pd.DataFrame:
    """Keep, per (lat, lon, date), the single row whose IST time is nearest the

    target (e.g. 13:30 for S5P-aligned wind). Robust to hourly/3-hourly cadence."""
    if spec.ist_target_h is None or "_ist_h" not in df:
        return df
    d = df.assign(_gap=(df["_ist_h"] - spec.ist_target_h).abs())
    d = d.sort_values("_gap").drop_duplicates([spec.lat_col, spec.lon_col, "date"], keep="first")
    return d.drop(columns=["_gap"])


def _clean(df: pd.DataFrame, spec: SourceSpec) -> pd.DataFrame:
    df = df.copy()
    # 1. sentinels -> NaN  (CRITICAL: VIIRS -999, S5P fill). Must run BEFORE dropna.
    sents = list(spec.sentinels) + [S5P_FILL_VALUE]
    for c in spec.value_cols:
        df[c] = df[c].replace(sents, np.nan)
    # 2. nonneg filter (MODIS uncertainty)
    for c in spec.nonneg_cols:
        if c in df: df = df[(df[c] >= 0) | df[c].isna()]
    # 3. drop rows with no valid value
    df = df.dropna(subset=spec.value_cols, how="all")   # only drop if ALL value cols null
    # 4. QA gate
    if spec.qa_col and spec.qa_min is not None:
        df = df[df[spec.qa_col] >= spec.qa_min]
    return df


def _finalize(out, gi, spec, dropped=None):
    out = out.rename(columns=spec.rename)
    out = out.merge(gi.centroids(), on="node_id", how="left").reset_index(drop=True)
    if dropped is not None: out.attrs["dropped_outside_grid"] = int(dropped)
    return out


def _containment(df, gi, spec):
    df = df.copy()
    df["node_id"] = gi.assign_node_id(df[spec.lat_col].values, df[spec.lon_col].values)
    dropped = int(df["node_id"].isna().sum())
    df = df[df["node_id"].notna()]
    if len(df) == 0:
        raise ValueError(f"[{spec.name}] nothing landed in grid")
    g = df.groupby(["node_id", "date"])
    if spec.agg == "count":
        out = g.size().to_frame("count")
        for c in spec.value_cols: out[c] = g[c].mean()
    else:
        out = g.agg({c: spec.agg for c in spec.value_cols})
    out["n_obs"] = g.size()
    out = out.reset_index()
    return _finalize(out, gi, spec, dropped)


def _centroid(df, gi, spec):
    if spec.pre_daily_mean:   # collapse hourly -> one row per (lat,lon,date)
        keys = [spec.lat_col, spec.lon_col, "date"]
        df = df.groupby(keys, as_index=False)[spec.value_cols].mean()
    fwd = Transformer.from_crs("EPSG:4326", gi.proj4, always_xy=True)
    cent = gi.centroids()
    cx, cy = fwd.transform(cent["centroid_lon"].values, cent["centroid_lat"].values)
    cxy = np.column_stack([cx, cy])
    frames = []
    for date, sub in df.groupby("date"):
        sx, sy = fwd.transform(sub[spec.lon_col].values, sub[spec.lat_col].values)
        tree = cKDTree(np.column_stack([sx, sy]))
        dist_m, idx = tree.query(cxy, k=1)
        rec = {"node_id": cent["node_id"].values, "date": date, "n_obs": 1}
        for c in spec.value_cols:
            v = sub[c].values[idx].astype(float)
            if spec.max_sample_km is not None:
                v[dist_m > spec.max_sample_km * 1000.0] = np.nan
            rec[c] = v
        frames.append(pd.DataFrame(rec))
    if not frames:
        raise ValueError(f"[{spec.name}] no rows survived filtering (check ist_target_h / sentinels / qa)")
    return _finalize(pd.concat(frames, ignore_index=True), gi, spec)


def ingest(raw, gi, spec):
    df = _clean(_to_date(raw, spec), spec)
    df = _select_nearest_ist(df, spec)
    if len(df) == 0:
        raise ValueError(f"[{spec.name}] empty after clean/filter")
    if spec.mode == "containment": return _containment(df, gi, spec)
    if spec.mode == "centroid":    return _centroid(df, gi, spec)
    raise ValueError(f"bad mode {spec.mode!r}")


# ==========================================================================
# REAL SPECS — locked to the HuggingFace audit schemas.
# S5P: one spec PER pollutant (each folder has a generic `value` column).
# ==========================================================================
SPECS = {
  # ---- S5P TROPOMI (per-pollutant files, col `value`, time_utc, qa_value) ----
  "s5p_no2": SourceSpec("s5p_no2","containment", value_cols=["value"],
      timestamp_col="time_utc", qa_col="qa_value", qa_min=0.75,
      rename={"value":"s5p_no2_column"}),
  "s5p_co": SourceSpec("s5p_co","containment", value_cols=["value"],
      timestamp_col="time_utc", qa_col="qa_value", qa_min=0.5,
      rename={"value":"s5p_co_column"}),
  "s5p_so2": SourceSpec("s5p_so2","containment", value_cols=["value"],
      timestamp_col="time_utc", qa_col="qa_value", qa_min=0.5,
      rename={"value":"s5p_so2_column"}),
  "s5p_ch4": SourceSpec("s5p_ch4","containment", value_cols=["value"],
      timestamp_col="time_utc",
      rename={"value":"s5p_ch4_column"}),   # ch4 qa_threshold null (guide)
  "s5p_o3": SourceSpec("s5p_o3","containment", value_cols=["value"],
      timestamp_col="time_utc", qa_col="qa_value", qa_min=0.5,
      rename={"value":"s5p_o3_column"}),   # OUTPUT pollutant; S5P-O3 input OPTIONAL (labels from CPCB)
  "s5p_hcho": SourceSpec("s5p_hcho","containment", value_cols=["value"],
      timestamp_col="time_utc", qa_col="qa_value", qa_min=0.5,
      rename={"value":"s5p_hcho_column"}), # INPUT-ONLY (blueprint Group A, biomass signal) — REQUIRED input
  "s5p_cloud": SourceSpec("s5p_cloud","containment", value_cols=["value"],
      timestamp_col="time_utc",
      rename={"value":"s5p_cloud_fraction"}),  # QA / cloud-fraction input
  "s5p_aer_ai": SourceSpec("s5p_aer_ai","containment", value_cols=["value"],
      timestamp_col="time_utc", qa_col="qa_value", qa_min=0.80,
      rename={"value":"s5p_aer_ai"}),

  # ---- MODIS AOD (lat/lon, ~70% null, negative uncertainty) ----
  "modis": SourceSpec("modis","containment", value_cols=["modis_aod"],
      lat_col="lat", lon_col="lon", date_col="date",
      nonneg_cols=["modis_aod_uncertainty"]),

  # ---- VIIRS AOD (lat/lon, -999 SENTINEL) ----
  "viirs": SourceSpec("viirs","containment", value_cols=["viirs_aod"],
      lat_col="lat", lon_col="lon", date_col="date",
      sentinels=[-999.0]),

  # ---- ERA5 (hourly 0.25deg grid) -> daily-mean node features, centroid sample ----
  "era5_daily": SourceSpec("era5_daily","centroid",
      value_cols=["era5_temperature","era5_boundary_layer_height",
                  "era5_relative_humidity","era5_surface_pressure",
                  "era5_cloud_cover","era5_wind_u","era5_wind_v","era5_rainfall"],
      # era5_solar_radiation EXCLUDED: all-NaN in data (would empty every row). Re-add if fixed.
      timestamp_col="time_utc", pre_daily_mean=True, max_sample_km=30),
  # ---- ERA5 13:30-IST wind ONLY (edge-term input; u/v kept as components) ----
  "era5_wind_1330": SourceSpec("era5_wind_1330","centroid",
      value_cols=["era5_wind_u","era5_wind_v"],
      timestamp_col="time_utc", ist_target_h=13.5, max_sample_km=30,  # nearest-to-13:30 from RAW hourly
      rename={"era5_wind_u":"u_1330ist","era5_wind_v":"v_1330ist"}),

  # ---- FIRMS fire -> count per cell/day (acq_date) ----
  "firms": SourceSpec("firms","containment", value_cols=["frp"],
      lat_col="latitude", lon_col="longitude", date_col="acq_date",
      agg="count", rename={"count":"fire_count"}),
}
# DEM (Copernicus GLO-30 GeoTIFF): NOT here — raster reproject to LAEA in static_gis.py.