test_nonlinear.py 20.4 KB
Newer Older
1
2
#!/usr/bin/env python

Paul McCarthy's avatar
Paul McCarthy committed
3
import itertools as it
4
import os.path   as op
5
6
7

import numpy   as np

8
9
import fsl.data.image           as fslimage
import fsl.utils.image.resample as resample
10
import fsl.utils.image.roi      as roi
11
12
13
import fsl.transform.affine     as affine
import fsl.transform.nonlinear  as nonlinear
import fsl.transform.fnirt      as fnirt
14
15
16


datadir = op.join(op.dirname(__file__), 'testdata')
17
18


Paul McCarthy's avatar
Paul McCarthy committed
19
20
21
22
def _random_image():
    vx, vy, vz = np.random.randint(10, 50, 3)
    dx, dy, dz = np.random.randint( 1, 10, 3)
    data       = (np.random.random((vx, vy, vz)) - 0.5) * 10
Paul McCarthy's avatar
Paul McCarthy committed
23
    aff        = affine.compose(
Paul McCarthy's avatar
Paul McCarthy committed
24
25
26
27
28
29
30
        (dx, dy, dz),
        np.random.randint(1, 100, 3),
        np.random.random(3) * np.pi / 2)

    return fslimage.Image(data, xform=aff)


31
def _random_field():
Paul McCarthy's avatar
Paul McCarthy committed
32
33

    src        = _random_image()
34
35
36
37
    vx, vy, vz = np.random.randint(10, 50, 3)
    dx, dy, dz = np.random.randint( 1, 10, 3)

    field = (np.random.random((vx, vy, vz, 3)) - 0.5) * 10
Paul McCarthy's avatar
Paul McCarthy committed
38
    aff   = affine.compose(
39
40
41
42
        (dx, dy, dz),
        np.random.randint(1, 100, 3),
        np.random.random(3) * np.pi / 2)

Paul McCarthy's avatar
Paul McCarthy committed
43
    return nonlinear.DeformationField(field, src=src, xform=aff)
44

45

46
47
48
49
50
51
52
53
def _affine_field(src, ref, xform, srcSpace, refSpace, shape=None, fv2w=None):

    if shape is None: shape = ref.shape[:3]
    if fv2w  is None: fv2w  = ref.getAffine('voxel', 'world')

    rx, ry, rz = np.meshgrid(np.arange(shape[0]),
                             np.arange(shape[1]),
                             np.arange(shape[2]), indexing='ij')
54
55

    rvoxels  = np.vstack((rx.flatten(), ry.flatten(), rz.flatten())).T
56
57
    f2r      = affine.concat(ref.getAffine('world', refSpace), fv2w)
    rcoords  = affine.transform(rvoxels, f2r)
58
59
    scoords  = affine.transform(rcoords, xform)

60
61
    field    = np.zeros(list(shape[:3]) + [3])
    field[:] = (scoords - rcoords).reshape(*it.chain(shape, [3]))
62
63
64
    field    = nonlinear.DeformationField(field, src, ref,
                                          srcSpace=srcSpace,
                                          refSpace=refSpace,
65
                                          xform=fv2w,
66
67
68
69
70
                                          header=ref.header,
                                          defType='relative')
    return field


71
72
73
74
75
76
def _random_affine_field():

    src = _random_image()
    ref = _random_image()

    # our test field just encodes an affine
Paul McCarthy's avatar
Paul McCarthy committed
77
    xform = affine.compose(
78
79
80
81
82
83
84
85
86
        np.random.randint(2, 5, 3),
        np.random.randint(1, 10, 3),
        np.random.random(3))

    rx, ry, rz = np.meshgrid(np.arange(ref.shape[0]),
                             np.arange(ref.shape[1]),
                             np.arange(ref.shape[2]), indexing='ij')

    rvoxels  = np.vstack((rx.flatten(), ry.flatten(), rz.flatten())).T
Paul McCarthy's avatar
Paul McCarthy committed
87
88
    rcoords  = affine.transform(rvoxels, ref.voxToScaledVoxMat)
    scoords  = affine.transform(rcoords, xform)
89
90
91

    field    = np.zeros(list(ref.shape[:3]) + [3])
    field[:] = (scoords - rcoords).reshape(*it.chain(ref.shape, [3]))
Paul McCarthy's avatar
Paul McCarthy committed
92
93
94
    field    = nonlinear.DeformationField(field, src, ref,
                                          header=ref.header,
                                          defType='relative')
95
96
    return field, xform

97
98
99
100
101
102
103

def _field_coords(field):
    vx, vy, vz = field.shape[ :3]
    coords     = np.meshgrid(np.arange(vx),
                             np.arange(vy),
                             np.arange(vz), indexing='ij')
    coords = np.array(coords).transpose((1, 2, 3, 0))
Paul McCarthy's avatar
Paul McCarthy committed
104
    return affine.transform(
105
106
107
108
        coords.reshape(-1, 3),
        field.getAffine('voxel', 'fsl')).reshape(field.shape)


Paul McCarthy's avatar
Paul McCarthy committed
109
def test_detectDeformationType():
110
111
    relfield = _random_field()
    coords   = _field_coords(relfield)
Paul McCarthy's avatar
Paul McCarthy committed
112
    absfield = nonlinear.DeformationField(
113
114
115
        relfield.data + coords,
        src=relfield.src,
        xform=relfield.voxToWorldMat)
116

Paul McCarthy's avatar
Paul McCarthy committed
117
118
    assert nonlinear.detectDeformationType(relfield) == 'relative'
    assert nonlinear.detectDeformationType(absfield) == 'absolute'
119
120


Paul McCarthy's avatar
Paul McCarthy committed
121
def test_convertDeformationType():
122

123
124
    relfield = _random_field()
    coords   = _field_coords(relfield)
Paul McCarthy's avatar
Paul McCarthy committed
125
    absfield = nonlinear.DeformationField(
126
127
128
        relfield.data + coords,
        src=relfield.src,
        xform=relfield.voxToWorldMat)
129

Paul McCarthy's avatar
Paul McCarthy committed
130
131
132
133
    gotconvrel1 = nonlinear.convertDeformationType(relfield)
    gotconvabs1 = nonlinear.convertDeformationType(absfield)
    gotconvrel2 = nonlinear.convertDeformationType(relfield, 'absolute')
    gotconvabs2 = nonlinear.convertDeformationType(absfield, 'relative')
134

135
    tol = dict(atol=1e-3, rtol=1e-3)
Paul McCarthy's avatar
Paul McCarthy committed
136

137
138
139
140
    assert np.all(np.isclose(gotconvrel1, absfield.data, **tol))
    assert np.all(np.isclose(gotconvabs1, relfield.data, **tol))
    assert np.all(np.isclose(gotconvrel2, absfield.data, **tol))
    assert np.all(np.isclose(gotconvabs2, relfield.data, **tol))
Paul McCarthy's avatar
Paul McCarthy committed
141
142


Paul McCarthy's avatar
Paul McCarthy committed
143
def test_convertDeformationSpace():
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163

    basefield, xform = _random_affine_field()
    src              = basefield.src
    ref              = basefield.ref

    # generate reference fsl->fsl coordinate mappings

    # For each combination of srcspace->tospace
    # Generate random coordinates, check that
    # displacements are correct
    spaces = ['fsl', 'voxel', 'world']
    spaces = list(it.combinations_with_replacement(spaces, 2))
    spaces = spaces + [(r, s) for s, r in spaces]
    spaces = list(set(spaces))

    for from_, to in spaces:

        refcoords = [np.random.randint(0, basefield.shape[0], 5),
                     np.random.randint(0, basefield.shape[1], 5),
                     np.random.randint(0, basefield.shape[2], 5)]
164
        refcoords = np.array(refcoords, dtype=int).T
Paul McCarthy's avatar
Paul McCarthy committed
165
        refcoords = affine.transform(refcoords, ref.voxToScaledVoxMat)
166
167
        srccoords = basefield.transform(refcoords)

Paul McCarthy's avatar
Paul McCarthy committed
168
        field   = nonlinear.convertDeformationSpace(basefield, from_, to)
169
170
171
        premat  = ref.getAffine('fsl', from_)
        postmat = src.getAffine('fsl', to)

Paul McCarthy's avatar
Paul McCarthy committed
172
173
        input  = affine.transform(refcoords, premat)
        expect = affine.transform(srccoords, postmat)
174
175
176
177
178
179
180
181
182

        got  = field.transform(input)
        enan = np.isnan(expect)
        gnan = np.isnan(got)

        assert np.all(np.isclose(enan, gnan))
        assert np.all(np.isclose(expect[~enan], got[~gnan]))


Paul McCarthy's avatar
Paul McCarthy committed
183
def test_DeformationField_transform():
184
185
186
187

    relfield, xform = _random_affine_field()
    src             = relfield.src
    ref             = relfield.ref
Paul McCarthy's avatar
Paul McCarthy committed
188
189
190
191
192

    rx, ry, rz = np.meshgrid(np.arange(ref.shape[0]),
                             np.arange(ref.shape[1]),
                             np.arange(ref.shape[2]), indexing='ij')
    rvoxels  = np.vstack((rx.flatten(), ry.flatten(), rz.flatten())).T
Paul McCarthy's avatar
Paul McCarthy committed
193
194
195
    rcoords  = affine.transform(rvoxels, ref.voxToScaledVoxMat)
    scoords  = affine.transform(rcoords, xform)
    svoxels  = affine.transform(scoords, src.scaledVoxToVoxMat)
Paul McCarthy's avatar
Paul McCarthy committed
196
197
198

    absfield    = np.zeros(list(ref.shape[:3]) + [3])
    absfield[:] = scoords.reshape(*it.chain(ref.shape, [3]))
Paul McCarthy's avatar
Paul McCarthy committed
199
200
201
    absfield    = nonlinear.DeformationField(absfield, src, ref,
                                             header=ref.header,
                                             defType='absolute')
Paul McCarthy's avatar
Paul McCarthy committed
202
203
204
205
206
207

    got = relfield.transform(rcoords)
    assert np.all(np.isclose(got, scoords))
    got = absfield.transform(rcoords)
    assert np.all(np.isclose(got, scoords))

Paul McCarthy's avatar
Paul McCarthy committed
208
209
210
211
    # test single set of coords
    got = absfield.transform(rcoords[0])
    assert np.all(np.isclose(got, scoords[0]))

Paul McCarthy's avatar
Paul McCarthy committed
212
213
214
215
216
217
218
219
    got = relfield.transform(rvoxels, from_='voxel', to='voxel')
    assert np.all(np.isclose(got, svoxels))
    got = absfield.transform(rvoxels, from_='voxel', to='voxel')
    assert np.all(np.isclose(got, svoxels))

    # test out of bounds are returned as nan
    rvoxels = np.array([[-1, -1, -1],
                        [ 0,  0,  0]])
Paul McCarthy's avatar
Paul McCarthy committed
220
221
222
    rcoords  = affine.transform(rvoxels, ref.voxToScaledVoxMat)
    scoords  = affine.transform(rcoords, xform)
    svoxels  = affine.transform(scoords, src.scaledVoxToVoxMat)
Paul McCarthy's avatar
Paul McCarthy committed
223
224
225
226
227
228
229

    got = relfield.transform(rcoords)
    assert np.all(np.isnan(got[0, :]))
    assert np.all(np.isclose(got[1, :], scoords[1, :]))
    got = absfield.transform(rcoords)
    assert np.all(np.isnan(got[0, :]))
    assert np.all(np.isclose(got[1, :], scoords[1, :]))
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

def test_CoefficientField_displacements():

    nldir = op.join(datadir, 'nonlinear')
    src   = op.join(nldir, 'src.nii.gz')
    ref   = op.join(nldir, 'ref.nii.gz')
    cf    = op.join(nldir, 'coefficientfield.nii.gz')
    df    = op.join(nldir, 'displacementfield_no_premat.nii.gz')

    src = fslimage.Image(src)
    ref = fslimage.Image(ref)
    cf  = fnirt.readFnirt(cf, src, ref)
    df  = fnirt.readFnirt(df, src, ref)

    ix, iy, iz = ref.shape[:3]
    x,  y,  z  = np.meshgrid(np.arange(ix),
                             np.arange(iy),
                             np.arange(iz), indexing='ij')
    x          = x.flatten()
    y          = y.flatten()
    z          = z.flatten()
    xyz        = np.vstack((x, y, z)).T

    disps = cf.displacements(xyz)
    disps = disps.reshape(df.shape)

    tol = dict(atol=1e-5, rtol=1e-5)
    assert np.all(np.isclose(disps, df.data, **tol))
Paul McCarthy's avatar
Paul McCarthy committed
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


def test_CoefficientField_transform():
    nldir = op.join(datadir, 'nonlinear')
    src   = op.join(nldir, 'src.nii.gz')
    ref   = op.join(nldir, 'ref.nii.gz')
    cf    = op.join(nldir, 'coefficientfield.nii.gz')
    df    = op.join(nldir, 'displacementfield.nii.gz')
    dfnp  = op.join(nldir, 'displacementfield_no_premat.nii.gz')

    src  = fslimage.Image(src)
    ref  = fslimage.Image(ref)
    cf   = fnirt.readFnirt(cf,   src, ref)
    df   = fnirt.readFnirt(df,   src, ref)
    dfnp = fnirt.readFnirt(dfnp, src, ref)

    spaces = ['fsl', 'voxel', 'world']
    spaces = list(it.combinations_with_replacement(spaces, 2))
    spaces = spaces + [(r, s) for s, r in spaces]
    spaces = list(set(spaces))

    rx, ry, rz = np.meshgrid(np.arange(ref.shape[0]),
                             np.arange(ref.shape[1]),
                             np.arange(ref.shape[2]), indexing='ij')
    rvoxels  = np.vstack((rx.flatten(), ry.flatten(), rz.flatten())).T

    refcoords = {
        'voxel' : rvoxels,
        'fsl'   : affine.transform(rvoxels, ref.getAffine('voxel', 'fsl')),
        'world' : affine.transform(rvoxels, ref.getAffine('voxel', 'world'))
    }

    srccoords = refcoords['fsl'] + df.data.reshape(-1, 3)
    srccoords = {
        'voxel' : affine.transform(srccoords, src.getAffine('fsl', 'voxel')),
        'fsl'   : srccoords,
        'world' : affine.transform(srccoords, src.getAffine('fsl', 'world'))
    }

    srccoordsnp = refcoords['fsl'] + dfnp.data.reshape(-1, 3)
    srccoordsnp = {
        'voxel' : affine.transform(srccoordsnp, src.getAffine('fsl', 'voxel')),
        'fsl'   : srccoordsnp,
        'world' : affine.transform(srccoordsnp, src.getAffine('fsl', 'world'))
    }

    tol = dict(atol=1e-5, rtol=1e-5)
    for srcspace, refspace in spaces:
        got   = cf.transform(refcoords[refspace], refspace, srcspace)
        gotnp = cf.transform(refcoords[refspace], refspace, srcspace,
                             premat=False)
        assert np.all(np.isclose(got,   srccoords[  srcspace], **tol))
        assert np.all(np.isclose(gotnp, srccoordsnp[srcspace], **tol))


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
def test_coefficientField_transform_altref():

    # test coordinates (manually determined).
    # original ref image is 2mm isotropic,
    # resampled is 1mm. Each tuple contains:
    #
    # (src, ref2mm, ref1mm)
    coords = [
        ((18.414, 26.579, 25.599), (11, 19, 11), (22, 38, 22)),
        ((14.727, 22.480, 20.340), ( 8, 17,  8), (16, 34, 16)),
        ((19.932, 75.616, 27.747), (11, 45,  5), (22, 90, 10))
    ]

    nldir  = op.join(datadir, 'nonlinear')
    src    = op.join(nldir, 'src.nii.gz')
    ref    = op.join(nldir, 'ref.nii.gz')
    cf     = op.join(nldir, 'coefficientfield.nii.gz')

    src      = fslimage.Image(src)
    ref2mm   = fslimage.Image(ref)
    ref1mm   = ref2mm.adjust((1, 1, 1))
    cfref2mm = fnirt.readFnirt(cf, src, ref2mm)
    cfref1mm = fnirt.readFnirt(cf, src, ref1mm)

    for srcc, ref2mmc, ref1mmc in coords:
        ref2mmc = cfref2mm.transform(ref2mmc, 'voxel', 'voxel')
        ref1mmc = cfref1mm.transform(ref1mmc, 'voxel', 'voxel')

        assert np.all(np.isclose(ref2mmc, srcc, 1e-4))
        assert np.all(np.isclose(ref1mmc, srcc, 1e-4))


Paul McCarthy's avatar
Paul McCarthy committed
346
def test_coefficientFieldToDeformationField():
347
348
349
350
351
352

    nldir = op.join(datadir, 'nonlinear')
    src   = op.join(nldir, 'src.nii.gz')
    ref   = op.join(nldir, 'ref.nii.gz')
    cf    = op.join(nldir, 'coefficientfield.nii.gz')
    df    = op.join(nldir, 'displacementfield.nii.gz')
353
    dfnp  = op.join(nldir, 'displacementfield_no_premat.nii.gz')
354
355
356

    src   = fslimage.Image(src)
    ref   = fslimage.Image(ref)
357
358
359
    cf    = fnirt.readFnirt(cf,   src, ref)
    rdf   = fnirt.readFnirt(df,   src, ref)
    rdfnp = fnirt.readFnirt(dfnp, src, ref)
Paul McCarthy's avatar
Paul McCarthy committed
360
361
362
363
364
365
366
367
368
369
370
    adf   = nonlinear.convertDeformationType(rdf)
    adfnp = nonlinear.convertDeformationType(rdfnp)

    rcnv   = nonlinear.coefficientFieldToDeformationField(cf)
    acnv   = nonlinear.coefficientFieldToDeformationField(cf,
                                                          defType='absolute')
    acnvnp = nonlinear.coefficientFieldToDeformationField(cf,
                                                          defType='absolute',
                                                          premat=False)
    rcnvnp = nonlinear.coefficientFieldToDeformationField(cf,
                                                          premat=False)
371

372
373
374
375
376
    tol = dict(atol=1e-5, rtol=1e-5)
    assert np.all(np.isclose(rcnv.data,   rdf  .data, **tol))
    assert np.all(np.isclose(acnv.data,   adf  .data, **tol))
    assert np.all(np.isclose(rcnvnp.data, rdfnp.data, **tol))
    assert np.all(np.isclose(acnvnp.data, adfnp.data, **tol))
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


def test_applyDeformation():

    src2ref = affine.compose(
        np.random.randint(2, 5, 3),
        np.random.randint(1, 10, 3),
        np.random.random(3))
    ref2src = affine.invert(src2ref)

    srcdata = np.random.randint(1, 65536, (10, 10, 10))
    refdata = np.random.randint(1, 65536, (10, 10, 10))

    src   = fslimage.Image(srcdata)
    ref   = fslimage.Image(refdata, xform=src2ref)
    field = _affine_field(src, ref, ref2src, 'world', 'world')

    expect, xf = resample.resampleToReference(
        src, ref, matrix=src2ref, order=1, mode='nearest')
    result = nonlinear.applyDeformation(
        src, field, order=1, mode='nearest')

    assert np.all(np.isclose(expect, result))


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
def test_applyDeformation_altsrc():

    src2ref = affine.compose(
        np.random.randint(2, 5, 3),
        np.random.randint(1, 10, 3),
        [0, 0, 0])
    ref2src = affine.invert(src2ref)

    srcdata = np.random.randint(1, 65536, (10, 10, 10))
    refdata = np.random.randint(1, 65536, (10, 10, 10))

    src   = fslimage.Image(srcdata)
    ref   = fslimage.Image(refdata, xform=src2ref)
    field = _affine_field(src, ref, ref2src, 'world', 'world')

    # First try a down-sampled version
    # of the original source image
    altsrc, xf = resample.resample(src, (5, 5, 5), origin='corner')
    altsrc     = fslimage.Image(altsrc, xform=xf, header=src.header)
    expect, xf = resample.resampleToReference(
        altsrc, ref, matrix=src2ref, order=1, mode='nearest')
    result = nonlinear.applyDeformation(
        altsrc, field, order=1, mode='nearest')
    assert np.all(np.isclose(expect, result))

    # Now try a down-sampled ROI
    # of the original source image
    altsrc     = roi.roi(src, [(2, 9), (2, 9), (2, 9)])
    altsrc, xf = resample.resample(altsrc, (4, 4, 4))
    altsrc     = fslimage.Image(altsrc, xform=xf, header=src.header)
    expect, xf = resample.resampleToReference(
        altsrc, ref, matrix=src2ref, order=1, mode='nearest')
    result = nonlinear.applyDeformation(
        altsrc, field, order=1, mode='nearest')
    assert np.all(np.isclose(expect, result))

    # down-sampled and offset ROI
    # of the original source image
    altsrc     = roi.roi(src, [(-5, 8), (-5, 8), (-5, 8)])
    altsrc, xf = resample.resample(altsrc, (6, 6, 6))
    altsrc     = fslimage.Image(altsrc, xform=xf, header=src.header)
    expect, xf = resample.resampleToReference(
        altsrc, ref, matrix=src2ref, order=1, mode='nearest')
    result = nonlinear.applyDeformation(
        altsrc, field, order=1, mode='nearest')
    assert np.all(np.isclose(expect, result))

449

Paul McCarthy's avatar
Paul McCarthy committed
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
def test_applyDeformation_premat():

    src2ref = affine.compose(
        np.random.randint(2, 5, 3),
        np.random.randint(1, 10, 3),
        [0, 0, 0])
    ref2src = affine.invert(src2ref)

    srcdata = np.random.randint(1, 65536, (10, 10, 10))
    refdata = np.random.randint(1, 65536, (10, 10, 10))

    src   = fslimage.Image(srcdata)
    ref   = fslimage.Image(refdata, xform=src2ref)
    field = _affine_field(src, ref, ref2src, 'world', 'world')

    # First try a down-sampled version
    # of the original source image
    altsrc, xf = resample.resample(src, (5, 5, 5), origin='corner')
    altsrc     = fslimage.Image(altsrc, xform=xf, header=src.header)
    expect, xf = resample.resampleToReference(
        altsrc, ref, matrix=src2ref, order=1, mode='nearest')
    premat = affine.concat(src   .getAffine('world', 'voxel'),
                           altsrc.getAffine('voxel', 'world'))
    result = nonlinear.applyDeformation(
        altsrc, field, order=1, mode='nearest', premat=premat)
    assert np.all(np.isclose(expect, result))

    # Now try a down-sampled ROI
    # of the original source image
    altsrc     = roi.roi(src, [(2, 9), (2, 9), (2, 9)])
    altsrc, xf = resample.resample(altsrc, (4, 4, 4))
    altsrc     = fslimage.Image(altsrc, xform=xf, header=src.header)
    expect, xf = resample.resampleToReference(
        altsrc, ref, matrix=src2ref, order=1, mode='nearest')
    premat = affine.concat(src   .getAffine('world', 'voxel'),
                           altsrc.getAffine('voxel', 'world'))
    result = nonlinear.applyDeformation(
        altsrc, field, order=1, mode='nearest', premat=premat)
    assert np.all(np.isclose(expect, result))

    # down-sampled and offset ROI
    # of the original source image
    altsrc     = roi.roi(src, [(-5, 8), (-5, 8), (-5, 8)])
    altsrc, xf = resample.resample(altsrc, (6, 6, 6))
    altsrc     = fslimage.Image(altsrc, xform=xf, header=src.header)
    expect, xf = resample.resampleToReference(
        altsrc, ref, matrix=src2ref, order=1, mode='nearest')
    premat = affine.concat(src   .getAffine('world', 'voxel'),
                           altsrc.getAffine('voxel', 'world'))
    result = nonlinear.applyDeformation(
        altsrc, field, order=1, mode='nearest', premat=premat)
    assert np.all(np.isclose(expect, result))


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
def test_applyDeformation_altref():
    src2ref = affine.compose(
        np.random.randint(2, 5, 3),
        np.random.randint(1, 10, 3),
        np.random.random(3))
    ref2src = affine.invert(src2ref)

    srcdata = np.random.randint(1, 65536, (10, 10, 10))
    refdata = np.random.randint(1, 65536, (10, 10, 10))

    src   = fslimage.Image(srcdata)
    ref   = fslimage.Image(refdata, xform=src2ref)
    field = _affine_field(src, ref, ref2src, 'world', 'world')

    altrefxform = affine.concat(
        src2ref,
        affine.scaleOffsetXform([1, 1, 1], [5, 0, 0]))

    altref = fslimage.Image(refdata, xform=altrefxform)

    expect, xf = resample.resampleToReference(
        src, altref, matrix=src2ref, order=1, mode='constant', cval=0)
    result = nonlinear.applyDeformation(
        src, field, ref=altref, order=1, mode='constant', cval=0)

529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
    # boundary voxels can get truncated
    # (4 is the altref-ref overlap boundary)
    expect[4, :, :] = 0
    result[4, :, :] = 0
    expect = expect[1:-1, 1:-1, 1:-1]
    result = result[1:-1, 1:-1, 1:-1]

    assert np.all(np.isclose(expect, result))


# test when reference/field
# are not voxel-aligned
def test_applyDeformation_worldAligned():
    refv2w   = affine.scaleOffsetXform([1, 1, 1], [10,   10,   10])
    fieldv2w = affine.scaleOffsetXform([2, 2, 2], [10.5, 10.5, 10.5])
    src2ref  = refv2w
    ref2src  = affine.invert(src2ref)

    srcdata = np.random.randint(1, 65536, (10, 10, 10))

    src   = fslimage.Image(srcdata)
    ref   = fslimage.Image(srcdata, xform=src2ref)
    field = _affine_field(src, ref, ref2src, 'world', 'world',
                          shape=(5, 5, 5), fv2w=fieldv2w)

    field = nonlinear.DeformationField(
        nonlinear.convertDeformationType(field, 'absolute'),
        header=field.header,
        src=src,
        ref=ref,
        srcSpace='world',
        refSpace='world',
        defType='absolute')

    expect, xf = resample.resampleToReference(
        src, ref, matrix=src2ref, order=1, mode='constant', cval=0)
    result = nonlinear.applyDeformation(
        src, field, order=1, mode='constant', cval=0)

568
569
570
571
    expect = expect[1:-1, 1:-1, 1:-1]
    result = result[1:-1, 1:-1, 1:-1]

    assert np.all(np.isclose(expect, result))