Passed
Push — master ( 98f4df...4133e1 )
by Fernando
01:03
created

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

Complexity

Conditions 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
import pprint
2
from typing import (
3
    Any,
4
    Dict,
5
    List,
6
    Tuple,
7
)
8
from ..torchio import TYPE, INTENSITY
9
from .image import Image
10
11
12
class Subject(dict):
13
    """Class to store information about the images corresponding to a subject.
14
15
    Args:
16
        *args: If provided, a dictionary of items.
17
        **kwargs: Items that will be added to the subject sample.
18
19
    Example:
20
21
        >>> import torchio
22
        >>> from torchio import Image, Subject
23
        >>> # One way:
24
        >>> subject = Subject(
25
        ...     one_image=Image('path_to_image.nii.gz', torchio.INTENSITY),
26
        ...     a_segmentation=Image('path_to_seg.nii.gz', torchio.LABEL),
27
        ...     age=45,
28
        ...     name='John Doe',
29
        ...     hospital='Hospital Juan Negrín',
30
        ... )
31
        >>> # If you want to create the mapping before, or have spaces in the keys:
32
        >>> subject_dict = {
33
        ...     'one image': Image('path_to_image.nii.gz', torchio.INTENSITY),
34
        ...     'a segmentation': Image('path_to_seg.nii.gz', torchio.LABEL),
35
        ...     'age': 45,
36
        ...     'name': 'John Doe',
37
        ...     'hospital': 'Hospital Juan Negrín',
38
        ... }
39
        >>> Subject(subject_dict)
40
41
    """
42
43
    def __init__(self, *args, **kwargs: Dict[str, Any]):
44
        if args:
45
            if len(args) == 1 and isinstance(args[0], dict):
46
                kwargs.update(args[0])
47
            else:
48
                message = (
49
                    'Only one dictionary as positional argument is allowed')
50
                raise ValueError(message)
51
        super().__init__(**kwargs)
52
        self.images = [
53
            (k, v) for (k, v) in self.items()
54
            if isinstance(v, Image)
55
        ]
56
        self._parse_images(self.images)
57
        self.is_sample = False  # set to True by ImagesDataset
58
        self.history = []
59
60
    def __repr__(self):
61
        string = (
62
            f'{self.__class__.__name__}'
63
            f'(Keys: {tuple(self.keys())}; images: {len(self.images)})'
64
        )
65
        return string
66
67
    @staticmethod
68
    def _parse_images(images: List[Tuple[str, Image]]) -> None:
69
        # Check that it's not empty
70
        if not images:
71
            raise ValueError('A subject without images cannot be created')
72
73
    @property
74
    def shape(self):
75
        """Return shape of first image in sample.
76
77
        Consistency of shapes across images in the sample is checked first.
78
        """
79
        self.check_consistent_shape()
80
        image = self.get_images(intensity_only=False)[0]
81
        return image.shape
82
83
    @property
84
    def spatial_shape(self):
85
        """Return spatial shape of first image in sample.
86
87
        Consistency of shapes across images in the sample is checked first.
88
        """
89
        return self.shape[1:]
90
91
    def get_images_dict(self, intensity_only=True):
92
        images = {}
93
        for image_name, image in self.items():
94
            if not isinstance(image, Image):
95
                continue
96
            if intensity_only and not image[TYPE] == INTENSITY:
97
                continue
98
            images[image_name] = image
99
        return images
100
101
    def get_images(self, intensity_only=True):
102
        images_dict = self.get_images_dict(intensity_only=intensity_only)
103
        return list(images_dict.values())
104
105
    def check_consistent_shape(self) -> None:
106
        shapes_dict = {}
107
        iterable = self.get_images_dict(intensity_only=False).items()
108
        for image_name, image in iterable:
109
            shapes_dict[image_name] = image.shape
110
        num_unique_shapes = len(set(shapes_dict.values()))
111
        if num_unique_shapes > 1:
112
            message = (
113
                'Images in sample have inconsistent shapes:'
114
                f'\n{pprint.pformat(shapes_dict)}'
115
            )
116
            raise ValueError(message)
117
118
    def add_transform(
119
            self,
120
            transform: 'Transform',
121
            parameters_dict: dict,
122
            ) -> None:
123
        self.history.append((transform.name, parameters_dict))
124