Passed
Pull Request — master (#353)
by Fernando
01:17
created

torchio.transforms.transform.Transform.to_range()   A

Complexity

Conditions 2

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nop 2
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
import copy
2
import numbers
3
from abc import ABC, abstractmethod
4
from typing import Optional, Union, Tuple, List
5
6
import torch
7
import numpy as np
8
import nibabel as nib
9
import SimpleITK as sitk
10
11
from .. import TypeData, DATA, AFFINE, TypeNumber
12
from ..data.subject import Subject
13
from ..data.image import Image, ScalarImage
14
from ..utils import nib_to_sitk, sitk_to_nib, to_tuple
15
from .interpolation import Interpolation
16
17
18
TypeTransformInput = Union[
19
    Subject,
20
    Image,
21
    torch.Tensor,
22
    np.ndarray,
23
    sitk.Image,
24
    dict,
25
    nib.Nifti1Image,
26
]
27
28
29
class Transform(ABC):
30
    """Abstract class for all TorchIO transforms.
31
32
    All subclasses should overwrite
33
    :py:meth:`torchio.tranforms.Transform.apply_transform`,
34
    which takes data, applies some transformation and returns the result.
35
36
    The input can be an instance of
37
    :py:class:`torchio.Subject`,
38
    :py:class:`torchio.Image`,
39
    :py:class:`numpy.ndarray`,
40
    :py:class:`torch.Tensor`,
41
    :py:class:`SimpleITK.image`,
42
    or a Python dictionary.
43
44
    Args:
45
        p: Probability that this transform will be applied.
46
        copy: Make a shallow copy of the input before applying the transform.
47
        keys: Mandatory if the input is a Python dictionary. The transform will
48
            be applied only to the data in each key.
49
    """
50
    def __init__(
51
            self,
52
            p: float = 1,
53
            copy: bool = True,
54
            keys: Optional[List[str]] = None,
55
            ):
56
        self.probability = self.parse_probability(p)
57
        self.copy = copy
58
        self.keys = keys
59
60
    def __call__(
61
            self,
62
            data: TypeTransformInput,
63
            ) -> TypeTransformInput:
64
        """Transform data and return a result of the same type.
65
66
        Args:
67
            data: Instance of :py:class:`~torchio.Subject`, 4D
68
                :py:class:`torch.Tensor` or 4D NumPy array with dimensions
69
                :math:`(C, W, H, D)`, where :math:`C` is the number of channels
70
                and :math:`W, H, D` are the spatial dimensions. If the input is
71
                a tensor, the affine matrix is an identity and a tensor will be
72
                also returned.
73
        """
74
        if torch.rand(1).item() > self.probability:
75
            return data
76
77
        data_parser = DataToSubject(data, keys=self.keys)
78
        subject = data_parser.get_subject()
79
80
        if self.copy:
81
            subject = copy.copy(subject)
82
83
        with np.errstate(all='raise'):
84
            transformed = self.apply_transform(subject)
85
86
        self.add_transform_to_subject_history(transformed)
87
88
        for image in transformed.get_images(intensity_only=False):
89
            ndim = image[DATA].ndim
90
            assert ndim == 4, f'Output of {self.name} is {ndim}D'
91
92
        output = data_parser.get_output(transformed)
93
94
        return output
95
96
    @abstractmethod
97
    def apply_transform(self, subject: Subject):
98
        raise NotImplementedError
99
100
    def add_transform_to_subject_history(self, subject):
101
        from .augmentation import RandomTransform
102
        from . import Compose, OneOf, CropOrPad
103
        call_others = (
104
            RandomTransform,
105
            Compose,
106
            OneOf,
107
            CropOrPad,
108
        )
109
        if not isinstance(self, call_others):
110
            subject.add_transform(self, self.get_arguments())
111
112
    @staticmethod
113
    def to_range(n, around):
114
        if around is None:
115
            return 0, n
116
        else:
117
            return around - n, around + n
118
119
    def parse_params(self, params, around, name, make_ranges=True, **kwargs):
120
        params = to_tuple(params)
121
        if len(params) == 1 or (len(params) == 2 and make_ranges):  # d or (a, b)
122
            params *= 3  # (d, d, d) or (a, b, a, b, a, b)
123
        if len(params) == 3 and make_ranges:  # (a, b, c)
124
            items = [self.to_range(n, around) for n in params]
125
            # (-a, a, -b, b, -c, c) or (1-a, 1+a, 1-b, 1+b, 1-c, 1+c)
126
            params = [n for prange in items for n in prange]
127
        if make_ranges and len(params) != 6:
128
            if len(params) != 6:
129
                message = (
130
                    f'If "{name}" is a sequence, it must have length 2, 3 or 6,'
131
                    f' not {len(params)}'
132
                )
133
                raise ValueError(message)
134
            for param_range in zip(params[::2], params[1::2]):
135
                self.parse_range(param_range, name, **kwargs)
136
        return tuple(params)
137
138
    @staticmethod
139
    def parse_range(
140
            nums_range: Union[TypeNumber, Tuple[TypeNumber, TypeNumber]],
141
            name: str,
142
            min_constraint: TypeNumber = None,
143
            max_constraint: TypeNumber = None,
144
            type_constraint: type = None,
145
            ) -> Tuple[TypeNumber, TypeNumber]:
146
        r"""Adapted from ``torchvision.transforms.RandomRotation``.
147
148
        Args:
149
            nums_range: Tuple of two numbers :math:`(n_{min}, n_{max})`,
150
                where :math:`n_{min} \leq n_{max}`.
151
                If a single positive number :math:`n` is provided,
152
                :math:`n_{min} = -n` and :math:`n_{max} = n`.
153
            name: Name of the parameter, so that an informative error message
154
                can be printed.
155
            min_constraint: Minimal value that :math:`n_{min}` can take,
156
                default is None, i.e. there is no minimal value.
157
            max_constraint: Maximal value that :math:`n_{max}` can take,
158
                default is None, i.e. there is no maximal value.
159
            type_constraint: Precise type that :math:`n_{max}` and
160
                :math:`n_{min}` must take.
161
162
        Returns:
163
            A tuple of two numbers :math:`(n_{min}, n_{max})`.
164
165
        Raises:
166
            ValueError: if :attr:`nums_range` is negative
167
            ValueError: if :math:`n_{max}` or :math:`n_{min}` is not a number
168
            ValueError: if :math:`n_{max} \lt n_{min}`
169
            ValueError: if :attr:`min_constraint` is not None and
170
                :math:`n_{min}` is smaller than :attr:`min_constraint`
171
            ValueError: if :attr:`max_constraint` is not None and
172
                :math:`n_{max}` is greater than :attr:`max_constraint`
173
            ValueError: if :attr:`type_constraint` is not None and
174
                :math:`n_{max}` and :math:`n_{max}` are not of type
175
                :attr:`type_constraint`.
176
        """
177
        if isinstance(nums_range, numbers.Number):  # single number given
178
            if nums_range < 0:
179
                raise ValueError(
180
                    f'If {name} is a single number,'
181
                    f' it must be positive, not {nums_range}')
182
            if min_constraint is not None and nums_range < min_constraint:
183
                raise ValueError(
184
                    f'If {name} is a single number, it must be greater'
185
                    f' than {min_constraint}, not {nums_range}'
186
                )
187
            if max_constraint is not None and nums_range > max_constraint:
188
                raise ValueError(
189
                    f'If {name} is a single number, it must be smaller'
190
                    f' than {max_constraint}, not {nums_range}'
191
                )
192
            if type_constraint is not None:
193
                if not isinstance(nums_range, type_constraint):
194
                    raise ValueError(
195
                        f'If {name} is a single number, it must be of'
196
                        f' type {type_constraint}, not {nums_range}'
197
                    )
198
            min_range = -nums_range if min_constraint is None else nums_range
199
            return (min_range, nums_range)
200
201
        try:
202
            min_value, max_value = nums_range
203
        except (TypeError, ValueError):
204
            raise ValueError(
205
                f'If {name} is not a single number, it must be'
206
                f' a sequence of len 2, not {nums_range}'
207
            )
208
209
        min_is_number = isinstance(min_value, numbers.Number)
210
        max_is_number = isinstance(max_value, numbers.Number)
211
        if not min_is_number or not max_is_number:
212
            message = (
213
                f'{name} values must be numbers, not {nums_range}')
214
            raise ValueError(message)
215
216
        if min_value > max_value:
217
            raise ValueError(
218
                f'If {name} is a sequence, the second value must be'
219
                f' equal or greater than the first, but it is {nums_range}')
220
221
        if min_constraint is not None and min_value < min_constraint:
222
            raise ValueError(
223
                f'If {name} is a sequence, the first value must be greater'
224
                f' than {min_constraint}, but it is {min_value}'
225
            )
226
227
        if max_constraint is not None and max_value > max_constraint:
228
            raise ValueError(
229
                f'If {name} is a sequence, the second value must be smaller'
230
                f' than {max_constraint}, but it is {max_value}'
231
            )
232
233
        if type_constraint is not None:
234
            min_type_ok = isinstance(min_value, type_constraint)
235
            max_type_ok = isinstance(max_value, type_constraint)
236
            if not min_type_ok or not max_type_ok:
237
                raise ValueError(
238
                    f'If "{name}" is a sequence, its values must be of'
239
                    f' type "{type_constraint}", not "{type(nums_range)}"'
240
                )
241
        return nums_range
242
243
    @staticmethod
244
    def parse_interpolation(interpolation: str) -> str:
245
        interpolation = interpolation.lower()
246
        is_string = isinstance(interpolation, str)
247
        supported_values = [key.name.lower() for key in Interpolation]
248
        is_supported = interpolation.lower() in supported_values
249
        if is_string and is_supported:
250
            return interpolation
251
        message = (
252
            f'Interpolation "{interpolation}" of type {type(interpolation)}'
253
            f' must be a string among the supported values: {supported_values}'
254
        )
255
        raise TypeError(message)
256
257
    @staticmethod
258
    def parse_probability(probability: float) -> float:
259
        is_number = isinstance(probability, numbers.Number)
260
        if not (is_number and 0 <= probability <= 1):
261
            message = (
262
                'Probability must be a number in [0, 1],'
263
                f' not {probability}'
264
            )
265
            raise ValueError(message)
266
        return probability
267
268
    @staticmethod
269
    def nib_to_sitk(data: TypeData, affine: TypeData) -> sitk.Image:
270
        return nib_to_sitk(data, affine)
271
272
    @staticmethod
273
    def sitk_to_nib(image: sitk.Image) -> Tuple[torch.Tensor, np.ndarray]:
274
        return sitk_to_nib(image)
275
276
    @property
277
    def name(self):
278
        return self.__class__.__name__
279
280
    def get_arguments(self):
281
        """
282
        Return a dictionary with the arguments that would be necessary to
283
        reproduce the transform exactly.
284
        """
285
        return {name: getattr(self, name) for name in self.args_names}
286
287
    def is_invertible(self):
288
        return hasattr(self, 'invert_transform')
289
290
    def inverse(self):
291
        if not self.is_invertible():
292
            raise RuntimeError(f'{self.name} is not invertible')
293
        new = copy.deepcopy(self)
294
        new.invert_transform = not self.invert_transform
295
        return new
296
297
298
class DataToSubject:
299
    def __init__(
300
            self,
301
            data: TypeTransformInput,
302
            keys: Optional[List[str]] = None,
303
            ):
304
        self.data = data
305
        self.keys = keys
306
        self.default_image_name = 'default_image_name'
307
        self.is_tensor = False
308
        self.is_array = False
309
        self.is_dict = False
310
        self.is_image = False
311
        self.is_sitk = False
312
        self.is_nib = False
313
314
    def get_subject(self):
315
        if isinstance(self.data, nib.Nifti1Image):
316
            tensor = self.data.get_fdata(dtype=np.float32)
317
            data = ScalarImage(tensor=tensor, affine=self.data.affine)
318
            subject = self._get_subject_from_image(data)
319
            self.is_nib = True
320
        elif isinstance(self.data, (np.ndarray, torch.Tensor)):
321
            subject = self._parse_tensor(self.data)
322
            self.is_array = isinstance(self.data, np.ndarray)
323
            self.is_tensor = True
324
        elif isinstance(self.data, Image):
325
            subject = self._get_subject_from_image(self.data)
326
            self.is_image = True
327
        elif isinstance(self.data, Subject):
328
            subject = self.data
329
        elif isinstance(self.data, sitk.Image):
330
            subject = self._get_subject_from_sitk_image(self.data)
331
            self.is_sitk = True
332
        elif isinstance(self.data, dict):  # e.g. Eisen or MONAI dicts
333
            if self.keys is None:
334
                message = (
335
                    'If input is a dictionary, a value for "keys" must be'
336
                    ' specified when instantiating the transform'
337
                )
338
                raise RuntimeError(message)
339
            subject = self._get_subject_from_dict(self.data, self.keys)
340
            self.is_dict = True
341
        else:
342
            raise ValueError(f'Input type not recognized: {type(self.data)}')
343
        self._parse_subject(subject)
344
        return subject
345
346
    def get_output(self, transformed):
347
        if self.is_tensor or self.is_sitk:
348
            image = transformed[self.default_image_name]
349
            transformed = image[DATA]
350
            if self.is_array:
351
                transformed = transformed.numpy()
352
            elif self.is_sitk:
353
                transformed = nib_to_sitk(image[DATA], image[AFFINE])
354
        elif self.is_image:
355
            transformed = transformed[self.default_image_name]
356
        elif self.is_dict:
357
            transformed = dict(transformed)
358
            for key, value in transformed.items():
359
                if isinstance(value, Image):
360
                    transformed[key] = value.data
361
        elif self.is_nib:
362
            image = transformed[self.default_image_name]
363
            data = image[DATA]
364
            if len(data) > 1:
365
                message = (
366
                    'Multichannel images not supported for input of type'
367
                    ' nibabel.nifti.Nifti1Image'
368
                )
369
                raise RuntimeError(message)
370
            transformed = nib.Nifti1Image(data[0].numpy(), image[AFFINE])
371
        return transformed
372
373
    @staticmethod
374
    def _parse_subject(subject: Subject) -> None:
375
        if not isinstance(subject, Subject):
376
            message = (
377
                'Input to a transform must be a tensor or an instance'
378
                f' of torchio.Subject, not "{type(subject)}"'
379
            )
380
            raise RuntimeError(message)
381
382
    def _parse_tensor(self, data: TypeData) -> Subject:
383
        if data.ndim != 4:
384
            message = (
385
                'The input must be a 4D tensor with dimensions'
386
                f' (channels, x, y, z) but it has shape {tuple(data.shape)}'
387
            )
388
            raise ValueError(message)
389
        return self._get_subject_from_tensor(data)
390
391
    def _get_subject_from_tensor(self, tensor: torch.Tensor) -> Subject:
392
        image = ScalarImage(tensor=tensor)
393
        return self._get_subject_from_image(image)
394
395
    def _get_subject_from_image(self, image: Image) -> Subject:
396
        subject = Subject({self.default_image_name: image})
397
        return subject
398
399
    @staticmethod
400
    def _get_subject_from_dict(
401
            data: dict,
402
            image_keys: List[str],
403
            ) -> Subject:
404
        subject_dict = {}
405
        for key, value in data.items():
406
            if key in image_keys:
407
                value = ScalarImage(tensor=value)
408
            subject_dict[key] = value
409
        return Subject(subject_dict)
410
411
    def _get_subject_from_sitk_image(self, image):
412
        tensor, affine = sitk_to_nib(image)
413
        image = ScalarImage(tensor=tensor, affine=affine)
414
        return self._get_subject_from_image(image)
415