This file is indexed.

/usr/lib/python2.7/dist-packages/dipy/align/tests/test_imaffine.py is in python-dipy 0.10.1-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
import numpy as np
import scipy as sp
import nibabel as nib
import numpy.linalg as npl
from numpy.testing import (assert_array_equal,
                           assert_array_almost_equal,
                           assert_almost_equal,
                           assert_equal,
                           assert_raises)
from dipy.core import geometry as geometry
from dipy.data import get_data
from dipy.viz import regtools as rt
from dipy.align import floating
from dipy.align import vector_fields as vf
from dipy.align import imaffine
from dipy.align.imaffine import AffineInversionError
from dipy.align.transforms import (Transform,
                                   regtransforms)
from dipy.align.tests.test_parzenhist import (setup_random_transform,
                                              sample_domain_regular)

# For each transform type, select a transform factor (indicating how large the
# true transform between static and moving images will be), a sampling scheme
# (either a positive integer less than or equal to 100, or None) indicating
# the percentage (if int) of voxels to be used for estimating the joint PDFs,
# or dense sampling (if None), and also specify a starting point (to avoid
# starting from the identity)
factors = {('TRANSLATION', 2): (2.0, 0.35, np.array([2.3, 4.5])),
           ('ROTATION', 2): (0.1, None, np.array([0.1])),
           ('RIGID', 2): (0.1, .50, np.array([0.12, 1.8, 2.7])),
           ('SCALING', 2): (0.01, None, np.array([1.05])),
           ('AFFINE', 2): (0.1, .50, np.array([0.99, -0.05, 1.3, 0.05, 0.99, 2.5])),
           ('TRANSLATION', 3): (2.0, None, np.array([2.3, 4.5, 1.7])),
           ('ROTATION', 3): (0.1, 1.0, np.array([0.1, 0.15, -0.11])),
           ('RIGID', 3): (0.1, None, np.array([0.1, 0.15, -0.11, 2.3, 4.5, 1.7])),
           ('SCALING', 3): (0.1, .35, np.array([0.95])),
           ('AFFINE', 3): (0.1, None, np.array([0.99, -0.05,  0.03, 1.3,
                                                0.05,  0.99, -0.10, 2.5,
                                                -0.07, 0.10,  0.99, -1.4]))}


def test_transform_centers_of_mass_3d():
    np.random.seed(1246592)
    shape = (64, 64, 64)
    rm = 8
    sp = vf.create_sphere(shape[0]//2, shape[1]//2, shape[2]//2, rm)
    moving = np.zeros(shape)
    # The center of mass will be (16, 16, 16), in image coordinates
    moving[:shape[0]//2, :shape[1]//2, :shape[2]//2] = sp[...]

    rs = 16
    # The center of mass will be (32, 32, 32), in image coordinates
    static = vf.create_sphere(shape[0], shape[1], shape[2], rs)

    # Create arbitrary image-to-space transforms
    axis = np.array([.5, 2.0, 1.5])
    t = 0.15 #translation factor
    trans = np.array([[1, 0, 0, -t*shape[0]],
                      [0, 1, 0, -t*shape[1]],
                      [0, 0, 1, -t*shape[2]],
                      [0, 0, 0, 1]])
    trans_inv = npl.inv(trans)

    for rotation_angle in [-1 * np.pi/6.0, 0.0, np.pi/5.0]:
        for scale_factor in [0.83,  1.3, 2.07]: #scale
            rot = np.zeros(shape=(4,4))
            rot[:3, :3] = geometry.rodrigues_axis_rotation(axis,
                                                           rotation_angle)
            rot[3,3] = 1.0
            scale = np.array([[1 * scale_factor, 0, 0, 0],
                              [0, 1 * scale_factor, 0, 0],
                              [0, 0, 1 * scale_factor, 0],
                              [0, 0, 0, 1]])

            static_grid2world = trans_inv.dot(scale.dot(rot.dot(trans)))
            moving_grid2world = npl.inv(static_grid2world)

            # Expected translation
            c_static = static_grid2world.dot((32, 32, 32, 1))[:3]
            c_moving = moving_grid2world.dot((16, 16, 16, 1))[:3]
            expected = np.eye(4);
            expected[:3, 3] = c_moving - c_static

            # Implementation under test
            actual = imaffine.transform_centers_of_mass(static, static_grid2world,
                                                        moving, moving_grid2world)
            assert_array_almost_equal(actual.affine, expected)


def test_transform_geometric_centers_3d():
    # Create arbitrary image-to-space transforms
    axis = np.array([.5, 2.0, 1.5])
    t = 0.15 #translation factor

    for theta in [-1 * np.pi/6.0, 0.0, np.pi/5.0]: #rotation angle
        for s in [0.83,  1.3, 2.07]: #scale
            m_shapes = [(256, 256, 128), (255, 255, 127), (64, 127, 142)]
            for shape_moving in m_shapes:
                s_shapes = [(256, 256, 128), (255, 255, 127), (64, 127, 142)]
                for shape_static in s_shapes:
                    moving = np.ndarray(shape=shape_moving)
                    static = np.ndarray(shape=shape_static)
                    trans = np.array([[1, 0, 0, -t*shape_static[0]],
                                      [0, 1, 0, -t*shape_static[1]],
                                      [0, 0, 1, -t*shape_static[2]],
                                      [0, 0, 0, 1]])
                    trans_inv = npl.inv(trans)
                    rot = np.zeros(shape=(4,4))
                    rot[:3, :3] = geometry.rodrigues_axis_rotation(axis, theta)
                    rot[3,3] = 1.0
                    scale = np.array([[1 * s, 0, 0, 0],
                                      [0, 1 * s, 0, 0],
                                      [0, 0, 1 * s, 0],
                                      [0, 0, 0, 1]])

                    static_grid2world = trans_inv.dot(scale.dot(rot.dot(trans)))
                    moving_grid2world = npl.inv(static_grid2world)

                    # Expected translation
                    c_static = np.array(shape_static, dtype = np.float64) * 0.5
                    c_static = tuple(c_static)
                    c_static = static_grid2world.dot(c_static+(1,))[:3]
                    c_moving = np.array(shape_moving, dtype = np.float64) * 0.5
                    c_moving = tuple(c_moving)
                    c_moving = moving_grid2world.dot(c_moving+(1,))[:3]
                    expected = np.eye(4);
                    expected[:3, 3] = c_moving - c_static

                    # Implementation under test
                    actual = imaffine.transform_geometric_centers(static,
                        static_grid2world, moving, moving_grid2world)
                    assert_array_almost_equal(actual.affine, expected)


def test_transform_origins_3d():
    # Create arbitrary image-to-space transforms
    axis = np.array([.5, 2.0, 1.5])
    t = 0.15 #translation factor

    for theta in [-1 * np.pi/6.0, 0.0, np.pi/5.0]: #rotation angle
        for s in [0.83,  1.3, 2.07]: #scale
            m_shapes = [(256, 256, 128), (255, 255, 127), (64, 127, 142)]
            for shape_moving in m_shapes:
                s_shapes = [(256, 256, 128), (255, 255, 127), (64, 127, 142)]
                for shape_static in s_shapes:
                    moving = np.ndarray(shape=shape_moving)
                    static = np.ndarray(shape=shape_static)
                    trans = np.array([[1, 0, 0, -t*shape_static[0]],
                                      [0, 1, 0, -t*shape_static[1]],
                                      [0, 0, 1, -t*shape_static[2]],
                                      [0, 0, 0, 1]])
                    trans_inv = npl.inv(trans)
                    rot = np.zeros(shape=(4,4))
                    rot[:3, :3] = geometry.rodrigues_axis_rotation(axis, theta)
                    rot[3,3] = 1.0
                    scale = np.array([[1*s, 0, 0, 0],
                                      [0, 1*s, 0, 0],
                                      [0, 0, 1*s, 0],
                                      [0, 0, 0, 1]])

                    static_grid2world = trans_inv.dot(scale.dot(rot.dot(trans)))
                    moving_grid2world = npl.inv(static_grid2world)

                    # Expected translation
                    c_static = static_grid2world[:3, 3]
                    c_moving = moving_grid2world[:3, 3]
                    expected = np.eye(4);
                    expected[:3, 3] = c_moving - c_static

                    # Implementation under test
                    actual = imaffine.transform_origins(static, static_grid2world,
                                                    moving, moving_grid2world)
                    assert_array_almost_equal(actual.affine, expected)


def test_affreg_all_transforms():
    # Test affine registration using all transforms with typical settings

    # Make sure dictionary entries are processed in the same order regardless of
    # the platform. Otherwise any random numbers drawn within the loop would make
    # the test non-deterministic even if we fix the seed before the loop.
    # Right now, this test does not draw any samples, but we still sort the entries
    # to prevent future related failures.
    for ttype in sorted(factors):
        dim = ttype[1]
        if dim == 2:
            nslices = 1
        else:
            nslices = 45
        factor = factors[ttype][0]
        sampling_pc = factors[ttype][1]
        transform = regtransforms[ttype]

        static, moving, static_grid2world, moving_grid2world, smask, mmask, T = \
                        setup_random_transform(transform, factor, nslices, 1.0)
        # Sum of absolute differences
        start_sad = np.abs(static - moving).sum()
        metric = imaffine.MutualInformationMetric(32, sampling_pc)
        affreg = imaffine.AffineRegistration(metric,
                                             [1000, 100, 50],
                                             [3, 1, 0],
                                             [4, 2, 1],
                                             'L-BFGS-B',
                                             None,
                                             options=None)
        x0 = transform.get_identity_parameters()
        affine_map = affreg.optimize(static, moving, transform, x0,
                                     static_grid2world, moving_grid2world)
        transformed = affine_map.transform(moving)
        # Sum of absolute differences
        end_sad = np.abs(static - transformed).sum()
        reduction = 1 - end_sad / start_sad
        print("%s>>%f"%(ttype, reduction))
        assert(reduction > 0.9)

    # Verify that exception is raised if level_iters is empty
    metric = imaffine.MutualInformationMetric(32)
    assert_raises(ValueError, imaffine.AffineRegistration, metric, [])


def test_affreg_defaults():
    # Test all default arguments with an arbitrary transform
    # Select an arbitrary transform (all of them are already tested
    # in test_affreg_all_transforms)
    transform_name = 'TRANSLATION'
    dim = 2
    ttype = (transform_name, dim)
    aff_options = ['mass', 'voxel-origin', 'centers', None, np.eye(dim+1)]

    for starting_affine in aff_options:
        if dim == 2:
            nslices = 1
        else:
            nslices = 45
        factor = factors[ttype][0]
        sampling_pc = factors[ttype][1]
        transform = regtransforms[ttype]
        id_param = transform.get_identity_parameters()

        static, moving, static_grid2world, moving_grid2world, smask, mmask, T = \
                        setup_random_transform(transform, factor, nslices, 1.0)
        # Sum of absolute differences
        start_sad = np.abs(static - moving).sum()

        metric = None
        x0 = None
        sigmas = None
        scale_factors = None
        level_iters = None
        static_grid2world = None
        moving_grid2world = None
        for ss_sigma_factor in [1.0, None]:
            affreg = imaffine.AffineRegistration(metric,
                                                 level_iters,
                                                 sigmas,
                                                 scale_factors,
                                                 'L-BFGS-B',
                                                 ss_sigma_factor,
                                                 options=None)
            affine_map = affreg.optimize(static, moving, transform, x0,
                                         static_grid2world, moving_grid2world,
                                         starting_affine)
            transformed = affine_map.transform(moving)
            # Sum of absolute differences
            end_sad = np.abs(static - transformed).sum()
            reduction = 1 - end_sad / start_sad
            print("%s>>%f"%(ttype, reduction))
            assert(reduction > 0.9)

            transformed_inv = affine_map.transform_inverse(static)
            # Sum of absolute differences
            end_sad = np.abs(moving - transformed_inv).sum()
            reduction = 1 - end_sad / start_sad
            print("%s>>%f"%(ttype, reduction))
            assert(reduction > 0.9)


def test_mi_gradient():
    np.random.seed(2022966)
    # Test the gradient of mutual information
    h = 1e-5
    # Make sure dictionary entries are processed in the same order regardless of
    # the platform. Otherwise any random numbers drawn within the loop would make
    # the test non-deterministic even if we fix the seed before the loop:
    # in this case the samples are drawn with `np.random.randn` below

    for ttype in sorted(factors):
        transform = regtransforms[ttype]
        dim = ttype[1]
        if dim == 2:
            nslices = 1
        else:
            nslices = 45
        factor = factors[ttype][0]
        sampling_proportion = factors[ttype][1]
        theta = factors[ttype][2]
        # Start from a small rotation
        start = regtransforms[('ROTATION', dim)]
        nrot = start.get_number_of_parameters()
        starting_affine = start.param_to_matrix(0.25 * np.random.randn(nrot))
        # Get data (pair of images related to each other by an known transform)
        static, moving, static_g2w, moving_g2w, smask, mmask, M = \
            setup_random_transform(transform, factor, nslices, 2.0)

        # Prepare a MutualInformationMetric instance
        mi_metric = imaffine.MutualInformationMetric(32, sampling_proportion)
        mi_metric.setup(transform, static, moving, starting_affine=starting_affine)
        # Compute the gradient with the implementation under test
        actual = mi_metric.gradient(theta)

        # Compute the gradient using finite-diferences
        n = transform.get_number_of_parameters()
        expected = np.empty(n, dtype=np.float64)

        val0 = mi_metric.distance(theta)
        for i in range(n):
            dtheta = theta.copy()
            dtheta[i] += h
            val1 = mi_metric.distance(dtheta)
            expected[i] = (val1 - val0) / h

        dp = expected.dot(actual)
        enorm = npl.norm(expected)
        anorm = npl.norm(actual)
        nprod = dp / (enorm * anorm)
        assert(nprod >= 0.99)


def create_affine_transforms(dim, translations, rotations, scales, rot_axis=None):
    r""" Creates a list of affine transforms with all combinations of params

    This function is intended to be used for testing only. It generates
    affine transforms for all combinations of the input parameters in the
    following order: let T be a translation, R a rotation and S a scale. The
    generated affine will be:

    A = T.dot(S).dot(R).dot(T^{-1})

    Translation is handled this way because it is convenient to provide
    the translation parameters in terms of the center of rotation we wish
    to generate.

    Parameters
    ----------
    dim: int (either dim=2 or dim=3)
        dimension of the affine transforms
    translations: sequence of dim-tuples
        each dim-tuple represents a translation parameter
    rotations: sequence of floats
        each number represents a rotation angle in radians
    scales: sequence of floats
        each number represents a scale
    rot_axis: rotation axis (used for dim=3 only)

    Returns
    -------
    transforms: sequence of (dim + 1)x(dim + 1) matrices
        each matrix correspond to an affine transform with a combination
        of the input parameters
    """
    transforms = []
    for t in translations:
        trans_inv = np.eye(dim + 1)
        trans_inv[:dim, dim] = -t[:dim]
        trans = npl.inv(trans_inv)
        for theta in rotations:  # rotation angle
            if dim == 2:
                ct = np.cos(theta)
                st = np.sin(theta)
                rot = np.array([[ct, -st, 0],
                                [st, ct, 0],
                                [0, 0, 1]])
            else:
                rot = np.eye(dim + 1)
                rot[:3, :3] = geometry.rodrigues_axis_rotation(rot_axis, theta)

            for s in scales:  # scale
                scale = np.eye(dim + 1) * s
                scale[dim,dim] = 1

            affine = trans.dot(scale.dot(rot.dot(trans_inv)))
            transforms.append(affine)
    return transforms


def test_affine_map():
    np.random.seed(2112927)
    dom_shape = np.array([64, 64, 64], dtype=np.int32)
    cod_shape = np.array([80, 80, 80], dtype=np.int32)
    nx = dom_shape[0]
    ny = dom_shape[1]
    nz = dom_shape[2]
    # Radius of the circle/sphere (testing image)
    radius = 16
    # Rotation axis (used for 3D transforms only)
    rot_axis = np.array([.5, 2.0, 1.5])
    # Arbitrary transform parameters
    t = 0.15
    rotations = [-1 * np.pi / 10.0, 0.0, np.pi / 10.0]
    scales = [0.9,  1.0, 1.1]
    for dim in [2, 3]:
        # Setup current dimension
        if dim == 2:
            # Create image of a circle
            img = vf.create_circle(cod_shape[0], cod_shape[1], radius)
            oracle_linear = vf.transform_2d_affine
            oracle_nn = vf.transform_2d_affine_nn
        else:
            # Create image of a sphere
            img = vf.create_sphere(cod_shape[0], cod_shape[1], cod_shape[2],
                                   radius)
            oracle_linear = vf.transform_3d_affine
            oracle_nn = vf.transform_3d_affine_nn
        img = np.array(img)
        # Translation is the only parameter differing for 2D and 3D
        translations = [t * dom_shape[:dim]]
        # Generate affine transforms
        gt_affines = create_affine_transforms(dim, translations, rotations,
                                              scales, rot_axis)
        # Include the None case
        gt_affines.append(None)

        for affine in gt_affines:

            # make both domain point to the same physical region
            # It's ok to use the same transform, we just want to test
            # that this information is actually being considered
            domain_grid2world = affine
            codomain_grid2world = affine
            grid2grid_transform = affine

            # Evaluate the transform with vector_fields module (already tested)
            expected_linear = oracle_linear(img, dom_shape[:dim],
                                            grid2grid_transform)
            expected_nn = oracle_nn(img, dom_shape[:dim], grid2grid_transform)

            # Evaluate the transform with the implementation under test
            affine_map = imaffine.AffineMap(affine,
                                            dom_shape[:dim], domain_grid2world,
                                            cod_shape[:dim], codomain_grid2world)
            actual_linear = affine_map.transform(img, interp='linear')
            actual_nn = affine_map.transform(img, interp='nearest')
            assert_array_almost_equal(actual_linear, expected_linear)
            assert_array_almost_equal(actual_nn, expected_nn)

            # Test set_affine with valid matrix
            affine_map.set_affine(affine)
            if affine is None:
                assert(affine_map.affine is None)
                assert(affine_map.affine_inv is None)
            else:
                assert_array_equal(affine, affine_map.affine)
                actual = affine_map.affine.dot(affine_map.affine_inv)
                assert_array_almost_equal(actual, np.eye(dim+1))

            # Evaluate via the inverse transform

            # AffineMap will use the inverse of the input matrix when we call
            # `transform_inverse`. Since the inverse of the inverse of a matrix
            # is not exactly equal to the original matrix (numerical limitations)
            # we need to invert the matrix twice to make sure the oracle and the
            # implementation under test apply the same transform
            aff_inv = None if affine is None else npl.inv(affine)
            aff_inv_inv = None if aff_inv is None else npl.inv(aff_inv)
            expected_linear = oracle_linear(img, dom_shape[:dim],
                                            aff_inv_inv)
            expected_nn = oracle_nn(img, dom_shape[:dim], aff_inv_inv)

            affine_map = imaffine.AffineMap(aff_inv,
                                            cod_shape[:dim], codomain_grid2world,
                                            dom_shape[:dim], domain_grid2world)
            actual_linear = affine_map.transform_inverse(img, interp='linear')
            actual_nn = affine_map.transform_inverse(img, interp='nearest')
            assert_array_almost_equal(actual_linear, expected_linear)
            assert_array_almost_equal(actual_nn, expected_nn)

        # Verify AffineMap cannot be created with a non-invertible matrix
        invalid_nan = np.zeros((dim + 1, dim + 1), dtype=np.float64)
        invalid_nan[1, 1] = np.nan
        invalid_zeros = np.zeros((dim + 1, dim + 1), dtype=np.float64)
        assert_raises(imaffine.AffineInversionError, imaffine.AffineMap, invalid_nan)
        assert_raises(imaffine.AffineInversionError, imaffine.AffineMap, invalid_zeros)

        # Test exception is raised when the affine transform matrix is not valid
        invalid_shape = np.eye(dim)
        affmap_invalid_shape = imaffine.AffineMap(invalid_shape,
                                                  dom_shape[:dim], None,
                                                  cod_shape[:dim], None)
        assert_raises(ValueError, affmap_invalid_shape.transform, img)
        assert_raises(ValueError, affmap_invalid_shape.transform_inverse, img)

        # Verify exception is raised when sampling info is not provided
        valid = np.eye(3)
        affmap_invalid_shape = imaffine.AffineMap(valid)
        assert_raises(ValueError, affmap_invalid_shape.transform, img)
        assert_raises(ValueError, affmap_invalid_shape.transform_inverse, img)

        # Verify exception is raised when requesting an invalid interpolation
        assert_raises(ValueError, affine_map.transform, img, 'invalid')
        assert_raises(ValueError, affine_map.transform_inverse, img, 'invalid')

        # Verify exception is raised when attempting to warp an image of
        # invalid dimension
        for dim in [2, 3]:
            affine_map = imaffine.AffineMap(np.eye(dim),
                                            cod_shape[:dim], None,
                                            dom_shape[:dim], None)
            for sh in [(2,), (2,2,2,2)]:
                img = np.zeros(sh)
                assert_raises(ValueError, affine_map.transform, img)
                assert_raises(ValueError, affine_map.transform_inverse, img)
            aff_sing = np.zeros((dim + 1, dim + 1))
            aff_nan = np.zeros((dim + 1, dim + 1))
            aff_nan[...] = np.nan
            aff_inf = np.zeros((dim + 1, dim + 1))
            aff_inf[...] = np.inf

            assert_raises(AffineInversionError, affine_map.set_affine, aff_sing)
            assert_raises(AffineInversionError, affine_map.set_affine, aff_nan)
            assert_raises(AffineInversionError, affine_map.set_affine, aff_inf)



def test_MIMetric_invalid_params():
    transform = regtransforms[('AFFINE', 3)]
    static = np.random.rand(20,20,20)
    moving = np.random.rand(20,20,20)
    n = transform.get_number_of_parameters()
    sampling_proportion = 0.3
    theta_sing = np.zeros(n)
    theta_nan = np.zeros(n)
    theta_nan[...] = np.nan
    theta_inf = np.zeros(n)
    theta_nan[...] = np.inf

    mi_metric = imaffine.MutualInformationMetric(32, sampling_proportion)
    mi_metric.setup(transform, static, moving)
    for theta in [theta_sing, theta_nan, theta_inf]:
        # Test metric value at invalid params
        actual_val = mi_metric.distance(theta)
        assert(np.isinf(actual_val))

        # Test gradient at invalid params
        expected_grad = np.zeros(n)
        actual_grad = mi_metric.gradient(theta)
        assert_equal(actual_grad, expected_grad)

        # Test both
        actual_val, actual_grad = mi_metric.distance_and_gradient(theta)
        assert(np.isinf(actual_val))
        assert_equal(actual_grad, expected_grad)