Passed
Pull Request — master (#417)
by Fernando
01:22
created

Subject.get_applied_transforms()   A

Complexity

Conditions 4

Size

Total Lines 17
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 15
nop 2
dl 0
loc 17
rs 9.65
c 0
b 0
f 0
1
import copy
2
import pprint
3
from typing import Any, Dict, List, Tuple, Optional, Sequence, TYPE_CHECKING
4
5
import numpy as np
6
7
from ..constants import TYPE, INTENSITY
8
from .image import Image
9
from ..utils import get_subclasses
10
11
if TYPE_CHECKING:
12
    from ..transforms import Transform, Compose
13
14
15
class Subject(dict):
16
    """Class to store information about the images corresponding to a subject.
17
18
    Args:
19
        *args: If provided, a dictionary of items.
20
        **kwargs: Items that will be added to the subject sample.
21
22
    Example:
23
24
        >>> import torchio as tio
25
        >>> # One way:
26
        >>> subject = tio.Subject(
27
        ...     one_image=tio.ScalarImage('path_to_image.nii.gz'),
28
        ...     a_segmentation=tio.LabelMap('path_to_seg.nii.gz'),
29
        ...     age=45,
30
        ...     name='John Doe',
31
        ...     hospital='Hospital Juan Negrín',
32
        ... )
33
        >>> # If you want to create the mapping before, or have spaces in the keys:
34
        >>> subject_dict = {
35
        ...     'one image': tio.ScalarImage('path_to_image.nii.gz'),
36
        ...     'a segmentation': tio.LabelMap('path_to_seg.nii.gz'),
37
        ...     'age': 45,
38
        ...     'name': 'John Doe',
39
        ...     'hospital': 'Hospital Juan Negrín',
40
        ... }
41
        >>> subject = tio.Subject(subject_dict)
42
43
    """
44
45
    def __init__(self, *args, **kwargs: Dict[str, Any]):
46
        if args:
47
            if len(args) == 1 and isinstance(args[0], dict):
48
                kwargs.update(args[0])
49
            else:
50
                message = (
51
                    'Only one dictionary as positional argument is allowed')
52
                raise ValueError(message)
53
        super().__init__(**kwargs)
54
        self._parse_images(self.get_images(intensity_only=False))
55
        self.update_attributes()  # this allows me to do e.g. subject.t1
56
        self.applied_transforms = []
57
58
    def __repr__(self):
59
        num_images = len(self.get_images(intensity_only=False))
60
        string = (
61
            f'{self.__class__.__name__}'
62
            f'(Keys: {tuple(self.keys())}; images: {num_images})'
63
        )
64
        return string
65
66
    def __copy__(self):
67
        result_dict = {}
68
        for key, value in self.items():
69
            if isinstance(value, Image):
70
                value = copy.copy(value)
71
            else:
72
                value = copy.deepcopy(value)
73
            result_dict[key] = value
74
        new = Subject(result_dict)
75
        new.applied_transforms = self.applied_transforms[:]
76
        return new
77
78
    def __len__(self):
79
        return len(self.get_images(intensity_only=False))
80
81
    @staticmethod
82
    def _parse_images(images: List[Tuple[str, Image]]) -> None:
83
        # Check that it's not empty
84
        if not images:
85
            raise ValueError('A subject without images cannot be created')
86
87
    @property
88
    def shape(self):
89
        """Return shape of first image in subject.
90
91
        Consistency of shapes across images in the subject is checked first.
92
        """
93
        self.check_consistent_attribute('shape')
94
        return self.get_first_image().shape
95
96
    @property
97
    def spatial_shape(self):
98
        """Return spatial shape of first image in subject.
99
100
        Consistency of spatial shapes across images in the subject is checked
101
        first.
102
        """
103
        self.check_consistent_spatial_shape()
104
        return self.get_first_image().spatial_shape
105
106
    @property
107
    def spacing(self):
108
        """Return spacing of first image in subject.
109
110
        Consistency of spacings across images in the subject is checked first.
111
        """
112
        self.check_consistent_attribute('spacing')
113
        return self.get_first_image().spacing
114
115
    @property
116
    def history(self):
117
        # Kept for backwards compatibility
118
        return self.get_applied_transforms()
119
120
    def get_applied_transforms(
121
            self,
122
            ignore_intensity: bool = False,
123
            ) -> List['Transform']:
124
        from ..transforms.transform import Transform
125
        from ..transforms.intensity_transform import IntensityTransform
126
        name_to_transform = {
127
            cls.__name__: cls
128
            for cls in get_subclasses(Transform)
129
        }
130
        transforms_list = []
131
        for transform_name, arguments in self.applied_transforms:
132
            transform = name_to_transform[transform_name](**arguments)
133
            if ignore_intensity and isinstance(transform, IntensityTransform):
134
                continue
135
            transforms_list.append(transform)
136
        return transforms_list
137
138
    def get_composed_history(
139
            self,
140
            ignore_intensity: bool = False,
141
            ) -> 'Compose':
142
        from ..transforms.augmentation.composition import Compose
143
        transforms = self.get_applied_transforms(
144
            ignore_intensity=ignore_intensity)
145
        return Compose(transforms)
146
147
    def get_inverse_transform(
148
            self,
149
            warn: bool = True,
150
            ignore_intensity: bool = True,
151
            ) ->  'Compose':
152
        """Get a reversed list of the inverses of the applied transforms.
153
154
        Args:
155
            warn: Issue a warning if some transforms are not invertible.
156
            ignore_intensity: If ``True``, all instances of
157
                :class:`~torchio.transforms.intensity_transform.IntensityTransform`
158
                will be ignored.
159
        """
160
        history_transform = self.get_composed_history(
161
            ignore_intensity=ignore_intensity)
162
        inverse_transform = history_transform.inverse(warn=warn)
163
        return inverse_transform
164
165
    def apply_inverse_transform(self, **kwargs) -> 'Subject':
166
        """Try to apply the inverse of all applied transforms, in reverse order.
167
168
        Args:
169
            **kwargs: Keyword arguments passed on to
170
                :meth:`~torchio.data.subject.Subject.get_inverse_transform`.
171
        """
172
        inverse_transform = self.get_inverse_transform(**kwargs)
173
        transformed = inverse_transform(self)
174
        transformed.clear_history()
175
        return transformed
176
177
    def clear_history(self) -> None:
178
        self.applied_transforms = []
179
180
    def check_consistent_attribute(self, attribute: str) -> None:
181
        values_dict = {}
182
        iterable = self.get_images_dict(intensity_only=False).items()
183
        for image_name, image in iterable:
184
            values_dict[image_name] = getattr(image, attribute)
185
        num_unique_values = len(set(values_dict.values()))
186
        if num_unique_values > 1:
187
            message = (
188
                f'More than one {attribute} found in subject images:'
189
                f'\n{pprint.pformat(values_dict)}'
190
            )
191
            raise RuntimeError(message)
192
193
    def check_consistent_spatial_shape(self) -> None:
194
        self.check_consistent_attribute('spatial_shape')
195
196
    def check_consistent_orientation(self) -> None:
197
        self.check_consistent_attribute('orientation')
198
199
    def check_consistent_affine(self):
200
        # https://github.com/fepegar/torchio/issues/354
201
        affine = None
202
        first_image = None
203
        iterable = self.get_images_dict(intensity_only=False).items()
204
        for image_name, image in iterable:
205
            if affine is None:
206
                affine = image.affine
207
                first_image = image_name
208
            elif not np.allclose(affine, image.affine, rtol=1e-6, atol=1e-6):
209
                message = (
210
                    f'Images "{first_image}" and "{image_name}" do not occupy'
211
                    ' the same physical space.'
212
                    f'\nAffine of "{first_image}":'
213
                    f'\n{pprint.pformat(affine)}'
214
                    f'\nAffine of "{image_name}":'
215
                    f'\n{pprint.pformat(image.affine)}'
216
                )
217
                raise RuntimeError(message)
218
219
    def check_consistent_space(self):
220
        self.check_consistent_spatial_shape()
221
        self.check_consistent_affine()
222
223
    def get_images_dict(
224
            self,
225
            intensity_only=True,
226
            include: Optional[Sequence[str]] = None,
227
            exclude: Optional[Sequence[str]] = None,
228
            ) -> Dict[str, Image]:
229
        images = {}
230
        for image_name, image in self.items():
231
            if not isinstance(image, Image):
232
                continue
233
            if intensity_only and not image[TYPE] == INTENSITY:
234
                continue
235
            if include is not None and image_name not in include:
236
                continue
237
            if exclude is not None and image_name in exclude:
238
                continue
239
            images[image_name] = image
240
        return images
241
242
    def get_images(
243
            self,
244
            intensity_only=True,
245
            include: Optional[Sequence[str]] = None,
246
            exclude: Optional[Sequence[str]] = None,
247
            ) -> List[Image]:
248
        images_dict = self.get_images_dict(intensity_only=intensity_only, include=include, exclude=exclude)
249
        return list(images_dict.values())
250
251
    def get_first_image(self) -> Image:
252
        return self.get_images(intensity_only=False)[0]
253
254
    # flake8: noqa: F821
255
    def add_transform(
256
            self,
257
            transform: 'Transform',
258
            parameters_dict: dict,
259
            ) -> None:
260
        self.applied_transforms.append((transform.name, parameters_dict))
261
262
    def load(self) -> None:
263
        """Load images in subject."""
264
        for image in self.get_images(intensity_only=False):
265
            image.load()
266
267
    def update_attributes(self) -> None:
268
        # This allows to get images using attribute notation, e.g. subject.t1
269
        self.__dict__.update(self)
270
271
    def add_image(self, image: Image, image_name: str) -> None:
272
        """Add an image."""
273
        self[image_name] = image
274
        self.update_attributes()
275
276
    def remove_image(self, image_name: str) -> None:
277
        """Remove an image."""
278
        del self[image_name]
279
280
    def plot(self, **kwargs) -> None:
281
        """Plot images."""
282
        from ..visualization import plot_subject  # avoid circular import
283
        plot_subject(self, **kwargs)
284