/
data.py
executable file
·381 lines (296 loc) · 16.4 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
import os
import csv
import nibabel as nib
import random
import datetime
import torch
from torchvision import transforms
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
import numpy as np
import scipy.ndimage as ndi
from scipy.ndimage.interpolation import map_coordinates
from scipy.ndimage.filters import gaussian_filter
KEY_CASE_ID = 'case_id'
KEY_CLINICAL_IDX = 'clinical_idx'
KEY_IMAGES = 'images'
KEY_LABELS = 'labels'
KEY_GLOBAL = 'clinical'
DIM_HORIZONTAL_NUMPY_3D = 0
DIM_DEPTH_NUMPY_3D = 2
DIM_CHANNEL_NUMPY_3D = 3
DIM_CHANNEL_TORCH3D_5 = 1
class StrokeLindaDataset3D(Dataset):
"""Ischemic stroke dataset with CBV, TTD, clinical data, and CBVmap, TTDmap, FUmap, and interpolations."""
PATH_ROOT = '/share/data_zoe1/lucas/Linda_Segmentations'
PATH_CSV = '/share/data_zoe1/lucas/Linda_Segmentations/clinical_cleaned.csv'
FN_PREFIX = 'train'
FN_PATTERN = '{1}/{0}{1}{2}.nii.gz'
ROW_OFFSET = 1
COL_OFFSET = 1
def __init__(self, root_dir=PATH_ROOT, modalities=[], labels=[], clinical=PATH_CSV, transform=None,
single_case_id=None):
self._root_dir = root_dir
self._clinical = self._load_clinical_data_from_csv(clinical, row_offset=self.ROW_OFFSET, col_offset=0)
self._transform = transform
self._modalities = modalities
self._labels = labels
self._item_index_map = []
for index in range(len(self._clinical)):
case_id = int(self._clinical[index][0])
if single_case_id is not None and single_case_id != case_id:
continue
self._item_index_map.append({KEY_CASE_ID: case_id, KEY_CLINICAL_IDX: index})
def _load_clinical_data_from_csv(self, filename, col_offset=0, row_offset=0):
result = []
with open(filename, 'r') as f:
rows = csv.reader(f, delimiter=',')
for row in rows:
if row_offset == 0:
result.append(row[col_offset:])
else:
row_offset -= 1
return result
def _load_image_data_from_nifti(self, case_id, suffix):
img_name = self.FN_PATTERN.format(self.FN_PREFIX, str(case_id), suffix)
filename = os.path.join(self._root_dir, img_name)
img_data = nib.load(filename).get_data()
return img_data[:, :, :, np.newaxis]
def __len__(self):
return len(self._item_index_map)
def __getitem__(self, item):
item_id = self._item_index_map[item]
case_id = item_id[KEY_CASE_ID]
clinical_data = self._clinical[item_id[KEY_CLINICAL_IDX]][1:]
result = {KEY_CASE_ID: case_id, KEY_IMAGES: [], KEY_LABELS: [], KEY_GLOBAL: []}
for value in clinical_data:
result[KEY_GLOBAL].append(float(value))
if result[KEY_GLOBAL]:
result[KEY_GLOBAL] = np.array(result[KEY_GLOBAL]).reshape((1, 1, 1, len(clinical_data)))
for label in self._labels:
result[KEY_LABELS].append(self._load_image_data_from_nifti(case_id, label))
if result[KEY_LABELS]:
result[KEY_LABELS] = np.concatenate(result[KEY_LABELS], axis=DIM_CHANNEL_NUMPY_3D)
for modality in self._modalities:
result[KEY_IMAGES].append(self._load_image_data_from_nifti(case_id, modality))
if result[KEY_IMAGES]:
result[KEY_IMAGES] = np.concatenate(result[KEY_IMAGES], axis=DIM_CHANNEL_NUMPY_3D)
if self._transform:
result = self._transform(result)
return result
def emptyCopyFromSample(sample):
result = {KEY_CASE_ID: int(sample[KEY_CASE_ID]), KEY_IMAGES: [], KEY_LABELS: [], KEY_GLOBAL: []}
return result
def set_np_seed(workerid):
torch_seed = torch.initial_seed()
numpy_seed = torch_seed % np.iinfo(np.int32).max
np.random.seed(numpy_seed)
def split_data_loader3D(modalities, labels, indices, batch_size, random_seed=None, valid_size=0.5, shuffle=True,
num_workers=4, pin_memory=False, train_transform=[], valid_transform=[]):
assert ((valid_size >= 0) and (valid_size <= 1)), "[!] valid_size should be in the range [0, 1]."
assert train_transform, "You must provide at least a numpy-to-torch transformation."
assert valid_transform, "You must provide at least a numpy-to-torch transformation."
# load the dataset
dataset_train = StrokeLindaDataset3D(modalities=modalities, labels=labels,
transform=transforms.Compose(train_transform))
dataset_valid = StrokeLindaDataset3D(modalities=modalities, labels=labels,
transform=transforms.Compose(valid_transform))
items = list(set(range(len(dataset_train))).intersection(set(indices)))
num_train = len(items)
split = int(np.floor(valid_size * num_train))
if shuffle == True:
random_state = np.random.RandomState(random_seed)
random_state.shuffle(items)
train_idx, valid_idx = items[split:], items[:split]
train_sampler = SubsetRandomSampler(train_idx)
valid_sampler = SubsetRandomSampler(valid_idx)
train_loader = DataLoader(dataset_train,
batch_size=batch_size, sampler=train_sampler,
num_workers=num_workers, pin_memory=pin_memory,
worker_init_fn=set_np_seed)
valid_loader = DataLoader(dataset_valid,
batch_size=batch_size, sampler=valid_sampler,
num_workers=num_workers, pin_memory=pin_memory)
return (train_loader, valid_loader)
def single_data_loader3D(modalities, labels, indices, batch_size, random_seed=None, valid_size=0.5, shuffle=True,
num_workers=4, pin_memory=False, train_transform=[]):
assert ((valid_size >= 0) and (valid_size <= 1)), "[!] valid_size should be in the range [0, 1]."
assert train_transform, "You must provide at least a numpy-to-torch transformation."
# load the dataset
dataset_train = StrokeLindaDataset3D(modalities=modalities, labels=labels,
transform=transforms.Compose(train_transform))
items = list(set(range(len(dataset_train))).intersection(set(indices)))
if shuffle == True:
random_state = np.random.RandomState(random_seed)
random_state.shuffle(items)
train_sampler = SubsetRandomSampler(items)
train_loader = DataLoader(dataset_train,
batch_size=batch_size, sampler=train_sampler,
num_workers=num_workers, pin_memory=pin_memory,
worker_init_fn=set_np_seed)
return train_loader
def get_stroke_shape_training_data(modalities, labels, train_transform, valid_transform, fold_indices, ratio, seed=4,
batchsize=2, split=True):
if split:
return split_data_loader3D(modalities, labels, fold_indices, batchsize, random_seed=seed,
valid_size=ratio, train_transform=train_transform,
valid_transform=valid_transform, num_workers=0)
return single_data_loader3D(modalities, labels, fold_indices, batchsize, random_seed=seed,
valid_size=ratio, train_transform=train_transform, num_workers=0), None
def get_stroke_prediction_training_data(modalities, labels, train_transform, valid_transform, fold_indices, ratio,
seed=4, batchsize=2, split=True):
if split:
return split_data_loader3D(modalities, labels, fold_indices, batchsize, random_seed=seed,
valid_size=ratio, train_transform=train_transform,
valid_transform=valid_transform, num_workers=0)
return single_data_loader3D(modalities, labels, fold_indices, batchsize, random_seed=seed,
valid_size=ratio, train_transform=train_transform, num_workers=0), None
def get_testdata(modalities, labels, indices, random_seed=None, shuffle=True, num_workers=4, pin_memory=False,
transform=[]):
assert transform, "You must provide at least a numpy-to-torch transformation."
dataset = StrokeLindaDataset3D(modalities=modalities, labels=labels, transform=transforms.Compose(transform))
items = list(set(range(len(dataset))).intersection(set(indices)))
if shuffle == True:
random_state = np.random.RandomState(random_seed)
random_state.shuffle(items)
sampler = SubsetRandomSampler(items)
loader = DataLoader(dataset, batch_size=1, sampler=sampler, num_workers=num_workers, pin_memory=pin_memory,
worker_init_fn=set_np_seed) # important to have batchsize=1 because metrics is computed on batch
return loader
class HemisphericFlipFixedToCaseId(object):
"""Flip numpy images along X-axis."""
def __init__(self, split_id):
self.split_id = split_id
def __call__(self, sample):
if int(sample[KEY_CASE_ID]) > self.split_id:
result = emptyCopyFromSample(sample)
if sample[KEY_IMAGES] != []:
result[KEY_IMAGES] = np.flip(sample[KEY_IMAGES], DIM_HORIZONTAL_NUMPY_3D).copy()
if sample[KEY_LABELS] != []:
result[KEY_LABELS] = np.flip(sample[KEY_LABELS], DIM_HORIZONTAL_NUMPY_3D).copy()
if sample[KEY_GLOBAL] != []:
result[KEY_GLOBAL] = np.flip(sample[KEY_GLOBAL], DIM_HORIZONTAL_NUMPY_3D).copy()
return result
return sample
class HemisphericFlip(object):
"""Flip numpy images along X-axis."""
def __call__(self, sample):
if random.random() > 0.5:
result = emptyCopyFromSample(sample)
if sample[KEY_IMAGES] != []:
result[KEY_IMAGES] = np.flip(sample[KEY_IMAGES], DIM_HORIZONTAL_NUMPY_3D).copy()
if sample[KEY_LABELS] != []:
result[KEY_LABELS] = np.flip(sample[KEY_LABELS], DIM_HORIZONTAL_NUMPY_3D).copy()
if sample[KEY_GLOBAL] != []:
result[KEY_GLOBAL] = np.flip(sample[KEY_GLOBAL], DIM_HORIZONTAL_NUMPY_3D).copy()
return result
return sample
class RandomPatch(object):
"""Random patches of certain size."""
def __init__(self, w, h, d, pad_x, pad_y, pad_z):
self._padx = pad_x
self._pady = pad_y
self._padz = pad_z
self._w = w
self._h = h
self._d = d
def __call__(self, sample):
sx, sy, sz, _ = sample[KEY_IMAGES].shape
rand_x = random.randint(0, sx - self._w)
rand_y = random.randint(0, sy - self._h)
rand_z = random.randint(0, sz - self._d)
result = emptyCopyFromSample(sample)
if sample[KEY_IMAGES] != []:
result[KEY_IMAGES] = sample[KEY_IMAGES][rand_x: rand_x + self._w,
rand_y: rand_y + self._h,
rand_z: rand_z + self._d, :]
if sample[KEY_LABELS] != []:
result[KEY_LABELS] = sample[KEY_LABELS][rand_x: rand_x + self._w - 2 * self._padx,
rand_y: rand_y + self._h - 2 * self._pady,
rand_z: rand_z + self._d - 2 * self._padz, :]
result[KEY_GLOBAL] = sample[KEY_GLOBAL]
return result
class PadImages(object):
"""Pad images with constant pad_value in all 6 directions (3D)."""
def __init__(self, pad_x, pad_y, pad_z, pad_value=0):
self._padx = pad_x
self._pady = pad_y
self._padz = pad_z
self._pad_value = float(pad_value)
def __call__(self, sample):
sx, sy, sz, sc = sample[KEY_IMAGES].shape
result = emptyCopyFromSample(sample)
if sample[KEY_IMAGES] != []:
result[KEY_IMAGES] = np.ones((sx + 2 * self._padx, sy + 2 * self._pady, sz + 2 * self._padz, sc), dtype=np.float32) * self._pad_value
result[KEY_IMAGES][self._padx:-self._padx, self._pady:-self._pady, self._padz:-self._padz, :] = sample[KEY_IMAGES]
result[KEY_LABELS] = sample[KEY_LABELS]
result[KEY_GLOBAL] = sample[KEY_GLOBAL]
return result
class ToTensor(object):
"""Convert ndarrays in sample to Tensors."""
def __call__(self, sample):
result = emptyCopyFromSample(sample)
if sample[KEY_IMAGES] != []:
result[KEY_IMAGES] = torch.from_numpy(sample[KEY_IMAGES]).permute(3, 2, 1, 0)
if sample[KEY_LABELS] != []:
result[KEY_LABELS] = torch.from_numpy(sample[KEY_LABELS]).permute(3, 2, 1, 0)
if sample[KEY_GLOBAL] != []:
result[KEY_GLOBAL] = torch.from_numpy(sample[KEY_GLOBAL]).permute(3, 2, 1, 0)
return result
class ElasticDeform(object):
"""Elastic deformation of images as described in [Simard2003]
Simard, Steinkraus and Platt, "Best Practices for Convolutional
Neural Networks applied to Visual Document Analysis", in Proc.
of the International Conference on Document Analysis and
Recognition, 2003.
"""
def __init__(self, alpha=100, sigma=4, apply_to_images=False):
self._alpha = alpha
self._sigma = sigma
self._apply_to_images = apply_to_images
def elastic_transform(self, image, alpha=100, sigma=4, random_state=None):
new_seed = datetime.datetime.now().second + datetime.datetime.now().microsecond
if random_state is None:
random_state = np.random.RandomState(new_seed)
shape = image.shape
dx = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode="constant", cval=0) * alpha
dy = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode="constant", cval=0) * alpha
dz = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode="constant", cval=0) * alpha * 0.22 # 28/128 TODO: correct according to voxel spacing
x, y, z = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]), np.arange(shape[2]))
indices = np.reshape(y + dy, (-1, 1)), np.reshape(x + dx, (-1, 1)), np.reshape(z + dz, (-1, 1))
return map_coordinates(image, indices, order=1).reshape(shape), random_state
def __call__(self, sample):
sample[KEY_LABELS][:, :, :, 0], random_state = self.elastic_transform(sample[KEY_LABELS][:, :, :, 0],
self._alpha, self._sigma)
for c in range(1, sample[KEY_LABELS].shape[3]):
sample[KEY_LABELS][:, :, :, c], _ = self.elastic_transform(sample[KEY_LABELS][:, :, :, c], self._alpha,
self._sigma, random_state=random_state)
if self._apply_to_images and sample[KEY_IMAGES] != []:
for c in range(sample[KEY_IMAGES].shape[3]):
sample[KEY_IMAGES][:, :, :, c], _ = self.elastic_transform(sample[KEY_IMAGES][:, :, :, c], self._alpha,
self._sigma, random_state=random_state)
return sample
class ResamplePlaneXY(object):
"""Down- or upsample images."""
def __init__(self, scale_factor=1, mode='nearest'):
self._scale_factor = scale_factor
if mode == 'bilinear':
self._order = 1
else:
self._order = 0
def __call__(self, sample):
result = emptyCopyFromSample(sample)
result[KEY_GLOBAL] = sample[KEY_GLOBAL]
if sample[KEY_IMAGES] != []:
sx, sy = ndi.zoom(sample[KEY_IMAGES][:, :, 0], self._scale_factor, order=0).shape[0:2] # just for init
result[KEY_IMAGES] = sample[KEY_IMAGES][:sx, :sy, :, :] # just for init correctly sized array with random values
for c in range(sample[KEY_IMAGES].shape[DIM_CHANNEL_NUMPY_3D]):
for z in range(sample[KEY_IMAGES].shape[DIM_DEPTH_NUMPY_3D]):
result[KEY_IMAGES][:, :, z, c] = ndi.zoom(sample[KEY_IMAGES][:, :, z, c], self._scale_factor, order=self._order)
if sample[KEY_LABELS] != []:
sx, sy = ndi.zoom(sample[KEY_LABELS][:, :, 0], self._scale_factor, order=0).shape[0:2] # just for init
result[KEY_LABELS] = sample[KEY_LABELS][:sx, :sy, :, :] # just for init correctly sized array with random values
for c in range(sample[KEY_LABELS].shape[DIM_CHANNEL_NUMPY_3D]):
for z in range(sample[KEY_LABELS].shape[DIM_DEPTH_NUMPY_3D]):
result[KEY_LABELS][:, :, z, c] = ndi.zoom(sample[KEY_LABELS][:, :, z, c], self._scale_factor, order=self._order)
return result