Passed
Pull Request — master (#207)
by Fernando
01:18
created

  A

Complexity

Conditions 4

Size

Total Lines 12
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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