File size: 3,694 Bytes
2621a72
9ac2fa1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2621a72
 
 
 
 
 
 
 
 
 
 
 
9ac2fa1
2621a72
9ac2fa1
2621a72
 
 
 
 
 
 
 
9ac2fa1
 
 
2621a72
 
 
9ac2fa1
2621a72
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
"""Area-conservative regridding of PARDIG or IMERG (0.1°) onto ERA5's grid (0.25°).

Both grids are regular, so the overlap weights factor into a latitude matrix (overlaps
measured in sin(latitude), i.e. in area) and a periodic longitude matrix. Each ERA5 cell
receives the area-weighted mean of the PARDIG cells it covers, so global totals are kept.
"""

from __future__ import annotations

import functools

import numpy as np
from scipy import sparse

from pardig_eval import grid

PARDIG_STEP = 0.1
PARDIG_LAT = np.round(np.linspace(-90.0, 90.0, 1801), 6)
PARDIG_LON = np.round(np.arange(3600) * PARDIG_STEP, 6)


def _edges(centres: np.ndarray, step: float, low: float | None = None, high: float | None = None) -> np.ndarray:
    edges = np.concatenate([centres - step / 2, [centres[-1] + step / 2]])
    if low is not None:
        edges = np.clip(edges, low, high)
    return edges


def overlap_matrix(target_edges: np.ndarray, source_edges: np.ndarray) -> sparse.csr_matrix:
    """Row-normalised overlap lengths between two increasing 1-D partitions."""
    rows, cols, values = [], [], []
    for i in range(len(target_edges) - 1):
        a, b = target_edges[i], target_edges[i + 1]
        first = max(np.searchsorted(source_edges, a, side="right") - 1, 0)
        last = min(np.searchsorted(source_edges, b, side="left"), len(source_edges) - 1)
        for k in range(first, last):
            length = min(b, source_edges[k + 1]) - max(a, source_edges[k])
            if length > 0:
                rows.append(i)
                cols.append(k)
                values.append(length)
    m = sparse.csr_matrix((values, (rows, cols)), shape=(len(target_edges) - 1, len(source_edges) - 1))
    total = np.asarray(m.sum(1)).ravel()
    return sparse.diags(1 / total) @ m


#: Fine source grids (ascending latitudes, longitudes 0..360), by name.
#: PARDIG has points on the 0.1° lines (poles included); IMERG has cell edges there (centres at .05).
IMERG_STEP = 0.1
IMERG_LAT = np.round(np.arange(1800) * IMERG_STEP - 89.95, 6)
IMERG_LON = np.round(np.arange(3600) * IMERG_STEP + 0.05, 6)
GRIDS = {"pardig": (PARDIG_LAT, PARDIG_LON, PARDIG_STEP), "imerg": (IMERG_LAT, IMERG_LON, IMERG_STEP)}


@functools.lru_cache(maxsize=4)
def matrices(source: str = "pardig") -> tuple[sparse.csr_matrix, sparse.csr_matrix]:
    """(latitude 721 x n_lat, longitude 1440 x n_lon) weights from a fine source grid to ERA5 cells."""
    src_lat, src_lon, step = GRIDS[source]
    lat_t = np.sin(np.deg2rad(_edges(grid.LAT, grid.STEP, -90, 90)))
    lat_s = np.sin(np.deg2rad(_edges(src_lat, step, -90, 90)))
    lat = overlap_matrix(lat_t, lat_s).tocsr()
    # Longitude is periodic: put the last source columns again in front of the first, 360° to the west,
    # so the ERA5 cell centred on 0° (edges -0.125..0.125) sees its western neighbours (one PARDIG cell,
    # two IMERG cells), then fold their weights back onto those columns.
    k = 2
    lon_s = np.concatenate([src_lon[-k:] - 360, src_lon])
    wrapped = overlap_matrix(_edges(grid.LON, grid.STEP), _edges(lon_s, step)).tocsc()
    lon = (wrapped[:, k:].tolil())
    lon[:, -k:] = lon[:, -k:] + wrapped[:, :k]
    return lat, lon.tocsr()


def to_era5_grid(field: np.ndarray, source: str = "pardig") -> np.ndarray:
    """(..., n_lat, n_lon) on a fine source grid -> (..., 721, 1440) on ERA5's, NaN-propagating."""
    lat, lon = matrices(source)
    lead = field.shape[:-2]
    flat = field.reshape(-1, *field.shape[-2:])
    out = np.empty((flat.shape[0], 721, 1440), dtype=np.float32)
    for n, f in enumerate(flat):
        f = f.astype(np.float64)
        out[n] = (lon @ (lat @ f).T).T
    return out.reshape(*lead, 721, 1440)