#!/usr/bin/env python3 """ torrent_tools.py — shared helpers for the TORRENT generic tools. All functions talk to public agency services only (NWIS, NLDI, Iowa State MT archive); nothing here depends on the authors' build machine. """ import gzip import io import json import math from datetime import datetime, timedelta, timezone from pathlib import Path import pandas as pd import requests NWIS_IV = "https://waterservices.usgs.gov/nwis/iv/" NWIS_SITE = "https://waterservices.usgs.gov/nwis/site/" NLDI_BASIN = "https://api.water.usgs.gov/nldi/linked-data/nwissite/USGS-{site}/basin" MTARCHIVE = "https://mtarchive.geol.iastate.edu" UA = {"User-Agent": "TORRENT-tools/1.0 (flash-flood benchmark)"} def haversine_km(lat1, lon1, lat2, lon2): r = 6371.0 p1, p2 = math.radians(lat1), math.radians(lat2) dp = math.radians(lat2 - lat1) dl = math.radians(lon2 - lon1) a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2 return 2 * r * math.asin(math.sqrt(a)) def parse_utc(s): t = pd.to_datetime(s, utc=True) return t.to_pydatetime() def sites_in_bbox(lat, lon, radius_km): """Active stream sites in a bounding box around (lat, lon).""" dlat = radius_km / 111.0 dlon = radius_km / (111.0 * max(0.2, math.cos(math.radians(lat)))) bbox = f"{lon-dlon:.4f},{lat-dlat:.4f},{lon+dlon:.4f},{lat+dlat:.4f}" r = requests.get(NWIS_SITE, params={ "format": "rdb", "bBox": bbox, "siteType": "ST", "siteStatus": "all", "hasDataTypeCd": "iv"}, headers=UA, timeout=60) if r.status_code != 200: return [] rows = [] header = None for line in r.text.splitlines(): if line.startswith("#"): continue parts = line.split("\t") if header is None: header = parts continue if parts and parts[0].endswith("s"): # rdb format row ("5s 15s ...") continue d = dict(zip(header, parts)) try: slat, slon = float(d["dec_lat_va"]), float(d["dec_long_va"]) except (KeyError, ValueError): continue dist = haversine_km(lat, lon, slat, slon) if dist <= radius_km: rows.append(dict(site_no=d["site_no"], station_nm=d.get("station_nm", ""), lat=slat, lon=slon, distance_km=round(dist, 2))) return sorted(rows, key=lambda x: x["distance_km"]) def fetch_iv(site, begin, end, parameter="00060"): """NWIS instantaneous values -> DataFrame(datetime_utc, value). Empty if none.""" r = requests.get(NWIS_IV, params={ "format": "json", "sites": site, "parameterCd": parameter, "startDT": begin.strftime("%Y-%m-%dT%H:%MZ"), "endDT": end.strftime("%Y-%m-%dT%H:%MZ")}, headers=UA, timeout=120) if r.status_code != 200: return pd.DataFrame(columns=["datetime_utc", "value"]) try: ts = r.json()["value"]["timeSeries"] vals = ts[0]["values"][0]["value"] except (KeyError, IndexError, ValueError): return pd.DataFrame(columns=["datetime_utc", "value"]) df = pd.DataFrame(vals) if df.empty: return pd.DataFrame(columns=["datetime_utc", "value"]) df["datetime_utc"] = pd.to_datetime(df["dateTime"], utc=True) df["value"] = pd.to_numeric(df["value"], errors="coerce") df = df[df["value"] > -999990] return df[["datetime_utc", "value"]].reset_index(drop=True) def fetch_basin(site): """NLDI contributing watershed as GeoJSON dict (retry twice: transient 5xx/404).""" url = NLDI_BASIN.format(site=site) last = None for _ in range(3): r = requests.get(url, headers=UA, timeout=90) last = r.status_code if r.status_code == 200: return r.json() raise RuntimeError(f"NLDI basin unavailable for {site} (HTTP {last}); " "retry later — most NLDI failures are transient") def mrms_precip_urls(begin, end): """2-min MRMS PrecipRate GRIB2 URLs on the Iowa State MT archive.""" t = begin.replace(second=0, microsecond=0) t -= timedelta(minutes=t.minute % 2) out = [] while t <= end: out.append((t, f"{MTARCHIVE}/{t:%Y/%m/%d}/mrms/ncep/PrecipRate/" f"PrecipRate_00.00_{t:%Y%m%d-%H%M%S}.grib2.gz")) t += timedelta(minutes=2) return out def episode_lookup(episode_id, data_dir): """Find an episode row (begin/end/coords) in the released L2, else L1, tables.""" l2 = Path(data_dir) / "L2" / "l2_episodes.csv" l1 = Path(data_dir) / "L1" / "l1_ncei_flash_flood_episodes.csv" for src in (l2, l1): if not src.exists(): continue df = pd.read_csv(src, low_memory=False) hit = df[df["ff_episode_id"] == episode_id] if len(hit): r = hit.iloc[0] lat = r.get("centroid_lat", r.get("begin_lat")) lon = r.get("centroid_lon", r.get("begin_lon")) return dict(begin=str(r["begin_dt"]), end=str(r["end_dt"]), lat=float(lat), lon=float(lon), source=src.name) raise SystemExit(f"episode {episode_id} not found under {data_dir}") def save_json(obj, path): Path(path).parent.mkdir(parents=True, exist_ok=True) with open(path, "w") as f: json.dump(obj, f, indent=2)