juannat7 commited on
Commit
34bd8b5
·
verified ·
1 Parent(s): 7a5dc21

Upload dataset.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. dataset.py +233 -0
dataset.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import Tensor
3
+ import torch.nn.functional as F
4
+ from torch.utils.data import Dataset
5
+ from typing import *
6
+ from pathlib import Path
7
+ import re
8
+ import xarray as xr
9
+ import numpy as np
10
+ import h5py
11
+
12
+
13
+ IGRA_VARS = ['air_temperature', 'relative_humidity', 'wind_speed', 'geopotential_height', 'air_dewpoint_depression']
14
+
15
+ CLARA_VARS_D = {
16
+ 'CFC': ['cfc'],
17
+ 'CTO': ['ctt', 'cth', 'ctp'],
18
+ 'IWP': ['iwp', 'cot_ice', 'cre_ice'],
19
+ 'LWP': ['lwp', 'cot_liq', 'cre_liq']
20
+ }
21
+
22
+ CLARA_VARS = [value for values_list in CLARA_VARS_D.values() for value in values_list]
23
+
24
+
25
+ class ERA5Dataset(Dataset):
26
+ def __init__(
27
+ self,
28
+ size: Tuple[int] = (720, 1440),
29
+ window: int = 1,
30
+ flatten: bool = True,
31
+ mode: str = 'train'
32
+ ) -> None:
33
+
34
+ self.size = size
35
+ self.window = window
36
+ self.flatten = flatten
37
+ self.mode = mode
38
+ self.data_dir = Path('.') / 'era5'
39
+ self.normalization_dir = Path('.') / 'era5' / 'stats_v0'
40
+
41
+ # Lazily load data
42
+ self.file_paths = list((self.data_dir / self.mode).glob('*.h5'))
43
+ self.file_paths.sort()
44
+
45
+ self.sample_indices = []
46
+ for file_idx, file_path in enumerate(self.file_paths):
47
+ h5_file = h5py.File(file_path, 'r')
48
+ num_samples = h5_file['fields'].shape[0]
49
+ self.sample_indices.extend([(file_idx, i) for i in range(num_samples)])
50
+ h5_file.close()
51
+
52
+
53
+ # Retrieve climatology to normalize
54
+ self.normalization_mean = np.load(self.normalization_dir / 'global_means.npy')
55
+ self.normalization_sigma = np.load(self.normalization_dir / 'global_stds.npy')
56
+
57
+
58
+ def _open_file(self, file_path, sample_idx):
59
+ h5_file = h5py.File(file_path, 'r')
60
+ sample = h5_file['fields'][sample_idx]
61
+ h5_file.close()
62
+
63
+ return sample[:, :self.size[0], :self.size[1]]
64
+
65
+
66
+ def __len__(self):
67
+ return len(self.sample_indices) - self.window + 1
68
+
69
+
70
+ def __getitem__(self, i):
71
+ step_indices = [target_idx for target_idx in range(i, i + self.window)]
72
+
73
+ x = list()
74
+ for step_idx in step_indices:
75
+ file_idx, sample_idx = self.sample_indices[step_idx]
76
+ x.append(self._open_file(self.file_paths[file_idx], sample_idx))
77
+
78
+ x = (x - self.normalization_mean) / self.normalization_sigma
79
+ x = torch.tensor(x).float()
80
+
81
+ if self.flatten:
82
+ return x.flatten(0, 1), {}
83
+ else:
84
+ return x, {}
85
+
86
+
87
+ class AuxDataset(Dataset):
88
+ def __init__(
89
+ self,
90
+ data_var: str = '',
91
+ size: Tuple[int] = (720, 1440),
92
+ window: int = 1,
93
+ flatten: bool = True,
94
+ mode: str = 'train'
95
+ ) -> None:
96
+
97
+ assert data_var in ['igra', 'clara'], 'Dataset is not implemented, choose one of [igra, clara]'
98
+
99
+ self.data_var = data_var
100
+ self.size = size
101
+ self.window = window
102
+ self.flatten = flatten
103
+ self.mode = mode
104
+
105
+ self.data_dir = Path('.') / data_var
106
+ self.normalization_file = Path('.') / 'climatology' / f'climatology_{self.data_var}.zarr'
107
+
108
+ # Check if years specified are within valid bounds
109
+ if self.mode == 'train':
110
+ years = [str(year) for year in np.arange(2011,2016)]
111
+ elif self.mode == 'val':
112
+ years = [str(year) for year in np.arange(2016,2018)]
113
+ elif self.mode == 'test':
114
+ years = [str(year) for year in np.arange(2018,2019)]
115
+ else:
116
+ raise NotImplementedError('Mode is invalid, choose one of [train, val, test]')
117
+
118
+ # Subset files that match with patterns (eg. years specified)
119
+ self.EXTENSION = 'nc'
120
+ self.ENGINE = 'netcdf4'
121
+ self.PARAMS = IGRA_VARS if self.data_var == 'igra' else CLARA_VARS
122
+
123
+ file_paths = list()
124
+ for year in years:
125
+ pattern = rf'.*{year}\d{{4}}\.{self.EXTENSION}$'
126
+ curr_files = list(self.data_dir.glob(f'*{year}*.{self.EXTENSION}'))
127
+ file_paths.extend(
128
+ [f for f in curr_files if re.match(pattern, str(f.name)) and not self._is_leap(f.name)]
129
+ )
130
+
131
+ self.file_paths = file_paths
132
+ self.file_paths.sort()
133
+
134
+ # Lazily load data (i.e., igra has multiple (4; 6-hourly) timesteps in a daily file, while clara only has 1)
135
+ self.sample_indices = []
136
+ if data_var == 'igra':
137
+ self.sample_indices = [(file_idx, i) for file_idx in range(len(self.file_paths)) for i in range(4)]
138
+
139
+ else:
140
+ self.sample_indices = [(file_idx, 0) for file_idx in range(len(self.file_paths)) for i in range(4)]
141
+
142
+ # Retrieve climatology to normalize
143
+ self.normalization = xr.open_dataset(self.normalization_file, engine='zarr')
144
+ self.normalization = self.normalization.sel(param=self.PARAMS)
145
+ self.normalization_mean = self.normalization['mean'].values[np.newaxis, :, np.newaxis, np.newaxis]
146
+ self.normalization_sigma = self.normalization['sigma'].values[np.newaxis, :, np.newaxis, np.newaxis]
147
+
148
+
149
+ def _is_leap(self, filename):
150
+ """FCN training data for ERA5 ignores leap day"""
151
+ match = re.search(r'(\d{4})(\d{2})(\d{2})', filename)
152
+ if match:
153
+ year, month, day = map(int, match.groups())
154
+ return month == 2 and day == 29
155
+
156
+ return False
157
+
158
+ def _open_file(self, file_path, sample_idx):
159
+ sample = xr.open_dataset(file_path, engine=self.ENGINE)
160
+ sample = sample[self.PARAMS]
161
+ sample = sample.sortby('lat', ascending=False) # aligned with FCN ERA5
162
+ sample = sample.roll(lon=len(sample.lon) // 2, roll_coords=True) # aligned with FCN ERA5
163
+
164
+
165
+ if self.data_var == 'igra':
166
+
167
+ # Some daily files do not have some snapshots in time; init an empty np.nan tensor instead
168
+ try:
169
+ sample = sample.isel(time=sample_idx).to_array().values
170
+
171
+ except:
172
+ sample = np.full((len(IGRA_VARS), self.size[0], self.size[1]), np.nan)
173
+
174
+
175
+ else:
176
+ sample = sample.to_array().values
177
+
178
+ return sample
179
+
180
+
181
+ def __len__(self):
182
+ return len(self.sample_indices) - self.window + 1
183
+
184
+
185
+ def __getitem__(self, i):
186
+ step_indices = [target_idx for target_idx in range(i, i + self.window)]
187
+
188
+ x = list()
189
+ for step_idx in step_indices:
190
+ file_idx, sample_idx = self.sample_indices[step_idx]
191
+ x.append(self._open_file(self.file_paths[file_idx], sample_idx))
192
+
193
+ x = (x - self.normalization_mean) / self.normalization_sigma
194
+ x = torch.tensor(x).float()
195
+ x = torch.nan_to_num(x)
196
+
197
+ if self.flatten:
198
+ return x.flatten(0, 1), {}
199
+ else:
200
+ return x, {}
201
+
202
+
203
+ class MultimodalDataset(Dataset):
204
+ def __init__(
205
+ self,
206
+ datasets,
207
+ background: bool=False
208
+ ):
209
+ self.datasets = datasets
210
+ self.is_flatten = datasets[0].flatten
211
+
212
+ # Handle variable future timestepping to generate background state
213
+ self.background = background
214
+
215
+ def __len__(self):
216
+ if self.background:
217
+ return len(self.datasets[0]) - 1 # lead_time = 1
218
+ else:
219
+ return len(self.datasets[0])
220
+
221
+ def __getitem__(self, idx):
222
+ dim = 0 if self.is_flatten else 1
223
+ x = [dataset[idx][0] for dataset in self.datasets]
224
+ x = torch.cat(x, dim=dim).float()
225
+
226
+ if self.background:
227
+ # Also return future lead_time as target y
228
+ y = [dataset[idx+1][0] for dataset in self.datasets]
229
+ y = torch.cat(y, dim=dim).float()
230
+ return x, y, {}
231
+
232
+ else:
233
+ return x, {}