예제 #1
0
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))
예제 #2
0
def test_readFnirt():

    src = op.join(datadir, 'src')
    ref = op.join(datadir, 'ref')
    coef = op.join(datadir, 'coefficientfield')
    disp = op.join(datadir, 'displacementfield')

    src = fslimage.Image(src)
    ref = fslimage.Image(ref)
    coef = fnirt.readFnirt(coef, src, ref)
    disp = fnirt.readFnirt(disp, src, ref)

    with pytest.raises(ValueError):
        fnirt.readFnirt(src, src, ref)

    assert isinstance(coef, nonlinear.CoefficientField)
    assert isinstance(disp, nonlinear.DeformationField)

    assert coef.src.sameSpace(src)
    assert coef.ref.sameSpace(ref)
    assert disp.src.sameSpace(src)
    assert disp.ref.sameSpace(ref)
    assert coef.srcSpace == 'fsl'
    assert coef.refSpace == 'fsl'
    assert disp.srcSpace == 'fsl'
    assert disp.refSpace == 'fsl'
예제 #3
0
def test_coefficientFieldToDeformationField():

    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)
    rdf = fnirt.readFnirt(df, src, ref)
    rdfnp = fnirt.readFnirt(dfnp, src, ref)
    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)

    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))
예제 #4
0
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))
예제 #5
0
def test_convert_fnirt_coefficient_field():

    datadir = op.join(op.dirname(__file__), '..', 'test_transform', 'testdata',
                      'nonlinear')
    srcfile = op.join(datadir, 'src.nii.gz')
    reffile = op.join(datadir, 'ref.nii.gz')
    cffile = op.join(datadir, 'coefficientfield.nii.gz')
    dffile = op.join(datadir, 'displacementfield.nii.gz')

    with tempdir.tempdir():

        # nii -> x5
        fsl_convert_x5.main('fnirt -s {} -r {} {} coef.x5'.format(
            srcfile, reffile, cffile).split())

        # x5 -> nii
        fsl_convert_x5.main('fnirt coef.x5 coef.nii.gz'.split())

        src = fslimage.Image(srcfile)
        ref = fslimage.Image(reffile)
        df = fnirt.readFnirt(dffile, src, ref)
        dfnii = fnirt.readFnirt('coef.nii.gz', src, ref)

        assert dfnii.sameSpace(df)
        assert dfnii.src.sameSpace(src)
        assert dfnii.ref.sameSpace(ref)

        assert dfnii.srcSpace == df.srcSpace
        assert dfnii.refSpace == df.refSpace
        assert dfnii.deformationType == 'relative'

        diff = np.abs(dfnii.data - df.data)
        tols = {'rtol': 1e-5, 'atol': 1e-5}
        assert np.all(np.isclose(dfnii.data, df.data, **tols))
예제 #6
0
def test_convert_fnirt_deformation_field():

    datadir = op.join(op.dirname(__file__), '..', 'test_transform', 'testdata',
                      'nonlinear')
    srcfile = op.join(datadir, 'src.nii.gz')
    reffile = op.join(datadir, 'ref.nii.gz')
    dffile = op.join(datadir, 'displacementfield.nii.gz')

    with tempdir.tempdir():

        # nii -> x5
        fsl_convert_x5.main('fnirt -s {} -r {} {} disp.x5'.format(
            srcfile, reffile, dffile).split())

        # x5 -> nii
        fsl_convert_x5.main('fnirt disp.x5 disp.nii.gz'.split())

        src = fslimage.Image(srcfile)
        ref = fslimage.Image(reffile)
        df = fnirt.readFnirt(dffile, src, ref)
        dfnii = fnirt.readFnirt('disp.nii.gz', src, ref)

        assert dfnii.src.sameSpace(src)
        assert dfnii.ref.sameSpace(ref)
        assert dfnii.srcSpace == df.srcSpace
        assert dfnii.refSpace == df.refSpace
        assert dfnii.deformationType == df.deformationType
        assert np.all(np.isclose(dfnii.data, df.data))
예제 #7
0
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))
예제 #8
0
def test_toFnirt():
    def check(got, exp):
        tol = dict(atol=1e-5, rtol=1e-5)
        assert np.all(np.isclose(got.data, exp.data, **tol))
        assert got.src.sameSpace(exp.src)
        assert got.ref.sameSpace(exp.ref)
        assert got.srcSpace == 'fsl'
        assert got.refSpace == 'fsl'

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

    spaces = it.permutations(('voxel', 'fsl', 'world'), 2)

    for from_, to in spaces:
        field = nonlinear.convertDeformationSpace(basefield, from_, to)
        got = fnirt.toFnirt(field)
        check(got, basefield)

    src = fslimage.Image(op.join(datadir, 'src'))
    ref = fslimage.Image(op.join(datadir, 'ref'))
    coef = fnirt.readFnirt(op.join(datadir, 'coefficientfield'), src, ref)
    got = fnirt.toFnirt(coef)
    check(got, coef)
예제 #9
0
파일: test_x5.py 프로젝트: physimals/fslpy
def test_readWriteNonLinearX5():
    datadir = op.join(op.dirname(__file__), 'testdata', 'nonlinear')
    dffile = op.join(datadir, 'displacementfield.nii.gz')
    srcfile = op.join(datadir, 'src.nii.gz')
    reffile = op.join(datadir, 'ref.nii.gz')

    src = fslimage.Image(srcfile)
    ref = fslimage.Image(reffile)
    dfield = fnirt.readFnirt(dffile, src, ref)
    wdfield = nonlinear.convertDeformationSpace(dfield, 'world', 'world')

    with tempdir.tempdir():

        # field must be world->world
        with pytest.raises(x5.X5Error):
            x5.writeNonLinearX5('nonlinear.x5', dfield)

        x5.writeNonLinearX5('nonlinear.x5', wdfield)

        gotdfield = x5.readNonLinearX5('nonlinear.x5')

        assert gotdfield.src.sameSpace(src)
        assert gotdfield.ref.sameSpace(ref)
        assert gotdfield.srcSpace == wdfield.srcSpace
        assert gotdfield.refSpace == wdfield.refSpace
        assert gotdfield.deformationType == wdfield.deformationType
        assert np.all(np.isclose(gotdfield.data, wdfield.data))

        with h5py.File('nonlinear.x5', 'r') as f:
            assert f.attrs['Type'] == 'nonlinear'
            _check_metadata(f)
            _check_deformation(f['/Transform'], wdfield)
            _check_space(f['/A'], ref)
            _check_space(f['/B'], src)
예제 #10
0
def test_fromFnirt():

    basefield, basexform = _random_affine_field()
    src = basefield.src
    ref = basefield.ref
    spaces = list(it.permutations(('voxel', 'fsl', 'world'), 2))

    for from_, to in spaces:

        got = fnirt.fromFnirt(basefield, from_, to)

        assert got.srcSpace == to
        assert got.refSpace == from_

        coords = [
            np.random.randint(0, basefield.shape[0], 5),
            np.random.randint(0, basefield.shape[1], 5),
            np.random.randint(0, basefield.shape[2], 5)
        ]
        coords = np.array(coords).T

        coords = affine.transform(coords, ref.getAffine('voxel', from_))

        aff = affine.concat(src.getAffine('fsl', to), basexform,
                            ref.getAffine(from_, 'fsl'))

        got = got.transform(coords)
        exp = affine.transform(coords, aff)

        enan = np.isnan(exp)
        gnan = np.isnan(got)

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

    # Converting from a FNIRT coefficient field
    src = fslimage.Image(op.join(datadir, 'src'))
    ref = fslimage.Image(op.join(datadir, 'ref'))
    coef = fnirt.readFnirt(op.join(datadir, 'coefficientfield'), src, ref)
    disp = fnirt.readFnirt(op.join(datadir, 'displacementfield'), src, ref)

    for from_, to in spaces:

        cnv = fnirt.fromFnirt(coef, from_, to)
        exp = nonlinear.convertDeformationSpace(disp, from_, to)
        tol = dict(atol=1e-5, rtol=1e-5)
        assert np.all(np.isclose(cnv.data, exp.data, **tol))
예제 #11
0
    def get_for_row(self, afq_object, row):
        nearest_warp, nearest_space = self.fnames[row['ses']][row['subject']]

        our_templ = afq_object.reg_template_img
        subj = Image(row['dwi_file'])
        their_templ = Image(nearest_space)
        warp = readFnirt(nearest_warp, their_templ, subj)

        return ConformedFnirtMapping(warp, our_templ.affine)
예제 #12
0
def fnirtToX5(args):
    """Convert a non-linear FNIRT transformation into an X5 transformation
    file.
    """
    src   = args.source
    ref   = args.reference
    field = fnirt.readFnirt(args.input, src=src, ref=ref)
    field = fnirt.fromFnirt(field, 'world', 'world')
    x5.writeNonLinearX5(args.output, field)
예제 #13
0
파일: mapping.py 프로젝트: bloomdt-uw/pyAFQ
    def get_for_subses(self, subses_dict, reg_template, reg_subject):
        nearest_warp, nearest_space = self.fnames[subses_dict['ses']][
            subses_dict['subject']]

        our_templ = reg_template
        subj = Image(subses_dict['dwi_file'])
        their_templ = Image(nearest_space)
        warp = readFnirt(nearest_warp, their_templ, subj)

        return ConformedFnirtMapping(warp, our_templ.affine)
예제 #14
0
def test_readFnirt_defType_intent():
    src = op.join(datadir, 'src.nii.gz')
    ref = op.join(datadir, 'ref.nii.gz')
    coef = op.join(datadir, 'coefficientfield.nii.gz')
    disp = op.join(datadir, 'displacementfield.nii.gz')

    src = fslimage.Image(src)
    ref = fslimage.Image(ref)

    field = fnirt.readFnirt(disp, src, ref, defType='absolute')
    assert field.deformationType == 'absolute'
    field = fnirt.readFnirt(disp, src, ref, defType='relative')
    assert field.deformationType == 'relative'

    img = nib.load(coef)
    img.header['intent_code'] = 0
    with tempdir.tempdir():
        img.to_filename('field.nii.gz')

        with pytest.raises(ValueError):
            fnirt.readFnirt('field', src, ref)

        field = fnirt.readFnirt('field',
                                src,
                                ref,
                                intent=constants.FSL_CUBIC_SPLINE_COEFFICIENTS)
        assert isinstance(field, nonlinear.CoefficientField)

        field = fnirt.readFnirt('field',
                                src,
                                ref,
                                intent=constants.FSL_FNIRT_DISPLACEMENT_FIELD)
        assert isinstance(field, nonlinear.DeformationField)