Datasets:
File size: 2,735 Bytes
9857bf2 | 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 | import argparse
from dataclasses import dataclass
from typing import Tuple
import numpy as np
import torch
import xarray as xr
from torch.utils.data import DataLoader, Dataset
@dataclass(frozen=True)
class WindowSpec:
in_days: int = 7
out_days: int = 7
stride_days: int = 7 # non-overlapping by default
class PacificSSTForecastDataset(Dataset):
"""Forecasting dataset over pacific_sst.zarr.
Returns:
x: (in_days, H, W) float32
y: (out_days, H, W) float32
"""
def __init__(self, zarr_path: str, *, split: str, window: WindowSpec = WindowSpec()) -> None:
self.ds = xr.open_zarr(zarr_path, consolidated=True)
self.var = self.ds["analysed_sst"]
self.window = window
t = self.ds["time"].values
if t.dtype.kind != "M":
raise ValueError("Expected datetime64 time coordinate")
train_end = np.datetime64("2018-12-30T09:00:00")
val_end = np.datetime64("2019-06-30T09:00:00")
if split == "train":
t0 = 0
t1 = int(np.searchsorted(t, train_end, side="right")) - 1
elif split == "val":
t0 = int(np.searchsorted(t, train_end, side="right"))
t1 = int(np.searchsorted(t, val_end, side="right")) - 1
elif split == "test":
t0 = int(np.searchsorted(t, val_end, side="right"))
t1 = len(t) - 1
else:
raise ValueError("split must be one of: train, val, test")
n = window.in_days + window.out_days
self.start_indices = list(range(t0, t1 - n + 2, window.stride_days))
def __len__(self) -> int:
return len(self.start_indices)
def __getitem__(self, idx: int) -> Tuple[torch.Tensor, torch.Tensor]:
i = self.start_indices[idx]
x = self.var.isel(time=slice(i, i + self.window.in_days)).values.astype(np.float32)
y = self.var.isel(
time=slice(i + self.window.in_days, i + self.window.in_days + self.window.out_days)
).values.astype(np.float32)
return torch.from_numpy(x), torch.from_numpy(y)
def main() -> None:
p = argparse.ArgumentParser()
p.add_argument("--zarr", default="pacific_sst.zarr")
p.add_argument("--split", default="train", choices=["train", "val", "test"])
p.add_argument("--batch-size", type=int, default=1)
p.add_argument("--num-workers", type=int, default=0)
args = p.parse_args()
ds = PacificSSTForecastDataset(args.zarr, split=args.split)
dl = DataLoader(ds, batch_size=args.batch_size, shuffle=(args.split == "train"), num_workers=args.num_workers)
x, y = next(iter(dl))
print("x:", tuple(x.shape), x.dtype, "y:", tuple(y.shape), y.dtype)
if __name__ == "__main__":
main()
|