File size: 8,627 Bytes
9ac2fa1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
"""One day of ERA5 and PARDIG reduced to per-tile sums that any region and date range can add up.

Every statistic is an area-weighted sum over the 0.25° cells of a 1° tile (weights from
:func:`pardig_eval.grid.cell_area`) and over the day's accumulation windows. Sums add across
tiles and days, so a region's score is computed from the sum of its tiles' sums
(:mod:`pardig_eval.scores`). Cells missing in either source get weight 0.

Windows are 1 h, 6 h (ending 06, 12, 18, 24 UTC) and 24 h. Thresholds, histogram bins and FSS
neighbourhoods are in mm per window and in 0.25° cells.
"""

from __future__ import annotations

import numpy as np
import pandas as pd
import xarray as xr
from scipy.ndimage import uniform_filter

from pardig_eval import grid

WINDOWS = (1, 6, 24)
MOMENTS = ("f", "o", "e", "abs_e", "e2", "f2", "o2", "fo")  # f = ERA5, o = PARDIG, e = f - o
#: Event thresholds per window, mm (CSI, frequency bias, ETS).
THRESHOLDS = {1: (0.1, 0.5, 1.0, 2.0, 5.0, 10.0), 6: (0.5, 1.0, 5.0, 10.0, 20.0, 50.0),
              24: (1.0, 5.0, 10.0, 20.0, 50.0, 100.0)}
OUTCOMES = ("hit", "false_alarm", "miss")
#: FSS thresholds per window, mm, and neighbourhood widths in 0.25° cells (~28 km at the equator).
FSS_THRESHOLDS = {1: (0.5, 2.0, 10.0), 6: (1.0, 10.0, 20.0), 24: (1.0, 20.0, 50.0)}
FSS_SCALES = (1, 3, 5, 9, 17, 33)
FSS_TERMS = ("num", "den")  # FSS = 1 - sum(num) / sum(den)
#: Histogram bin edges, mm per window (the first bin is "dry").
BINS = np.array([0, 0.01, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, 100, 200, 500, np.inf])
SOURCES = ("era5", "pardig")
KINDS = ("count", "amount")
#: Diurnal statistics, from the 1 h window, by UTC hour of the interval end (0..23).
DIURNAL = ("amount", "wet")
WET_MM_H = 0.1
#: Daily series kept per day (24 h window): enough for bias, MAE, RMSE and a few CSIs.
DAILY = ("n", "f", "o", "abs_e", "e2", "hit_1", "false_alarm_1", "miss_1", "hit_10", "false_alarm_10",
         "miss_10", "hit_50", "false_alarm_50", "miss_50")


def windows(hourly: np.ndarray) -> dict[int, np.ndarray]:
    """Hourly (24, lat, lon) depths -> {window: (n, lat, lon)} depths."""
    return {w: hourly.reshape(24 // w, w, *hourly.shape[1:]).sum(1) for w in WINDOWS}


def _fractions(binary: np.ndarray, valid: np.ndarray, size: int) -> np.ndarray:
    """Fraction of valid cells above threshold in a size x size window, latitude edges clamped,
    longitude periodic. Matches the PR's precipitation_metrics._fractions on valid cells."""
    sizes = (1, size, size)
    modes = ("constant", "nearest", "wrap")
    count = uniform_filter(valid.astype(np.float32), sizes, mode=modes)
    hit = uniform_filter((binary & valid).astype(np.float32), sizes, mode=modes)
    with np.errstate(invalid="ignore", divide="ignore"):
        return np.where(count > 0, hit / count, 0.0)


def day_sums(era5: np.ndarray, pardig: np.ndarray) -> xr.Dataset:
    """All per-tile sums for one day from hourly (24, 721, 1440) mm fields."""
    if era5.shape != (24, 721, 1440) or pardig.shape != era5.shape:
        raise ValueError("expected two (24, 721, 1440) hourly fields")
    area = grid.cell_area()[:, None].astype(np.float64)
    f_win, o_win = windows(era5), windows(pardig)

    n = np.zeros((len(WINDOWS), 180, 360))
    moments = np.zeros((len(WINDOWS), len(MOMENTS), 180, 360))
    contingency = np.zeros((len(WINDOWS), 6, len(OUTCOMES), 180, 360))
    fss = np.zeros((len(WINDOWS), 3, len(FSS_SCALES), len(FSS_TERMS), 180, 360))
    hist = np.zeros((len(WINDOWS), len(SOURCES), len(BINS) - 1, len(KINDS), 180, 360))

    for iw, w in enumerate(WINDOWS):
        f, o = f_win[w].astype(np.float64), o_win[w].astype(np.float64)
        valid = np.isfinite(f) & np.isfinite(o)
        weight = np.where(valid, area, 0.0)
        f = np.where(valid, f, 0.0)
        o = np.where(valid, o, 0.0)
        e = f - o

        def tsum(x):
            return grid.tile_sum((weight * x).sum(0))

        n[iw] = grid.tile_sum(weight.sum(0))
        for im, x in enumerate((f, o, e, np.abs(e), e * e, f * f, o * o, f * o)):
            moments[iw, im] = tsum(x)
        for it, t in enumerate(THRESHOLDS[w]):
            fy, oy = f >= t, o >= t
            contingency[iw, it, 0] = tsum(fy & oy)
            contingency[iw, it, 1] = tsum(fy & ~oy)
            contingency[iw, it, 2] = tsum(~fy & oy)
        for it, t in enumerate(FSS_THRESHOLDS[w]):
            fy, oy = f >= t, o >= t
            for js, s in enumerate(FSS_SCALES):
                pf, po = _fractions(fy, valid, s), _fractions(oy, valid, s)
                fss[iw, it, js, 0] = tsum((pf - po) ** 2)
                fss[iw, it, js, 1] = tsum(pf * pf + po * po)
        for isrc, x in enumerate((f, o)):
            index = np.digitize(x, BINS[1:-1])  # 0 .. len(BINS) - 2
            for b in range(len(BINS) - 1):
                inside = index == b
                hist[iw, isrc, b, 0] = tsum(inside)
                hist[iw, isrc, b, 1] = tsum(np.where(inside, x, 0.0))

    # Diurnal cycle: hour h holds the interval ending at (h + 1) mod 24 UTC.
    diurnal = np.zeros((len(SOURCES), 24, len(DIURNAL), 180, 360))
    f, o = f_win[1].astype(np.float64), o_win[1].astype(np.float64)
    valid = np.isfinite(f) & np.isfinite(o)
    weight = np.where(valid, area, 0.0)
    for isrc, x in enumerate((np.where(valid, f, 0), np.where(valid, o, 0))):
        for h in range(24):
            utc = (h + 1) % 24
            diurnal[isrc, utc, 0] = grid.tile_sum(weight[h] * x[h])
            diurnal[isrc, utc, 1] = grid.tile_sum(weight[h] * (x[h] >= WET_MM_H))

    # Daily series from the 24 h window.
    i24 = WINDOWS.index(24)
    th = THRESHOLDS[24]
    daily = [n[i24], moments[i24, 0], moments[i24, 1], moments[i24, 3], moments[i24, 4]]
    for t in (1.0, 10.0, 50.0):
        daily.extend(contingency[i24, th.index(t)])
    daily = np.stack(daily)

    f32 = np.float32
    return xr.Dataset(
        {
            "n": (("window", "tile_lat", "tile_lon"), n.astype(f32)),
            "moments": (("window", "moment", "tile_lat", "tile_lon"), moments.astype(f32)),
            "contingency": (("window", "threshold", "outcome", "tile_lat", "tile_lon"), contingency.astype(f32)),
            "fss": (("window", "fss_threshold", "scale", "term", "tile_lat", "tile_lon"), fss.astype(f32)),
            "histogram": (("window", "source", "bin", "kind", "tile_lat", "tile_lon"), hist.astype(f32)),
            "diurnal": (("source", "utc_hour", "diurnal_stat", "tile_lat", "tile_lon"), diurnal.astype(f32)),
            "daily": (("daily_stat", "tile_lat", "tile_lon"), daily.astype(f32)),
        },
        coords=coords(),
    )


def coords() -> dict:
    return {
        "window": list(WINDOWS),
        "moment": list(MOMENTS),
        "threshold_mm": (("window", "threshold"), np.array([THRESHOLDS[w] for w in WINDOWS])),
        "outcome": list(OUTCOMES),
        "fss_threshold_mm": (("window", "fss_threshold"), np.array([FSS_THRESHOLDS[w] for w in WINDOWS])),
        "scale": list(FSS_SCALES),
        "term": list(FSS_TERMS),
        "source": list(SOURCES),
        "bin_low_mm": ("bin", BINS[:-1]),
        "bin_high_mm": ("bin", BINS[1:]),
        "kind": list(KINDS),
        "utc_hour": np.arange(24),
        "diurnal_stat": list(DIURNAL),
        "daily_stat": list(DAILY),
        "tile_lat": grid.TILE_LAT,
        "tile_lon": grid.TILE_LON,
    }


def as_month(day_ds: xr.Dataset, day, era5_name: str, preliminary: bool) -> xr.Dataset:
    """Wrap one day's sums as a one-day month file: totals plus the day in the daily series."""
    day = pd.Timestamp(day).normalize()
    month = day_ds.drop_vars("daily")
    month["daily"] = day_ds["daily"].expand_dims(day=[day.to_datetime64()])
    month["era5_source"] = ("day", [era5_name])
    month["era5_preliminary"] = ("day", [preliminary])
    return month


def add_day(month: xr.Dataset | None, day_month: xr.Dataset) -> xr.Dataset:
    """Add a one-day month file to a month's totals (days must not repeat)."""
    if month is None:
        return day_month
    new = day_month["day"].values
    if np.isin(new, month["day"].values).any():
        raise ValueError(f"day {new} is already in the month")
    totals = [v for v in day_month.data_vars if "day" not in day_month[v].dims]
    out = month[totals] + day_month[totals]
    per_day = xr.concat([month[[v for v in month.data_vars if v not in totals]],
                         day_month[[v for v in day_month.data_vars if v not in totals]]], dim="day")
    out = xr.merge([out, per_day.sortby("day")])
    return out.assign_coords({k: v for k, v in day_month.coords.items() if k not in out.coords})