Пример #1
0
def test_fslmerge(create_files_in_directory):
    filelist, outdir, _ = create_files_in_directory

    merger = fsl.Merge()

    # make sure command gets called
    assert merger.cmd == 'fslmerge'

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

    # .inputs based parameters setting
    merger.inputs.in_files = filelist
    merger.inputs.merged_file = 'foo_merged.nii'
    merger.inputs.dimension = 't'
    merger.inputs.output_type = 'NIFTI'
    assert merger.cmdline == 'fslmerge -t foo_merged.nii %s' % ' '.join(
        filelist)

    # verify that providing a tr value updates the dimension to tr
    merger.inputs.tr = 2.25
    assert merger.cmdline == 'fslmerge -tr foo_merged.nii %s %.2f' % (
        ' '.join(filelist), 2.25)

    # .run based parameter setting
    merger2 = fsl.Merge(in_files=filelist,
                        merged_file='foo_merged.nii',
                        dimension='t',
                        output_type='NIFTI',
                        tr=2.25)

    assert merger2.cmdline == \
        'fslmerge -tr foo_merged.nii %s %.2f' % (' '.join(filelist), 2.25)
Пример #2
0
def test_fslmerge():
    filelist, outdir, cwd, _ = create_files_in_directory()

    merger = fsl.Merge()

    # make sure command gets called
    yield assert_equal, merger.cmd, 'fslmerge'

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

    # .inputs based parameters setting
    merger.inputs.in_files = filelist
    merger.inputs.merged_file = 'foo_merged.nii'
    merger.inputs.dimension = 't'
    merger.inputs.output_type = 'NIFTI'
    yield assert_equal, merger.cmdline, 'fslmerge -t foo_merged.nii %s' % ' '.join(filelist)

    # verify that providing a tr value updates the dimension to tr
    merger.inputs.tr = 2.25
    yield assert_equal, merger.cmdline, 'fslmerge -tr foo_merged.nii %s %.2f' % (' '.join(filelist), 2.25)

    # .run based parameter setting
    merger2 = fsl.Merge(in_files=filelist,
                        merged_file='foo_merged.nii',
                        dimension='t',
                        output_type='NIFTI',
                        tr=2.25)

    yield assert_equal, merger2.cmdline, \
        'fslmerge -tr foo_merged.nii %s %.2f' % (' '.join(filelist), 2.25)

    clean_directory(outdir, cwd)
Пример #3
0
def test_fslmerge(create_files_in_directory_plus_output_type):
    filelist, outdir, _ = create_files_in_directory_plus_output_type

    merger = fsl.Merge()

    # make sure command gets called
    assert merger.cmd == "fslmerge"

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

    # .inputs based parameters setting
    merger.inputs.in_files = filelist
    merger.inputs.merged_file = "foo_merged.nii"
    merger.inputs.dimension = "t"
    merger.inputs.output_type = "NIFTI"
    assert merger.cmdline == "fslmerge -t foo_merged.nii %s" % " ".join(filelist)

    # verify that providing a tr value updates the dimension to tr
    merger.inputs.tr = 2.25
    assert merger.cmdline == "fslmerge -tr foo_merged.nii %s %.2f" % (
        " ".join(filelist),
        2.25,
    )

    # .run based parameter setting
    merger2 = fsl.Merge(
        in_files=filelist,
        merged_file="foo_merged.nii",
        dimension="t",
        output_type="NIFTI",
        tr=2.25,
    )

    assert merger2.cmdline == "fslmerge -tr foo_merged.nii %s %.2f" % (
        " ".join(filelist),
        2.25,
    )
Пример #4
0
def test_merge():
    input_map = dict(
        args=dict(argstr='%s', ),
        dimension=dict(
            argstr='-%s',
            mandatory=True,
        ),
        environ=dict(),
        in_files=dict(
            mandatory=True,
            argstr='%s',
        ),
        merged_file=dict(argstr='%s', ),
        output_type=dict(),
    )
    instance = fsl.Merge()
    for key, metadata in input_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(instance.inputs.traits()[key],
                                        metakey), value
Пример #5
0
def create_eddy_correct_pipeline(name="eddy_correct"):
    """Creates a pipeline that replaces eddy_correct script in FSL. It takes a
    series of diffusion weighted images and linearly corregisters them to one
    reference image.

    Example
    -------

    >>> nipype_eddycorrect = create_eddy_correct_pipeline("nipype_eddycorrect")
    >>> nipype_eddycorrect.inputs.inputnode.in_file = 'diffusion.nii'
    >>> nipype_eddycorrect.inputs.inputnode.ref_num = 0
    >>> nipype_eddycorrect.run() # doctest: +SKIP

    Inputs::

    inputnode.in_file
    inputnode.ref_num

    Outputs::

    outputnode.eddy_corrected
    """
    import nipype.pipeline.engine as pe
    import nipype.interfaces.utility as util
    import nipype.interfaces.fsl as fsl
    inputnode = pe.Node(interface = util.IdentityInterface(fields=["in_file", "bvals"]),
        name="inputnode")

    pipeline = pe.Workflow(name=name)

    split = pe.MapNode(fsl.Split(dimension='t'), name="split", iterfield=['in_file'])
    pipeline.connect([(inputnode, split, [("in_file", "in_file")])])

    getb0 = pe.Node(util.Function(input_names=['bvals'],
                                    output_names=['b0'],
                                    function=get_b0),
        name='get_b0_indices')

    pick_ref = pe.MapNode(util.Select(), name="pick_b0_scans", iterfield=["inlist"])
    pick0 = pe.MapNode(util.Select(index=0), name="pick_first_scan", iterfield=["inlist"])


    getmotion = pe.MapNode(util.Function(input_names=['flirt_out_mats'],
                                         output_names=['motion_params'],
                                         function=get_flirt_motion_parameters),
        name='getmotion', iterfield=['flirt_out_mats'])



    pipeline.connect(split, 'out_files', pick_ref, "inlist")
    pipeline.connect(split, 'out_files', pick0, "inlist")
    pipeline.connect(inputnode,'bvals', getb0, 'bvals')
    pipeline.connect(getb0, 'b0', pick_ref, "index")
    #pipeline.connect([(split, pick_ref, [("out_files", "inlist")]),
    #    (inputnode, pick_ref, [("ref_num", "index")])])

    coregistration = pe.MapNode(util.Function(input_names=['in_file', 'reference'],
        output_names=['out_file', 'out_matrix_file'],
        function = mapnode_coregistration),
        name = "coregister_b0",
        iterfield=["in_file","reference"])
    pipeline.connect([(pick_ref, coregistration, [("out", "in_file")]),
        (pick0, coregistration, [("out", "reference")])])

    art_mean = art_mean_workflow()
    art_mean.inputs.inputspec.parameter_source='FSL'

    pipeline.connect(coregistration,'out_matrix_file', getmotion, 'flirt_out_mats')
    pipeline.connect(getmotion, 'motion_params', art_mean, 'inputspec.realignment_parameters')

    merge = pe.MapNode(fsl.Merge(dimension="t"), name="merge", iterfield=["in_files"])
    pipeline.connect([(coregistration, merge, [("out_file", "in_files")])
    ])

    pipeline.connect(merge,'merged_file',art_mean,'inputspec.realigned_files')

    outputnode = pe.Node(interface = util.IdentityInterface(fields=["eddy_corrected","mean_image","coreg_mat_files"]),
        name="outputnode")

    pipeline.connect(art_mean, 'outputspec.mean_image', outputnode, "mean_image")

    coreg_all = coregistration.clone("coregister_all")
    pipeline.connect(split, 'out_files', coreg_all, 'in_file')
    pipeline.connect(art_mean,'outputspec.mean_image',coreg_all,"reference")

    merge_all = merge.clone("merge_all")
    pipeline.connect([(coreg_all, merge_all, [("out_file", "in_files")])
    ])
    pipeline.connect(coreg_all, 'out_matrix_file', outputnode, "coreg_mat_files")
    pipeline.connect(merge_all,'merged_file',outputnode,"eddy_corrected")

    return pipeline
def remove_frames(scan, todel, matfile, tr, order=''):
    """ given a 4d scan, a list of frames to remove, and an _extra.mat file,
    will remove indicated frames from the time dimension of scan and update
    _extra.mat file to reflect changes.

    tr should reflect the actual TR of the acquisition data.

    order indicates which scan is being edited for recording purposes only
    and can be left blank

    """

    # turn todel dict back into a list
    to_remove = []
    for k in sorted(todel.keys()):
        for i in range(k, k + todel[k]):
            to_remove.append(i)

    to_remove = remove_dupes(to_remove)  # remove duplicates in list of frames)

    print 'removing the following frames from scan %s: %s' % (order, to_remove)
    print 'splitting scan into volumes and removing frames'

    # split 4D image into volumes
    split = fsl.Split()
    split.inputs.in_file = scan
    split.inputs.dimension = 't'
    split.inputs.output_type = 'NIFTI_GZ'
    split.run()  # outputs frames in same directory as volxxxx.nii.gz

    # remove desired frames
    for rem_ind in to_remove:
        to_del = os.path.join(scan_dir, 'vol%04d.nii.gz' % (rem_ind))
        os.remove(to_del)

    # merge remaining frames back into single image
    jnk, flnme = os.path.split(scan)

    vols = sorted(glob(os.path.join(scan_dir, 'vol*')))

    merge = fsl.Merge()
    merge.inputs.in_files = vols
    merge.inputs.dimension = 't'
    merge.inputs.tr = tr
    merge.inputs.merged_file = os.path.join(output_dir, flnme)
    merge.inputs.output_type = 'NIFTI_GZ'
    merge.inputs.ignore_exception

    print 'creating new file %s' % (os.path.join(output_dir, flnme))
    merge.run()

    print 'updating _extra.mat file'

    # update _extra.mat file
    update_extra_mat(matfile, to_remove)

    print 'cleaning up'

    # clean up
    vols = sorted(glob(os.path.join(scan_dir, 'vol*')))
    for vol in vols:
        os.remove(vol)