Passed
Pull Request — main (#656)
by Yunguan
02:58
created

test.unit.test_layer.test_deconv3d_block()   A

Complexity

Conditions 1

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 22
rs 9.75
c 0
b 0
f 0
cc 1
nop 0
1
# coding=utf-8
2
3
"""
4
Tests for deepreg/model/layer
5
"""
6
from typing import Optional
7
8
import numpy as np
9
import pytest
10
import tensorflow as tf
11
12
import deepreg.model.layer as layer
13
14
15
@pytest.mark.parametrize(
16
    ("input_shape", "output_shape", "expected_shape"),
17
    [
18
        ((6, 7, 8), (12, 14, 16), (12, 14, 16)),
19
        ((6, 7, 8), (11, 13, 15), (11, 13, 15)),
20
        ((6, 7, 8), None, (12, 14, 16)),
21
    ],
0 ignored issues
show
introduced by
"input_shape" missing in parameter type documentation
Loading history...
22
)
23
def test_deconv3d(input_shape, output_shape: Optional[tuple], expected_shape: tuple):
24
    """
25
    Test output shapes and configs.
26
27
    :param input_shape: input shape for layer definition
28
    :param output_shape: output shape for layer definition
29
    :param expected_shape: expected output shape
30
    """
31
    batch_size = 5
32
33
    deconv3d = layer.Deconv3d(filters=3, strides=2, output_shape=output_shape)
34
35
    inputs = tf.ones(shape=(batch_size,) + input_shape + (1,))
36
    output = deconv3d(inputs)
37
38
    assert output.shape == (batch_size,) + expected_shape + (3,)
39
40
    config = deconv3d.get_config()
41
    assert config == dict(
42
        filters=3,
43
        output_shape=output_shape,
44
        kernel_size=3,
45
        strides=2,
46
        padding="same",
47
        name="deconv3d",
48
        trainable=True,
49
        dtype="float32",
50
    )
51
52
53
@pytest.mark.parametrize("layer_name", ["conv3d", "deconv3d"])
54
@pytest.mark.parametrize("norm_name", ["batch", "layer"])
55
@pytest.mark.parametrize("activation", ["relu", "elu"])
56
def test_norm_block(layer_name: str, norm_name: str, activation: str):
57
    """
58
    Test output shapes and configs.
59
60
    :param layer_name: layer_name for layer definition
61
    :param norm_name: norm_name for layer definition
62
    :param activation: activation for layer definition
63
    """
64
    input_size = (2, 3, 4, 5, 6)  # (batch, *shape, ch)
65
    conv_block = layer.NormBlock(
66
        layer_name=layer_name,
67
        norm_name=norm_name,
68
        activation=activation,
69
        filters=3,
70
        kernel_size=1,
71
        padding="same",
72
    )
73
    inputs = tf.ones(shape=input_size)
74
    outputs = conv_block(inputs)
75
    assert outputs.shape == input_size[:-1] + (3,)
76
77
    config = conv_block.get_config()
78
    assert config == dict(
79
        layer_name=layer_name,
80
        norm_name=norm_name,
81
        activation=activation,
82
        filters=3,
83
        kernel_size=1,
84
        padding="same",
85
        name="norm_block",
86
        trainable=True,
87
        dtype="float32",
88
    )
89
90
91
def test_downsample_resnet_block():
92
    """
93
    Test the layer.DownSampleResnetBlock class and its default attributes.
94
    """
95
    model = layer.DownSampleResnetBlock(8)
96
97
    assert model._pooling is True
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _pooling was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
98
99
    assert isinstance(model._residual_block, layer.Residual3dBlock)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _residual_block was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
100
    assert model._conv3d_block3 is None
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _conv3d_block3 was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
101
102
    model = layer.DownSampleResnetBlock(8, pooling=False)
103
    assert model._max_pool3d is None
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _max_pool3d was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
104
105
106
def test_upsample_resnet_block():
107
    """
108
    Test the layer.UpSampleResnetBlock class and its default attributes.
109
    """
110
    batch_size = 5
111
    channels = 4
112
    input_size = (32, 32, 16)
113
    output_size = (64, 64, 32)
114
115
    input_tensor_size = (batch_size,) + input_size + (channels,)
116
    skip_tensor_size = (batch_size,) + output_size + (channels // 2,)
117
118
    model = layer.UpSampleResnetBlock(8)
119
    model.build([input_tensor_size, skip_tensor_size])
120
121
    assert model._filters == 8
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _filters was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
122
    assert model._concat is False
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _concat was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
123
    assert isinstance(model._conv3d_block, layer.Conv3dBlock)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _conv3d_block was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
124
    assert isinstance(model._residual_block, layer.Residual3dBlock)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _residual_block was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
125
    assert isinstance(model._deconv3d_block, layer.Deconv3dBlock)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _deconv3d_block was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
126
127
128
def test_warping():
129
    """
130
    Test the layer.Warping class, its default attributes and its call() method.
131
    """
132
    batch_size = 5
133
    fixed_image_size = (32, 32, 16)
134
    moving_image_size = (24, 24, 16)
135
    ndims = len(moving_image_size)
136
137
    grid_size = (1,) + fixed_image_size + (3,)
138
    model = layer.Warping(fixed_image_size)
139
140
    assert all(x == y for x, y in zip(grid_size, model.grid_ref.shape))
141
142
    # Pass an input of all zeros
143
    inputs = [
144
        np.ones((batch_size, *fixed_image_size, ndims), dtype="float32"),
145
        np.ones((batch_size, *moving_image_size), dtype="float32"),
146
    ]
147
    # Get outputs by calling
148
    output = model.call(inputs)
149
    # Expected shape is (5, 1, 2, 3, 3)
150
    assert all(x == y for x, y in zip((batch_size,) + fixed_image_size, output.shape))
151
152
153
def test_init_dvf():
154
    """
155
    Test the layer.IntDVF class, its default attributes and its call() method.
156
    """
157
158
    batch_size = 5
159
    fixed_image_size = (32, 32, 16)
160
    ndims = len(fixed_image_size)
161
162
    model = layer.IntDVF(fixed_image_size)
163
164
    assert isinstance(model._warping, layer.Warping)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _warping was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
165
    assert model._num_steps == 7
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _num_steps was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
166
167
    inputs = np.ones((batch_size, *fixed_image_size, ndims))
168
    output = model.call(inputs)
169
    assert all(
170
        x == y
171
        for x, y in zip((batch_size,) + fixed_image_size + (ndims,), output.shape)
172
    )
173
174
175
def test_additive_upsampling():
176
    """
177
    Test the layer.AdditiveUpSampling class and its default attributes.
178
    """
179
    channels = 8
180
    batch_size = 5
181
    output_size = (32, 32, 16)
182
    input_size = (24, 24, 16)
183
184
    # Test __init__()
185
    model = layer.AdditiveUpSampling(output_size)
186
    assert model._stride == 2
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _stride was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
187
    assert model._output_shape == output_size
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _output_shape was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
188
189
    # Test call()
190
    inputs = np.ones(
191
        (batch_size, input_size[0], input_size[1], input_size[2], channels)
192
    )
193
    output = model(inputs)
194
    assert all(
195
        x == y
196
        for x, y in zip((batch_size,) + output_size + (channels / 2,), output.shape)
197
    )
198
199
    # Test the exceptions
200
    model = layer.AdditiveUpSampling(output_size, stride=3)
201
    with pytest.raises(ValueError):
202
        model(inputs)
203
204
205
def test_local_net_residual3d_block():
206
    """
207
    Test the layer.LocalNetResidual3dBlock class's,
208
    default attributes and call() function.
209
    """
210
211
    # Test __init__()
212
    conv3d_block = layer.LocalNetResidual3dBlock(8)
213
214
    assert conv3d_block._conv3d.kernel_size == (3, 3, 3)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _conv3d was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
215
    assert conv3d_block._conv3d.strides == (1, 1, 1)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _conv3d was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
216
    assert conv3d_block._conv3d.padding == "same"
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _conv3d was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
217
    assert conv3d_block._conv3d.use_bias is False
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _conv3d was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
218
219
220
def test_local_net_upsample_resnet_block():
221
    """
222
    Test the layer.LocalNetUpSampleResnetBlock class,
223
    its default attributes and its call() function.
224
    """
225
    batch_size = 5
226
    channels = 4
227
    input_size = (32, 32, 16)
228
    output_size = (64, 64, 32)
229
230
    nonskip_tensor_size = (batch_size,) + input_size + (channels,)
231
    skip_tensor_size = (batch_size,) + output_size + (channels,)
232
233
    # Test __init__() and build()
234
    model = layer.LocalNetUpSampleResnetBlock(8)
235
    model.build([nonskip_tensor_size, skip_tensor_size])
236
237
    assert model._filters == 8
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _filters was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
238
    assert model._use_additive_upsampling is True
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _use_additive_upsampling was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
239
240
    assert isinstance(model._deconv3d_block, layer.Deconv3dBlock)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _deconv3d_block was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
241
    assert isinstance(model._additive_upsampling, layer.AdditiveUpSampling)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _additive_upsampling was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
242
    assert isinstance(model._conv3d_block, layer.Conv3dBlock)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _conv3d_block was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
243
    assert isinstance(model._residual_block, layer.LocalNetResidual3dBlock)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _residual_block was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
244
245
246
class TestResizeCPTransform:
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
247
    @pytest.mark.parametrize(
248
        "parameter,cp_spacing", [((8, 8, 8), 8), ((8, 24, 16), (8, 24, 16))]
249
    )
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
250
    def test_attributes(self, parameter, cp_spacing):
251
        model = layer.ResizeCPTransform(cp_spacing)
252
253
        if isinstance(cp_spacing, int):
254
            cp_spacing = [cp_spacing] * 3
255
        assert list(model.cp_spacing) == list(parameter)
256
        assert model.kernel_sigma == [0.44 * cp for cp in cp_spacing]
257
258
    @pytest.mark.parametrize(
259
        "input_size,output_size,cp_spacing",
260
        [
261
            ((1, 8, 8, 8, 3), (12, 8, 12), (8, 16, 8)),
262
            ((1, 8, 8, 8, 3), (12, 12, 12), 8),
263
        ],
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
264
    )
265
    def test_build(self, input_size, output_size, cp_spacing):
266
        model = layer.ResizeCPTransform(cp_spacing)
267
        model.build(input_size)
268
269
        assert [a == b for a, b, in zip(model._output_shape, output_size)]
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _output_shape was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
270
271
    @pytest.mark.parametrize(
272
        "input_size,output_size,cp_spacing",
273
        [
274
            ((1, 68, 68, 68, 3), (1, 12, 8, 12, 3), (8, 16, 8)),
275
            ((1, 68, 68, 68, 3), (1, 12, 12, 12, 3), 8),
276
        ],
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
277
    )
278
    def test_call(self, input_size, output_size, cp_spacing):
279
        model = layer.ResizeCPTransform(cp_spacing)
280
        model.build(input_size)
281
282
        input = tf.random.normal(shape=input_size, dtype=tf.float32)
0 ignored issues
show
Bug Best Practice introduced by
This seems to re-define the built-in input.

It is generally discouraged to redefine built-ins as this makes code very hard to read.

Loading history...
283
        output = model(input)
284
285
        assert output.shape == output_size
286
287
288
class TestBSplines3DTransform:
289
    """
290
    Test the layer.BSplines3DTransform class,
291
    its default attributes and its call() function.
292
    """
293
294
    @pytest.mark.parametrize(
295
        "input_size,cp",
296
        [((1, 8, 8, 8, 3), 8), ((1, 8, 8, 8, 3), (8, 16, 12))],
297
    )
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
298
    def test_init(self, input_size, cp):
299
        model = layer.BSplines3DTransform(cp, input_size[1:-1])
300
301
        if isinstance(cp, int):
302
            cp = (cp, cp, cp)
303
304
        assert model.cp_spacing == cp
305
306
    @pytest.mark.parametrize(
307
        "input_size,cp",
308
        [((1, 8, 8, 8, 3), (8, 8, 8)), ((1, 8, 8, 8, 3), (8, 16, 12))],
309
    )
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
310
    def generate_filter_coefficients(self, cp_spacing):
311
312
        b = {
313
            0: lambda u: np.float64((1 - u) ** 3 / 6),
314
            1: lambda u: np.float64((3 * (u ** 3) - 6 * (u ** 2) + 4) / 6),
315
            2: lambda u: np.float64((-3 * (u ** 3) + 3 * (u ** 2) + 3 * u + 1) / 6),
316
            3: lambda u: np.float64(u ** 3 / 6),
317
        }
318
319
        filters = np.zeros(
320
            (
321
                4 * cp_spacing[0],
322
                4 * cp_spacing[1],
323
                4 * cp_spacing[2],
324
                3,
325
                3,
326
            ),
327
            dtype=np.float32,
328
        )
329
330
        for u in range(cp_spacing[0]):
0 ignored issues
show
unused-code introduced by
Too many nested blocks (7/5)
Loading history...
331
            for v in range(cp_spacing[1]):
332
                for w in range(cp_spacing[2]):
333
                    for x in range(4):
334
                        for y in range(4):
335
                            for z in range(4):
336
                                for it_dim in range(3):
337
                                    u_norm = 1 - (u + 0.5) / cp_spacing[0]
338
                                    v_norm = 1 - (v + 0.5) / cp_spacing[1]
339
                                    w_norm = 1 - (w + 0.5) / cp_spacing[2]
340
                                    filters[
341
                                        x * cp_spacing[0] + u,
342
                                        y * cp_spacing[1] + v,
343
                                        z * cp_spacing[2] + w,
344
                                        it_dim,
345
                                        it_dim,
346
                                    ] = (
347
                                        b[x](u_norm) * b[y](v_norm) * b[z](w_norm)
348
                                    )
349
        return filters
350
351
    @pytest.mark.parametrize(
352
        "input_size,cp",
353
        [((1, 8, 8, 8, 3), (8, 8, 8)), ((1, 8, 8, 8, 3), (8, 16, 12))],
354
    )
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
355
    def test_build(self, input_size, cp):
356
        model = layer.BSplines3DTransform(cp, input_size[1:-1])
357
358
        model.build(input_size)
359
        assert model.filter.shape == (
360
            4 * cp[0],
361
            4 * cp[1],
362
            4 * cp[2],
363
            3,
364
            3,
365
        )
366
367
    @pytest.mark.parametrize(
368
        "input_size,cp",
369
        [((1, 8, 8, 8, 3), (8, 8, 8)), ((1, 8, 8, 8, 3), (8, 16, 12))],
370
    )
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
371
    def test_coefficients(self, input_size, cp):
372
373
        filters = self.generate_filter_coefficients(cp_spacing=cp)
374
375
        model = layer.BSplines3DTransform(cp, input_size[1:-1])
376
        model.build(input_size)
377
378
        assert np.allclose(filters, model.filter.numpy(), atol=1e-8)
379
380
    @pytest.mark.parametrize(
381
        "input_size,cp",
382
        [((1, 8, 8, 8, 3), (8, 8, 8)), ((1, 8, 8, 8, 3), (8, 16, 12))],
383
    )
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
384
    def test_interpolation(self, input_size, cp):
385
        model = layer.BSplines3DTransform(cp, input_size[1:-1])
386
        model.build(input_size)
387
388
        vol_shape = input_size[1:-1]
389
        num_cp = (
390
            [input_size[0]]
391
            + [int(np.ceil(isize / cpsize) + 3) for isize, cpsize in zip(vol_shape, cp)]
392
            + [input_size[-1]]
393
        )
394
395
        field = tf.random.normal(shape=num_cp, dtype=tf.float32)
396
397
        ddf = model.call(field)
398
        assert ddf.shape == input_size
399
400
401
class TestResize3d:
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
402
    @pytest.mark.parametrize(
403
        ("input_shape", "resize_shape", "output_shape"),
404
        [
405
            ((1, 2, 3), (3, 4, 5), (3, 4, 5)),
406
            ((2, 1, 2, 3), (3, 4, 5), (2, 3, 4, 5)),
407
            ((2, 1, 2, 3, 1), (3, 4, 5), (2, 3, 4, 5, 1)),
408
            ((2, 1, 2, 3, 6), (3, 4, 5), (2, 3, 4, 5, 6)),
409
            ((1, 2, 3), (1, 2, 3), (1, 2, 3)),
410
            ((2, 1, 2, 3), (1, 2, 3), (2, 1, 2, 3)),
411
            ((2, 1, 2, 3, 1), (1, 2, 3), (2, 1, 2, 3, 1)),
412
            ((2, 1, 2, 3, 6), (1, 2, 3), (2, 1, 2, 3, 6)),
413
        ],
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
414
    )
415
    def test_forward(self, input_shape, resize_shape, output_shape):
416
        inputs = tf.ones(shape=input_shape)
417
        outputs = layer.Resize3d(shape=resize_shape)(inputs)
418
        assert outputs.shape == output_shape
419
420
    def test_get_config(self):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
421
        resize = layer.Resize3d(shape=(2, 3, 4))
422
        config = resize.get_config()
423
        assert config == dict(
424
            shape=(2, 3, 4),
425
            method=tf.image.ResizeMethod.BILINEAR,
426
            name="resize3d",
427
            trainable=True,
428
            dtype="float32",
429
        )
430
431
    def test_shape_err(self):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
432
        with pytest.raises(AssertionError):
433
            layer.Resize3d(shape=(2, 3))
434
435
    def test_image_shape_err(self):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
436
        with pytest.raises(ValueError) as err_info:
437
            resize = layer.Resize3d(shape=(2, 3, 4))
438
            resize(tf.ones(1, 1))
439
        assert "Resize3d takes input image of dimension 3 or 4 or 5" in str(
440
            err_info.value
441
        )
442