Exemplo n.º 1
0
def create_pipeline(name="spline", opt=""):

    parameters = {'step_length': '0.5'}

    inputnode = pe.Node(
        interface=util.IdentityInterface(fields=["tck", "odf"]),
        name="inputnode")

    if opt is not None:
        opt_list = opt.split(',')
        for o in opt_list:
            try:
                [key, value] = o.split(':')
                parameters[key] = value
            except ValueError:
                print(o + ': irregular format, skipping')

    spline_filter = pe.Node(dtk.SplineFilter(), name='spline_filt')
    spline_filter.inputs.step_length = float(parameters['step_length'])

    output_fields = ["tck_post"]
    outputnode = pe.Node(
        interface=util.IdentityInterface(fields=output_fields),
        name="outputnode")

    workflow = pe.Workflow(name=name)
    workflow.base_output_dir = name

    workflow.connect([(inputnode, spline_filter, [("tck", "track_file")])])

    workflow.connect([(spline_filter, outputnode, [("smoothed_track_file",
                                                    "tck_post")])])

    return workflow
Exemplo n.º 2
0
    def _run_interface(self, runtime):
        # run streamline
        dtb_streamline = DTB_streamline(out_file=self.inputs.out_file)
        dtb_streamline.inputs.dir_file = self.inputs.dir_file
        dtb_streamline.inputs.wm_mask = self.inputs.wm_mask
        dtb_streamline.inputs.angle = self.inputs.angle
        dtb_streamline.inputs.step_size = self.inputs.step_size
        dtb_streamline.inputs.seeds = self.inputs.seeds
        dtb_streamline.inputs.out_file = self.inputs.out_file
        res_stream = dtb_streamline.run()
        
        if self.inputs.spline_filter:
            dtk_splinefilter = dtk.SplineFilter(step_length=1)
            dtk_splinefilter.inputs.step_length = self.inputs.spline_filter_step_length
            dtk_splinefilter.inputs.track_file = res_stream.outputs.out_file
            res_splinefilter = dtk_splinefilter.run()
            out_track_file = res_splinefilter.outputs.smoothed_track_file
        else:
            out_track_file = res_stream.outputs.out_file
            
        if self.inputs.fiberlength_filter:
            cmtk_filterfibers = CMTK_filterfibers()
            cmtk_filterfibers.inputs.track_file = out_track_file
            cmtk_filterfibers.run()

        return runtime
Exemplo n.º 3
0
def spline_filter(input_file, output_file, step_length=0.1):
    ''' Executes spline_filter, a TrackVis method that smoothes TrackVIs track files with a B-Spline filter
	'''
    filt = dtk.SplineFilter()
    filt.inputs.track_file = input_file
    filt.inputs.output_file = output_file
    filt.inputs.step_length = step_length
    filt.run()
def FA_connectome(subject_list,base_directory,out_directory):

	#==============================================================
	# Loading required packages
	import nipype.interfaces.io as nio
	import nipype.pipeline.engine as pe
	import nipype.interfaces.utility as util
	import nipype.interfaces.fsl as fsl
	import nipype.interfaces.dipy as dipy
	import nipype.interfaces.mrtrix as mrt
	from own_nipype import DipyDenoise as denoise
	from own_nipype import trk_Coreg as trkcoreg
	from own_nipype import TXT2PCK as txt2pck
	from own_nipype import FAconnectome as connectome
	from own_nipype import Extractb0 as extract_b0
	import nipype.interfaces.cmtk as cmtk
	import nipype.interfaces.diffusion_toolkit as dtk
	import nipype.algorithms.misc as misc

	from nipype import SelectFiles
	import os
	registration_reference = os.environ['FSLDIR'] + '/data/standard/FMRIB58_FA_1mm.nii.gz'
	nodes = list()

	#====================================
	# Defining the nodes for the workflow

	# Utility nodes
	gunzip = pe.Node(interface=misc.Gunzip(), name='gunzip')
	gunzip2 = pe.Node(interface=misc.Gunzip(), name='gunzip2')
	fsl2mrtrix = pe.Node(interface=mrt.FSL2MRTrix(invert_x=True),name='fsl2mrtrix')

	# Getting the subject ID
	infosource  = pe.Node(interface=util.IdentityInterface(fields=['subject_id']),name='infosource')
	infosource.iterables = ('subject_id', subject_list)

	# Getting the relevant diffusion-weighted data
	templates = dict(dwi='{subject_id}/dwi/{subject_id}_dwi.nii.gz',
		bvec='{subject_id}/dwi/{subject_id}_dwi.bvec',
		bval='{subject_id}/dwi/{subject_id}_dwi.bval')

	selectfiles = pe.Node(SelectFiles(templates),
	                   name='selectfiles')
	selectfiles.inputs.base_directory = os.path.abspath(base_directory)

	# Denoising
	denoise = pe.Node(interface=denoise(), name='denoise')

	# Eddy-current and motion correction
	eddycorrect = pe.Node(interface=fsl.epi.EddyCorrect(), name='eddycorrect')
	eddycorrect.inputs.ref_num = 0

	# Upsampling
	resample = pe.Node(interface=dipy.Resample(interp=3,vox_size=(1.,1.,1.)), name='resample')

	# Extract b0 image
	extract_b0 = pe.Node(interface=extract_b0(),name='extract_b0')

	# Fitting the diffusion tensor model
	dwi2tensor = pe.Node(interface=mrt.DWI2Tensor(), name='dwi2tensor')
	tensor2vector = pe.Node(interface=mrt.Tensor2Vector(), name='tensor2vector')
	tensor2adc = pe.Node(interface=mrt.Tensor2ApparentDiffusion(), name='tensor2adc')
	tensor2fa = pe.Node(interface=mrt.Tensor2FractionalAnisotropy(), name='tensor2fa')

	# Create a brain mask
	bet = pe.Node(interface=fsl.BET(frac=0.3,robust=False,mask=True),name='bet')

	# Eroding the brain mask
	erode_mask_firstpass = pe.Node(interface=mrt.Erode(), name='erode_mask_firstpass')
	erode_mask_secondpass = pe.Node(interface=mrt.Erode(), name='erode_mask_secondpass')
	MRmultiply = pe.Node(interface=mrt.MRMultiply(), name='MRmultiply')
	MRmult_merge = pe.Node(interface=util.Merge(2), name='MRmultiply_merge')
	threshold_FA = pe.Node(interface=mrt.Threshold(absolute_threshold_value = 0.7), name='threshold_FA')

	# White matter mask
	gen_WM_mask = pe.Node(interface=mrt.GenerateWhiteMatterMask(), name='gen_WM_mask')
	threshold_wmmask = pe.Node(interface=mrt.Threshold(absolute_threshold_value = 0.4), name='threshold_wmmask')

	# CSD probabilistic tractography 
	estimateresponse = pe.Node(interface=mrt.EstimateResponseForSH(maximum_harmonic_order = 8), name='estimateresponse')
	csdeconv = pe.Node(interface=mrt.ConstrainedSphericalDeconvolution(maximum_harmonic_order = 8), name='csdeconv')

	# Tracking 
	probCSDstreamtrack = pe.Node(interface=mrt.ProbabilisticSphericallyDeconvolutedStreamlineTrack(), name='probCSDstreamtrack')
	probCSDstreamtrack.inputs.inputmodel = 'SD_PROB'
	probCSDstreamtrack.inputs.desired_number_of_tracks = 150000
	tck2trk = pe.Node(interface=mrt.MRTrix2TrackVis(), name='tck2trk')

	# smoothing the tracts 
	smooth = pe.Node(interface=dtk.SplineFilter(step_length=0.5), name='smooth')

	# Co-registration with MNI space
	mrconvert = pe.Node(mrt.MRConvert(extension='nii'), name='mrconvert')
	flt = pe.Node(interface=fsl.FLIRT(reference=registration_reference, dof=12, cost_func='corratio'), name='flt')

	# Moving tracts to common space
	trkcoreg = pe.Node(interface=trkcoreg(reference=registration_reference),name='trkcoreg')

	# calcuating the connectome matrix 
	calc_matrix = pe.Node(interface=connectome(ROI_file='/home/jb07/Desktop/aal.nii.gz'),name='calc_matrix')

	# Converting the adjacency matrix from txt to pck format
	txt2pck = pe.Node(interface=txt2pck(), name='txt2pck')

	# Calculate graph theory measures with NetworkX and CMTK
	nxmetrics = pe.Node(interface=cmtk.NetworkXMetrics(treat_as_weighted_graph = True), name='nxmetrics')

	#====================================
	# Setting up the workflow
	fa_connectome = pe.Workflow(name='FA_connectome')

	# Reading in files
	fa_connectome.connect(infosource, 'subject_id', selectfiles, 'subject_id')

	# Denoising
	fa_connectome.connect(selectfiles, 'dwi', denoise, 'in_file')

	# Eddy current and motion correction
	fa_connectome.connect(denoise, 'out_file',eddycorrect, 'in_file')
	fa_connectome.connect(eddycorrect, 'eddy_corrected', resample, 'in_file')
	fa_connectome.connect(resample, 'out_file', extract_b0, 'in_file')
	fa_connectome.connect(resample, 'out_file', gunzip,'in_file')

	# Brain extraction
	fa_connectome.connect(extract_b0, 'out_file', bet, 'in_file')

	# Creating tensor maps
	fa_connectome.connect(selectfiles,'bval',fsl2mrtrix,'bval_file')
	fa_connectome.connect(selectfiles,'bvec',fsl2mrtrix,'bvec_file')
	fa_connectome.connect(gunzip,'out_file',dwi2tensor,'in_file')
	fa_connectome.connect(fsl2mrtrix,'encoding_file',dwi2tensor,'encoding_file')
	fa_connectome.connect(dwi2tensor,'tensor',tensor2vector,'in_file')
	fa_connectome.connect(dwi2tensor,'tensor',tensor2adc,'in_file')
	fa_connectome.connect(dwi2tensor,'tensor',tensor2fa,'in_file')
	fa_connectome.connect(tensor2fa,'FA', MRmult_merge, 'in1')

	# Thresholding to create a mask of single fibre voxels
	fa_connectome.connect(gunzip2, 'out_file', erode_mask_firstpass, 'in_file')
	fa_connectome.connect(erode_mask_firstpass, 'out_file', erode_mask_secondpass, 'in_file')
	fa_connectome.connect(erode_mask_secondpass,'out_file', MRmult_merge, 'in2')
	fa_connectome.connect(MRmult_merge, 'out', MRmultiply,  'in_files')
	fa_connectome.connect(MRmultiply, 'out_file', threshold_FA, 'in_file')

	# Create seed mask
	fa_connectome.connect(gunzip, 'out_file', gen_WM_mask, 'in_file')
	fa_connectome.connect(bet, 'mask_file', gunzip2, 'in_file')
	fa_connectome.connect(gunzip2, 'out_file', gen_WM_mask, 'binary_mask')
	fa_connectome.connect(fsl2mrtrix, 'encoding_file', gen_WM_mask, 'encoding_file')
	fa_connectome.connect(gen_WM_mask, 'WMprobabilitymap', threshold_wmmask, 'in_file')

	# Estimate response
	fa_connectome.connect(gunzip, 'out_file', estimateresponse, 'in_file')
	fa_connectome.connect(fsl2mrtrix, 'encoding_file', estimateresponse, 'encoding_file')
	fa_connectome.connect(threshold_FA, 'out_file', estimateresponse, 'mask_image')

	# CSD calculation
	fa_connectome.connect(gunzip, 'out_file', csdeconv, 'in_file')
	fa_connectome.connect(gen_WM_mask, 'WMprobabilitymap', csdeconv, 'mask_image')
	fa_connectome.connect(estimateresponse, 'response', csdeconv, 'response_file')
	fa_connectome.connect(fsl2mrtrix, 'encoding_file', csdeconv, 'encoding_file')

	# Running the tractography
	fa_connectome.connect(threshold_wmmask, "out_file", probCSDstreamtrack, "seed_file")
	fa_connectome.connect(csdeconv, "spherical_harmonics_image", probCSDstreamtrack, "in_file")
	fa_connectome.connect(gunzip, "out_file", tck2trk, "image_file")
	fa_connectome.connect(probCSDstreamtrack, "tracked", tck2trk, "in_file")

	# Smoothing the trackfile
	fa_connectome.connect(tck2trk, 'out_file',smooth,'track_file')

	# Co-registering FA with FMRIB58_FA_1mm standard space 
	fa_connectome.connect(MRmultiply,'out_file',mrconvert,'in_file')
	fa_connectome.connect(mrconvert,'converted',flt,'in_file')
	fa_connectome.connect(smooth,'smoothed_track_file',trkcoreg,'in_file')
	fa_connectome.connect(mrconvert,'converted',trkcoreg,'FA_file')
	fa_connectome.connect(flt,'out_matrix_file',trkcoreg,'transfomation_matrix')

	# Calculating the FA connectome
	fa_connectome.connect(trkcoreg,'transformed_track_file',calc_matrix,'trackfile')
	fa_connectome.connect(flt,'out_file',calc_matrix,'FA_file')

	# Calculating graph measures 
	fa_connectome.connect(calc_matrix,'out_file',txt2pck,'in_file')
	fa_connectome.connect(txt2pck,'out_file',nxmetrics,'in_file')

	#====================================
	# Running the workflow
	fa_connectome.base_dir = os.path.abspath(out_directory)
	fa_connectome.write_graph()
	fa_connectome.run('PBSGraph')
Exemplo n.º 5
0
                     (eddycorrect, odf_recon, [('outputnode.eddy_corrected',
                                                'DWI')]),
                     (eddycorrect, hardi_mat, [('outputnode.eddy_corrected',
                                                'reference_file')]),
                     (hardi_mat, odf_recon, [('out_file', 'matrix')])])
"""
Setup for Tracktography
-----------------------
Here we will create a workflow to enable deterministic tracktography
"""

tractography = pe.Workflow(name='tractography')

odf_tracker = pe.Node(interface=dtk.ODFTracker(), name="odf_tracker")

smooth_trk = pe.Node(interface=dtk.SplineFilter(), name="smooth_trk")
smooth_trk.inputs.step_length = 1
"""
connect all the nodes for this workflow
"""

tractography.connect([(odf_tracker, smooth_trk, [('track_file', 'track_file')])
                      ])
"""
Setup the pipeline that combines the two workflows: tractography and compute_ODF
----------------------------------------------------------------------------------
"""

dwiproc = pe.Workflow(name="dwiproc")
dwiproc.base_dir = os.path.abspath('dtk_odf_tutorial')
dwiproc.connect([
    def connectome(subject_list, base_directory, out_directory):

        # ==================================================================
        # Loading required packages
        import nipype.pipeline.engine as pe
        import nipype.interfaces.utility as util
        from nipype.interfaces.freesurfer import ApplyVolTransform
        from nipype.interfaces.freesurfer import BBRegister
        import nipype.interfaces.fsl as fsl
        import nipype.interfaces.diffusion_toolkit as dtk
        from nipype.interfaces.utility import Merge
        import numpy as np
        from additional_interfaces import AtlasValues
        from additional_interfaces import AparcStats
        from additional_interfaces import CalcMatrix
        from additional_interfaces import FreeSurferValues
        from additional_interfaces import Tractography
        from additional_pipelines import DWIPreproc
        from additional_pipelines import SubjectSpaceParcellation
        from additional_pipelines import T1Preproc

        from nipype import SelectFiles
        import os

        # ==================================================================
        # Defining the nodes for the workflow

        # Getting the subject ID
        infosource = pe.Node(
            interface=util.IdentityInterface(fields=['subject_id']),
            name='infosource')
        infosource.iterables = ('subject_id', subject_list)

        # Getting the relevant diffusion-weighted data
        templates = dict(T1='{subject_id}/anat/{subject_id}_T1w.nii.gz',
                         dwi='{subject_id}/dwi/{subject_id}_dwi.nii.gz',
                         bvec='{subject_id}/dwi/{subject_id}_dwi.bvec',
                         bval='{subject_id}/dwi/{subject_id}_dwi.bval')

        selectfiles = pe.Node(SelectFiles(templates), name='selectfiles')
        selectfiles.inputs.base_directory = os.path.abspath(base_directory)

        # ==============================================================
        # T1 processing
        t1_preproc = pe.Node(interface=T1Preproc(), name='t1_preproc')
        t1_preproc.inputs.out_directory = out_directory + '/connectome/'
        t1_preproc.inputs.template_directory = template_directory

        # DWI processing
        dwi_preproc = pe.Node(interface=DWIPreproc(), name='dwi_preproc')
        dwi_preproc.inputs.out_directory = out_directory + '/connectome/'
        dwi_preproc.inputs.acqparams = acquisition_parameters
        dwi_preproc.inputs.index_file = index_file
        dwi_preproc.inputs.out_directory = out_directory + '/connectome/'

        # Eroding the brain mask
        erode_mask = pe.Node(interface=fsl.maths.ErodeImage(),
                             name='erode_mask')

        # Reconstruction and tractography
        tractography = pe.Node(interface=Tractography(), name='tractography')
        tractography.iterables = ('model', ['CSA', 'CSD'])

        # smoothing the tracts
        smooth = pe.Node(interface=dtk.SplineFilter(step_length=0.5),
                         name='smooth')

        # Moving to subject space
        subject_parcellation = pe.Node(interface=SubjectSpaceParcellation(),
                                       name='subject_parcellation')
        subject_parcellation.inputs.source_subject = 'fsaverage'
        subject_parcellation.inputs.source_annot_file = 'aparc'
        subject_parcellation.inputs.out_directory = out_directory + '/connectome/'
        subject_parcellation.inputs.parcellation_directory = parcellation_directory

        # Co-registering T1 and dwi
        bbreg = pe.Node(interface=BBRegister(), name='bbreg')
        bbreg.inputs.init = 'fsl'
        bbreg.inputs.contrast_type = 't2'

        applyreg = pe.Node(interface=ApplyVolTransform(), name='applyreg')
        applyreg.inputs.interp = 'nearest'
        applyreg.inputs.inverse = True

        # Merge outputs to pass on to CalcMatrix
        merge = pe.Node(interface=Merge(3), name='merge')

        # calcuating the connectome matrix
        calc_matrix = pe.MapNode(interface=CalcMatrix(),
                                 name='calc_matrix',
                                 iterfield=['scalar_file'])
        calc_matrix.iterables = ('threshold', np.arange(0, 100, 10))

        # Getting values of diffusion measures
        FA_values = pe.Node(interface=AtlasValues(), name='FA_values')
        RD_values = pe.Node(interface=AtlasValues(), name='RD_values')
        AD_values = pe.Node(interface=AtlasValues(), name='AD_values')
        MD_values = pe.Node(interface=AtlasValues(), name='MD_values')

        # Getting additional surface measures
        aparcstats = pe.Node(interface=AparcStats(), name='aparcstats')
        aparcstats.inputs.parcellation_name = 'aparc'

        freesurfer_values = pe.Node(interface=FreeSurferValues(),
                                    name='freesurfer_values')
        freesurfer_values.inputs.parcellation_name = 'aparc'

        # ==================================================================
        # Setting up the workflow
        connectome = pe.Workflow(name='connectome')

        # Reading in files
        connectome.connect(infosource, 'subject_id', selectfiles, 'subject_id')

        # DWI preprocessing
        connectome.connect(infosource, 'subject_id', dwi_preproc, 'subject_id')
        connectome.connect(selectfiles, 'dwi', dwi_preproc, 'dwi')
        connectome.connect(selectfiles, 'bval', dwi_preproc, 'bvals')
        connectome.connect(selectfiles, 'bvec', dwi_preproc, 'bvecs')

        # CSD model and streamline tracking
        connectome.connect(dwi_preproc, 'mask', erode_mask, 'in_file')

        connectome.connect(selectfiles, 'bvec', tractography, 'bvec')
        connectome.connect(selectfiles, 'bval', tractography, 'bval')
        connectome.connect(dwi_preproc, 'dwi', tractography, 'in_file')
        connectome.connect(dwi_preproc, 'FA', tractography, 'FA')
        connectome.connect(erode_mask, 'out_file', tractography, 'brain_mask')

        # Smoothing the trackfile
        connectome.connect(tractography, 'out_track', smooth, 'track_file')

        # Preprocessing the T1-weighted file
        connectome.connect(infosource, 'subject_id', t1_preproc, 'subject_id')
        connectome.connect(selectfiles, 'T1', t1_preproc, 'T1')
        connectome.connect(t1_preproc, 'wm', subject_parcellation, 'wm')
        connectome.connect(t1_preproc, 'subjects_dir', subject_parcellation,
                           'subjects_dir')
        connectome.connect(t1_preproc, 'subject_id', subject_parcellation,
                           'subject_id')

        # Getting the parcellation into diffusion space
        connectome.connect(t1_preproc, 'subject_id', bbreg, 'subject_id')
        connectome.connect(t1_preproc, 'subjects_dir', bbreg, 'subjects_dir')
        connectome.connect(dwi_preproc, 'b0', bbreg, 'source_file')

        connectome.connect(dwi_preproc, 'b0', applyreg, 'source_file')
        connectome.connect(bbreg, 'out_reg_file', applyreg, 'reg_file')
        connectome.connect(subject_parcellation, 'renum_expanded', applyreg,
                           'target_file')

        # Calculating the FA connectome
        connectome.connect(tractography, 'out_file', calc_matrix, 'track_file')
        connectome.connect(dwi_preproc, 'FA', merge, 'in1')
        connectome.connect(dwi_preproc, 'RD', merge, 'in2')
        connectome.connect(tractography, 'GFA', merge, 'in3')
        connectome.connect(merge, 'out', calc_matrix, 'scalar_file')
        connectome.connect(applyreg, 'transformed_file', calc_matrix,
                           'ROI_file')

        # Getting values for additional measures
        connectome.connect(dwi_preproc, 'FA', FA_values, 'morpho_filename')
        connectome.connect(dwi_preproc, 'RD', RD_values, 'morpho_filename')
        connectome.connect(dwi_preproc, 'AD', AD_values, 'morpho_filename')
        connectome.connect(dwi_preproc, 'MD', MD_values, 'morpho_filename')
        connectome.connect(applyreg, 'transformed_file', FA_values,
                           'atlas_filename')
        connectome.connect(applyreg, 'transformed_file', RD_values,
                           'atlas_filename')
        connectome.connect(applyreg, 'transformed_file', AD_values,
                           'atlas_filename')
        connectome.connect(applyreg, 'transformed_file', MD_values,
                           'atlas_filename')

        # Getting FreeSurfer morphological values
        connectome.connect(t1_preproc, 'subject_id', aparcstats, 'subject_id')
        connectome.connect(t1_preproc, 'subjects_dir', aparcstats,
                           'subjects_dir')
        connectome.connect(aparcstats, 'lh_stats', freesurfer_values,
                           'lh_filename')
        connectome.connect(aparcstats, 'rh_stats', freesurfer_values,
                           'rh_filename')

        # ==================================================================
        # Running the workflow
        connectome.base_dir = os.path.abspath(out_directory)
        connectome.write_graph()
        connectome.run()
Exemplo n.º 7
0
    def whole_brain_tractography(subject_list, base_directory, out_directory):

        # ==================================================================
        # Loading required packages
        import nipype.pipeline.engine as pe
        import nipype.interfaces.utility as util
        from nipype.interfaces.freesurfer import ApplyVolTransform
        from nipype.interfaces.freesurfer import BBRegister
        import nipype.interfaces.fsl as fsl
        import nipype.interfaces.dipy as dipy
        import nipype.interfaces.diffusion_toolkit as dtk
        import nipype.algorithms.misc as misc
        from nipype.interfaces.utility import Merge
        from BrainTypes_additional_interfaces import Tractography
        from BrainTypes_additional_interfaces import DipyDenoise
        from BrainTypes_additional_pipelines import DWIPreproc
        from BrainTypes_additional_interfaces import CalcMatrix
        from BrainTypes_additional_pipelines import T1Preproc
        from BrainTypes_additional_pipelines import SubjectSpaceParcellation
        from BrainTypes_additional_interfaces import Extractb0 as extract_b0

        from nipype import SelectFiles
        import os

        # ==================================================================
        # Defining the nodes for the workflow

        # Getting the subject ID
        infosource = pe.Node(
            interface=util.IdentityInterface(fields=['subject_id']),
            name='infosource')
        infosource.iterables = ('subject_id', subject_list)

        # Getting the relevant diffusion-weighted data
        templates = dict(T1='{subject_id}/anat/{subject_id}_T1w.nii.gz',
                         dwi='{subject_id}/dwi/{subject_id}_dwi.nii.gz',
                         bvec='{subject_id}/dwi/{subject_id}_dwi.bvec',
                         bval='{subject_id}/dwi/{subject_id}_dwi.bval')

        selectfiles = pe.Node(SelectFiles(templates), name='selectfiles')
        selectfiles.inputs.base_directory = os.path.abspath(base_directory)

        # ==============================================================
        # T1 processing
        t1_preproc = pe.Node(interface=T1Preproc(), name='t1_preproc')
        t1_preproc.inputs.out_directory = out_directory + '/whole_brain_tractography/'
        t1_preproc.inputs.template_directory = template_directory

        # DWI processing
        dwi_preproc = pe.Node(interface=DWIPreproc(), name='dwi_preproc')
        dwi_preproc.inputs.out_directory = out_directory + '/whole_brain_tractography/'
        dwi_preproc.inputs.acqparams = acquisition_parameters
        dwi_preproc.inputs.index_file = index_file
        dwi_preproc.inputs.out_directory = out_directory + '/whole_brain_tractography/'

        # Eroding the brain mask
        erode_mask = pe.Node(interface=fsl.maths.ErodeImage(),
                             name='erode_mask')

        # Reconstruction and tractography
        tractography = pe.Node(interface=Tractography(), name='tractography')
        tractography.iterables = ('model', ['CSA', 'CSD'])

        # smoothing the tracts
        smooth = pe.Node(interface=dtk.SplineFilter(step_length=0.5),
                         name='smooth')

        # Moving to subject space
        subject_parcellation = pe.Node(interface=SubjectSpaceParcellation(),
                                       name='subject_parcellation')
        subject_parcellation.inputs.source_subject = 'fsaverage'
        subject_parcellation.inputs.source_annot_file = 'aparc'
        subject_parcellation.inputs.out_directory = out_directory + '/connectome/'
        subject_parcellation.inputs.parcellation_directory = parcellation_directory

        # Co-registering T1 and dwi
        bbreg = pe.Node(interface=BBRegister(), name='bbreg')
        bbreg.inputs.init = 'fsl'
        bbreg.inputs.contrast_type = 't2'

        applyreg = pe.Node(interface=ApplyVolTransform(), name='applyreg')
        applyreg.inputs.interp = 'nearest'
        applyreg.inputs.inverse = True

        # ==================================================================
        # Setting up the workflow
        whole_brain_tractography = pe.Workflow(name='whole_brain_tractography')

        # Reading in files
        whole_brain_tractography.connect(infosource, 'subject_id', selectfiles,
                                         'subject_id')

        # DWI preprocessing
        whole_brain_tractography.connect(infosource, 'subject_id', dwi_preproc,
                                         'subject_id')
        whole_brain_tractography.connect(selectfiles, 'dwi', dwi_preproc,
                                         'dwi')
        whole_brain_tractography.connect(selectfiles, 'bval', dwi_preproc,
                                         'bvals')
        whole_brain_tractography.connect(selectfiles, 'bvec', dwi_preproc,
                                         'bvecs')

        # CSD model and streamline tracking
        whole_brain_tractography.connect(dwi_preproc, 'mask', erode_mask,
                                         'in_file')

        whole_brain_tractography.connect(selectfiles, 'bvec', tractography,
                                         'bvec')
        whole_brain_tractography.connect(selectfiles, 'bval', tractography,
                                         'bval')
        whole_brain_tractography.connect(dwi_preproc, 'dwi', tractography,
                                         'in_file')
        whole_brain_tractography.connect(dwi_preproc, 'FA', tractography, 'FA')
        whole_brain_tractography.connect(erode_mask, 'out_file', tractography,
                                         'brain_mask')

        # Smoothing the trackfile
        whole_brain_tractography.connect(tractography, 'out_track', smooth,
                                         'track_file')

        # Preprocessing the T1-weighted file
        whole_brain_tractography.connect(infosource, 'subject_id', t1_preproc,
                                         'subject_id')
        whole_brain_tractography.connect(selectfiles, 'T1', t1_preproc, 'T1')
        whole_brain_tractography.connect(t1_preproc, 'wm',
                                         subject_parcellation, 'wm')
        whole_brain_tractography.connect(t1_preproc, 'subjects_dir',
                                         subject_parcellation, 'subjects_dir')
        whole_brain_tractography.connect(t1_preproc, 'subject_id',
                                         subject_parcellation, 'subject_id')

        # Getting the parcellation into diffusion space
        whole_brain_tractography.connect(t1_preproc, 'subject_id', bbreg,
                                         'subject_id')
        whole_brain_tractography.connect(t1_preproc, 'subjects_dir', bbreg,
                                         'subjects_dir')
        whole_brain_tractography.connect(dwi_preproc, 'b0', bbreg,
                                         'source_file')

        whole_brain_tractography.connect(dwi_preproc, 'b0', applyreg,
                                         'source_file')
        whole_brain_tractography.connect(bbreg, 'out_reg_file', applyreg,
                                         'reg_file')
        whole_brain_tractography.connect(subject_parcellation,
                                         'renum_expanded', applyreg,
                                         'target_file')

        # ==================================================================
        # Running the workflow
        whole_brain_tractography.base_dir = os.path.abspath(out_directory)
        whole_brain_tractography.write_graph()
        whole_brain_tractography.run()
def create_prepare_seeds_from_fmri_pipeline(name="prepare_seeds_from_fmri"):

    inputnode = pe.Node(interface=util.IdentityInterface(fields=[
        'epi', "stat", "dwi", "mask", "phsamples", "thsamples", "fsamples",
        "T1", "stat_labels"
    ]),
                        name="inputnode")

    first_dwi = pe.Node(interface=fsl.ExtractROI(t_min=0, t_size=1),
                        name="first_dwi")
    first_epi = first_dwi.clone(name="first_epi")

    coregister = pe.Node(interface=fsl.FLIRT(), name="coregister_epi2dwi")

    reslice_stat = pe.MapNode(interface=fsl.FLIRT(),
                              name="reslice_stat",
                              iterfield=["in_file"])
    reslice_stat.inputs.apply_xfm = True
    reslice_mask = pe.Node(interface=fsl.FLIRT(), name="reslice_mask")
    reslice_mask.inputs.interp = "nearestneighbour"

    smm = pe.MapNode(interface=fsl.SMM(),
                     name="smm",
                     iterfield=['spatial_data_file'])

    threshold = pe.MapNode(interface=fsl.Threshold(),
                           name="threshold",
                           iterfield=['in_file'])
    threshold.inputs.thresh = 0.95

    probtractx = pe.Node(interface=fsl.ProbTrackX(),
                         name="probtractx")  #, iterfield=['waypoints'])
    probtractx.inputs.opd = True
    probtractx.inputs.loop_check = True
    probtractx.inputs.c_thresh = 0.2
    probtractx.inputs.n_steps = 2000
    probtractx.inputs.step_length = 0.5
    probtractx.inputs.n_samples = 100
    probtractx.inputs.correct_path_distribution = True
    probtractx.inputs.verbose = 2

    segment = pe.Node(interface=spm.Segment(), name="segment")
    segment.inputs.gm_output_type = [False, False, True]
    segment.inputs.wm_output_type = [False, False, True]
    segment.inputs.csf_output_type = [False, False, False]

    th_wm = pe.Node(interface=fsl.Threshold(), name="th_wm")
    th_wm.inputs.direction = "below"
    th_wm.inputs.thresh = 0.2
    th_gm = th_wm.clone("th_gm")

    wm_gm_interface = pe.Node(fsl.ApplyMask(), name="wm_gm_interface")

    bet_t1 = pe.Node(fsl.BET(), name="bet_t1")

    coregister_t1_to_dwi = pe.Node(interface=fsl.FLIRT(),
                                   name="coregister_t1_to_dwi")

    invert_dwi_to_t1_xfm = pe.Node(interface=fsl.ConvertXFM(),
                                   name="invert_dwi_to_t1_xfm")
    invert_dwi_to_t1_xfm.inputs.invert_xfm = True

    reslice_gm = pe.Node(interface=fsl.FLIRT(), name="reslice_gm")
    reslice_gm.inputs.apply_xfm = True

    reslice_wm = reslice_gm.clone("reslice_wm")

    particles2trackvis = pe.Node(interface=neuroutils.Particle2Trackvis(),
                                 name='particles2trackvis')

    annotate_trackvis = pe.Node(interface=neuroutils.AnnotateTracts(),
                                name='annotate_trackvis')

    smooth_tracks = pe.Node(interface=dt.SplineFilter(), name="smooth_tracks")
    smooth_tracks.inputs.step_length = 0.5

    pipeline = pe.Workflow(name=name)
    pipeline.connect([
        (inputnode, first_dwi, [("dwi", "in_file")]),
        (inputnode, first_epi, [("epi", "in_file")]),
        (first_epi, coregister, [("roi_file", "in_file")]),
        (first_dwi, coregister, [("roi_file", "reference")]),
        (inputnode, reslice_stat, [("stat", "in_file"), ("dwi", "reference")]),
        (inputnode, reslice_mask, [("mask", "in_file"), ("dwi", "reference")]),
        (coregister, reslice_stat, [("out_matrix_file", "in_matrix_file")]),
        (coregister, reslice_mask, [("out_matrix_file", "in_matrix_file")]),
        (reslice_stat, smm, [("out_file", "spatial_data_file")]),
        (reslice_mask, smm, [("out_file", "mask")]),
        (smm, threshold, [('activation_p_map', 'in_file')]),
        (inputnode, probtractx, [("phsamples", "phsamples"),
                                 ("thsamples", "thsamples"),
                                 ("fsamples", "fsamples")]),
        (reslice_mask, probtractx, [("out_file", "mask")]),
        #(threshold, probtractx, [("out_file", "waypoints")]),
        (inputnode, segment, [("T1", "data")]),
        (inputnode, bet_t1, [("T1", "in_file")]),
        (bet_t1, coregister_t1_to_dwi, [("out_file", "reference")]),
        (first_dwi, coregister_t1_to_dwi, [("roi_file", "in_file")]),
        (coregister_t1_to_dwi, invert_dwi_to_t1_xfm, [("out_matrix_file",
                                                       "in_file")]),
        (invert_dwi_to_t1_xfm, reslice_gm, [("out_file", "in_matrix_file")]),
        (segment, reslice_gm, [("native_gm_image", "in_file")]),
        (first_dwi, reslice_gm, [("roi_file", "reference")]),
        (reslice_gm, th_gm, [("out_file", "in_file")]),
        (th_gm, wm_gm_interface, [("out_file", "in_file")]),
        (invert_dwi_to_t1_xfm, reslice_wm, [("out_file", "in_matrix_file")]),
        (segment, reslice_wm, [("native_wm_image", "in_file")]),
        (first_dwi, reslice_wm, [("roi_file", "reference")]),
        (reslice_wm, th_wm, [("out_file", "in_file")]),
        (th_wm, wm_gm_interface, [("out_file", "mask_file")]),
        (wm_gm_interface, probtractx, [("out_file", "seed")]),
        (probtractx, particles2trackvis, [('particle_files', 'particle_files')
                                          ]),
        (reslice_mask, particles2trackvis, [("out_file", "reference_file")]),
        (particles2trackvis, annotate_trackvis, [('trackvis_file',
                                                  'trackvis_file')]),
        (smm, annotate_trackvis, [('activation_p_map', 'stat_files')]),
        (inputnode, annotate_trackvis, [('stat_labels', 'stat_labels')]),
        (annotate_trackvis, smooth_tracks, [('annotated_trackvis_file',
                                             'track_file')])
    ])
    return pipeline