File size: 4,669 Bytes
5ced181 | 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 | """
grid_index.py — the ONE place that maps (lat, lon) <-> grid cell.
This is the shared container key. Every satellite (S5P, MODIS, VIIRS), ERA5,
and CPCB gets assigned to cells THROUGH this object, so they all land on the
same node_id for the same location. No source's native grid leaks in.
Two directions:
assign_node_id(lat, lon) -> node_id (pixel/point -> which cell holds it)
.nodes[centroid_lat/lon] -> the cell centre lat/lon (for sampling gridded
fields AT the centre)
"""
from __future__ import annotations
import numpy as np
import pandas as pd
from pyproj import Transformer
# Frozen grid config (recovered from grid_nodes.parquet, matches build_grid).
DEFAULT_PROJ4 = "+proj=laea +lat_0=23 +lon_0=80 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"
class GridIndex:
def __init__(self, nodes: pd.DataFrame, proj4: str = DEFAULT_PROJ4):
req = {"node_id", "row", "col", "projection_x", "projection_y",
"centroid_lat", "centroid_lon", "grid_resolution_km"}
missing = req - set(nodes.columns)
if missing:
raise ValueError(f"grid_nodes missing columns: {missing}")
self.nodes = nodes.reset_index(drop=True)
self.proj4 = proj4
self.cell_m = float(nodes["grid_resolution_km"].iloc[0]) * 1000.0
self._fwd = Transformer.from_crs("EPSG:4326", proj4, always_xy=True)
# Recover the PINNED origin straight from the data (no config file to
# drift). proj_x = origin_x + (col + 0.5)*cell_m -> invert it.
ox = nodes["projection_x"].values - (nodes["col"].values + 0.5) * self.cell_m
oy = nodes["projection_y"].values - (nodes["row"].values + 0.5) * self.cell_m
if ox.std() > 1e-3 or oy.std() > 1e-3:
raise ValueError("origin not consistent across nodes — grid corrupt")
self.origin_x, self.origin_y = float(np.median(ox)), float(np.median(oy))
# (row, col) -> positional index. Vectorised: pack (row,col) into one
# int key, keep sorted keys + their positions for O(log n) searchsorted
# lookup of MILLIONS of pixels at once (no Python per-row loop).
self._KEYM = 100000
keys = (nodes["row"].astype(np.int64).values * self._KEYM
+ nodes["col"].astype(np.int64).values)
order = np.argsort(keys)
self._skeys = keys[order] # ascending
self._spos = order.astype(np.int64) # original position of each sorted key
self._node_id = nodes["node_id"].astype(str).values
# self-check: every stored centroid must assign back to its own cell.
back = self.assign_index(nodes["centroid_lat"].values, nodes["centroid_lon"].values)
if not (back == np.arange(len(nodes))).all():
raise AssertionError("round-trip failed: centroids don't map to own cells")
@classmethod
def from_parquet(cls, path: str, proj4: str = DEFAULT_PROJ4) -> "GridIndex":
return cls(pd.read_parquet(path), proj4)
# ---- pixel/point -> cell (containment) ----------------------------------
def assign_index(self, lat, lon) -> np.ndarray:
"""Positional index into self.nodes for each (lat, lon). -1 = the point's
cell is not in the grid (ocean / foreign / outside)."""
lat = np.asarray(lat, float); lon = np.asarray(lon, float)
x, y = self._fwd.transform(lon, lat) # always_xy: (lon,lat)
col = np.floor((np.asarray(x) - self.origin_x) / self.cell_m).astype(np.int64)
row = np.floor((np.asarray(y) - self.origin_y) / self.cell_m).astype(np.int64)
qk = row * self._KEYM + col
idx = np.searchsorted(self._skeys, qk)
idxc = np.clip(idx, 0, len(self._skeys) - 1)
hit = self._skeys[idxc] == qk
out = np.where(hit, self._spos[idxc], -1)
return out
def assign_node_id(self, lat, lon) -> np.ndarray:
"""node_id (str) for each point, or None if outside the grid."""
idx = self.assign_index(lat, lon)
out = np.full(idx.shape, None, dtype=object)
hit = idx >= 0
out[hit] = self._node_id[idx[hit]]
return out
# ---- cell centroids (for sampling gridded fields) -----------------------
def centroids(self) -> pd.DataFrame:
"""One row per cell: node_id + centre lat/lon. Use this to sample a
gridded product (ERA5, MODIS) AT the cell centre."""
return self.nodes[["node_id", "centroid_lat", "centroid_lon"]].copy()
def __len__(self):
return len(self.nodes) |