Passed
Pull Request — master (#246)
by Fernando
01:10
created

RandomGhosting.add_artifact()   C

Complexity

Conditions 9

Size

Total Lines 43
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 33
nop 6
dl 0
loc 43
rs 6.6666
c 0
b 0
f 0
1
from typing import Tuple, Optional, Union
2
import torch
3
import numpy as np
4
from ....torchio import DATA
5
from ....data.subject import Subject
6
from .. import RandomTransform
7
8
9
class RandomGhosting(RandomTransform):
10
    r"""Add random MRI ghosting artifact.
11
12
    Args:
13
        num_ghosts: Number of 'ghosts' :math:`n` in the image.
14
            If :py:attr:`num_ghosts` is a tuple :math:`(a, b)`, then
15
            :math:`n \sim \mathcal{U}(a, b) \cap \mathbb{N}`.
16
            If only one value :math:`d` is provided,
17
            :math:`\n \sim \mathcal{U}(0, d) \cap \mathbb{N}`.
18
        axes: Axis along which the ghosts will be created. If
19
            :py:attr:`axes` is a tuple, the axis will be randomly chosen
20
            from the passed values.
21
        intensity: Positive number representing the artifact strength
22
            :math:`s` with respect to the maximum of the :math:`k`-space.
23
            If ``0``, the ghosts will not be visible. If a tuple
24
            :math:`(a, b)` is provided then :math:`s \sim \mathcal{U}(a, b)`.
25
            If only one value :math:`d` is provided,
26
            :math:`\s \sim \mathcal{U}(0, d)`.
27
        restore: Number between ``0`` and ``1`` indicating how much of the
28
            :math:`k`-space center should be restored after removing the planes
29
            that generate the artifact.
30
        p: Probability that this transform will be applied.
31
        seed: See :py:class:`~torchio.transforms.augmentation.RandomTransform`.
32
33
    .. note:: The execution time of this transform does not depend on the
34
        number of ghosts.
35
    """
36
    def __init__(
37
            self,
38
            num_ghosts: Union[int, Tuple[int, int]] = (4, 10),
39
            axes: Union[int, Tuple[int, ...]] = (0, 1, 2),
40
            intensity: Union[float, Tuple[float, float]] = (0.5, 1),
41
            restore: float = 0.02,
42
            p: float = 1,
43
            seed: Optional[int] = None,
44
            ):
45
        super().__init__(p=p, seed=seed)
46
        if not isinstance(axes, tuple):
47
            try:
48
                axes = tuple(axes)
49
            except TypeError:
50
                axes = (axes,)
51
        for axis in axes:
52
            if axis not in (0, 1, 2):
53
                raise ValueError(f'Axes must be in (0, 1, 2), not "{axes}"')
54
        self.axes = axes
55
        self.num_ghosts_range = self.parse_range(
56
            num_ghosts, 'num_ghosts', min_constraint=0, type_constraint=int)
57
        self.intensity_range = self.parse_range(
58
            intensity, 'intensity_range', min_constraint=0)
59
        self.restore = self.parse_restore(restore)
60
61
    @staticmethod
62
    def parse_restore(restore):
63
        if not isinstance(restore, float):
64
            raise TypeError(f'Restore must be a float, not {restore}')
65
        if not 0 <= restore <= 1:
66
            message = (
67
                f'Restore must be a number between 0 and 1, not {restore}')
68
            raise ValueError(message)
69
        return restore
70
71
    def apply_transform(self, sample: Subject) -> dict:
72
        random_parameters_images_dict = {}
73
        for image_name, image in sample.get_images_dict().items():
74
            transformed_tensors = []
75
            is_2d = image.is_2d()
76
            axes = [a for a in self.axes if a != 0] if is_2d else self.axes
77
            for channel_idx, tensor in enumerate(image[DATA]):
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable DATA does not seem to be defined.
Loading history...
78
                params = self.get_params(
79
                    self.num_ghosts_range,
80
                    axes,
81
                    self.intensity_range,
82
                )
83
                num_ghosts_param, axis_param, intensity_param = params
84
                random_parameters_dict = {
85
                    'axis': axis_param,
86
                    'num_ghosts': num_ghosts_param,
87
                    'intensity': intensity_param,
88
                }
89
                key = f'{image_name}_channel_{channel_idx}'
90
                random_parameters_images_dict[key] = random_parameters_dict
91
                transformed_tensor = self.add_artifact(
92
                    tensor,
93
                    num_ghosts_param,
94
                    axis_param,
95
                    intensity_param,
96
                    self.restore,
97
                )
98
                transformed_tensors.append(transformed_tensor)
99
            image[DATA] = torch.stack(transformed_tensors)
100
        sample.add_transform(self, random_parameters_images_dict)
101
        return sample
102
103
    @staticmethod
104
    def get_params(
105
            num_ghosts_range: Tuple[int, int],
106
            axes: Tuple[int, ...],
107
            intensity_range: Tuple[float, float],
108
            ) -> Tuple:
109
        ng_min, ng_max = num_ghosts_range
110
        num_ghosts = torch.randint(ng_min, ng_max + 1, (1,)).item()
111
        axis = axes[torch.randint(0, len(axes), (1,))]
112
        intensity = torch.FloatTensor(1).uniform_(*intensity_range).item()
113
        return num_ghosts, axis, intensity
114
115
    def add_artifact(
116
            self,
117
            tensor: torch.Tensor,
118
            num_ghosts: int,
119
            axis: int,
120
            intensity: float,
121
            restore_center: float,
122
            ):
123
        if not num_ghosts or not intensity:
124
            return tensor
125
126
        array = tensor.numpy()
127
        spectrum = self.fourier_transform(array)
128
129
        shape = np.array(array.shape)
130
        ri, rj, rk = np.round(restore_center * shape).astype(np.uint16)
131
        mi, mj, mk = np.array(array.shape) // 2
132
133
        # Variable "planes" is the part of the spectrum that will be modified
134
        if axis == 0:
135
            planes = spectrum[::num_ghosts, :, :]
136
            restore = spectrum[mi, :, :].copy()
137
        elif axis == 1:
138
            planes = spectrum[:, ::num_ghosts, :]
139
            restore = spectrum[:, mj, :].copy()
140
        elif axis == 2:
141
            planes = spectrum[:, :, ::num_ghosts]
142
            restore = spectrum[:, :, mk].copy()
143
144
        # Multiply by 0 if intensity is 1
145
        planes *= 1 - intensity
0 ignored issues
show
introduced by
The variable planes does not seem to be defined for all execution paths.
Loading history...
146
147
        # Restore the center of k-space to avoid extreme artifacts
148
        if axis == 0:
149
            spectrum[mi, :, :] = restore
0 ignored issues
show
introduced by
The variable restore does not seem to be defined for all execution paths.
Loading history...
150
        elif axis == 1:
151
            spectrum[:, mj, :] = restore
152
        elif axis == 2:
153
            spectrum[:, :, mk] = restore
154
155
        array_ghosts = self.inv_fourier_transform(spectrum)
156
        array_ghosts = np.real(array_ghosts)
157
        return torch.from_numpy(array_ghosts)
158