"""The scoring grid (ERA5's 0.25°) and the 1° tiles its statistics are summed into. Every field here is on ascending latitudes -90..90 (721) and longitudes 0..359.75 (1440). A tile holds 4 x 4 cells: tile row ``r`` has the cells of latitude index ``4r..4r+3`` (the north-pole row joins the last tile), tile column ``c`` the cells of longitude index ``4c..4c+3``. With cells 0.25° wide, tile ``(r, c)`` spans latitudes ``[-90.125 + r, -89.125 + r)`` and longitudes ``[c - 0.125, c + 0.875)``, clipped at the poles. """ from __future__ import annotations import numpy as np STEP = 0.25 LAT = np.linspace(-90.0, 90.0, 721) LON = np.arange(1440) * STEP TILE = 4 N_TILE_LAT = 180 N_TILE_LON = 360 #: Tile centres, for labels and for selecting the tiles of a region. TILE_LAT = np.arange(N_TILE_LAT) - 89.625 TILE_LON = np.arange(N_TILE_LON) + 0.375 def cell_area() -> np.ndarray: """Relative area of each latitude row of cells, 1 at the equator, shape (721,).""" half = np.deg2rad(STEP / 2) lat = np.deg2rad(LAT) top = np.minimum(lat + half, np.pi / 2) bottom = np.maximum(lat - half, -np.pi / 2) return (np.sin(top) - np.sin(bottom)) / (2 * np.sin(half)) def tile_sum(x: np.ndarray) -> np.ndarray: """Sum the last two axes (721, 1440) into tiles (180, 360).""" if x.shape[-2:] != (721, 1440): raise ValueError(f"expected (..., 721, 1440), got {x.shape}") lead = x.shape[:-2] body = x[..., :720, :].reshape(*lead, N_TILE_LAT, TILE, N_TILE_LON, TILE).sum((-3, -1)) body[..., -1, :] += x[..., 720, :].reshape(*lead, N_TILE_LON, TILE).sum(-1) return body def tiles_in_box(lat_min: float, lat_max: float, lon_min: float, lon_max: float) -> tuple[np.ndarray, np.ndarray]: """Boolean masks of the tile rows and columns whose centres fall in a box. Longitudes may be given in -180..180 or 0..360; ``lon_min > lon_max`` crosses the date line (in -180..180) or Greenwich (in 0..360). """ if lat_min > lat_max: raise ValueError("lat_min must not exceed lat_max") rows = (TILE_LAT >= lat_min) & (TILE_LAT <= lat_max) lo, hi = lon_min % 360, lon_max % 360 if lon_max - lon_min >= 360: cols = np.ones(N_TILE_LON, bool) elif lo <= hi: cols = (TILE_LON >= lo) & (TILE_LON <= hi) else: cols = (TILE_LON >= lo) | (TILE_LON <= hi) return rows, cols