예제 #1
0
def test_bet():
    tmp_infile, tp_dir = setup_infile()
    better = fsl.BET()
    yield assert_equal, better.cmd, 'bet'

    # Test raising error with mandatory args absent
    yield assert_raises, ValueError, better.run

    # Test generated outfile name
    better.inputs.in_file = tmp_infile
    outfile = fsl_name(better, 'foo_brain')
    outpath = os.path.join(os.getcwd(), outfile)
    realcmd = 'bet %s %s' % (tmp_infile, outpath)
    yield assert_equal, better.cmdline, realcmd
    # Test specified outfile name
    outfile = fsl_name(better, '/newdata/bar')
    better.inputs.out_file = outfile
    realcmd = 'bet %s %s' % (tmp_infile, outfile)
    yield assert_equal, better.cmdline, realcmd

    # infile foo.nii doesn't exist
    def func():
        better.run(in_file='foo2.nii', out_file='bar.nii')

    yield assert_raises, TraitError, func

    # Our options and some test values for them
    # Should parallel the opt_map structure in the class for clarity
    opt_map = {
        'outline': ('-o', True),
        'mask': ('-m', True),
        'skull': ('-s', True),
        'no_output': ('-n', True),
        'frac': ('-f 0.40', 0.4),
        'vertical_gradient': ('-g 0.75', 0.75),
        'radius': ('-r 20', 20),
        'center': ('-c 54 75 80', [54, 75, 80]),
        'threshold': ('-t', True),
        'mesh': ('-e', True),
        'surfaces': ('-A', True)
        # 'verbose':            ('-v', True),
        # 'flags':              ('--i-made-this-up', '--i-made-this-up'),
    }
    # Currently we don't test -R, -S, -B, -Z, -F, -A or -A2

    # test each of our arguments
    better = fsl.BET()
    outfile = fsl_name(better, 'foo_brain')
    outpath = os.path.join(os.getcwd(), outfile)
    for name, settings in list(opt_map.items()):
        better = fsl.BET(**{name: settings[1]})
        # Add mandatory input
        better.inputs.in_file = tmp_infile
        realcmd = ' '.join([better.cmd, tmp_infile, outpath, settings[0]])
        yield assert_equal, better.cmdline, realcmd
    teardown_infile(tmp_dir)
예제 #2
0
    transforms=['Rigid'],
    transform_parameters=[(0.1, )],
    metric=['MI'],
    metric_weight=[1.0],
    number_of_iterations=[[1000]],
    convergence_threshold=[1.e-7],
    convergence_window_size=[10],
    shrink_factors=[[4]],
    smoothing_sigmas=[[2.]],
    output_warped_image=True,
    output_transform_prefix='T1w_to_FLAIR'),
                          name='ants_reg')

# BET: skullstrip T1
bet_t1 = ni_engine.Node(ni_fsl_preproc.BET(frac=0.2,
                                           robust=True,
                                           output_type='NIFTI_GZ',
                                           mask=True),
                        name="bet_t1")

ants_warp_lesion = ni_engine.Node(ni_ants.ApplyTransforms(
    dimension=3,
    interpolation='NearestNeighbor',
    invert_transform_flags=[True],
    default_value=0),
                                  name='ants_warp_lesion')

ants_warp_flair = ni_engine.Node(ni_ants.ApplyTransforms(
    dimension=3,
    interpolation='NearestNeighbor',
    invert_transform_flags=[True],
    default_value=0),
예제 #3
0
파일: workflows.py 프로젝트: MichlF/misc
def create_B0_workflow(name='b0_unwarping', scanner='philips'):
    """ Does B0 field unwarping

    Example
    -------
    >>> nipype_epicorrect = create_unwarping_workflow('unwarp',)
    >>> unwarp.inputs.input_node.in_file = 'subj1_run1_bold.nii.gz'
    >>> unwarp.inputs.input_node.fieldmap_mag = 'subj1_run1_mag.nii.gz'
    >>> unwarp.inputs.input_node.fieldmap_pha = 'subj1_run1_phas.nii.gz'
    >>> unwarp.inputs.input_node.wfs = 12.223
    >>> unwarp.inputs.input_node.epi_factor = 35.0
    >>> unwarp.inputs.input_node.acceleration = 3.0
    >>> unwarp.inputs.input_node.te_diff = 0.005
    >>> unwarp.inputs.input_node.phase_encoding_direction = 'y'
    >>> nipype_epicorrect.run()

    Inputs::
        input_node.in_file - Volume acquired with EPI sequence
        input_node.fieldmap_mag - Magnitude of the fieldmap
        input_node.fieldmap_pha - Phase difference of the fieldmap
        input_node.wfs - Water-fat-shift in pixels
        input_node.epi_factor - EPI factor
        input_node.acceleration - Acceleration factor used for EPI parallel imaging (SENSE)
        input_node.te_diff - Time difference between TE in seconds.
        input_node.phase_encoding_direction - Unwarp direction (default should be "y")
    Outputs::
        outputnode.epi_corrected
    """

    # Nodes:
    # ------

    # Define input and workflow:
    input_node = pe.Node(name='inputspec',
                         interface=IdentityInterface(fields=[
                             'in_files', 'fieldmap_mag', 'fieldmap_pha', 'wfs',
                             'epi_factor', 'acceleration', 'echo_spacing',
                             'te_diff', 'phase_encoding_direction'
                         ]))

    # Normalize phase difference of the fieldmap phase to be [-pi, pi)
    norm_pha = pe.Node(interface=Prepare_phasediff, name='normalize_phasediff')

    # Mask the magnitude of the fieldmap
    mask_mag = pe.Node(fsl.BET(mask=True), name='mask_magnitude')
    mask_mag_dil = pe.Node(interface=Dilate_mask, name='mask_dilate')

    # Unwrap fieldmap phase using FSL PRELUDE
    prelude = pe.Node(fsl.PRELUDE(process3d=True), name='phase_unwrap')

    # Convert unwrapped fieldmap phase to radials per second:
    radials_per_second = pe.Node(interface=Radials_per_second,
                                 name='radials_ps')

    # in case of SIEMENS scanner:
    prepare_fieldmap = pe.Node(PrepareFieldmap(), name='prepare_fieldmap')

    # Register unwrapped fieldmap (rad/s) to epi, using the magnitude of the fieldmap
    registration = pe.MapNode(fsl.FLIRT(bins=256,
                                        cost='corratio',
                                        dof=6,
                                        interp='trilinear',
                                        searchr_x=[-10, 10],
                                        searchr_y=[-10, 10],
                                        searchr_z=[-10, 10]),
                              iterfield=['reference'],
                              name='registration')

    # transform unwrapped fieldmap (rad/s)
    applyxfm = pe.MapNode(fsl.ApplyXFM(interp='trilinear'),
                          iterfield=['reference', 'in_matrix_file'],
                          name='apply_xfm')

    # compute effective echospacing:
    echo_spacing_philips = pe.Node(interface=Compute_echo_spacing_philips,
                                   name='echo_spacing_philips')
    echo_spacing_siemens = pe.Node(interface=Compute_echo_spacing_siemens,
                                   name='echo_spacing_siemens')
    te_diff_in_ms = pe.Node(interface=TE_diff_ms, name='te_diff_in_ms')

    # Unwarp with FSL Fugue
    fugue = pe.MapNode(interface=fsl.FUGUE(median_2dfilter=True),
                       iterfield=['in_file', 'unwarped_file', 'fmap_in_file'],
                       name='fugue')

    # Convert unwrapped fieldmap phase to radials per second:
    out_file = pe.MapNode(interface=Make_output_filename,
                          iterfield=['in_file'],
                          name='out_file')

    # Define output node
    outputnode = pe.Node(
        IdentityInterface(fields=['out_files', 'field_coefs']),
        name='outputspec')

    # Workflow:
    # ---------

    unwarp_workflow = pe.Workflow(name=name)
    unwarp_workflow.connect(input_node, 'in_files', out_file, 'in_file')

    # registration:
    unwarp_workflow.connect(input_node, 'fieldmap_mag', mask_mag, 'in_file')
    unwarp_workflow.connect(mask_mag, 'mask_file', mask_mag_dil, 'in_file')
    unwarp_workflow.connect(mask_mag, 'out_file', registration, 'in_file')
    unwarp_workflow.connect(input_node, 'in_files', registration, 'reference')

    if scanner == 'philips':

        # prepare fieldmap:
        unwarp_workflow.connect(input_node, 'fieldmap_pha', norm_pha,
                                'in_file')
        unwarp_workflow.connect(input_node, 'fieldmap_mag', prelude,
                                'magnitude_file')
        unwarp_workflow.connect(norm_pha, 'out_file', prelude, 'phase_file')
        unwarp_workflow.connect(mask_mag_dil, 'out_file', prelude, 'mask_file')
        unwarp_workflow.connect(prelude, 'unwrapped_phase_file',
                                radials_per_second, 'in_file')
        unwarp_workflow.connect(input_node, 'te_diff', radials_per_second,
                                'asym')

        # transform fieldmap:
        unwarp_workflow.connect(radials_per_second, 'out_file', applyxfm,
                                'in_file')
        unwarp_workflow.connect(registration, 'out_matrix_file', applyxfm,
                                'in_matrix_file')
        unwarp_workflow.connect(input_node, 'in_files', applyxfm, 'reference')

        # compute echo spacing:
        unwarp_workflow.connect(input_node, 'wfs', echo_spacing_philips, 'wfs')
        unwarp_workflow.connect(input_node, 'epi_factor', echo_spacing_philips,
                                'epi_factor')
        unwarp_workflow.connect(input_node, 'acceleration',
                                echo_spacing_philips, 'acceleration')
        unwarp_workflow.connect(echo_spacing_philips, 'echo_spacing', fugue,
                                'dwell_time')

    elif scanner == 'siemens':

        unwarp_workflow.connect(input_node, 'te_diff', te_diff_in_ms,
                                'te_diff')

        # prepare fieldmap:
        unwarp_workflow.connect(mask_mag, 'out_file', prepare_fieldmap,
                                'in_magnitude')
        unwarp_workflow.connect(input_node, 'fieldmap_pha', prepare_fieldmap,
                                'in_phase')
        unwarp_workflow.connect(te_diff_in_ms, 'te_diff', prepare_fieldmap,
                                'delta_TE')

        # transform fieldmap:
        unwarp_workflow.connect(prepare_fieldmap, 'out_fieldmap', applyxfm,
                                'in_file')
        unwarp_workflow.connect(registration, 'out_matrix_file', applyxfm,
                                'in_matrix_file')
        unwarp_workflow.connect(input_node, 'in_files', applyxfm, 'reference')

        # compute echo spacing:
        unwarp_workflow.connect(input_node, 'acceleration',
                                echo_spacing_siemens, 'acceleration')
        unwarp_workflow.connect(input_node, 'echo_spacing',
                                echo_spacing_siemens, 'echo_spacing')
        unwarp_workflow.connect(echo_spacing_siemens, 'echo_spacing', fugue,
                                'dwell_time')

    unwarp_workflow.connect(input_node, 'in_files', fugue, 'in_file')
    unwarp_workflow.connect(out_file, 'out_file', fugue, 'unwarped_file')
    unwarp_workflow.connect(applyxfm, 'out_file', fugue, 'fmap_in_file')
    unwarp_workflow.connect(input_node, 'te_diff', fugue, 'asym_se_time')
    unwarp_workflow.connect(input_node, 'phase_encoding_direction', fugue,
                            'unwarp_direction')
    unwarp_workflow.connect(fugue, 'unwarped_file', outputnode, 'out_files')
    unwarp_workflow.connect(applyxfm, 'out_file', outputnode, 'field_coefs')

    # # Connect
    # unwarp_workflow.connect(input_node, 'in_files', out_file, 'in_file')
    # unwarp_workflow.connect(input_node, 'fieldmap_pha', norm_pha, 'in_file')
    # unwarp_workflow.connect(input_node, 'fieldmap_mag', mask_mag, 'in_file')
    # unwarp_workflow.connect(mask_mag, 'mask_file', mask_mag_dil, 'in_file')
    # unwarp_workflow.connect(input_node, 'fieldmap_mag', prelude, 'magnitude_file')
    # unwarp_workflow.connect(norm_pha, 'out_file', prelude, 'phase_file')
    # unwarp_workflow.connect(mask_mag_dil, 'out_file', prelude, 'mask_file')
    # unwarp_workflow.connect(prelude, 'unwrapped_phase_file', radials_per_second, 'in_file')
    # unwarp_workflow.connect(input_node, 'te_diff', radials_per_second, 'asym')
    # unwarp_workflow.connect(mask_mag, 'out_file', registration, 'in_file')
    # unwarp_workflow.connect(input_node, 'in_files', registration, 'reference')
    # unwarp_workflow.connect(radials_per_second, 'out_file', applyxfm, 'in_file')
    # unwarp_workflow.connect(registration, 'out_matrix_file', applyxfm, 'in_matrix_file')
    # unwarp_workflow.connect(input_node, 'in_files', applyxfm, 'reference')
    # if compute_echo_spacing:
    #     unwarp_workflow.connect(input_node, 'wfs', echo_spacing, 'wfs')
    #     unwarp_workflow.connect(input_node, 'epi_factor', echo_spacing, 'epi_factor')
    #     unwarp_workflow.connect(input_node, 'acceleration', echo_spacing, 'acceleration')
    #     unwarp_workflow.connect(echo_spacing, 'echo_spacing', fugue, 'dwell_time')
    # else:
    #     unwarp_workflow.connect(input_node, 'echo_spacing', fugue, 'dwell_time')
    # unwarp_workflow.connect(input_node, 'in_files', fugue, 'in_file')
    # unwarp_workflow.connect(out_file, 'out_file', fugue, 'unwarped_file')
    # unwarp_workflow.connect(applyxfm, 'out_file', fugue, 'fmap_in_file')
    # unwarp_workflow.connect(input_node, 'te_diff', fugue, 'asym_se_time')
    # unwarp_workflow.connect(input_node, 'phase_encoding_direction', fugue, 'unwarp_direction')
    # unwarp_workflow.connect(fugue, 'unwarped_file', outputnode, 'out_files')
    # unwarp_workflow.connect(applyxfm, 'out_file', outputnode, 'field_coefs')

    return unwarp_workflow
예제 #4
0
def VERBOSE_EXTRACTER():
	#--- 1)  Import modules
	import nipype.interfaces.dcm2nii as dcm2nii
	import nipype.pipeline.engine as pe
	import matplotlib
	import os
	os.system('clear')
	from glob import glob
	from nilearn import plotting
	from nilearn import image
	from nipype.interfaces.utility import Function
	import nipype.interfaces.fsl.preprocess as fsl
	import nipype.interfaces.fsl.utils as fslu
	import numpy

	#--- 2)  Record intial working directory

	INITDIR=os.getcwd();

	#--- 3) Prompt user for directory containing NIFTI FILES

	NIFTIFILE=raw_input('Please drag in the \nnifti file you wish to extract\n(ensure there is no blank space at the end)\n')
	os.system('clear')
	print '---\n'
	NIFTIFILE=NIFTIFILE.strip('\'"')
	NIFTIDIR=os.path.split(NIFTIFILE)[0]
	frac=list(numpy.linspace(start=0,stop=1,num=6))
	grad=list(numpy.linspace(start=-1,stop=1,num=6))

	#--- 3) Move to directory

	os.chdir(NIFTIDIR)


	#--- 4) Realign for good practice. Seems like BET should assume a default orientation.

	realigner=pe.Node(interface=fslu.Reorient2Std(),name='REORIENTED')
	realigner.inputs.in_file=NIFTIFILE


	#--- 5) Set up extracter node


	#The input parameters depend on the dimensions of the file, so check these using nilearn.
	niftifiledim=len(image.load_img(NIFTIFILE).shape)

	extracter=pe.Node(interface=fsl.BET(),name='EXTRACTED')

	# Input can either be a list or float. Lists are iterables, floats are inputs.
	if type(grad) == float and type(frac) == float:
		extracter.inputs.frac=float(frac)
		extracter.inputs.vertical_gradient=float(grad)
	elif type(grad) == list and type(frac) == list:
		extracter.iterables=([('frac',frac),('vertical_gradient',grad)])
	elif type(grad) == float and type(frac) == list:
		extracter.iterables=([('frac',frac)])
		extracter.inputs.vertical_gradient=float(grad)
	elif type(grad) == list and type(frac) == float:
		extracter.iterables=([('vertical_gradient',grad)])
		extracter.inputs.frac=float(frac)


	if niftifiledim == 3:
		extracter.inputs.functional=bool(0)
	else:
		extracter.inputs.functional=bool(1)


	#--- 6) Set up a plotting node


	# Overlay extraction on original file.
	def bplot(in_file,in_file2):
		from nilearn import image
		from nilearn import plotting
		import matplotlib
		niftifiledim=len(image.load_img(in_file).shape)
		if niftifiledim == 3:
			display=plotting.plot_anat(in_file2)		
			display.add_contours(in_file,filled=True, alpha=0.5,levels=[0.2], colors='b')
			matplotlib.pyplot.show()
		else:
			firstim=image.index_img(in_file, 0)
			firstim2=image.index_img(in_file2, 0)
			display=plotting.plot_anat(firstim2)	
			display.add_contours(firstim,filled=True, alpha=0.5,levels=[0.2], colors='b')
			matplotlib.pyplot.show()
		return niftifiledim



	showextract= pe.Node(Function(input_names=['in_file','in_file2'],output_names=['niftifiledim'],function=bplot),name='SHOWEXTRACT')

	#--- 7) Set up workflow
	workflow = pe.Workflow(name='EXTRACTER')
	workflow.base_dir = NIFTIDIR

	#--- 8) Connect nodes.
	workflow.connect(realigner,'out_file',extracter,'in_file')
	workflow.connect(realigner,'out_file',showextract,'in_file2')
	workflow.connect(extracter,'out_file',showextract,'in_file')

	workflow.write_graph(graph2use='exec')

	#--- 9) Run workflow
	result=workflow.run()

	#--- 10) Show plot


	print "Node completed. Returning to intital directory\n"
	os.chdir(INITDIR)