| """Reference PyTorch ``Dataset`` for the AtmosPair paired ERA5 / WRF zarr store.""" |
|
|
| from __future__ import annotations |
|
|
| from pathlib import Path |
| from typing import Iterable, Union |
|
|
| import numpy as np |
| import torch |
| import xarray as xr |
| from torch.utils.data import Dataset |
|
|
|
|
| class PairedDownscalingDataset(Dataset): |
| """Paired ERA5 / WRF samples from the AtmosPair zarr store. |
| |
| The store is a single consolidated zarr group with paired ``era5`` and |
| ``wrf`` 4-D arrays on a shared ``(time, channel, south_north, west_east)`` |
| grid, plus per-channel center and scale parameters (``*_center``, |
| ``*_scale``), per-(time, channel) validity masks (``*_valid``), and |
| string variable arrays (``*_variable``). |
| |
| Pairing and validity |
| -------------------- |
| A timestep is returned only when **both sides are valid**: |
| ``wrf_valid`` is True for that timestep AND ``era5_valid`` is True for |
| every ERA5 channel at that timestep. Timesteps where either side is |
| flagged invalid are dropped. |
| |
| Normalization |
| ------------- |
| Normalization is on by default; pass ``normalize=False`` for |
| physical-unit tensors. The ``normalize_*`` and ``denormalize_*`` methods |
| accept NumPy arrays or torch tensors with shape ``(C, H, W)``, |
| ``(B, C, H, W)``, or ``(B, E, C, H, W)``. |
| |
| Parameters |
| ---------- |
| zarr_path : str or Path |
| Path to the consolidated zarr store, or an ``hf://`` URL. |
| years : iterable of int |
| Years to include. Timesteps from any other year are excluded. |
| normalize : bool, default True |
| If True, ``__getitem__`` returns normalized tensors. If False, |
| returns physical-unit tensors. The normalize/denormalize methods |
| are available either way. |
| dtype : torch.dtype, default torch.float32 |
| Output dtype. |
| |
| Returns |
| ------- |
| Each ``__getitem__`` call yields a dict with keys: |
| ``era5`` : (68, 112, 112) tensor of ERA5 input channels |
| ``wrf`` : (49, 112, 112) tensor of WRF target channels |
| ``time`` : ISO-8601 UTC timestamp string |
| ``time_index`` : integer index into the underlying zarr time axis |
| |
| Required: ``xarray``, ``zarr<3``, ``numpy``, ``torch``. |
| """ |
|
|
| def __init__( |
| self, |
| zarr_path: Union[str, Path], |
| years: Iterable[int], |
| normalize: bool = True, |
| dtype: torch.dtype = torch.float32, |
| ) -> None: |
| self.zarr_path = zarr_path |
| self.normalize = normalize |
| self.dtype = dtype |
| self._ds = xr.open_zarr(zarr_path, consolidated=True) |
|
|
| |
| |
| |
| time_years = self._ds.time.dt.year.values |
| in_years = np.isin(time_years, list(years)) |
| wrf_valid = self._ds.wrf_valid.values.astype(bool) |
| era5_valid = self._ds.era5_valid.values.astype(bool).all(axis=1) |
| self._idx = np.where(in_years & wrf_valid & era5_valid)[0] |
| if self._idx.size == 0: |
| raise ValueError( |
| f"No valid timesteps for years={list(years)}. " |
| f"Available years: {sorted(set(int(y) for y in time_years))}." |
| ) |
|
|
| |
| self._era5_center = self._ds.era5_center.values.astype(np.float32) |
| self._era5_scale = self._ds.era5_scale.values.astype(np.float32) |
| self._wrf_center = self._ds.wrf_center.values.astype(np.float32) |
| self._wrf_scale = self._ds.wrf_scale.values.astype(np.float32) |
|
|
| |
| self.era5_variable: list[str] = self._ds.era5_variable.values.astype(str).tolist() |
| self.wrf_variable: list[str] = self._ds.wrf_variable.values.astype(str).tolist() |
|
|
| def __len__(self) -> int: |
| return int(self._idx.size) |
|
|
| def __getitem__(self, i: int) -> dict: |
| t = int(self._idx[i]) |
| era5 = torch.from_numpy(self._ds.era5.isel(time=t).values.astype(np.float32)).to(self.dtype) |
| wrf = torch.from_numpy(self._ds.wrf.isel(time=t).values.astype(np.float32)).to(self.dtype) |
| if self.normalize: |
| era5 = self.normalize_era5(era5) |
| wrf = self.normalize_wrf(wrf) |
| return { |
| "era5": era5, |
| "wrf": wrf, |
| "time": np.datetime_as_string(self._ds.time.values[t], unit="h"), |
| "time_index": t, |
| } |
|
|
| def __repr__(self) -> str: |
| return ( |
| f"PairedDownscalingDataset(n_samples={len(self)}, " |
| f"era5_channels={len(self.era5_variable)}, " |
| f"wrf_channels={len(self.wrf_variable)}, " |
| f"normalize={self.normalize})" |
| ) |
|
|
| |
|
|
| def normalize_era5(self, arr): |
| return self._affine(arr, self._era5_center, self._era5_scale, forward=True) |
|
|
| def denormalize_era5(self, arr): |
| return self._affine(arr, self._era5_center, self._era5_scale, forward=False) |
|
|
| def normalize_wrf(self, arr): |
| return self._affine(arr, self._wrf_center, self._wrf_scale, forward=True) |
|
|
| def denormalize_wrf(self, arr): |
| return self._affine(arr, self._wrf_center, self._wrf_scale, forward=False) |
|
|
| @staticmethod |
| def _affine(arr, center, scale, forward): |
| """Apply ``(arr - center) / scale`` (or its inverse) along the channel axis. |
| |
| The channel axis is fixed at position ``-3``, which covers ``(C, H, W)``, |
| ``(B, C, H, W)``, and ``(B, E, C, H, W)`` shapes uniformly. Accepts NumPy |
| arrays or torch tensors. |
| """ |
| n = center.shape[0] |
| if arr.ndim < 3 or arr.shape[-3] != n: |
| raise ValueError( |
| f"expected channel axis at position -3 with size {n}, " |
| f"got shape {tuple(arr.shape)}" |
| ) |
| if isinstance(arr, torch.Tensor): |
| c = torch.as_tensor(center, dtype=arr.dtype, device=arr.device).view(-1, 1, 1) |
| s = torch.as_tensor(scale, dtype=arr.dtype, device=arr.device).view(-1, 1, 1) |
| else: |
| c = center.reshape(-1, 1, 1) |
| s = scale.reshape(-1, 1, 1) |
| return (arr - c) / s if forward else arr * s + c |
|
|