-
Notifications
You must be signed in to change notification settings - Fork 1
/
data.py
559 lines (452 loc) · 15 KB
/
data.py
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
from timeit import default_timer
import h5py
from einops import rearrange, reduce, repeat
import numpy as np
import scipy.io
from scipy.io import loadmat
import tensorflow as tf
import torch
def read_data(
path,
property_names,
as_torch=False,
to_cuda=False,
):
with h5py.File(path) as f:
properties = dict(
zip(property_names,
[f[p][:].squeeze() for p in property_names]))
X = f['input'][...].astype(np.float32)
Y = f['output'][...].astype(np.float32)
if as_torch:
X = torch.from_numpy(X)
Y = torch.from_numpy(Y)
if to_cuda:
X = X.cuda()
Y = Y.cuda()
return X, Y, properties
def subsample(array,
ss_rates
):
"""Subsample a tensor with a given rate for each dimension."""
obj = [
slice(0,
array.shape[dim],
ss_rates[dim]) for dim in range(array.ndim)
]
return array[tuple(obj)]
def to_dataloader(X,
Y,
num_samples,
batch_size=20,
pin_memory=True,
shuffle=True,
name=None
):
"""Generate a PyTorch DataLoader from input and target tensors."""
num_samples = num_samples - (num_samples % batch_size)
dataloader = torch.utils.data.DataLoader(
torch.utils.data.TensorDataset(X[:num_samples, ...],
Y[:num_samples, ...]),
batch_size=batch_size,
pin_memory=pin_memory,
shuffle=shuffle,
name=name,
)
return dataloader
class FunctionDataset(object):
"""
"""
def __init__(self):
super(FunctionDataset,
self).__init__()
self.X = None
self.Y = None
self.properties = None
def read_data(
self,
path,
property_names,
backend='torch',
cuda=False,
):
X_list = []
Y_list = []
for file in path.iterdir():
with h5py.File(file) as f:
if self.properties is None:
self.properties = dict(
zip(property_names,
[f[p][:].squeeze() for p in property_names]))
X_ = f['input'][...].astype(np.float32)
Y_ = f['output'][...].astype(np.float32)
X_list.append(X_)
Y_list.append(Y_)
self.X = rearrange(X_list,
'x b -> b x')
self.Y = rearrange(Y_list,
'x b -> b x')
if backend == 'torch':
self.X = torch.from_numpy(self.X)
self.Y = torch.from_numpy(self.Y)
if backend == 'tf':
self.X = tf.from_numpy(self.X)
self.Y = tf.from_numpy(self.Y)
if cuda:
self.X = self.X.cuda()
self.Y = self.Y.cuda()
return
def add_domain_channel(
self,
X,
lower,
upper,
):
raise NotImplementedError
def gen_dataset(
self,
ntrain,
ntest,
domain,
ss_rate=None,
batch_size=20,
):
raise NotImplementedError
class FunctionDataset1D(FunctionDataset):
"""
"""
def __init__(self, ):
super(FunctionDataset,
self).__init__()
self.properties = None
self.X = None
self.Y = None
def add_domain_channel(
self,
X,
lower,
upper,
):
"""
Add 1D domain coordinates as a channel to input tensor X.
"""
b, x = [*X.shape]
domain = torch.tensor(
repeat(np.linspace(lower,
upper,
x),
'x -> b x',
b=b))
X_aug = rearrange([X, domain],
'c b x -> b x c')
return X_aug
def gen_dataset(
self,
ntrain,
ntest,
domain,
ss_rate=None,
batch_size=20,
):
"""
Generate a DataLoader of data for input to a model.
Specifies input data properties for a given network
training/testing run:
subsampling,
test/train split,
batch size,
"""
# resample
X_ss = subsample(self.X,
[1, ss_rate])
Y_ss = subsample(self.Y,
[1, ss_rate])
# add domain channel
X_aug = self.add_domain_channel(X_ss,
*domain)
# make test/train DataLoaders
train_DL = to_dataloader(X_aug,
Y_ss,
ntrain,
name='train_data')
test_DL = to_dataloader(X_aug,
Y_ss,
ntest,
shuffle=False,
name='test_data')
return train_DL, test_DL
class FunctionDataset2D(FunctionDataset):
"""
"""
def __init__(
self,
properties,
filename=None,
ndim=None,
ss_rate=None,
):
super(FunctionDataset,
self).__init__()
self.properties = properties
self.samples = None
self.ss_rate = None
self.ndim = None
self.x_data = None
self.y_data = None
def add_domain_channel(
self,
X,
lower,
upper,
):
"""
Add 2D domain coordinates as channels to input tensor X.
"""
b, x, y = [*X.shape]
x_ax = torch.tensor(
repeat(np.linspace(lower,
upper,
x),
'w -> b h w',
h=y,
b=b))
y_ax = torch.tensor(
repeat(np.linspace(lower,
upper,
y),
'h -> b h w',
w=x,
b=b))
X_aug = rearrange([X, x_ax, y_ax],
'c b x y -> b x y c')
return X_aug
def gen_dataset(
self,
ntrain,
ntest,
domain,
ss_rate=None,
batch_size=20,
):
"""
Generate a DataLoader of data for input to a model.
Specifies input data properties for a given network
training/testing run:
subsampling,
test/train split,
batch size,
"""
# resample
X_ss = subsample(self.X,
[1, ss_rate, ss_rate])
Y_ss = subsample(self.Y,
[1, ss_rate, ss_rate])
# add domain channel
X_aug = self.add_domain_channel(X_ss,
*domain)
# make test/train DataLoaders
train_DL = to_dataloader(X_aug,
Y_ss,
ntrain,
name='train_data')
test_DL = to_dataloader(X_aug,
Y_ss,
ntest,
shuffle=False,
name='test_data')
return train_DL, test_DL
class MatReader(object):
def __init__(self,
file_path,
to_torch=True,
to_cuda=False,
to_float=True
):
super(MatReader,
self).__init__()
self.to_torch = to_torch
self.to_cuda = to_cuda
self.to_float = to_float
self.file_path = file_path
self.data = None
self.old_mat = None
self._load_file()
def _load_file(self):
try:
self.data = scipy.io.loadmat(self.file_path)
self.old_mat = True
except:
self.data = h5py.File(self.file_path)
self.old_mat = False
def load_file(self,
file_path
):
self.file_path = file_path
self._load_file()
def read_field(self,
field
):
x = self.data[field]
if not self.old_mat:
x = x[()]
x = np.transpose(x,
axes=range(len(x.shape) - 1,
-1,
-1))
if self.to_float:
x = x.astype(np.float32)
if self.to_torch:
x = torch.from_numpy(x)
if self.to_cuda:
x = x.cuda()
return x
def set_cuda(self,
to_cuda
):
self.to_cuda = to_cuda
def set_torch(self,
to_torch
):
self.to_torch = to_torch
def set_float(self,
to_float
):
self.to_float = to_float
def mat_to_tensor1d(TRAIN_PATH,
TEST_PATH,
ss_rate,
x_field,
y_field,
vsamples=None,
normalize=False
):
"""Converts .mat file contents to torch tensors.
Args:
:param TRAIN_PATH: list of .mat file names to concatenate into
training tensors
:param TEST_PATH: list of .mat file names to concatenate into test
tensors
:param ss_rate: [train subsampling rate, test rate]
:param x_field: names of input field in the .mat file
:param y_field: names of output field in the .mat file
:param vsamples: [ntest, ntrain]
:param normalize: Apply normalization to the tensors; default False
"""
reader = MatReader(TRAIN_PATH)
x_data = reader.read_field(x_field)
y_data = reader.read_field(y_field)
dimension = len(x_data.shape) - 1
mat_info = {
"input signal vector samples": x_data.shape[0],
"output signal vector samples": y_data.shape[0],
"input signal entry samples": x_data.shape[1],
"output signal entry samples": y_data.shape[1],
"signal dimension": dimension
}
ntrain = vsamples[0]
ntest = vsamples[1]
full_res = x_data.shape[1]
tr_ss = ss_rate[0]
tst_ss = ss_rate[1]
tr_esamples = int(((full_res - 1) / tr_ss) + 1)
x_train = x_data[ntrain:, ::tr_ss][:, :tr_esamples]
y_train = y_data[ntrain:, ::tr_ss][:, :tr_esamples]
if TRAIN_PATH != TEST_PATH:
# using separate files for test/train data
test_reader = MatReader(TEST_PATH)
x_test = test_reader.read_field(x_field)
y_test = test_reader.read_field(y_field)
full_res = x_test.shape[1]
tst_esamples = int(((full_res - 1) / tst_ss) + 1)
x_test = x_test[ntest:, ::tst_ss][:, :tst_esamples]
y_test = y_test[ntest:, ::tst_ss][:, :tst_esamples]
else:
full_res = x_data.shape[1]
tst_esamples = int(((full_res - 1) / tst_ss) + 1)
# same file; use last (ntest) samples
x_test = x_data[-ntest:, ::tst_ss][:, :tst_esamples]
y_test = y_data[-ntest:, ::tst_ss][:, :tst_esamples]
ds_info = {
"training dataset": TRAIN_PATH,
"test dataset": TEST_PATH,
"input train samples": x_train.shape[0],
"output train samples": y_train.shape[0],
"input train resolution": x_train.shape[1],
"output train resolution": y_train.shape[1],
"input test samples": x_test.shape[0],
"output test samples": y_test.shape[0],
"input test resolution": x_test.shape[1],
"output test resolution": y_test.shape[1]
}
t2 = default_timer()
return x_train, y_train, x_test, y_test, mat_info, ds_info
def mat_to_tensor2d(TRAIN_PATH,
TEST_PATH,
ss_rate,
x_field,
y_field,
vsamples=None,
normalize=False
):
"""Converts .mat file contents to torch tensors.
Args:
:param TRAIN_PATH: list of .mat file names to concatenate into
training tensors
:param TEST_PATH: list of .mat file names to concatenate into test
tensors
:param ss_rate: [train subsampling rate, test rate]
:param x_field: names of input field in the .mat file
:param y_field: names of output field in the .mat file
:param vsamples: [ntest, ntrain]
:param normalize: Apply normalization to the tensors; default False
"""
reader = MatReader(TRAIN_PATH)
x_data = reader.read_field(x_field)
y_data = reader.read_field(y_field)
dimension = len(x_data.shape) - 1
mat_info = {
"input signal vector samples": x_data.shape[0],
"output signal vector samples": y_data.shape[0],
"input signal entry samples": x_data.shape[1],
"output signal entry samples": y_data.shape[1],
"signal dimension": dimension
}
print(mat_info)
ntrain = vsamples[0]
ntest = vsamples[1]
full_res = x_data.shape[1]
tr_ss = ss_rate[0]
tst_ss = ss_rate[1]
tr_esamples = int(((full_res - 1) / tr_ss) + 1)
x_train = x_data[:ntrain, ::tr_ss, ::tr_ss][:, :tr_esamples, :tr_esamples]
y_train = y_data[:ntrain, ::tr_ss, ::tr_ss][:, :tr_esamples, :tr_esamples]
if TRAIN_PATH != TEST_PATH:
# using separate files for test/train data
test_reader = MatReader(TEST_PATH)
x_test = test_reader.read_field(x_field)
y_test = test_reader.read_field(y_field)
full_res = x_test.shape[1]
tst_esamples = int(((full_res - 1) / tst_ss) + 1)
x_test = x_test[:ntest,::tst_ss,::tst_ss][:,:tst_esamples,:tst_esamples]
y_test = y_test[:ntest,::tst_ss,::tst_ss][:,:tst_esamples,:tst_esamples]
else:
full_res = x_data.shape[1]
tst_esamples = int(((full_res - 1) / tst_ss) + 1)
# same file; use last (ntest) samples
x_test = x_data[-ntest:,::tst_ss,::tst_ss][:,:tst_esamples,:tst_esamples]
y_test = y_data[-ntest:,::tst_ss,::tst_ss][:,:tst_esamples,:tst_esamples]
ds_info = {
"training dataset": TRAIN_PATH,
"test dataset": TEST_PATH,
"input train samples": x_train.shape[0],
"output train samples": y_train.shape[0],
"input train resolution": x_train.shape[1],
"output train resolution": y_train.shape[1],
"input test samples": x_test.shape[0],
"output test samples": y_test.shape[0],
"input test resolution": x_test.shape[1],
"output test resolution": y_test.shape[1]
}
print(mat_info)
t2 = default_timer()
return x_train, y_train, x_test, y_test, mat_info, ds_info