#!/usr/bin/env python3 """ download_forcing.py — download 2-min MRMS PrecipRate over an event window from the Iowa State MT archive, clip to a watershed polygon, and write the basin-mean precipitation-rate time series (same format as the released mrms_2min_precip_basin_mean.csv: datetime_utc, precip_rate_mm_hr). Requires: rasterio (GDAL GRIB driver), shapely, numpy, pandas, requests. Example (light-package testbed -> add its forcing) -------------------------------------------------- python download_forcing.py \ --watershed ../../data/L3/testbeds/FF_2024_09_VA_ep011/03165500/watershed.geojson \ --begin 2024-09-27T06:30 --end 2024-09-28T04:00 \ --out mrms_2min_precip_basin_mean.csv --cache ./mrms_cache Window convention: the released forcing covers episode begin - 24 h to episode end + 6 h; pass --pre-hours/--post-hours to change it. """ import argparse import gzip import io import tempfile from datetime import timedelta from pathlib import Path import numpy as np import pandas as pd import requests from torrent_tools import UA, mrms_precip_urls, parse_utc def load_watershed(path): import json from shapely.geometry import shape from shapely.ops import unary_union gj = json.load(open(path)) geoms = [shape(f["geometry"]) for f in gj.get("features", [gj])] poly = unary_union(geoms) return poly, poly.bounds # (west, south, east, north) def clip_mean(grib_bytes, bounds, mask_cache, poly): import rasterio import rasterio.windows from rasterio.features import geometry_mask w, s, e, n = bounds with tempfile.NamedTemporaryFile(suffix=".grib2") as tf: tf.write(grib_bytes) tf.flush() with rasterio.open(tf.name) as src: win = rasterio.windows.from_bounds(w + 360 if src.bounds.left > 180 else w, s, e + 360 if src.bounds.left > 180 else e, n, transform=src.transform) win = win.round_offsets().round_lengths() arr = src.read(1, window=win).astype(float) tfm = src.window_transform(win) arr[arr < 0] = np.nan if mask_cache.get("mask") is None or mask_cache.get("shape") != arr.shape: from shapely.affinity import translate p = poly if tfm.c > 180: # grid uses 0-360 longitudes p = translate(poly, xoff=360.0) mask_cache["mask"] = geometry_mask([p.__geo_interface__], out_shape=arr.shape, transform=tfm, invert=True) # True inside mask_cache["shape"] = arr.shape if not mask_cache["mask"].any(): # degenerate: fall back to bbox mean mask_cache["mask"] = np.ones(arr.shape, bool) vals = arr[mask_cache["mask"]] return float(np.nanmean(vals)) if np.isfinite(vals).any() else np.nan def main(): ap = argparse.ArgumentParser() ap.add_argument("--watershed", required=True, help="watershed.geojson") ap.add_argument("--begin", required=True, help="episode begin (UTC)") ap.add_argument("--end", required=True, help="episode end (UTC)") ap.add_argument("--pre-hours", type=float, default=24.0) ap.add_argument("--post-hours", type=float, default=6.0) ap.add_argument("--out", default="mrms_2min_precip_basin_mean.csv") ap.add_argument("--cache", default="./mrms_cache", help="GRIB download cache dir") args = ap.parse_args() poly, bounds = load_watershed(args.watershed) b = parse_utc(args.begin) - timedelta(hours=args.pre_hours) e = parse_utc(args.end) + timedelta(hours=args.post_hours) steps = mrms_precip_urls(b, e) cache = Path(args.cache) cache.mkdir(parents=True, exist_ok=True) print(f"{len(steps)} 2-min timesteps {b} -> {e}") mask_cache = {} rows, missing = [], 0 with requests.Session() as ses: ses.headers.update(UA) for i, (t, url) in enumerate(steps): gz = cache / url.rsplit("/", 1)[-1] if not gz.exists(): r = ses.get(url, timeout=60) if r.status_code != 200: missing += 1 rows.append((t, np.nan)) continue gz.write_bytes(r.content) try: raw = gzip.decompress(gz.read_bytes()) rows.append((t, clip_mean(raw, bounds, mask_cache, poly))) except Exception: missing += 1 rows.append((t, np.nan)) if (i + 1) % 100 == 0: print(f" {i+1}/{len(steps)} done ({missing} missing)") df = pd.DataFrame(rows, columns=["datetime_utc", "precip_rate_mm_hr"]) df.to_csv(args.out, index=False) tot = np.nansum(df.precip_rate_mm_hr.to_numpy()) * (2 / 60) print(f"wrote {args.out} ({len(df)} steps, {missing} missing, " f"event total ~{tot:.1f} mm)") if __name__ == "__main__": main()