This repository has been archived by the owner on Mar 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 142
/
full_image_dataset.py
371 lines (320 loc) · 17.9 KB
/
full_image_dataset.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
# ------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# ------------------------------------------------------------------------------------------
import logging
import os
from abc import ABC
from collections import Counter
from pathlib import Path
from typing import Any, Callable, Dict, Generic, List, Mapping, Optional, Tuple, TypeVar
import pandas as pd
import torch.utils.data
from torch.utils.data import BatchSampler, DataLoader, Dataset, RandomSampler, Sampler, SequentialSampler
from torch.utils.data.dataloader import default_collate # type: ignore
from InnerEye.ML.config import SegmentationModelBase
from InnerEye.ML.dataset.sample import GeneralSampleMetadata, PatientDatasetSource, \
PatientMetadata, Sample
from InnerEye.ML.model_config_base import ModelConfigBase
from InnerEye.ML.utils import io_util
from InnerEye.ML.utils.csv_util import CSV_CHANNEL_HEADER, CSV_PATH_HEADER, \
CSV_SUBJECT_HEADER
from InnerEye.ML.utils.transforms import Compose3D
COMPRESSION_EXTENSIONS = ['sz', 'gz']
def collate_with_metadata(batch: List[Dict[str, Any]]) -> Dict[str, Any]:
"""
The collate function that the dataloader workers should use. It does the same thing for all "normal" fields
(all fields are put into tensors with outer dimension batch_size), except for the special "metadata" field.
Those metadata objects are collated into a simple list.
:param batch: A list of samples that should be collated.
:return: collated result
"""
elem = batch[0]
if isinstance(elem, Mapping):
result = dict()
for key in elem:
# Special handling for all fields that store metadata, and for fields that are list.
# Lists are used in SequenceDataset.
# All these are collated by turning them into lists or lists of lists.
if isinstance(elem[key], (list, PatientMetadata, GeneralSampleMetadata)):
result[key] = [d[key] for d in batch]
else:
result[key] = default_collate([d[key] for d in batch])
return result
raise TypeError(f"Unexpected batch data: Expected a dictionary, but got: {type(elem)}")
class _RepeatSampler(BatchSampler):
"""
A batch sampler that wraps another batch sampler. It repeats the contents of that other sampler forever.
"""
def __init__(self, sampler: Sampler, batch_size: int, drop_last: bool = False, max_repeats: int = 0) -> None:
super().__init__(sampler, batch_size, drop_last)
self.sampler = sampler
self.max_repeats = max_repeats
def __iter__(self) -> Any:
repeats = 0
while self.max_repeats == 0 or repeats < self.max_repeats:
yield from iter(self.sampler)
repeats += 1
class ImbalancedSampler(Sampler):
"""
Sampler that performs naive over-sampling by drawing samples with
replacements. The probability of being drawn depends on the label of
each data point, rare labels have a higher probability to be drawn.
Assumes the dataset implements the "get_all_labels" functions in order
to compute the weights associated with each data point.
Side note: the sampler choice is independent from the data augmentation
pipeline. Data augmentation is performed on the images while loading them
at a later stage. This sampler merely affects which item is selected.
"""
# noinspection PyMissingConstructor
def __init__(self, dataset: Any, num_samples: int = None) -> None:
"""
:param dataset: a dataset
:num_samples: number of samples to draw. If None the number of samples
corresponds to the length of the dataset.
"""
self.dataset = dataset
self.indices = list(range(len(dataset)))
self.weights = self.get_weights()
self.num_samples = len(dataset) if num_samples is None else num_samples
def get_weights(self) -> torch.Tensor:
labels = self.dataset.get_labels_for_imbalanced_sampler()
counts_per_label: Dict = Counter(labels)
return torch.tensor([1.0 / counts_per_label[labels[i]] for i in self.indices])
def __iter__(self) -> Any:
# noinspection PyTypeChecker
return iter([self.indices[i] for i in torch.multinomial(self.weights, self.num_samples, # type: ignore
replacement=True)])
def __len__(self) -> int:
return self.num_samples
class RepeatDataLoader(DataLoader):
"""
This class implements a data loader that avoids spawning a new process after each epoch.
It uses an infinite sampler.
This is adapted from https://github.com/pytorch/pytorch/issues/15849
"""
def __init__(self,
dataset: Any,
max_repeats: int,
batch_size: int = 1,
shuffle: bool = False,
use_imbalanced_sampler: bool = False,
drop_last: bool = False,
**kwargs: Any):
"""
Creates a new data loader.
:param dataset: The dataset that should be loaded.
:param batch_size: The number of samples per minibatch.
:param shuffle: If true, the dataset will be shuffled randomly.
:param drop_last: If true, drop incomplete minibatches at the end.
:param kwargs: Additional arguments that will be passed through to the Dataloader constructor.
"""
sampler = RandomSampler(dataset) if shuffle else SequentialSampler(dataset)
if use_imbalanced_sampler:
sampler = ImbalancedSampler(dataset)
self._actual_batch_sampler = BatchSampler(sampler, batch_size, drop_last)
repeat_sampler = _RepeatSampler(self._actual_batch_sampler, batch_size=batch_size, max_repeats=max_repeats)
super().__init__(dataset=dataset, batch_sampler=repeat_sampler, **kwargs)
self.iterator = None
def __len__(self) -> int:
return len(self._actual_batch_sampler)
def __iter__(self) -> Any:
if self.iterator is None:
self.iterator = super().__iter__() # type: ignore
assert self.iterator is not None # for mypy
for i in range(len(self)):
yield next(self.iterator)
D = TypeVar('D', bound=ModelConfigBase)
class GeneralDataset(Dataset, ABC, Generic[D]):
def __init__(self, args: D, data_frame: Optional[pd.DataFrame] = None,
name: Optional[str] = None):
self.name = name or "None"
self.args = args
self.data_frame = args.dataset_data_frame if data_frame is None else data_frame
logging.info(f"Processing dataset (name={self.name})")
def as_data_loader(self,
shuffle: bool,
batch_size: Optional[int] = None,
num_dataload_workers: Optional[int] = None,
use_imbalanced_sampler: bool = False,
drop_last_batch: bool = False,
max_repeats: Optional[int] = None) -> DataLoader:
num_dataload_workers = num_dataload_workers or self.args.num_dataload_workers
batch_size = batch_size or self.args.train_batch_size
if self.args.avoid_process_spawn_in_data_loaders:
if max_repeats is None:
max_repeats = self.args.get_total_number_of_training_epochs()
return RepeatDataLoader(
self,
max_repeats=max_repeats,
batch_size=batch_size,
shuffle=shuffle,
num_workers=num_dataload_workers,
pin_memory=self.args.pin_memory,
collate_fn=collate_with_metadata,
use_imbalanced_sampler=use_imbalanced_sampler,
drop_last=drop_last_batch
)
else:
if use_imbalanced_sampler:
sampler: Optional[Sampler] = ImbalancedSampler(self)
shuffle = False
else:
sampler = None
return DataLoader(
self,
batch_size=batch_size,
shuffle=shuffle,
num_workers=num_dataload_workers,
pin_memory=self.args.pin_memory,
collate_fn=collate_with_metadata,
sampler=sampler, # type: ignore
drop_last=drop_last_batch
)
class FullImageDataset(GeneralDataset):
"""
Dataset class that loads and creates samples with full 3D images from a given pd.Dataframe. The following
are the operations performed to generate a sample from this dataset:
-------------------------------------------------------------------------------------------------
1) On initialization parses the provided pd.Dataframe with dataset information, to cache the set of file paths
and patient mappings to load as PatientDatasetSource. The sources are then saved in a list: dataset_sources.
2) dataset_sources is iterated in a batched fashion, where for each batch it loads the full 3D images, and applies
pre-processing functions (e.g. normalization), returning a sample that can be used for full image operations.
"""
def __init__(self, args: SegmentationModelBase, data_frame: pd.DataFrame,
full_image_sample_transforms: Optional[Compose3D[Sample]] = None):
super().__init__(args, data_frame)
self.full_image_sample_transforms = full_image_sample_transforms
self.allow_incomplete_labels = args.allow_incomplete_labels
# Check base_path
assert self.args.local_dataset is not None
if not self.args.local_dataset.is_dir():
raise ValueError("local_dataset should be the path to the base directory of the data: {}".
format(self.args.local_dataset))
# cache all of the available dataset sources
dataloader: Callable[[], Any] = self._load_dataset_sources
self.dataset_sources: Dict[str, PatientDatasetSource] = dataloader()
self.dataset_indices: List[str] = sorted(self.dataset_sources.keys())
def __len__(self) -> int:
return len(self.dataset_indices)
def __getitem__(self, i: int) -> Dict[str, Any]:
return self.get_samples_at_index(index=i)[0].get_dict()
@staticmethod
def _extension_from_df_file_paths(file_paths: List[str]) -> str:
file_extensions = [f.split('.')[-2] if f.endswith(tuple(COMPRESSION_EXTENSIONS))
else f.split('.')[-1] for f in file_paths]
if len(file_extensions) == 0:
raise Exception("No files of expected format (Nifti) were found")
# files must all be of same type
unique_file_extensions = list(set(file_extensions))
if len(unique_file_extensions) > 1:
raise Exception("More than one file type was found. This is not supported.")
return "." + unique_file_extensions[0]
def get_samples_at_index(self, index: int) -> List[Sample]:
# load the channels into memory
ds = self.dataset_sources[self.dataset_indices[index]]
samples = [io_util.load_images_from_dataset_source(dataset_source=ds,
check_exclusive=self.args.check_exclusive)] # type: ignore
return [Compose3D.apply(self.full_image_sample_transforms, x) for x in samples]
def _load_dataset_sources(self) -> Dict[str, PatientDatasetSource]:
assert self.args.local_dataset is not None
return load_dataset_sources(dataframe=self.data_frame,
local_dataset_root_folder=self.args.local_dataset,
image_channels=self.args.image_channels,
ground_truth_channels=self.args.ground_truth_ids,
mask_channel=self.args.mask_id,
allow_incomplete_labels=self.allow_incomplete_labels)
def convert_channels_to_file_paths(channels: List[str],
rows: pd.DataFrame,
local_dataset_root_folder: Path,
patient_id: str,
allow_incomplete_labels: bool = False) -> Tuple[List[Optional[Path]], str]:
"""
Returns: 1) A list of path file objects specified in the training, validation and testing datasets, and
2) a string with description of missing channels, files and more than one channel per patient.
:param channels: channel type defined in the configuration file
:param rows: Input Pandas dataframe object containing subjectIds, path of local dataset, channel information
:param local_dataset_root_folder: Root directory which points to the local dataset
:param patient_id: string which contains subject identifier
:param allow_incomplete_labels: boolean flag. If false, all ground truth files must be provided. If true, ground
truth files are optional
"""
paths: List[Optional[Path]] = []
failed_channel_info = ''
for channel_id in channels:
row = rows.loc[rows[CSV_CHANNEL_HEADER] == channel_id]
if len(row) == 0 and not allow_incomplete_labels:
failed_channel_info += f"Patient {patient_id} does not have channel '{channel_id}'" + os.linesep
elif len(row) == 0 and allow_incomplete_labels:
# Keeps track of missing channels order
paths.append(None)
elif len(row) > 1:
failed_channel_info += f"Patient {patient_id} has more than one entry for channel '{channel_id}'" + \
os.linesep
elif len(row) == 1:
image_path = local_dataset_root_folder / row[CSV_PATH_HEADER].values[0]
if not image_path.is_file():
failed_channel_info += f"Patient {patient_id}, file {image_path} does not exist" + os.linesep
else:
paths.append(image_path)
return paths, failed_channel_info
def load_dataset_sources(dataframe: pd.DataFrame,
local_dataset_root_folder: Path,
image_channels: List[str],
ground_truth_channels: List[str],
mask_channel: Optional[str],
allow_incomplete_labels: bool = False) -> Dict[str, PatientDatasetSource]:
"""
Prepares a patient-to-images mapping from a dataframe read directly from a dataset CSV file.
The dataframe contains per-patient per-channel image information, relative to a root directory.
This method converts that into a per-patient dictionary, that contains absolute file paths
separated for for image channels, ground truth channels, and mask channels.
:param dataframe: A dataframe read directly from a dataset CSV file.
:param local_dataset_root_folder: The root folder that contains all images.
:param image_channels: The names of the image channels that should be used in the result.
:param ground_truth_channels: The names of the ground truth channels that should be used in the result.
:param mask_channel: The name of the mask channel that should be used in the result. This can be None.
:param allow_incomplete_labels: Boolean flag. If false, all ground truth files must be provided. If true, ground
truth files are optional. Default value is false.
:return: A dictionary mapping from an integer subject ID to a PatientDatasetSource.
"""
expected_headers = {CSV_SUBJECT_HEADER, CSV_PATH_HEADER, CSV_CHANNEL_HEADER}
# validate the csv file
actual_headers = list(dataframe)
if not expected_headers.issubset(actual_headers):
raise ValueError("The dataset CSV file should contain at least these columns: {}, but got: {}"
.format(expected_headers, actual_headers))
# Calculate unique data points, first, and last data point
unique_ids: List[str] = sorted(pd.unique(dataframe[CSV_SUBJECT_HEADER]))
if not local_dataset_root_folder.is_dir():
raise ValueError("The dataset root folder does not exist: {}".format(local_dataset_root_folder))
def get_mask_channel_or_default() -> Optional[Path]:
if mask_channel is None:
return None
paths = get_paths_for_channel_ids(channels=[mask_channel], allow_incomplete_labels_flag=allow_incomplete_labels)
if len(paths) == 0:
return None
else:
return paths[0]
def get_paths_for_channel_ids(channels: List[str], allow_incomplete_labels_flag: bool) -> List[Optional[Path]]:
if len(set(channels)) < len(channels):
raise ValueError(f"ids have duplicated entries: {channels}")
rows = dataframe.loc[dataframe[CSV_SUBJECT_HEADER] == patient_id]
# converts channels to paths and makes second sanity check for channel data
paths, failed_channel_info = convert_channels_to_file_paths(channels, rows, local_dataset_root_folder,
patient_id, allow_incomplete_labels_flag)
if failed_channel_info:
raise ValueError(failed_channel_info)
return paths
dataset_sources = {}
for patient_id in unique_ids:
metadata = PatientMetadata.from_dataframe(dataframe, patient_id)
dataset_sources[patient_id] = PatientDatasetSource(
metadata=metadata,
image_channels=get_paths_for_channel_ids(channels=image_channels, # type: ignore
allow_incomplete_labels_flag=False),
mask_channel=get_mask_channel_or_default(),
ground_truth_channels=get_paths_for_channel_ids(channels=ground_truth_channels, # type: ignore
allow_incomplete_labels_flag=allow_incomplete_labels),
allow_incomplete_labels=allow_incomplete_labels)
return dataset_sources