Passed
Pull Request — master (#248)
by Fernando
01:11
created

torchio.data.subject.Subject.__copy__()   A

Complexity

Conditions 3

Size

Total Lines 11
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
nop 1
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
1
import copy
2
import pprint
3
from typing import Any, Dict, List, Tuple
4
from ..torchio import TYPE, INTENSITY
5
from .image import Image
6
7
8
class Subject(dict):
9
    """Class to store information about the images corresponding to a subject.
10
11
    Args:
12
        *args: If provided, a dictionary of items.
13
        **kwargs: Items that will be added to the subject sample.
14
15
    Example:
16
17
        >>> import torchio
18
        >>> from torchio import Image, Subject
19
        >>> # One way:
20
        >>> subject = Subject(
21
        ...     one_image=Image('path_to_image.nii.gz', type=torchio.INTENSITY),
22
        ...     a_segmentation=Image('path_to_seg.nii.gz', type=torchio.LABEL),
23
        ...     age=45,
24
        ...     name='John Doe',
25
        ...     hospital='Hospital Juan Negrín',
26
        ... )
27
        >>> # If you want to create the mapping before, or have spaces in the keys:
28
        >>> subject_dict = {
29
        ...     'one image': Image('path_to_image.nii.gz', type=torchio.INTENSITY),
30
        ...     'a segmentation': Image('path_to_seg.nii.gz', type=torchio.LABEL),
31
        ...     'age': 45,
32
        ...     'name': 'John Doe',
33
        ...     'hospital': 'Hospital Juan Negrín',
34
        ... }
35
        >>> Subject(subject_dict)
36
37
    """
38
39
    def __init__(self, *args, **kwargs: Dict[str, Any]):
40
        if args:
41
            if len(args) == 1 and isinstance(args[0], dict):
42
                kwargs.update(args[0])
43
            else:
44
                message = (
45
                    'Only one dictionary as positional argument is allowed')
46
                raise ValueError(message)
47
        super().__init__(**kwargs)
48
        self.images = [
49
            (k, v) for (k, v) in self.items()
50
            if isinstance(v, Image)
51
        ]
52
        self._parse_images(self.images)
53
        self.update_attributes()  # this allows me to do e.g. subject.t1
54
        self.history = []
55
56
    def __repr__(self):
57
        string = (
58
            f'{self.__class__.__name__}'
59
            f'(Keys: {tuple(self.keys())}; images: {len(self.images)})'
60
        )
61
        return string
62
63
    def __copy__(self):
64
        result_dict = {}
65
        for key, value in self.items():
66
            if isinstance(value, Image):
67
                value = copy.copy(value)
68
            else:
69
                value = copy.deepcopy(value)
70
            result_dict[key] = value
71
        new = Subject(result_dict)
72
        new.history = self.history
73
        return new
74
75
    @staticmethod
76
    def _parse_images(images: List[Tuple[str, Image]]) -> None:
77
        # Check that it's not empty
78
        if not images:
79
            raise ValueError('A subject without images cannot be created')
80
81
    @property
82
    def shape(self):
83
        """Return shape of first image in subject.
84
85
        Consistency of shapes across images in the subject is checked first.
86
        """
87
        self.check_consistent_shape()
88
        image = self.get_images(intensity_only=False)[0]
89
        return image.shape
90
91
    @property
92
    def spatial_shape(self):
93
        """Return spatial shape of first image in subject.
94
95
        Consistency of shapes across images in the subject is checked first.
96
        """
97
        return self.shape[1:]
98
99
    @property
100
    def spacing(self):
101
        """Return spacing of first image in subject.
102
103
        Consistency of shapes across images in the subject is checked first.
104
        """
105
        self.check_consistent_shape()
106
        image = self.get_images(intensity_only=False)[0]
107
        return image.spacing
108
109
    def get_images_dict(self, intensity_only=True):
110
        images = {}
111
        for image_name, image in self.items():
112
            if not isinstance(image, Image):
113
                continue
114
            if intensity_only and not image[TYPE] == INTENSITY:
115
                continue
116
            images[image_name] = image
117
        return images
118
119
    def get_images(self, intensity_only=True):
120
        images_dict = self.get_images_dict(intensity_only=intensity_only)
121
        return list(images_dict.values())
122
123
    def check_consistent_shape(self) -> None:
124
        shapes_dict = {}
125
        iterable = self.get_images_dict(intensity_only=False).items()
126
        for image_name, image in iterable:
127
            shapes_dict[image_name] = image.shape
128
        num_unique_shapes = len(set(shapes_dict.values()))
129
        if num_unique_shapes > 1:
130
            message = (
131
                'Images in sample have inconsistent shapes:'
132
                f'\n{pprint.pformat(shapes_dict)}'
133
            )
134
            raise ValueError(message)
135
136
    def add_transform(
137
            self,
138
            transform: 'Transform',
139
            parameters_dict: dict,
140
            ) -> None:
141
        self.history.append((transform.name, parameters_dict))
142
143
    def load(self):
144
        for image in self.get_images(intensity_only=False):
145
            image._load()
146
147
    def crop(self, index_ini, index_fin):
148
        result_dict = {}
149
        for key, value in self.items():
150
            if isinstance(value, Image):
151
                # patch.clone() is much faster than copy.deepcopy(patch)
152
                value = value.crop(index_ini, index_fin)
153
            else:
154
                value = copy.deepcopy(value)
155
            result_dict[key] = value
156
        new = Subject(result_dict)
157
        new.history = self.history
158
        return new
159
160
    def update_attributes(self):
161
        # This allows to get images using attribute notation, e.g. subject.t1
162
        self.__dict__.update(self)
163
164
    def add_image(self, image, image_name):
165
        self[image_name] = image
166
        self.update_attributes()
167