Passed
Pull Request — master (#520)
by Fernando
01:15
created

torchio.data.sampler.uniform   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 23
dl 0
loc 34
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A UniformSampler.get_probability_map() 0 2 1
A UniformSampler._generate_patches() 0 16 4
1
import torch
2
from ...data.subject import Subject
3
from .sampler import RandomSampler
4
from typing import Generator
5
import numpy as np
6
7
8
class UniformSampler(RandomSampler):
9
    """Randomly extract patches from a volume with uniform probability.
10
11
    Args:
12
        patch_size: See :class:`~torchio.data.PatchSampler`.
13
    """
14
15
    def get_probability_map(self, subject: Subject) -> torch.Tensor:
16
        return torch.ones(1, *subject.spatial_shape)
17
18
    def _generate_patches(
19
            self,
20
            subject: Subject,
21
            num_patches: int = None,
22
            ) -> Generator[Subject, None, None]:
23
        valid_range = subject.spatial_shape - self.patch_size
24
        patches_left = num_patches if num_patches is not None else True
25
        while patches_left:
26
            index_ini = [
27
                torch.randint(x + 1, (1,)).item()
28
                for x in valid_range
29
            ]
30
            index_ini_array = np.asarray(index_ini)
31
            yield self.extract_patch(subject, index_ini_array)
32
            if num_patches is not None:
33
                patches_left -= 1
34