"""Scores from summed statistics (see :mod:`pardig_eval.sums`), for any set of tiles and days. Definitions follow ``precipitation_metrics`` in weather-forecast-model-downscaler (PR #8), rewritten as ratios of sums so they can be built for any region; all of them area-weighted. ERA5 is deterministic, so its fair CRPS equals its MAE. """ from __future__ import annotations import numpy as np import xarray as xr from pardig_eval import grid, sums def select(ds: xr.Dataset, box: tuple[float, float, float, float] | None) -> xr.Dataset: """Tiles of a (lat_min, lat_max, lon_min, lon_max) box, or all of them.""" if box is None: return ds rows, cols = grid.tiles_in_box(*box) return ds.isel(tile_lat=np.flatnonzero(rows), tile_lon=np.flatnonzero(cols)) def total(ds: xr.Dataset) -> xr.Dataset: """Sum over tiles (and days, for the daily series).""" return ds.sum(("tile_lat", "tile_lon")) def _div(a, b): with np.errstate(invalid="ignore", divide="ignore"): return xr.where(b > 0, a / b, np.nan) def amount(t: xr.Dataset) -> xr.Dataset: """Per window: mean depths, bias, MAE (= CRPS), RMSE, correlation, all in mm per window.""" n = t["n"] m = t["moments"] f, o = m.sel(moment="f", drop=True) / n, m.sel(moment="o", drop=True) / n var_f = m.sel(moment="f2", drop=True) / n - f**2 var_o = m.sel(moment="o2", drop=True) / n - o**2 cov = m.sel(moment="fo", drop=True) / n - f * o return xr.Dataset({ "era5_mean_mm": f, "pardig_mean_mm": o, "bias_mm": f - o, "relative_bias": _div(f, o) - 1, "mae_mm": m.sel(moment="abs_e", drop=True) / n, "rmse_mm": np.sqrt(m.sel(moment="e2", drop=True) / n), "correlation": _div(cov, np.sqrt(var_f * var_o)), }).drop_vars("moment", errors="ignore") def occurrence(t: xr.Dataset) -> xr.Dataset: """Per window and threshold: CSI, frequency bias, POD, FAR, ETS, event frequencies.""" c = t["contingency"] hit, fa, miss = c.sel(outcome="hit", drop=True), c.sel(outcome="false_alarm", drop=True), c.sel(outcome="miss", drop=True) n = t["n"] random = (hit + fa) * (hit + miss) / n return xr.Dataset({ "csi": _div(hit, hit + fa + miss), "frequency_bias": _div(hit + fa, hit + miss), "pod": _div(hit, hit + miss), "far": _div(fa, hit + fa), "ets": _div(hit - random, hit + fa + miss - random), "era5_frequency": (hit + fa) / n, "pardig_frequency": (hit + miss) / n, }).drop_vars("outcome", errors="ignore") def structure(t: xr.Dataset) -> xr.Dataset: """Per window, FSS threshold and scale: FSS, and its 'useful' level 0.5 + f/2 (Roberts & Lean 2008).""" fss = 1 - _div(t["fss"].sel(term="num", drop=True), t["fss"].sel(term="den", drop=True)) # Observed frequency at each FSS threshold, from the matching event threshold. observed = [] for w in sums.WINDOWS: occ = (t["contingency"].sel(window=w, outcome="hit") + t["contingency"].sel(window=w, outcome="miss")) occ = occ.assign_coords(threshold=list(sums.THRESHOLDS[w])) observed.append(xr.DataArray( [float(occ.sel(threshold=x)) / float(t["n"].sel(window=w)) for x in sums.FSS_THRESHOLDS[w]], dims="fss_threshold")) observed = xr.concat(observed, dim="window").assign_coords(window=list(sums.WINDOWS)) return xr.Dataset({"fss": fss.drop_vars("term", errors="ignore"), "useful_fss": 0.5 + observed / 2}) def intensity(t: xr.Dataset) -> xr.Dataset: """Per window and source: frequency and share of total rain in each intensity bin.""" h = t["histogram"] count, amount_ = h.sel(kind="count", drop=True), h.sel(kind="amount", drop=True) return xr.Dataset({ "frequency": count / count.sum("bin"), "rain_share": _div(amount_, amount_.sum("bin")), }).drop_vars("kind", errors="ignore") def quantiles(t: xr.Dataset, qs=(0.9, 0.95, 0.99, 0.999)) -> xr.Dataset: """Approximate quantiles of all values (dry included) from the histogram, log-interpolated in each bin.""" counts = t["histogram"].sel(kind="count", drop=True) out = [] for q in qs: values = [] for w in counts["window"].values: row = [] for s in counts["source"].values: c = counts.sel(window=w, source=s).values cdf = np.cumsum(c) / c.sum() b = int(np.searchsorted(cdf, q)) lo, hi = sums.BINS[b], sums.BINS[b + 1] below = cdf[b - 1] if b else 0.0 frac = (q - below) / (cdf[b] - below) if cdf[b] > below else 0.0 if lo == 0: row.append(hi * frac) elif np.isinf(hi): row.append(lo) else: row.append(float(np.exp(np.log(lo) + frac * (np.log(hi) - np.log(lo))))) values.append(row) out.append(values) return xr.Dataset({"quantile_mm": (("quantile", "window", "source"), np.array(out))}, coords={"quantile": list(qs), "window": counts["window"].values, "source": counts["source"].values}) def diurnal(ds: xr.Dataset) -> xr.Dataset: """Mean hourly rain and wet-hour frequency by LOCAL SOLAR hour, summed over the tiles in ``ds``. Each tile's 24 UTC hours are shifted by its longitude / 15 before the tiles are added, so a region spanning several time zones keeps its afternoon peak in the afternoon. """ d = ds["diurnal"] n = ds["n"].sel(window=1) / 24 # weight per hour shift = np.round(ds["tile_lon"].values / 15).astype(int) % 24 values = d.values # (source, utc_hour, stat, lat, lon) local = np.zeros(values.shape[:3]) for j, s in enumerate(shift): local += np.roll(values[..., j], s, axis=1).sum(-1) weight = float(n.sum()) return xr.Dataset({ "rain_mm_h": (("source", "local_hour"), local[:, :, 0] / weight), "wet_frequency": (("source", "local_hour"), local[:, :, 1] / weight), }, coords={"source": d["source"].values, "local_hour": np.arange(24)}) def daily(ds: xr.Dataset) -> xr.Dataset: """Daily series (24 h window) for the tiles in ``ds``.""" d = ds["daily"].sum(("tile_lat", "tile_lon")) n = d.sel(daily_stat="n", drop=True) out = { "era5_mm": d.sel(daily_stat="f", drop=True) / n, "pardig_mm": d.sel(daily_stat="o", drop=True) / n, "mae_mm": d.sel(daily_stat="abs_e", drop=True) / n, "rmse_mm": np.sqrt(d.sel(daily_stat="e2", drop=True) / n), } for t in (1, 10, 50): h, fa, m = (d.sel(daily_stat=f"{k}_{t}", drop=True) for k in ("hit", "false_alarm", "miss")) out[f"csi_{t}mm"] = _div(h, h + fa + m) out[f"frequency_bias_{t}mm"] = _div(h + fa, h + m) out["bias_mm"] = out["era5_mm"] - out["pardig_mm"] return xr.Dataset(out).drop_vars("daily_stat", errors="ignore") def tile_map(ds: xr.Dataset, metric: str, window: int, threshold: float | None = None) -> xr.DataArray: """A score per tile (days summed), for maps.""" n = ds["n"].sel(window=window) m = ds["moments"].sel(window=window) if metric == "bias_mm": return (m.sel(moment="e", drop=True) / n) if metric == "relative_bias": return _div(m.sel(moment="f", drop=True), m.sel(moment="o", drop=True)) - 1 if metric == "mae_mm": return (m.sel(moment="abs_e", drop=True) / n) if metric == "rmse_mm": return np.sqrt(m.sel(moment="e2", drop=True) / n) if metric in ("era5_mean_mm", "pardig_mean_mm"): return (m.sel(moment="f" if metric.startswith("era5") else "o") / n) c = ds["contingency"].sel(window=window) c = c.isel(threshold=list(sums.THRESHOLDS[window]).index(threshold)) hit, fa, miss = c.sel(outcome="hit", drop=True), c.sel(outcome="false_alarm", drop=True), c.sel(outcome="miss", drop=True) if metric == "csi": return _div(hit, hit + fa + miss) if metric == "frequency_bias": return _div(hit + fa, hit + miss) raise ValueError(f"unknown metric {metric}")