Пример #1
0
def test_staple():

    # Create a node object
    staple = LabelFusion()

    # Check if the command is properly defined
    assert staple.cmd == get_custom_path('seg_LabFusion')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        staple.run()

    # Assign some input data
    in_file = example_data('im1.nii')
    file_to_seg = example_data('im2.nii')
    template_file = example_data('im3.nii')
    staple.inputs.in_file = in_file
    staple.inputs.kernel_size = 2.0
    staple.inputs.file_to_seg = file_to_seg
    staple.inputs.template_file = template_file
    staple.inputs.template_num = 2
    staple.inputs.classifier_type = 'STAPLE'

    cmd_tmp = '{cmd} -in {in_file} -STAPLE -ALL -out {out_file}'
    expected_cmd = cmd_tmp.format(cmd=get_custom_path('seg_LabFusion'),
                                  in_file=in_file,
                                  file_to_seg=file_to_seg,
                                  template_file=template_file,
                                  out_file=os.path.join(
                                      os.getcwd(), 'im1_staple.nii'))

    assert staple.cmdline == expected_cmd
Пример #2
0
def test_mv():

    # Create a node object
    mv = LabelFusion()

    # Check if the command is properly defined
    assert mv.cmd == get_custom_path('seg_LabFusion')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        mv.run()

    # Assign some input data
    in_file = example_data('im1.nii')
    file_to_seg = example_data('im2.nii')
    template_file = example_data('im3.nii')
    mv.inputs.in_file = in_file
    mv.inputs.file_to_seg = file_to_seg
    mv.inputs.template_file = template_file
    mv.inputs.template_num = 2
    mv.inputs.classifier_type = 'MV'
    mv.inputs.sm_ranking = 'ROINCC'
    mv.inputs.dilation_roi = 2

    cmd_tmp = '{cmd} -in {in_file} -MV -ROINCC 2 2 {file_to_seg} \
{template_file} -out {out_file}'

    expected_cmd = cmd_tmp.format(cmd=get_custom_path('seg_LabFusion'),
                                  in_file=in_file,
                                  file_to_seg=file_to_seg,
                                  template_file=template_file,
                                  out_file=os.path.join(
                                      os.getcwd(), 'im1_mv.nii'))

    assert mv.cmdline == expected_cmd
Пример #3
0
def test_reg_jacobian_jac_l():

    # Create a reg_jacobian object
    nr = RegJacobian()

    # Check if the command is properly defined
    assert nr.cmd == get_custom_path('reg_jacobian')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        nr.run()

    # Assign some input data
    ref_file = example_data('im1.nii')
    trans_file = example_data('warpfield.nii')
    nr.inputs.ref_file = ref_file
    nr.inputs.trans_file = trans_file
    nr.inputs.type = 'jacL'
    nr.inputs.omp_core_val = 4

    cmd_tmp = '{cmd} -omp 4 -ref {ref} -trans {trans} -jacL {jac}'
    expected_cmd = cmd_tmp.format(
        cmd=get_custom_path('reg_jacobian'),
        ref=ref_file,
        trans=trans_file,
        jac=os.path.join(os.getcwd(), 'warpfield_jacL.nii.gz'))

    assert nr.cmdline == expected_cmd
Пример #4
0
def test_normalize_tpms(tmpdir):

    in_mask = example_data("tpms_msk.nii.gz")
    mskdata = np.asanyarray(nb.load(in_mask).dataobj)
    mskdata[mskdata > 0.0] = 1.0

    mapdata = []
    in_files = []
    out_files = []

    for i in range(3):
        mapname = example_data("tpm_%02d.nii.gz" % i)
        filename = tmpdir.join("modtpm_%02d.nii.gz" % i).strpath
        out_files.append(tmpdir.join("normtpm_%02d.nii.gz" % i).strpath)

        im = nb.load(mapname)
        data = im.get_fdata()
        mapdata.append(data)

        nb.Nifti1Image(2.0 * (data * mskdata), im.affine,
                       im.header).to_filename(filename)
        in_files.append(filename)

    normalize_tpms(in_files, in_mask, out_files=out_files)

    sumdata = np.zeros_like(mskdata)

    for i, tstfname in enumerate(out_files):
        normdata = nb.load(tstfname).get_fdata()
        sumdata += normdata
        assert np.all(normdata[mskdata == 0] == 0)
        assert np.allclose(normdata, mapdata[i])

    assert np.allclose(sumdata[sumdata > 0.0], 1.0)
Пример #5
0
def test_reg_average_avg_lts():

    # Create a reg_average object
    nr = RegAverage()

    # Check if the command is properly defined
    assert nr.cmd == get_custom_path('reg_average')

    # Assign some input data
    one_file = example_data('TransformParameters.0.txt')
    two_file = example_data('ants_Affine.txt')
    three_file = example_data('elastix.txt')
    nr.inputs.avg_lts_files = [one_file, two_file, three_file]
    nr.cmdline

    # Read the reg_average_cmd
    reg_average_cmd = os.path.join(os.getcwd(), 'reg_average_cmd')
    with open(reg_average_cmd, 'rb') as f:
        argv = f.read()
    os.remove(reg_average_cmd)

    expected_argv = ('%s %s -avg_lts %s %s %s' %
                     (get_custom_path('reg_average'),
                      os.path.join(os.getcwd(), 'avg_out.txt'), one_file,
                      two_file, three_file))

    assert argv == expected_argv

    expected_cmd = ('%s --cmd_file %s' %
                    (get_custom_path('reg_average'), reg_average_cmd))

    assert nr.cmdline == expected_cmd
Пример #6
0
def test_reg_transform_comp_nii():

    # Create a reg_transform object
    nr = RegTransform()

    # Check if the command is properly defined
    assert nr.cmd == get_custom_path('reg_transform')

    # Assign some input data
    ref_file = example_data('im1.nii')
    trans_file = example_data('warpfield.nii')
    trans2_file = example_data('anatomical.nii')
    nr.inputs.ref1_file = ref_file
    nr.inputs.comp_input2 = trans2_file
    nr.inputs.comp_input = trans_file
    nr.inputs.omp_core_val = 4

    cmd_tmp = '{cmd} -ref {ref_file} -omp 4 -comp {trans1} {trans2} {out_file}'
    expected_cmd = cmd_tmp.format(cmd=get_custom_path('reg_transform'),
                                  ref_file=ref_file,
                                  trans1=trans_file,
                                  trans2=trans2_file,
                                  out_file=os.path.join(
                                      os.getcwd(), 'warpfield_trans.nii.gz'))

    assert nr.cmdline == expected_cmd
Пример #7
0
def test_reg_f3d():

    # Create a reg_f3d object
    nr = RegF3D()

    # Check if the command is properly defined
    yield assert_equal, nr.cmd, get_custom_path('reg_f3d')

    # Assign some input data
    ref_file = example_data('im1.nii')
    flo_file = example_data('im2.nii')
    rmask_file = example_data('mask.nii')
    nr.inputs.ref_file = ref_file
    nr.inputs.flo_file = flo_file
    nr.inputs.rmask_file = rmask_file
    nr.inputs.omp_core_val = 4
    nr.inputs.vel_flag = True
    nr.inputs.be_val = 0.1
    nr.inputs.le_val = 0.1

    expected_cmd = get_custom_path('reg_f3d') + ' ' + '-be 0.100000 ' +\
                   '-cpp ' + os.getcwd() + os.sep + 'im2_cpp.nii.gz ' +'-flo ' + flo_file + ' ' +\
                   '-le 0.100000 ' + '-omp 4 ' + '-ref ' + ref_file + ' ' +\
                   '-res ' + os.getcwd() + os.sep + 'im2_res.nii.gz ' + '-rmask ' + rmask_file + ' ' + '-vel'
    yield assert_equal, nr.cmdline, expected_cmd
Пример #8
0
def test_reg_average_avg_lts():

    # Create a reg_average object
    nr = RegAverage()

    # Check if the command is properly defined
    yield assert_equal, nr.cmd, get_custom_path('reg_average')

    # Assign some input data
    one_file = example_data('TransformParameters.0.txt')
    two_file = example_data('ants_Affine.txt')
    three_file = example_data('elastix.txt')
    nr.inputs.avg_lts_files = [one_file, two_file, three_file]
    nr.cmdline

    # Read the reg_average_cmd
    reg_average_cmd = os.path.join(os.getcwd(), 'reg_average_cmd')
    with open(reg_average_cmd, 'rb') as f:
        argv = f.read()
    os.remove(reg_average_cmd)

    expected_argv = ('%s %s -avg_lts %s %s %s'
                     % (get_custom_path('reg_average'),
                        os.path.join(os.getcwd(), 'avg_out.txt'),
                        one_file, two_file, three_file))

    yield assert_equal, argv, expected_argv

    expected_cmd = ('%s --cmd_file %s'
                    % (get_custom_path('reg_average'), reg_average_cmd))

    yield assert_equal, nr.cmdline, expected_cmd
Пример #9
0
def test_overlap(tmpdir):
    from nipype.algorithms.metrics import Overlap

    def check_close(val1, val2):
        import numpy.testing as npt

        return npt.assert_almost_equal(val1, val2, decimal=3)

    in1 = example_data("segmentation0.nii.gz")
    in2 = example_data("segmentation1.nii.gz")

    tmpdir.chdir()
    overlap = Overlap()
    overlap.inputs.volume1 = in1
    overlap.inputs.volume2 = in1
    res = overlap.run()
    check_close(res.outputs.jaccard, 1.0)

    overlap = Overlap()
    overlap.inputs.volume1 = in1
    overlap.inputs.volume2 = in2
    res = overlap.run()
    check_close(res.outputs.jaccard, 0.99705)

    overlap = Overlap()
    overlap.inputs.volume1 = in1
    overlap.inputs.volume2 = in2
    overlap.inputs.vol_units = "mm"
    res = overlap.run()
    check_close(res.outputs.jaccard, 0.99705)
    check_close(res.outputs.roi_voldiff, np.array([0.0063086, -0.0025506,
                                                   0.0]))
Пример #10
0
def test_dvars(tmpdir):
    ground_truth = np.loadtxt(example_data('ds003_sub-01_mc.DVARS'))
    dvars = ComputeDVARS(
        in_file=example_data('ds003_sub-01_mc.nii.gz'),
        in_mask=example_data('ds003_sub-01_mc_brainmask.nii.gz'),
        save_all=True,
        intensity_normalization=0)
    os.chdir(str(tmpdir))
    res = dvars.run()

    dv1 = np.loadtxt(res.outputs.out_all, skiprows=1)
    assert (np.abs(dv1[:, 0] - ground_truth[:, 0]).sum() / len(dv1)) < 0.05

    assert (np.abs(dv1[:, 1] - ground_truth[:, 1]).sum() / len(dv1)) < 0.05

    assert (np.abs(dv1[:, 2] - ground_truth[:, 2]).sum() / len(dv1)) < 0.05

    dvars = ComputeDVARS(
        in_file=example_data('ds003_sub-01_mc.nii.gz'),
        in_mask=example_data('ds003_sub-01_mc_brainmask.nii.gz'),
        save_all=True)
    res = dvars.run()

    dv1 = np.loadtxt(res.outputs.out_all, skiprows=1)
    assert (np.abs(dv1[:, 0] - ground_truth[:, 0]).sum() / len(dv1)) < 0.05

    assert (np.abs(dv1[:, 1] - ground_truth[:, 1]).sum() / len(dv1)) > 0.05

    assert (np.abs(dv1[:, 2] - ground_truth[:, 2]).sum() / len(dv1)) < 0.05
Пример #11
0
def test_bedpostx2():
    filelist, outdir, cwd = create_files_in_directory()
    bpx = fsl.BEDPOSTX()

    # make sure command gets called
    yield assert_equal, bpx.cmd, 'bedpostx'

    # test raising error with mandatory args absent
    yield assert_raises, ValueError, bpx.run

    # .inputs based parameters setting
    bpx2 = fsl.BEDPOSTX()
    bpx2.inputs.mask = example_data('mask.nii')
    bpx2.inputs.dwi = example_data('diffusion.nii')
    bpx2.inputs.bvals = example_data('bvals')
    bpx2.inputs.bvecs = example_data('bvecs')
    bpx2.inputs.fibres = 2
    bpx2.inputs.weight = 0.3
    bpx2.inputs.burn_period = 200
    bpx2.inputs.jumps = 500
    bpx2.inputs.sampling = 20
    actualCmdline = sorted(bpx2.cmdline.split())
    cmd = 'bedpostx bedpostx -b 200 -n 2 -j 500 -s 20 -w 0.30'
    desiredCmdline = sorted(cmd.split())
    yield assert_equal, actualCmdline, desiredCmdline
Пример #12
0
def test_reg_aladin():

    # Create a reg_aladin object
    nr = RegAladin()

    # Check if the command is properly defined
    assert nr.cmd == get_custom_path('reg_aladin')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        nr.run()

    # Assign some input data
    ref_file = example_data('im1.nii')
    flo_file = example_data('im2.nii')
    rmask_file = example_data('mask.nii')
    nr.inputs.ref_file = ref_file
    nr.inputs.flo_file = flo_file
    nr.inputs.rmask_file = rmask_file
    nr.inputs.omp_core_val = 4

    cmd_tmp = '{cmd} -aff {aff} -flo {flo} -omp 4 -ref {ref} -res {res} \
-rmask {rmask}'
    expected_cmd = cmd_tmp.format(
        cmd=get_custom_path('reg_aladin'),
        aff=os.path.join(os.getcwd(), 'im2_aff.txt'),
        flo=flo_file,
        ref=ref_file,
        res=os.path.join(os.getcwd(), 'im2_res.nii.gz'),
        rmask=rmask_file)

    assert nr.cmdline == expected_cmd
Пример #13
0
def test_reg_jacobian_jac_l():

    # Create a reg_jacobian object
    nr = RegJacobian()

    # Check if the command is properly defined
    assert nr.cmd == get_custom_path('reg_jacobian')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        nr.run()

    # Assign some input data
    ref_file = example_data('im1.nii')
    trans_file = example_data('warpfield.nii')
    nr.inputs.ref_file = ref_file
    nr.inputs.trans_file = trans_file
    nr.inputs.type = 'jacL'
    nr.inputs.omp_core_val = 4

    cmd_tmp = '{cmd} -omp 4 -ref {ref} -trans {trans} -jacL {jac}'
    expected_cmd = cmd_tmp.format(cmd=get_custom_path('reg_jacobian'),
                                  ref=ref_file,
                                  trans=trans_file,
                                  jac=os.path.join(os.getcwd(),
                                                   'warpfield_jacL.nii.gz'))

    assert nr.cmdline == expected_cmd
Пример #14
0
def test_seg_filllesions():

    # Create a node object
    seg_fill = FillLesions()

    # Check if the command is properly defined
    assert seg_fill.cmd == get_custom_path('seg_FillLesions')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        seg_fill.run()

    # Assign some input data
    in_file = example_data('im1.nii')
    lesion_mask = example_data('im2.nii')
    seg_fill.inputs.in_file = in_file
    seg_fill.inputs.lesion_mask = lesion_mask

    expected_cmd = '{cmd} -i {in_file} -l {lesion_mask} -o {out_file}'.format(
                cmd=get_custom_path('seg_FillLesions'),
                in_file=in_file,
                lesion_mask=lesion_mask,
                out_file=os.path.join(os.getcwd(), 'im1_lesions_filled.nii'))

    assert seg_fill.cmdline == expected_cmd
Пример #15
0
def test_reg_f3d():
    """ tests for reg_f3d interface"""
    # Create a reg_f3d object
    nr_f3d = RegF3D()

    # Check if the command is properly defined
    assert nr_f3d.cmd == get_custom_path('reg_f3d')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        nr_f3d.run()

    # Assign some input data
    ref_file = example_data('im1.nii')
    flo_file = example_data('im2.nii')
    rmask_file = example_data('mask.nii')
    nr_f3d.inputs.ref_file = ref_file
    nr_f3d.inputs.flo_file = flo_file
    nr_f3d.inputs.rmask_file = rmask_file
    nr_f3d.inputs.omp_core_val = 4
    nr_f3d.inputs.vel_flag = True
    nr_f3d.inputs.be_val = 0.1
    nr_f3d.inputs.le_val = 0.1

    cmd_tmp = '{cmd} -be 0.100000 -cpp {cpp} -flo {flo} -le 0.100000 -omp 4 \
-ref {ref} -res {res} -rmask {rmask} -vel'
    expected_cmd = cmd_tmp.format(
        cmd=get_custom_path('reg_f3d'),
        cpp=os.path.join(os.getcwd(), 'im2_cpp.nii.gz'),
        flo=flo_file,
        ref=ref_file,
        res=os.path.join(os.getcwd(), 'im2_res.nii.gz'),
        rmask=rmask_file)

    assert nr_f3d.cmdline == expected_cmd
Пример #16
0
def test_staple():

    # Create a node object
    staple = LabelFusion()

    # Check if the command is properly defined
    assert staple.cmd == get_custom_path('seg_LabFusion')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        staple.run()

    # Assign some input data
    in_file = example_data('im1.nii')
    file_to_seg = example_data('im2.nii')
    template_file = example_data('im3.nii')
    staple.inputs.in_file = in_file
    staple.inputs.kernel_size = 2.0
    staple.inputs.file_to_seg = file_to_seg
    staple.inputs.template_file = template_file
    staple.inputs.template_num = 2
    staple.inputs.classifier_type = 'STAPLE'

    cmd_tmp = '{cmd} -in {in_file} -STAPLE -ALL -out {out_file}'
    expected_cmd = cmd_tmp.format(
                        cmd=get_custom_path('seg_LabFusion'),
                        in_file=in_file,
                        file_to_seg=file_to_seg,
                        template_file=template_file,
                        out_file=os.path.join(os.getcwd(), 'im1_staple.nii'))

    assert staple.cmdline == expected_cmd
Пример #17
0
def test_mv():

    # Create a node object
    mv = LabelFusion()

    # Check if the command is properly defined
    assert mv.cmd == get_custom_path('seg_LabFusion')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        mv.run()

    # Assign some input data
    in_file = example_data('im1.nii')
    file_to_seg = example_data('im2.nii')
    template_file = example_data('im3.nii')
    mv.inputs.in_file = in_file
    mv.inputs.file_to_seg = file_to_seg
    mv.inputs.template_file = template_file
    mv.inputs.template_num = 2
    mv.inputs.classifier_type = 'MV'
    mv.inputs.sm_ranking = 'ROINCC'
    mv.inputs.dilation_roi = 2

    cmd_tmp = '{cmd} -in {in_file} -MV -ROINCC 2 2 {file_to_seg} \
{template_file} -out {out_file}'
    expected_cmd = cmd_tmp.format(
                        cmd=get_custom_path('seg_LabFusion'),
                        in_file=in_file,
                        file_to_seg=file_to_seg,
                        template_file=template_file,
                        out_file=os.path.join(os.getcwd(), 'im1_mv.nii'))

    assert mv.cmdline == expected_cmd
Пример #18
0
def test_reg_average_avg_nii():

    # Create a reg_average object
    nr = RegAverage()

    # Check if the command is properly defined
    assert nr.cmd == get_custom_path('reg_average')

    # Assign some input data
    one_file = example_data('im1.nii')
    two_file = example_data('im2.nii')
    three_file = example_data('im3.nii')
    nr.inputs.avg_files = [one_file, two_file, three_file]
    nr.cmdline

    # Read the reg_average_cmd
    reg_average_cmd = os.path.join(os.getcwd(), 'reg_average_cmd')
    with open(reg_average_cmd, 'rb') as f:
        argv = f.read()
    os.remove(reg_average_cmd)

    expected_argv = '%s %s -avg %s %s %s' % (get_custom_path(
        'reg_average'), os.path.join(
            os.getcwd(), 'avg_out.nii.gz'), one_file, two_file, three_file)

    assert argv == expected_argv

    expected_cmd = ('%s --cmd_file %s' %
                    (get_custom_path('reg_average'), reg_average_cmd))

    assert nr.cmdline == expected_cmd
Пример #19
0
def test_reg_measure():
    """ tests for reg_measure interface """
    # Create a reg_measure object
    nr_measure = RegMeasure()

    # Check if the command is properly defined
    assert nr_measure.cmd == get_custom_path('reg_measure')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        nr_measure.run()

    # Assign some input data
    ref_file = example_data('im1.nii')
    flo_file = example_data('im2.nii')
    nr_measure.inputs.ref_file = ref_file
    nr_measure.inputs.flo_file = flo_file
    nr_measure.inputs.measure_type = 'lncc'
    nr_measure.inputs.omp_core_val = 4

    cmd_tmp = '{cmd} -flo {flo} -lncc -omp 4 -out {out} -ref {ref}'
    expected_cmd = cmd_tmp.format(
        cmd=get_custom_path('reg_measure'),
        flo=flo_file,
        out='im2_lncc.txt',
        ref=ref_file)

    assert nr_measure.cmdline == expected_cmd
Пример #20
0
def test_dvars(tmpdir):
    ground_truth = np.loadtxt(example_data('ds003_sub-01_mc.DVARS'))
    dvars = ComputeDVARS(in_file=example_data('ds003_sub-01_mc.nii.gz'),
                         in_mask=example_data('ds003_sub-01_mc_brainmask.nii.gz'),
                         save_all=True,
                         intensity_normalization=0)
    os.chdir(str(tmpdir))
    res = dvars.run()

    dv1 = np.loadtxt(res.outputs.out_all, skiprows=1)
    assert (np.abs(dv1[:, 0] - ground_truth[:, 0]).sum()/ len(dv1)) < 0.05

    assert (np.abs(dv1[:, 1] - ground_truth[:, 1]).sum() / len(dv1)) < 0.05

    assert (np.abs(dv1[:, 2] - ground_truth[:, 2]).sum() / len(dv1)) < 0.05

    dvars = ComputeDVARS(in_file=example_data('ds003_sub-01_mc.nii.gz'),
                         in_mask=example_data(
                             'ds003_sub-01_mc_brainmask.nii.gz'),
                         save_all=True)
    res = dvars.run()

    dv1 = np.loadtxt(res.outputs.out_all, skiprows=1)
    assert (np.abs(dv1[:, 0] - ground_truth[:, 0]).sum() / len(dv1)) < 0.05

    assert (np.abs(dv1[:, 1] - ground_truth[:, 1]).sum() / len(dv1)) > 0.05

    assert (np.abs(dv1[:, 2] - ground_truth[:, 2]).sum() / len(dv1)) < 0.05
Пример #21
0
def test_merge():

    # Create a node object
    merge = Merge()

    # Check if the command is properly defined
    assert merge.cmd == get_custom_path('seg_maths')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        merge.run()

    # Assign some input data
    in_file = example_data('im1.nii')
    file1 = example_data('im2.nii')
    file2 = example_data('im3.nii')
    merge.inputs.in_file = in_file
    merge.inputs.merge_files = [file1, file2]
    merge.inputs.dimension = 2
    merge.inputs.output_datatype = 'float'

    cmd_tmp = '{cmd} {in_file} -merge 2 2 {f1} {f2} -odt float {out_file}'
    expected_cmd = cmd_tmp.format(
        cmd=get_custom_path('seg_maths'),
        in_file=in_file,
        f1=file1,
        f2=file2,
        out_file=os.path.join(os.getcwd(), 'im1_merged.nii'))

    assert merge.cmdline == expected_cmd
Пример #22
0
def test_tuple_maths():

    # Create a node object
    tuplem = TupleMaths()

    # Check if the command is properly defined
    assert tuplem.cmd == get_custom_path('seg_maths')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        tuplem.run()

    # Assign some input data
    in_file = example_data('im1.nii')
    op_file = example_data('im2.nii')
    tuplem.inputs.in_file = in_file
    tuplem.inputs.operation = 'lncc'
    tuplem.inputs.operand_file1 = op_file
    tuplem.inputs.operand_value2 = 2.0
    tuplem.inputs.output_datatype = 'float'

    cmd_tmp = '{cmd} {in_file} -lncc {op} 2.00000000 -odt float {out_file}'
    expected_cmd = cmd_tmp.format(
        cmd=get_custom_path('seg_maths'),
        in_file=in_file,
        op=op_file,
        out_file=os.path.join(os.getcwd(), 'im1_lncc.nii'))

    assert tuplem.cmdline == expected_cmd
Пример #23
0
def test_seg_em():

    # Create a reg_aladin object
    test_node = FitDwi()

    # Check if the command is properly defined
    yield assert_equal, test_node.cmd, get_custom_path('fit_dwi')

    # Assign some input data
    in_file = example_data('diffusion.nii')
    bval_file = example_data('bvals')
    bvec_file = example_data('bvecs')
    test_node.inputs.source_file = in_file
    test_node.inputs.bval_file = bval_file
    test_node.inputs.bvec_file = bvec_file

    cmd_tmp = '{cmd} -bval {bval} -bvec {bvec} -famap dwifit__famap -mcmap \
dwifit__mcmap -mdmap dwifit__mdmap -res dwifit__resmap -rgbmap dwifit__rgbmap \
-source {in_file} -syn dwifit__syn -tenmap2 dwifit__tenmap2 -v1map \
dwifit__v1map'
    expected_cmd = cmd_tmp.format(
        cmd=get_custom_path('fit_dwi'),
        in_file=in_file,
        bval=bval_file,
        bvec=bvec_file)

    yield assert_equal, test_node.cmdline, expected_cmd
Пример #24
0
def test_JointFusion_cmd():
    at = JointFusion()
    at.inputs.dimension = 3
    at.inputs.modalities = 1
    at.inputs.method = 'Joint[0.1,2]'
    at.inputs.output_label_image = 'fusion_labelimage_output.nii'
    warped_intensity_images = [example_data('im1.nii'),
                               example_data('im2.nii')]
    at.inputs.warped_intensity_images = warped_intensity_images
    segmentation_images = [example_data('segmentation0.nii.gz'),
                           example_data('segmentation1.nii.gz')]
    at.inputs.warped_label_images = segmentation_images
    T1_image = example_data('T1.nii')
    at.inputs.target_image = T1_image
    at.inputs.patch_radius = [3,2,1]
    at.inputs.search_radius = [1,2,3]
    expected_command = ('jointfusion 3 1 -m Joint[0.1,2] -rp 3x2x1 -rs 1x2x3'
                        ' -tg %s -g %s -g %s -l %s -l %s'
                        ' fusion_labelimage_output.nii') % (T1_image,
                                                            warped_intensity_images[0],
                                                            warped_intensity_images[1],
                                                            segmentation_images[0],
                                                            segmentation_images[1])
    yield assert_equal, at.cmdline, expected_command
    # setting intensity or labels with unequal lengths raises error
    yield assert_raises, AssertionError, at._format_arg, 'warped_intensity_images', InputMultiPath, warped_intensity_images + [example_data('im3.nii')]
Пример #25
0
def test_normalize_tpms(tmpdir):
    tempdir = str(tmpdir)

    in_mask = example_data('tpms_msk.nii.gz')
    mskdata = nb.load(in_mask, mmap=NUMPY_MMAP).get_data()
    mskdata[mskdata > 0.0] = 1.0

    mapdata = []
    in_files = []
    out_files = []

    for i in range(3):
        mapname = example_data('tpm_%02d.nii.gz' % i)
        filename = os.path.join(tempdir, 'modtpm_%02d.nii.gz' % i)
        out_files.append(os.path.join(tempdir, 'normtpm_%02d.nii.gz' % i))

        im = nb.load(mapname, mmap=NUMPY_MMAP)
        data = im.get_data()
        mapdata.append(data.copy())

        nb.Nifti1Image(2.0 * (data * mskdata), im.affine,
                       im.header).to_filename(filename)
        in_files.append(filename)

    normalize_tpms(in_files, in_mask, out_files=out_files)

    sumdata = np.zeros_like(mskdata)

    for i, tstfname in enumerate(out_files):
        normdata = nb.load(tstfname, mmap=NUMPY_MMAP).get_data()
        sumdata += normdata
        assert np.all(normdata[mskdata == 0] == 0)
        assert np.allclose(normdata, mapdata[i])

    assert np.allclose(sumdata[sumdata > 0.0], 1.0)
Пример #26
0
def test_reg_average_avg_nii():

    # Create a reg_average object
    nr = RegAverage()

    # Check if the command is properly defined
    yield assert_equal, nr.cmd, get_custom_path('reg_average')

    # Assign some input data
    one_file = example_data('im1.nii')
    two_file = example_data('im2.nii')
    three_file = example_data('im3.nii')
    nr.inputs.avg_files = [one_file, two_file, three_file]
    nr.cmdline

    # Read the reg_average_cmd
    reg_average_cmd = os.path.join(os.getcwd(), 'reg_average_cmd')
    with open(reg_average_cmd, 'rb') as f:
        argv = f.read()
    os.remove(reg_average_cmd)

    expected_argv = '%s %s -avg %s %s %s' % (get_custom_path('reg_average'),
                                             os.path.join(os.getcwd(),
                                                          'avg_out.nii.gz'),
                                             one_file, two_file, three_file)

    yield assert_equal, argv, expected_argv

    expected_cmd = ('%s --cmd_file %s'
                    % (get_custom_path('reg_average'), reg_average_cmd))

    yield assert_equal, nr.cmdline, expected_cmd
Пример #27
0
def test_reg_resample_blank():

    # Create a reg_resample object
    nr = RegResample()

    # Check if the command is properly defined
    assert nr.cmd == get_custom_path('reg_resample')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        nr.run()

    # Assign some input data
    ref_file = example_data('im1.nii')
    flo_file = example_data('im2.nii')
    trans_file = example_data('warpfield.nii')
    nr.inputs.ref_file = ref_file
    nr.inputs.flo_file = flo_file
    nr.inputs.trans_file = trans_file
    nr.inputs.type = 'blank'
    nr.inputs.inter_val = 'LIN'
    nr.inputs.omp_core_val = 4

    cmd_tmp = '{cmd} -flo {flo} -inter 1 -omp 4 -ref {ref} -trans {trans} \
-blank {blank}'

    expected_cmd = cmd_tmp.format(cmd=get_custom_path('reg_resample'),
                                  flo=flo_file,
                                  ref=ref_file,
                                  trans=trans_file,
                                  blank=os.path.join(os.getcwd(),
                                                     'im2_blank.nii.gz'))

    assert nr.cmdline == expected_cmd
Пример #28
0
def test_overlap():
    from nipype.algorithms.metrics import Overlap

    def check_close(val1, val2):
        import numpy.testing as npt
        return npt.assert_almost_equal(val1, val2, decimal=3)

    tempdir = mkdtemp()
    in1 = example_data('segmentation0.nii.gz')
    in2 = example_data('segmentation1.nii.gz')

    os.chdir(tempdir)
    overlap = Overlap()
    overlap.inputs.volume1 = in1
    overlap.inputs.volume2 = in1
    res = overlap.run()
    yield check_close, res.outputs.jaccard, 1.0
    overlap = Overlap()
    overlap.inputs.volume1 = in1
    overlap.inputs.volume2 = in2
    res = overlap.run()

    yield check_close, res.outputs.jaccard, 0.99705

    overlap = Overlap()
    overlap.inputs.volume1 = in1
    overlap.inputs.volume2 = in2
    overlap.inputs.vol_units = 'mm'
    res = overlap.run()

    yield check_close, res.outputs.jaccard, 0.99705
    yield (check_close, res.outputs.roi_voldiff,
           np.array([0.0063086, -0.0025506, 0.0]))

    rmtree(tempdir)
Пример #29
0
def test_merge():

    # Create a node object
    merge = Merge()

    # Check if the command is properly defined
    assert merge.cmd == get_custom_path('seg_maths')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        merge.run()

    # Assign some input data
    in_file = example_data('im1.nii')
    file1 = example_data('im2.nii')
    file2 = example_data('im3.nii')
    merge.inputs.in_file = in_file
    merge.inputs.merge_files = [file1, file2]
    merge.inputs.dimension = 2
    merge.inputs.output_datatype = 'float'

    cmd_tmp = '{cmd} {in_file} -merge 2 2 {f1} {f2} -odt float {out_file}'
    expected_cmd = cmd_tmp.format(cmd=get_custom_path('seg_maths'),
                                  in_file=in_file,
                                  f1=file1,
                                  f2=file2,
                                  out_file=os.path.join(
                                      os.getcwd(), 'im1_merged.nii'))

    print merge.cmdline
    print '\n'
    print expected_cmd
    assert merge.cmdline == expected_cmd
Пример #30
0
def test_reg_resample_blank():

    # Create a reg_resample object
    nr = RegResample()

    # Check if the command is properly defined
    assert nr.cmd == get_custom_path('reg_resample')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        nr.run()

    # Assign some input data
    ref_file = example_data('im1.nii')
    flo_file = example_data('im2.nii')
    trans_file = example_data('warpfield.nii')
    nr.inputs.ref_file = ref_file
    nr.inputs.flo_file = flo_file
    nr.inputs.trans_file = trans_file
    nr.inputs.type = 'blank'
    nr.inputs.inter_val = 'LIN'
    nr.inputs.omp_core_val = 4

    cmd_tmp = '{cmd} -flo {flo} -inter 1 -omp 4 -ref {ref} -trans {trans} \
-blank {blank}'
    expected_cmd = cmd_tmp.format(
        cmd=get_custom_path('reg_resample'),
        flo=flo_file,
        ref=ref_file,
        trans=trans_file,
        blank=os.path.join(os.getcwd(), 'im2_blank.nii.gz'))

    assert nr.cmdline == expected_cmd
Пример #31
0
def test_tuple_maths():

    # Create a node object
    tuplem = TupleMaths()

    # Check if the command is properly defined
    assert tuplem.cmd == get_custom_path('seg_maths')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        tuplem.run()

    # Assign some input data
    in_file = example_data('im1.nii')
    op_file = example_data('im2.nii')
    tuplem.inputs.in_file = in_file
    tuplem.inputs.operation = 'lncc'
    tuplem.inputs.operand_file1 = op_file
    tuplem.inputs.operand_value2 = 2.0
    tuplem.inputs.output_datatype = 'float'

    cmd_tmp = '{cmd} {in_file} -lncc {op} 2.00000000 -odt float {out_file}'
    expected_cmd = cmd_tmp.format(cmd=get_custom_path('seg_maths'),
                                  in_file=in_file,
                                  op=op_file,
                                  out_file=os.path.join(
                                      os.getcwd(), 'im1_lncc.nii'))

    assert tuplem.cmdline == expected_cmd
Пример #32
0
def test_seg_patchmatch():

    # Create a node object
    seg_patchmatch = PatchMatch()

    # Check if the command is properly defined
    cmd = get_custom_path('seg_PatchMatch', env_dir='NIFTYSEGDIR')
    assert seg_patchmatch.cmd == cmd

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        seg_patchmatch.run()

    # Assign some input data
    in_file = example_data('im1.nii')
    mask_file = example_data('im2.nii')
    db_file = example_data('db.xml')
    seg_patchmatch.inputs.in_file = in_file
    seg_patchmatch.inputs.mask_file = mask_file
    seg_patchmatch.inputs.database_file = db_file

    cmd_tmp = '{cmd} -i {in_file} -m {mask_file} -db {db} -o {out_file}'
    expected_cmd = cmd_tmp.format(
        cmd=cmd,
        in_file=in_file,
        mask_file=mask_file,
        db=db_file,
        out_file='im1_pm.nii.gz',
    )

    assert seg_patchmatch.cmdline == expected_cmd
Пример #33
0
def test_JointFusion_cmd():
    at = JointFusion()
    at.inputs.dimension = 3
    at.inputs.modalities = 1
    at.inputs.method = 'Joint[0.1,2]'
    at.inputs.output_label_image = 'fusion_labelimage_output.nii'
    warped_intensity_images = [example_data('im1.nii'),
                               example_data('im2.nii')]
    at.inputs.warped_intensity_images = warped_intensity_images
    segmentation_images = [example_data('segmentation0.nii.gz'),
                           example_data('segmentation1.nii.gz')]
    at.inputs.warped_label_images = segmentation_images
    T1_image = example_data('T1.nii')
    at.inputs.target_image = T1_image
    at.inputs.patch_radius = [3,2,1]
    at.inputs.search_radius = [1,2,3]
    expected_command = ('jointfusion 3 1 -m Joint[0.1,2] -rp 3x2x1 -rs 1x2x3'
                        ' -tg %s -g %s -g %s -l %s -l %s'
                        ' fusion_labelimage_output.nii') % (T1_image,
                                                            warped_intensity_images[0],
                                                            warped_intensity_images[1],
                                                            segmentation_images[0],
                                                            segmentation_images[1])
    yield assert_equal, at.cmdline, expected_command
    # setting intensity or labels with unequal lengths raises error
    yield assert_raises, AssertionError, at._format_arg, 'warped_intensity_images', InputMultiPath, warped_intensity_images + [example_data('im3.nii')]
Пример #34
0
def test_reg_measure():
    """ tests for reg_measure interface """
    # Create a reg_measure object
    nr_measure = RegMeasure()

    # Check if the command is properly defined
    assert nr_measure.cmd == get_custom_path('reg_measure')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        nr_measure.run()

    # Assign some input data
    ref_file = example_data('im1.nii')
    flo_file = example_data('im2.nii')
    nr_measure.inputs.ref_file = ref_file
    nr_measure.inputs.flo_file = flo_file
    nr_measure.inputs.measure_type = 'lncc'
    nr_measure.inputs.omp_core_val = 4

    cmd_tmp = '{cmd} -flo {flo} -lncc -omp 4 -out {out} -ref {ref}'
    expected_cmd = cmd_tmp.format(cmd=get_custom_path('reg_measure'),
                                  flo=flo_file,
                                  out=os.path.join(os.getcwd(),
                                                   'im2_lncc.txt'),
                                  ref=ref_file)

    assert nr_measure.cmdline == expected_cmd
Пример #35
0
def test_bedpostx2():
    filelist, outdir, cwd = create_files_in_directory()
    bpx = fsl.BEDPOSTX()

    # make sure command gets called
    yield assert_equal, bpx.cmd, 'bedpostx'

    # test raising error with mandatory args absent
    yield assert_raises, ValueError, bpx.run

    # .inputs based parameters setting
    bpx2 = fsl.BEDPOSTX()
    bpx2.inputs.mask = example_data('mask.nii')
    bpx2.inputs.dwi = example_data('diffusion.nii')
    bpx2.inputs.bvals = example_data('bvals')
    bpx2.inputs.bvecs = example_data('bvecs')
    bpx2.inputs.fibres = 2
    bpx2.inputs.weight = 0.3
    bpx2.inputs.burn_period = 200
    bpx2.inputs.jumps = 500
    bpx2.inputs.sampling = 20
    actualCmdline = sorted(bpx2.cmdline.split())
    cmd = 'bedpostx bedpostx -b 200 -n 2 -j 500 -s 20 -w 0.30'
    desiredCmdline = sorted(cmd.split())
    yield assert_equal, actualCmdline, desiredCmdline
Пример #36
0
def test_seg_calctopncc():
    """ Test interfaces for seg_CalctoNCC"""
    # Create a node object
    calctopncc = CalcTopNCC()

    # Check if the command is properly defined
    assert calctopncc.cmd == get_custom_path('seg_CalcTopNCC')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        calctopncc.run()

    # Assign some input data
    in_file = example_data('im1.nii')
    file1 = example_data('im2.nii')
    file2 = example_data('im3.nii')
    calctopncc.inputs.in_file = in_file
    calctopncc.inputs.num_templates = 2
    calctopncc.inputs.in_templates = [file1, file2]
    calctopncc.inputs.top_templates = 1

    cmd_tmp = '{cmd} -target {in_file} -templates 2 {file1} {file2} -n 1'
    expected_cmd = cmd_tmp.format(cmd=get_custom_path('seg_CalcTopNCC'),
                                  in_file=in_file,
                                  file1=file1,
                                  file2=file2)

    assert calctopncc.cmdline == expected_cmd
Пример #37
0
def test_overlap(tmpdir):
    from nipype.algorithms.metrics import Overlap

    def check_close(val1, val2):
        import numpy.testing as npt

        return npt.assert_almost_equal(val1, val2, decimal=3)

    in1 = example_data("segmentation0.nii.gz")
    in2 = example_data("segmentation1.nii.gz")

    os.chdir(str(tmpdir))
    overlap = Overlap()
    overlap.inputs.volume1 = in1
    overlap.inputs.volume2 = in1
    res = overlap.run()
    check_close(res.outputs.jaccard, 1.0)

    overlap = Overlap()
    overlap.inputs.volume1 = in1
    overlap.inputs.volume2 = in2
    res = overlap.run()
    check_close(res.outputs.jaccard, 0.99705)

    overlap = Overlap()
    overlap.inputs.volume1 = in1
    overlap.inputs.volume2 = in2
    overlap.inputs.vol_units = "mm"
    res = overlap.run()
    check_close(res.outputs.jaccard, 0.99705)
    check_close(res.outputs.roi_voldiff, np.array([0.0063086, -0.0025506, 0.0]))
Пример #38
0
def test_overlap():
    from nipype.algorithms.metrics import Overlap

    def check_close(val1, val2):
        import numpy.testing as npt
        return npt.assert_almost_equal(val1, val2, decimal=3)

    tempdir = mkdtemp()
    in1 = example_data('segmentation0.nii.gz')
    in2 = example_data('segmentation1.nii.gz')

    os.chdir(tempdir)
    overlap = Overlap()
    overlap.inputs.volume1 = in1
    overlap.inputs.volume2 = in1
    res = overlap.run()
    yield check_close, res.outputs.jaccard, 1.0
    overlap = Overlap()
    overlap.inputs.volume1 = in1
    overlap.inputs.volume2 = in2
    res = overlap.run()

    yield check_close, res.outputs.jaccard, 0.99705

    overlap = Overlap()
    overlap.inputs.volume1 = in1
    overlap.inputs.volume2 = in2
    overlap.inputs.vol_units = 'mm'
    res = overlap.run()

    yield check_close, res.outputs.jaccard, 0.99705
    yield (check_close, res.outputs.roi_voldiff,
           np.array([0.0063086, -0.0025506, 0.0]))

    rmtree(tempdir)
Пример #39
0
def test_reg_aladin():
    """ tests for reg_aladin interface"""
    # Create a reg_aladin object
    nr_aladin = RegAladin()

    # Check if the command is properly defined
    assert nr_aladin.cmd == get_custom_path('reg_aladin')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        nr_aladin.run()

    # Assign some input data
    ref_file = example_data('im1.nii')
    flo_file = example_data('im2.nii')
    rmask_file = example_data('mask.nii')
    nr_aladin.inputs.ref_file = ref_file
    nr_aladin.inputs.flo_file = flo_file
    nr_aladin.inputs.rmask_file = rmask_file
    nr_aladin.inputs.omp_core_val = 4

    cmd_tmp = '{cmd} -aff {aff} -flo {flo} -omp 4 -ref {ref} -res {res} \
-rmask {rmask}'

    expected_cmd = cmd_tmp.format(
        cmd=get_custom_path('reg_aladin'),
        aff='im2_aff.txt',
        flo=flo_file,
        ref=ref_file,
        res='im2_res.nii.gz',
        rmask=rmask_file,
    )

    assert nr_aladin.cmdline == expected_cmd
Пример #40
0
def test_seg_calctopncc():
    """ Test interfaces for seg_CalctoNCC"""
    # Create a node object
    calctopncc = CalcTopNCC()

    # Check if the command is properly defined
    assert calctopncc.cmd == get_custom_path('seg_CalcTopNCC')

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        calctopncc.run()

    # Assign some input data
    in_file = example_data('im1.nii')
    file1 = example_data('im2.nii')
    file2 = example_data('im3.nii')
    calctopncc.inputs.in_file = in_file
    calctopncc.inputs.num_templates = 2
    calctopncc.inputs.in_templates = [file1, file2]
    calctopncc.inputs.top_templates = 1

    cmd_tmp = '{cmd} -target {in_file} -templates 2 {file1} {file2} -n 1'
    expected_cmd = cmd_tmp.format(
        cmd=get_custom_path('seg_CalcTopNCC'),
        in_file=in_file,
        file1=file1,
        file2=file2
    )

    assert calctopncc.cmdline == expected_cmd
Пример #41
0
def test_reg_transform_comp_nii():

    # Create a reg_transform object
    nr = RegTransform()

    # Check if the command is properly defined
    assert nr.cmd == get_custom_path('reg_transform')

    # Assign some input data
    ref_file = example_data('im1.nii')
    trans_file = example_data('warpfield.nii')
    trans2_file = example_data('anatomical.nii')
    nr.inputs.ref1_file = ref_file
    nr.inputs.comp_input2 = trans2_file
    nr.inputs.comp_input = trans_file
    nr.inputs.omp_core_val = 4

    cmd_tmp = '{cmd} -ref {ref_file} -omp 4 -comp {trans1} {trans2} {out_file}'
    expected_cmd = cmd_tmp.format(
        cmd=get_custom_path('reg_transform'),
        ref_file=ref_file,
        trans1=trans_file,
        trans2=trans2_file,
        out_file=os.path.join(os.getcwd(), 'warpfield_trans.nii.gz'))

    assert nr.cmdline == expected_cmd
Пример #42
0
def test_fd():
    tempdir = mkdtemp()
    ground_truth = np.loadtxt(example_data('fsl_motion_outliers_fd.txt'))
    fd = FramewiseDisplacement(in_plots=example_data('fsl_mcflirt_movpar.txt'),
                               out_file=tempdir + '/fd.txt')
    res = fd.run()
    yield assert_equal, np.allclose(ground_truth, np.loadtxt(res.outputs.out_file)), True
    yield assert_equal, np.abs(ground_truth.mean() - res.outputs.fd_average) < 1e-4, True
    rmtree(tempdir)
Пример #43
0
    def setUp(self):

        self.accuracy = 10

        self.path_to_fixed = example_data("segmentation0.nii.gz")
        self.path_to_moving = example_data("segmentation1.nii.gz")

        self.fixed_sitk = sitk.ReadImage(self.path_to_fixed)
        self.moving_sitk = sitk.ReadImage(self.path_to_moving)
Пример #44
0
def test_BaseInterface_load_save_inputs():
    tmp_dir = tempfile.mkdtemp()
    tmp_json = os.path.join(tmp_dir, 'settings.json')

    class InputSpec(nib.TraitedSpec):
        input1 = nib.traits.Int()
        input2 = nib.traits.Float()
        input3 = nib.traits.Bool()
        input4 = nib.traits.Str()

    class DerivedInterface(nib.BaseInterface):
        input_spec = InputSpec

        def __init__(self, **inputs):
            super(DerivedInterface, self).__init__(**inputs)

    inputs_dict = {'input1': 12, 'input3': True, 'input4': 'some string'}
    bif = DerivedInterface(**inputs_dict)
    bif.save_inputs_to_json(tmp_json)
    bif2 = DerivedInterface()
    bif2.load_inputs_from_json(tmp_json)
    yield assert_equal, bif2.inputs.get_traitsfree(), inputs_dict

    bif3 = DerivedInterface(from_file=tmp_json)
    yield assert_equal, bif3.inputs.get_traitsfree(), inputs_dict

    inputs_dict2 = inputs_dict.copy()
    inputs_dict2.update({'input4': 'some other string'})
    bif4 = DerivedInterface(from_file=tmp_json, input4=inputs_dict2['input4'])
    yield assert_equal, bif4.inputs.get_traitsfree(), inputs_dict2

    bif5 = DerivedInterface(input4=inputs_dict2['input4'])
    bif5.load_inputs_from_json(tmp_json, overwrite=False)
    yield assert_equal, bif5.inputs.get_traitsfree(), inputs_dict2

    bif6 = DerivedInterface(input4=inputs_dict2['input4'])
    bif6.load_inputs_from_json(tmp_json)
    yield assert_equal, bif6.inputs.get_traitsfree(), inputs_dict

    # test get hashval in a complex interface
    from nipype.interfaces.ants import Registration
    settings = example_data(
        example_data('smri_ants_registration_settings.json'))
    with open(settings) as setf:
        data_dict = json.load(setf)

    tsthash = Registration()
    tsthash.load_inputs_from_json(settings)
    yield assert_equal, {}, check_dict(data_dict,
                                       tsthash.inputs.get_traitsfree())

    tsthash2 = Registration(from_file=settings)
    yield assert_equal, {}, check_dict(data_dict,
                                       tsthash2.inputs.get_traitsfree())

    _, hashvalue = tsthash.inputs.get_hashval(hash_method='timestamp')
    yield assert_equal, 'ec5755e07287e04a4b409e03b77a517c', hashvalue
Пример #45
0
    def setUp(self):

        self.accuracy = 10

        self.path_to_fixed = example_data("segmentation0.nii.gz")
        self.path_to_moving = example_data("segmentation1.nii.gz")

        self.fixed = st.Stack.from_filename(self.path_to_fixed)
        self.moving = st.Stack.from_filename(self.path_to_moving)
Пример #46
0
def test_dvars(tmpdir):
    ground_truth = np.loadtxt(example_data('ds003_sub-01_mc.DVARS'))
    dvars = ComputeDVARS(in_file=example_data('ds003_sub-01_mc.nii.gz'),
                         in_mask=example_data('ds003_sub-01_mc_brainmask.nii.gz'),
                         save_all=True)
    os.chdir(str(tmpdir))
    res = dvars.run()

    dv1 = np.loadtxt(res.outputs.out_std)
    assert (np.abs(dv1 - ground_truth).sum()/ len(dv1)) < 0.05
Пример #47
0
def test_BaseInterface_load_save_inputs():
    tmp_dir = tempfile.mkdtemp()
    tmp_json = os.path.join(tmp_dir, 'settings.json')

    class InputSpec(nib.TraitedSpec):
        input1 = nib.traits.Int()
        input2 = nib.traits.Float()
        input3 = nib.traits.Bool()
        input4 = nib.traits.Str()

    class DerivedInterface(nib.BaseInterface):
        input_spec = InputSpec

        def __init__(self, **inputs):
            super(DerivedInterface, self).__init__(**inputs)

    inputs_dict = {'input1': 12, 'input3': True,
                   'input4': 'some string'}
    bif = DerivedInterface(**inputs_dict)
    bif.save_inputs_to_json(tmp_json)
    bif2 = DerivedInterface()
    bif2.load_inputs_from_json(tmp_json)
    yield assert_equal, bif2.inputs.get_traitsfree(), inputs_dict

    bif3 = DerivedInterface(from_file=tmp_json)
    yield assert_equal, bif3.inputs.get_traitsfree(), inputs_dict

    inputs_dict2 = inputs_dict.copy()
    inputs_dict2.update({'input4': 'some other string'})
    bif4 = DerivedInterface(from_file=tmp_json, input4=inputs_dict2['input4'])
    yield assert_equal, bif4.inputs.get_traitsfree(), inputs_dict2

    bif5 = DerivedInterface(input4=inputs_dict2['input4'])
    bif5.load_inputs_from_json(tmp_json, overwrite=False)
    yield assert_equal, bif5.inputs.get_traitsfree(), inputs_dict2

    bif6 = DerivedInterface(input4=inputs_dict2['input4'])
    bif6.load_inputs_from_json(tmp_json)
    yield assert_equal, bif6.inputs.get_traitsfree(), inputs_dict

    # test get hashval in a complex interface
    from nipype.interfaces.ants import Registration
    settings = example_data(example_data('smri_ants_registration_settings.json'))
    with open(settings) as setf:
        data_dict = json.load(setf)

    tsthash = Registration()
    tsthash.load_inputs_from_json(settings)
    yield assert_equal, {}, check_dict(data_dict, tsthash.inputs.get_traitsfree())

    tsthash2 = Registration(from_file=settings)
    yield assert_equal, {}, check_dict(data_dict, tsthash2.inputs.get_traitsfree())

    _, hashvalue = tsthash.inputs.get_hashval(hash_method='timestamp')
    yield assert_equal, 'ec5755e07287e04a4b409e03b77a517c', hashvalue
Пример #48
0
def test_dvars(tmpdir):
    ground_truth = np.loadtxt(example_data('ds003_sub-01_mc.DVARS'))
    dvars = ComputeDVARS(
        in_file=example_data('ds003_sub-01_mc.nii.gz'),
        in_mask=example_data('ds003_sub-01_mc_brainmask.nii.gz'),
        save_all=True)
    os.chdir(str(tmpdir))
    res = dvars.run()

    dv1 = np.loadtxt(res.outputs.out_std)
    assert (np.abs(dv1 - ground_truth).sum() / len(dv1)) < 0.05
Пример #49
0
def test_apply_transform():
    moving = example_data(infile="functional.nii")
    mat = example_data(infile="trans.mat")
    applymat = spmu.ApplyTransform(matlab_cmd="mymatlab")
    assert applymat.inputs.matlab_cmd == "mymatlab"
    applymat.inputs.in_file = moving
    applymat.inputs.mat = mat
    scrpt = applymat._make_matlab_command(None)
    expected = "[p n e v] = spm_fileparts(V.fname);"
    assert expected in scrpt
    expected = "V.mat = transform.M * V.mat;"
    assert expected in scrpt
Пример #50
0
def test_apply_transform():
    moving = example_data(infile='functional.nii')
    mat = example_data(infile='trans.mat')
    applymat = spmu.ApplyTransform(matlab_cmd='mymatlab')
    assert_equal(applymat.inputs.matlab_cmd, 'mymatlab')
    applymat.inputs.in_file = moving
    applymat.inputs.mat = mat
    scrpt = applymat._make_matlab_command(None)
    expected = 'img_space = spm_get_space(infile);'
    assert_equal(expected in scrpt, True)
    expected = 'spm_get_space(infile, transform.M * img_space);'
    assert_equal(expected in scrpt, True)
Пример #51
0
def test_apply_transform():
    moving = example_data(infile='functional.nii')
    mat = example_data(infile='trans.mat')
    applymat = spmu.ApplyTransform(matlab_cmd='mymatlab')
    assert_equal(applymat.inputs.matlab_cmd, 'mymatlab')
    applymat.inputs.in_file = moving
    applymat.inputs.mat = mat
    scrpt = applymat._make_matlab_command(None)
    expected = '[p n e v] = spm_fileparts(V.fname);'
    assert_equal(expected in scrpt, True)
    expected = 'V.mat = transform.M * V.mat;'
    assert_equal(expected in scrpt, True)
Пример #52
0
def test_fit_asl():
    """ Testing FitAsl interface."""
    # Create the test node
    fit_asl = FitAsl()

    # Check if the command is properly defined
    cmd = get_custom_path('fit_asl', env_dir='NIFTYFIT_DIR')
    assert fit_asl.cmd == cmd

    # test raising error with mandatory args absent
    with pytest.raises(ValueError):
        fit_asl.run()

    # Tests on the interface:
    # Runs cbf fitting assuming all tissue is GM!
    in_file = example_data('asl.nii.gz')
    fit_asl.inputs.source_file = in_file

    cmd_tmp = '{cmd} -source {in_file} -cbf {cbf} -error {error} -syn {syn}'
    expected_cmd = cmd_tmp.format(
        cmd=cmd,
        in_file=in_file,
        cbf='asl_cbf.nii.gz',
        error='asl_error.nii.gz',
        syn='asl_syn.nii.gz',
    )

    assert fit_asl.cmdline == expected_cmd

    # Runs cbf fitting using IR/SR T1 data to estimate the local T1 and uses
    # the segmentation data to fit tissue specific blood flow parameters
    # (lambda,transit times,T1)
    fit_asl2 = FitAsl(sig=True)
    in_file = example_data('asl.nii.gz')
    t1map = example_data('T1map.nii.gz')
    seg = example_data('segmentation0.nii.gz')
    fit_asl2.inputs.source_file = in_file
    fit_asl2.inputs.t1map = t1map
    fit_asl2.inputs.seg = seg

    cmd_tmp = '{cmd} -source {in_file} -cbf {cbf} -error {error} \
-seg {seg} -sig -syn {syn} -t1map {t1map}'
    expected_cmd = cmd_tmp.format(
        cmd=cmd,
        in_file=in_file,
        t1map=t1map,
        seg=seg,
        cbf='asl_cbf.nii.gz',
        error='asl_error.nii.gz',
        syn='asl_syn.nii.gz',
    )

    assert fit_asl2.cmdline == expected_cmd
Пример #53
0
def test_apply_transform():
    moving = example_data(infile="functional.nii")
    mat = example_data(infile="trans.mat")
    applymat = spmu.ApplyTransform(matlab_cmd="mymatlab")
    assert_equal(applymat.inputs.matlab_cmd, "mymatlab")
    applymat.inputs.in_file = moving
    applymat.inputs.mat = mat
    scrpt = applymat._make_matlab_command(None)
    expected = "img_space = spm_get_space(infile);"
    assert_equal(expected in scrpt, True)
    expected = "spm_get_space(infile, M * img_space);"
    assert_equal(expected in scrpt, True)
Пример #54
0
def test_apply_transform():
    moving = example_data(infile='functional.nii')
    mat = example_data(infile='trans.mat')
    applymat = spmu.ApplyTransform(matlab_cmd='mymatlab')
    assert_equal(applymat.inputs.matlab_cmd, 'mymatlab')
    applymat.inputs.in_file = moving
    applymat.inputs.mat = mat
    scrpt = applymat._make_matlab_command(None)
    expected = '[p n e v] = spm_fileparts(V.fname);'
    assert_equal(expected in scrpt, True)
    expected = 'V.mat = transform.M * V.mat;'
    assert_equal(expected in scrpt, True)
Пример #55
0
def test_read_csv():
    """Test that reading the data from csv file gives you back a reasonable
    time-series object """
    CA = nitime.CoherenceAnalyzer()
    CA.inputs.TR = 1.89  # bogus value just to pass traits test
    CA.inputs.in_file = example_data('fmri_timeseries_nolabels.csv')
    yield assert_raises, ValueError, CA._read_csv

    CA.inputs.in_file = example_data('fmri_timeseries.csv')
    data, roi_names = CA._read_csv()
    yield assert_equal, data[0][0], 10125.9
    yield assert_equal, roi_names[0], 'WM'
Пример #56
0
def test_read_csv():
    """Test that reading the data from csv file gives you back a reasonable
    time-series object """
    CA = nitime.CoherenceAnalyzer()
    CA.inputs.TR = 1.89  # bogus value just to pass traits test
    CA.inputs.in_file = example_data('fmri_timeseries_nolabels.csv')
    yield assert_raises, ValueError, CA._read_csv

    CA.inputs.in_file = example_data('fmri_timeseries.csv')
    data, roi_names = CA._read_csv()
    yield assert_equal, data[0][0], 10125.9
    yield assert_equal, roi_names[0], 'WM'