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

torchio.transforms.transform   F

Complexity

Total Complexity 85

Size/Duplication

Total Lines 409
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 263
dl 0
loc 409
rs 2
c 0
b 0
f 0
wmc 85

24 Methods

Rating   Name   Duplication   Size   Complexity  
A Transform.parse_probability() 0 10 3
F Transform.parse_range() 0 104 21
A Transform.sitk_to_nib() 0 3 1
A Transform.to_range() 0 6 2
A Transform.add_transform_to_subject_history() 0 5 2
A Transform.__init__() 0 9 1
A Transform.parse_interpolation() 0 13 3
C Transform.parse_params() 0 18 10
A Transform.__call__() 0 35 5
A Transform.nib_to_sitk() 0 3 1
A Transform.name() 0 3 1
A Transform.apply_transform() 0 3 1
A DataToSubject._get_subject_from_tensor() 0 3 1
A DataToSubject._get_subject_from_sitk_image() 0 4 1
A DataToSubject._parse_subject() 0 8 2
A DataToSubject._get_subject_from_image() 0 3 1
A DataToSubject.__init__() 0 14 1
A Transform.get_arguments() 0 6 1
C DataToSubject.get_output() 0 26 11
A DataToSubject._parse_tensor() 0 8 2
A DataToSubject._get_subject_from_dict() 0 11 3
A Transform.inverse() 0 6 2
B DataToSubject.get_subject() 0 31 8
A Transform.is_invertible() 0 2 1

How to fix   Complexity   

Complexity

Complex classes like torchio.transforms.transform often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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 .augmentation.composition import Compose, OneOf
103
        if not isinstance(self, (RandomTransform, Compose, OneOf)):
104
            subject.add_transform(self, self.get_arguments())
105
106
    @staticmethod
107
    def to_range(n, around):
108
        if around is None:
109
            return 0, n
110
        else:
111
            return around - n, around + n
112
113
    def parse_params(self, params, around, name, make_ranges=True, **kwargs):
114
        params = to_tuple(params)
115
        if len(params) == 1 or (len(params) == 2 and make_ranges):  # d or (a, b)
116
            params *= 3  # (d, d, d) or (a, b, a, b, a, b)
117
        if len(params) == 3 and make_ranges:  # (a, b, c)
118
            items = [self.to_range(n, around) for n in params]
119
            # (-a, a, -b, b, -c, c) or (1-a, 1+a, 1-b, 1+b, 1-c, 1+c)
120
            params = [n for prange in items for n in prange]
121
        if make_ranges and len(params) != 6:
122
            if len(params) != 6:
123
                message = (
124
                    f'If "{name}" is a sequence, it must have length 2, 3 or 6,'
125
                    f' not {len(params)}'
126
                )
127
                raise ValueError(message)
128
            for param_range in zip(params[::2], params[1::2]):
129
                self.parse_range(param_range, name, **kwargs)
130
        return tuple(params)
131
132
    @staticmethod
133
    def parse_range(
134
            nums_range: Union[TypeNumber, Tuple[TypeNumber, TypeNumber]],
135
            name: str,
136
            min_constraint: TypeNumber = None,
137
            max_constraint: TypeNumber = None,
138
            type_constraint: type = None,
139
            ) -> Tuple[TypeNumber, TypeNumber]:
140
        r"""Adapted from ``torchvision.transforms.RandomRotation``.
141
142
        Args:
143
            nums_range: Tuple of two numbers :math:`(n_{min}, n_{max})`,
144
                where :math:`n_{min} \leq n_{max}`.
145
                If a single positive number :math:`n` is provided,
146
                :math:`n_{min} = -n` and :math:`n_{max} = n`.
147
            name: Name of the parameter, so that an informative error message
148
                can be printed.
149
            min_constraint: Minimal value that :math:`n_{min}` can take,
150
                default is None, i.e. there is no minimal value.
151
            max_constraint: Maximal value that :math:`n_{max}` can take,
152
                default is None, i.e. there is no maximal value.
153
            type_constraint: Precise type that :math:`n_{max}` and
154
                :math:`n_{min}` must take.
155
156
        Returns:
157
            A tuple of two numbers :math:`(n_{min}, n_{max})`.
158
159
        Raises:
160
            ValueError: if :attr:`nums_range` is negative
161
            ValueError: if :math:`n_{max}` or :math:`n_{min}` is not a number
162
            ValueError: if :math:`n_{max} \lt n_{min}`
163
            ValueError: if :attr:`min_constraint` is not None and
164
                :math:`n_{min}` is smaller than :attr:`min_constraint`
165
            ValueError: if :attr:`max_constraint` is not None and
166
                :math:`n_{max}` is greater than :attr:`max_constraint`
167
            ValueError: if :attr:`type_constraint` is not None and
168
                :math:`n_{max}` and :math:`n_{max}` are not of type
169
                :attr:`type_constraint`.
170
        """
171
        if isinstance(nums_range, numbers.Number):  # single number given
172
            if nums_range < 0:
173
                raise ValueError(
174
                    f'If {name} is a single number,'
175
                    f' it must be positive, not {nums_range}')
176
            if min_constraint is not None and nums_range < min_constraint:
177
                raise ValueError(
178
                    f'If {name} is a single number, it must be greater'
179
                    f' than {min_constraint}, not {nums_range}'
180
                )
181
            if max_constraint is not None and nums_range > max_constraint:
182
                raise ValueError(
183
                    f'If {name} is a single number, it must be smaller'
184
                    f' than {max_constraint}, not {nums_range}'
185
                )
186
            if type_constraint is not None:
187
                if not isinstance(nums_range, type_constraint):
188
                    raise ValueError(
189
                        f'If {name} is a single number, it must be of'
190
                        f' type {type_constraint}, not {nums_range}'
191
                    )
192
            min_range = -nums_range if min_constraint is None else nums_range
193
            return (min_range, nums_range)
194
195
        try:
196
            min_value, max_value = nums_range
197
        except (TypeError, ValueError):
198
            raise ValueError(
199
                f'If {name} is not a single number, it must be'
200
                f' a sequence of len 2, not {nums_range}'
201
            )
202
203
        min_is_number = isinstance(min_value, numbers.Number)
204
        max_is_number = isinstance(max_value, numbers.Number)
205
        if not min_is_number or not max_is_number:
206
            message = (
207
                f'{name} values must be numbers, not {nums_range}')
208
            raise ValueError(message)
209
210
        if min_value > max_value:
211
            raise ValueError(
212
                f'If {name} is a sequence, the second value must be'
213
                f' equal or greater than the first, but it is {nums_range}')
214
215
        if min_constraint is not None and min_value < min_constraint:
216
            raise ValueError(
217
                f'If {name} is a sequence, the first value must be greater'
218
                f' than {min_constraint}, but it is {min_value}'
219
            )
220
221
        if max_constraint is not None and max_value > max_constraint:
222
            raise ValueError(
223
                f'If {name} is a sequence, the second value must be smaller'
224
                f' than {max_constraint}, but it is {max_value}'
225
            )
226
227
        if type_constraint is not None:
228
            min_type_ok = isinstance(min_value, type_constraint)
229
            max_type_ok = isinstance(max_value, type_constraint)
230
            if not min_type_ok or not max_type_ok:
231
                raise ValueError(
232
                    f'If "{name}" is a sequence, its values must be of'
233
                    f' type "{type_constraint}", not "{type(nums_range)}"'
234
                )
235
        return nums_range
236
237
    @staticmethod
238
    def parse_interpolation(interpolation: str) -> str:
239
        interpolation = interpolation.lower()
240
        is_string = isinstance(interpolation, str)
241
        supported_values = [key.name.lower() for key in Interpolation]
242
        is_supported = interpolation.lower() in supported_values
243
        if is_string and is_supported:
244
            return interpolation
245
        message = (
246
            f'Interpolation "{interpolation}" of type {type(interpolation)}'
247
            f' must be a string among the supported values: {supported_values}'
248
        )
249
        raise TypeError(message)
250
251
    @staticmethod
252
    def parse_probability(probability: float) -> float:
253
        is_number = isinstance(probability, numbers.Number)
254
        if not (is_number and 0 <= probability <= 1):
255
            message = (
256
                'Probability must be a number in [0, 1],'
257
                f' not {probability}'
258
            )
259
            raise ValueError(message)
260
        return probability
261
262
    @staticmethod
263
    def nib_to_sitk(data: TypeData, affine: TypeData) -> sitk.Image:
264
        return nib_to_sitk(data, affine)
265
266
    @staticmethod
267
    def sitk_to_nib(image: sitk.Image) -> Tuple[torch.Tensor, np.ndarray]:
268
        return sitk_to_nib(image)
269
270
    @property
271
    def name(self):
272
        return self.__class__.__name__
273
274
    def get_arguments(self):
275
        """
276
        Return a dictionary with the arguments that would be necessary to
277
        reproduce the transform exactly.
278
        """
279
        return {name: getattr(self, name) for name in self.args_names}
280
281
    def is_invertible(self):
282
        return hasattr(self, 'invert_transform')
283
284
    def inverse(self):
285
        if not self.is_invertible():
286
            raise RuntimeError(f'{self.name} is not invertible')
287
        new = copy.deepcopy(self)
288
        new.invert_transform = not self.invert_transform
289
        return new
290
291
292
class DataToSubject:
293
    def __init__(
294
            self,
295
            data: TypeTransformInput,
296
            keys: Optional[List[str]] = None,
297
            ):
298
        self.data = data
299
        self.keys = keys
300
        self.default_image_name = 'default_image_name'
301
        self.is_tensor = False
302
        self.is_array = False
303
        self.is_dict = False
304
        self.is_image = False
305
        self.is_sitk = False
306
        self.is_nib = False
307
308
    def get_subject(self):
309
        if isinstance(self.data, nib.Nifti1Image):
310
            tensor = self.data.get_fdata(dtype=np.float32)
311
            data = ScalarImage(tensor=tensor, affine=self.data.affine)
312
            subject = self._get_subject_from_image(data)
313
            self.is_nib = True
314
        elif isinstance(self.data, (np.ndarray, torch.Tensor)):
315
            subject = self._parse_tensor(self.data)
316
            self.is_array = isinstance(self.data, np.ndarray)
317
            self.is_tensor = True
318
        elif isinstance(self.data, Image):
319
            subject = self._get_subject_from_image(self.data)
320
            self.is_image = True
321
        elif isinstance(self.data, Subject):
322
            subject = self.data
323
        elif isinstance(self.data, sitk.Image):
324
            subject = self._get_subject_from_sitk_image(self.data)
325
            self.is_sitk = True
326
        elif isinstance(self.data, dict):  # e.g. Eisen or MONAI dicts
327
            if self.keys is None:
328
                message = (
329
                    'If input is a dictionary, a value for "keys" must be'
330
                    ' specified when instantiating the transform'
331
                )
332
                raise RuntimeError(message)
333
            subject = self._get_subject_from_dict(self.data, self.keys)
334
            self.is_dict = True
335
        else:
336
            raise ValueError(f'Input type not recognized: {type(self.data)}')
337
        self._parse_subject(subject)
338
        return subject
339
340
    def get_output(self, transformed):
341
        if self.is_tensor or self.is_sitk:
342
            image = transformed[self.default_image_name]
343
            transformed = image[DATA]
344
            if self.is_array:
345
                transformed = transformed.numpy()
346
            elif self.is_sitk:
347
                transformed = nib_to_sitk(image[DATA], image[AFFINE])
348
        elif self.is_image:
349
            transformed = transformed[self.default_image_name]
350
        elif self.is_dict:
351
            transformed = dict(transformed)
352
            for key, value in transformed.items():
353
                if isinstance(value, Image):
354
                    transformed[key] = value.data
355
        elif self.is_nib:
356
            image = transformed[self.default_image_name]
357
            data = image[DATA]
358
            if len(data) > 1:
359
                message = (
360
                    'Multichannel images not supported for input of type'
361
                    ' nibabel.nifti.Nifti1Image'
362
                )
363
                raise RuntimeError(message)
364
            transformed = nib.Nifti1Image(data[0].numpy(), image[AFFINE])
365
        return transformed
366
367
    @staticmethod
368
    def _parse_subject(subject: Subject) -> None:
369
        if not isinstance(subject, Subject):
370
            message = (
371
                'Input to a transform must be a tensor or an instance'
372
                f' of torchio.Subject, not "{type(subject)}"'
373
            )
374
            raise RuntimeError(message)
375
376
    def _parse_tensor(self, data: TypeData) -> Subject:
377
        if data.ndim != 4:
378
            message = (
379
                'The input must be a 4D tensor with dimensions'
380
                f' (channels, x, y, z) but it has shape {tuple(data.shape)}'
381
            )
382
            raise ValueError(message)
383
        return self._get_subject_from_tensor(data)
384
385
    def _get_subject_from_tensor(self, tensor: torch.Tensor) -> Subject:
386
        image = ScalarImage(tensor=tensor)
387
        return self._get_subject_from_image(image)
388
389
    def _get_subject_from_image(self, image: Image) -> Subject:
390
        subject = Subject({self.default_image_name: image})
391
        return subject
392
393
    @staticmethod
394
    def _get_subject_from_dict(
395
            data: dict,
396
            image_keys: List[str],
397
            ) -> Subject:
398
        subject_dict = {}
399
        for key, value in data.items():
400
            if key in image_keys:
401
                value = ScalarImage(tensor=value)
402
            subject_dict[key] = value
403
        return Subject(subject_dict)
404
405
    def _get_subject_from_sitk_image(self, image):
406
        tensor, affine = sitk_to_nib(image)
407
        image = ScalarImage(tensor=tensor, affine=affine)
408
        return self._get_subject_from_image(image)
409