SLAMS / dataset.py
juannat7's picture
Upload dataset.py with huggingface_hub
34bd8b5 verified
raw
history blame
7.94 kB
import torch
from torch import Tensor
import torch.nn.functional as F
from torch.utils.data import Dataset
from typing import *
from pathlib import Path
import re
import xarray as xr
import numpy as np
import h5py
IGRA_VARS = ['air_temperature', 'relative_humidity', 'wind_speed', 'geopotential_height', 'air_dewpoint_depression']
CLARA_VARS_D = {
'CFC': ['cfc'],
'CTO': ['ctt', 'cth', 'ctp'],
'IWP': ['iwp', 'cot_ice', 'cre_ice'],
'LWP': ['lwp', 'cot_liq', 'cre_liq']
}
CLARA_VARS = [value for values_list in CLARA_VARS_D.values() for value in values_list]
class ERA5Dataset(Dataset):
def __init__(
self,
size: Tuple[int] = (720, 1440),
window: int = 1,
flatten: bool = True,
mode: str = 'train'
) -> None:
self.size = size
self.window = window
self.flatten = flatten
self.mode = mode
self.data_dir = Path('.') / 'era5'
self.normalization_dir = Path('.') / 'era5' / 'stats_v0'
# Lazily load data
self.file_paths = list((self.data_dir / self.mode).glob('*.h5'))
self.file_paths.sort()
self.sample_indices = []
for file_idx, file_path in enumerate(self.file_paths):
h5_file = h5py.File(file_path, 'r')
num_samples = h5_file['fields'].shape[0]
self.sample_indices.extend([(file_idx, i) for i in range(num_samples)])
h5_file.close()
# Retrieve climatology to normalize
self.normalization_mean = np.load(self.normalization_dir / 'global_means.npy')
self.normalization_sigma = np.load(self.normalization_dir / 'global_stds.npy')
def _open_file(self, file_path, sample_idx):
h5_file = h5py.File(file_path, 'r')
sample = h5_file['fields'][sample_idx]
h5_file.close()
return sample[:, :self.size[0], :self.size[1]]
def __len__(self):
return len(self.sample_indices) - self.window + 1
def __getitem__(self, i):
step_indices = [target_idx for target_idx in range(i, i + self.window)]
x = list()
for step_idx in step_indices:
file_idx, sample_idx = self.sample_indices[step_idx]
x.append(self._open_file(self.file_paths[file_idx], sample_idx))
x = (x - self.normalization_mean) / self.normalization_sigma
x = torch.tensor(x).float()
if self.flatten:
return x.flatten(0, 1), {}
else:
return x, {}
class AuxDataset(Dataset):
def __init__(
self,
data_var: str = '',
size: Tuple[int] = (720, 1440),
window: int = 1,
flatten: bool = True,
mode: str = 'train'
) -> None:
assert data_var in ['igra', 'clara'], 'Dataset is not implemented, choose one of [igra, clara]'
self.data_var = data_var
self.size = size
self.window = window
self.flatten = flatten
self.mode = mode
self.data_dir = Path('.') / data_var
self.normalization_file = Path('.') / 'climatology' / f'climatology_{self.data_var}.zarr'
# Check if years specified are within valid bounds
if self.mode == 'train':
years = [str(year) for year in np.arange(2011,2016)]
elif self.mode == 'val':
years = [str(year) for year in np.arange(2016,2018)]
elif self.mode == 'test':
years = [str(year) for year in np.arange(2018,2019)]
else:
raise NotImplementedError('Mode is invalid, choose one of [train, val, test]')
# Subset files that match with patterns (eg. years specified)
self.EXTENSION = 'nc'
self.ENGINE = 'netcdf4'
self.PARAMS = IGRA_VARS if self.data_var == 'igra' else CLARA_VARS
file_paths = list()
for year in years:
pattern = rf'.*{year}\d{{4}}\.{self.EXTENSION}$'
curr_files = list(self.data_dir.glob(f'*{year}*.{self.EXTENSION}'))
file_paths.extend(
[f for f in curr_files if re.match(pattern, str(f.name)) and not self._is_leap(f.name)]
)
self.file_paths = file_paths
self.file_paths.sort()
# Lazily load data (i.e., igra has multiple (4; 6-hourly) timesteps in a daily file, while clara only has 1)
self.sample_indices = []
if data_var == 'igra':
self.sample_indices = [(file_idx, i) for file_idx in range(len(self.file_paths)) for i in range(4)]
else:
self.sample_indices = [(file_idx, 0) for file_idx in range(len(self.file_paths)) for i in range(4)]
# Retrieve climatology to normalize
self.normalization = xr.open_dataset(self.normalization_file, engine='zarr')
self.normalization = self.normalization.sel(param=self.PARAMS)
self.normalization_mean = self.normalization['mean'].values[np.newaxis, :, np.newaxis, np.newaxis]
self.normalization_sigma = self.normalization['sigma'].values[np.newaxis, :, np.newaxis, np.newaxis]
def _is_leap(self, filename):
"""FCN training data for ERA5 ignores leap day"""
match = re.search(r'(\d{4})(\d{2})(\d{2})', filename)
if match:
year, month, day = map(int, match.groups())
return month == 2 and day == 29
return False
def _open_file(self, file_path, sample_idx):
sample = xr.open_dataset(file_path, engine=self.ENGINE)
sample = sample[self.PARAMS]
sample = sample.sortby('lat', ascending=False) # aligned with FCN ERA5
sample = sample.roll(lon=len(sample.lon) // 2, roll_coords=True) # aligned with FCN ERA5
if self.data_var == 'igra':
# Some daily files do not have some snapshots in time; init an empty np.nan tensor instead
try:
sample = sample.isel(time=sample_idx).to_array().values
except:
sample = np.full((len(IGRA_VARS), self.size[0], self.size[1]), np.nan)
else:
sample = sample.to_array().values
return sample
def __len__(self):
return len(self.sample_indices) - self.window + 1
def __getitem__(self, i):
step_indices = [target_idx for target_idx in range(i, i + self.window)]
x = list()
for step_idx in step_indices:
file_idx, sample_idx = self.sample_indices[step_idx]
x.append(self._open_file(self.file_paths[file_idx], sample_idx))
x = (x - self.normalization_mean) / self.normalization_sigma
x = torch.tensor(x).float()
x = torch.nan_to_num(x)
if self.flatten:
return x.flatten(0, 1), {}
else:
return x, {}
class MultimodalDataset(Dataset):
def __init__(
self,
datasets,
background: bool=False
):
self.datasets = datasets
self.is_flatten = datasets[0].flatten
# Handle variable future timestepping to generate background state
self.background = background
def __len__(self):
if self.background:
return len(self.datasets[0]) - 1 # lead_time = 1
else:
return len(self.datasets[0])
def __getitem__(self, idx):
dim = 0 if self.is_flatten else 1
x = [dataset[idx][0] for dataset in self.datasets]
x = torch.cat(x, dim=dim).float()
if self.background:
# Also return future lead_time as target y
y = [dataset[idx+1][0] for dataset in self.datasets]
y = torch.cat(y, dim=dim).float()
return x, y, {}
else:
return x, {}