Passed
Pull Request — master (#225)
by Fernando
01:17
created

tests.test_utils.TestUtils.get_sample()   A

Complexity

Conditions 2

Size

Total Lines 23
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 19
nop 2
dl 0
loc 23
rs 9.45
c 0
b 0
f 0
1
#!/usr/bin/env python
2
3
"""Tests for `utils` package."""
4
5
import unittest
6
import torch
7
import numpy as np
8
import SimpleITK as sitk
9
from torchio import LABEL, INTENSITY, RandomFlip
10
from torchio.utils import (
11
    to_tuple,
12
    get_stem,
13
    guess_type,
14
    sitk_to_nib,
15
    apply_transform_to_file,
16
)
17
from .utils import TorchioTestCase
18
19
20
class TestUtils(TorchioTestCase):
21
    """Tests for `utils` module."""
22
23
    def test_to_tuple(self):
24
        assert to_tuple(1) == (1,)
25
        assert to_tuple((1,)) == (1,)
26
        assert to_tuple(1, length=3) == (1, 1, 1)
27
        assert to_tuple((1, 2)) == (1, 2)
28
        assert to_tuple((1, 2), length=3) == (1, 2)
29
        assert to_tuple([1, 2], length=3) == (1, 2)
30
31
    def test_get_stem(self):
32
        assert get_stem('/home/image.nii.gz') == 'image'
33
        assert get_stem('/home/image.nii') == 'image'
34
        assert get_stem('/home/image.nrrd') == 'image'
35
36
    def test_guess_type(self):
37
        assert guess_type('None') is None
38
        assert isinstance(guess_type('1'), int)
39
        assert isinstance(guess_type('1.5'), float)
40
        assert isinstance(guess_type('(1, 3, 5)'), tuple)
41
        assert isinstance(guess_type('(1,3,5)'), tuple)
42
        assert isinstance(guess_type('[1,3,5]'), list)
43
        assert isinstance(guess_type('test'), str)
44
45
    def test_check_consistent_shape(self):
46
        good_sample = self.sample
47
        bad_sample = self.get_inconsistent_sample()
48
        good_sample.check_consistent_shape()
49
        with self.assertRaises(ValueError):
50
            bad_sample.check_consistent_shape()
51
52
    def test_apply_transform_to_file(self):
53
        transform = RandomFlip()
54
        apply_transform_to_file(
55
            self.get_image_path('input'),
56
            transform,
57
            self.get_image_path('output'),
58
            verbose=True,
59
        )
60
61
    def test_sitk_to_nib(self):
62
        data = np.random.rand(10, 10)
63
        image = sitk.GetImageFromArray(data)
64
        tensor, affine = sitk_to_nib(image)
65
        self.assertAlmostEqual(data.sum(), tensor.sum())
66