def deaccumulate_forecast(da: xr.DataArray) -> xr.DataArray:
"""
Convert forecast accumulations that reset when a new forecast cycle starts
into per-step increments (same units as the input accumulation).
"""
vals = np.asarray(da.values, dtype=np.float64) # compute vals
out = np.empty_like(vals) # compute out
out[0] = vals[0] # set out[0]
# Vectorized reset detection along time for the full 3-D cube.
prev = vals[:-1] # prev
cur = vals[1:] # cur
# Reset when magnitude drops sharply relative to the previous step.
reset = np.abs(cur) < (0.5 * np.abs(prev)) # compute reset
increments = np.where(reset, cur, cur - prev) # compute increments
out[1:] = increments # set out[1:]
return xr.DataArray(out, coords=da.coords, dims=da.dims, name=da.name, attrs=dict(da.attrs)) # return the computed result
def prepare_variable(da: xr.DataArray, kind: str) -> xr.DataArray:
"""Convert a raw ERA field to analysis units."""
if kind == "temp_c":
out = (da - 273.15).astype("float32") # cast to the target dtype
out.attrs.update({"units": "degC"})
return out # return the computed result
if kind == "flux_wm2":
# Accumulated J m**-2 over each forecast step -> approximate W m**-2
incr = deaccumulate_forecast(da) # incr
out = (incr / SECONDS_3H).astype("float32") # cast to the target dtype
out.attrs.update({"units": "W m-2"})
return out # return the computed result
if kind == "evap_mm":
# Accumulated m of water -> mm over the step
incr = deaccumulate_forecast(da) # incr
out = (incr * 1000.0).astype("float32") # cast to the target dtype
out.attrs.update({"units": "mm"})
return out # return the computed result
raise ValueError(f"Unknown kind: {kind}") # fail with a clear error message
def to_monthly_mean(da: xr.DataArray) -> xr.DataArray:
"""Aggregate sub-daily values to calendar-month means."""
monthly = da.resample(time="1MS").mean(skipna=True) # temporally resample / aggregate
# Keep only months inside the analysis year
monthly = monthly.sel(time=slice(f"{YEAR}-01-01", f"{YEAR}-12-31")) # select along coordinates or indices
return monthly # return the computed result
def monthly_to_points(monthly: xr.DataArray) -> gpd.GeoDataFrame:
"""One row per grid node; one column per month (YYYY-MM)."""
lon2d, lat2d = np.meshgrid(monthly.longitude.values, monthly.latitude.values) # build 2-D coordinate grids
n_pts = lon2d.size # n_pts
station_id = [f"S{i:04d}" for i in range(n_pts)] # station_id
vals = np.moveaxis(monthly.values, 0, -1).reshape(n_pts, monthly.sizes["time"]) # compute vals
months = pd.to_datetime(monthly.time.values).strftime("%Y-%m") # parse timestamps
df = pd.DataFrame(vals, columns=months) # compute df
df.insert(0, "station_id", station_id)
df.insert(1, "lon", lon2d.ravel().astype("float64"))
df.insert(2, "lat", lat2d.ravel().astype("float64"))
geometry = gpd.points_from_xy(df["lon"], df["lat"], crs=WGS84) # build point geometries from x/y
return gpd.GeoDataFrame(df, geometry=geometry, crs=WGS84) # return the computed result
def reproject_and_clip(gdf: gpd.GeoDataFrame, bd: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
proj = gdf.to_crs(bd.crs) # reproject to the target CRS
clipped = gpd.clip(proj, bd) # clip points to the boundary
return clipped.reset_index(drop=True) # return the computed result
def make_target_grid(bd: gpd.GeoDataFrame, resolution_m: float = 2000.0):
bounds = bd.total_bounds # bounds
width = int(np.ceil((bounds[2] - bounds[0]) / resolution_m)) # compute width
height = int(np.ceil((bounds[3] - bounds[1]) / resolution_m)) # compute height
transform = from_bounds(bounds[0], bounds[1], bounds[2], bounds[3], width, height) # affine transform from map bounds
xs = bounds[0] + (np.arange(width) + 0.5) * resolution_m # compute xs
ys = bounds[3] - (np.arange(height) + 0.5) * resolution_m # compute ys
X, Y = np.meshgrid(xs, ys) # build 2-D coordinate grids
grid_xy = np.column_stack([X.ravel(), Y.ravel()]) # stack coordinate columns
mask = geometry_mask( # mask
bd.geometry, out_shape=(height, width), transform=transform, invert=True # bd.geometry container
)
return width, height, transform, grid_xy, mask # return the computed result
def tps_interpolate_band(coords_xy, values, grid_xy, height, width, mask):
valid = np.isfinite(values) # compute valid
if valid.sum() < 3:
return np.full((height, width), np.nan, dtype="float32") # return the computed result
rbf = RBFInterpolator( # rbf
coords_xy[valid], values[valid], kernel="thin_plate_spline", smoothing=0.0 # set coords_xy[valid]
)
pred = rbf(grid_xy).reshape(height, width).astype("float32") # cast to the target dtype
pred[~mask] = np.nan # compute pred[~mask]
return pred # return the computed result
def write_multiband_geotiff(path: Path, bands, band_names, transform, crs):
height, width = bands[0].shape # height
with rasterio.open(
path,
"w",
driver="GTiff", # driver
height=height, # height
width=width, # width
count=len(bands), # count
dtype="float32", # dtype
crs=crs, # crs
transform=transform, # transform
nodata=np.nan, # compute nodata
compress="lzw", # compress
) as dst:
for i, (arr, name) in enumerate(zip(bands, band_names), start=1): # iterate over items
dst.write(arr, i)
dst.set_band_description(i, name)
def stack_multiband_geotiff_to_mdr(path: Path, variable_name: str) -> MultidimensionalRaster:
"""Read a 12-band monthly GeoTIFF into MultidimensionalRaster(time, y, x)."""
with rasterio.open(path) as src: # open a context-managed resource
data = src.read().astype("float32") # (bands, y, x)
nodata = src.nodata # nodata
if nodata is not None:
data = np.where(data == nodata, np.nan, data) # compute data
data = np.where(np.abs(data) > 1e30, np.nan, data) # compute data
transform = src.transform # transform
height, width = src.height, src.width # height
xs = transform.c + (np.arange(width) + 0.5) * transform.a # compute xs
ys = transform.f + (np.arange(height) + 0.5) * transform.e # compute ys
n_bands = src.count # n_bands
# Prefer band descriptions like 2018-01; fall back to month starts.
times = [] # times
for i in range(1, n_bands + 1): # iterate over items
desc = src.descriptions[i - 1] # desc
if desc:
times.append(np.datetime64(desc + "-01" if len(desc) == 7 else desc))
else:
times.append(np.datetime64(f"{YEAR}-{i:02d}-01"))
da = xr.DataArray( # da
data,
dims=("time", "y", "x"), # dims
coords={"time": np.array(times, dtype="datetime64[ns]"), "y": ys, "x": xs}, # coords
name=variable_name, # name
)
return MultidimensionalRaster(da) # return the computed result
def process_variable_monthly(nc_path, varname, meta, bd, grid_cache, ras_dir, tab_dir, year=YEAR):
"""
Full monthly pipeline for one variable:
load -> convert -> monthly mean -> points -> clip -> CSV -> TPS -> GeoTIFF.
"""
alias = meta["alias"] # alias
print(f"\n=== {varname} ({alias}): {meta['long_name']} ===") # status / summary print
tif_path = ras_dir / f"{alias}_{year}_monthly_{int(RESOLUTION_M)}m.tif" # tif_path
csv_path = tab_dir / f"{alias}_{year}_monthly_means.csv" # csv_path
if tif_path.is_file() and csv_path.is_file(): # only when the path exists
print(f" skip (exists): {tif_path.name}") # status / summary print
return csv_path, tif_path # return the computed result
ds = xr.open_dataset(nc_path) # open the NetCDF / dataset
raw = ds[varname].sel(time=slice(f"{year}-01-01", f"{year}-12-31")) # select along coordinates or indices
if raw.sizes.get("time", 0) == 0:
ds.close() # release the file handle
raise ValueError(f"No timesteps for {varname} in {year}") # fail with a clear error message
converted = prepare_variable(raw.load(), meta["kind"]) # converted
ds.close() # release the file handle
monthly = to_monthly_mean(converted) # aggregate along time or groups
print(f" monthly slices: {monthly.sizes['time']}") # status / summary print
gdf = monthly_to_points(monthly) # gdf
clipped = reproject_and_clip(gdf, bd) # reproject or clip geometries
print(f" points after clip: {len(clipped)}") # status / summary print
month_cols = [c for c in clipped.columns if c not in {"station_id", "lon", "lat", "geometry"}] # month_cols
wgs = clipped.to_crs(WGS84) # reproject to the target CRS
table = pd.DataFrame( # table
{
"station_id": clipped["station_id"].values,
"lon": wgs.geometry.x.values,
"lat": wgs.geometry.y.values,
}
)
for col in month_cols: # iterate over items
table[col] = clipped[col].astype("float32").values # cast to the target dtype
table.to_csv(csv_path, index=False) # set table.to_csv(csv_path
print(f" CSV -> {csv_path.name}") # status / summary print
width, height, transform, grid_xy, mask = grid_cache # width
coords_xy = np.column_stack([clipped.geometry.x.values, clipped.geometry.y.values]) # stack coordinate columns
bands, band_names = [], [] # bands
for col in month_cols: # iterate over items
arr = tps_interpolate_band( # arr
coords_xy, table[col].to_numpy(), grid_xy, height, width, mask
)
bands.append(arr)
band_names.append(col)
print(f" TPS {col}") # status / summary print
write_multiband_geotiff(tif_path, bands, band_names, transform, bd.crs)
print(f" GeoTIFF -> {tif_path.name} ({len(bands)} bands, {width}x{height})") # status / summary print
return csv_path, tif_path # return the computed result
print("Helpers ready.") # status / summary print