Ejemplo n.º 1
0
def mrtrix_dti(name='MRTrix_DTI'):
    """
    A workflow for DTI reconstruction using the tensor fitting included with
    MRTrix.
    :inputs:
        * in_dwi: the input dMRI volume to be reconstructed
        * in_bvec: b-vectors file in FSL format
        * in_bval: b-values file in FSL format
        * in_mask: input whole-brain mask (dwi space)
    """
    from nipype.pipeline import engine as pe
    from nipype.interfaces import utility as niu
    from nipype.interfaces import mrtrix as mrt
    from nipype.interfaces import freesurfer as fs

    inputnode = pe.Node(niu.IdentityInterface(
        fields=['in_bvec', 'in_bval', 'in_dwi', 'in_mask']), name='inputnode')
    outputnode = pe.Node(niu.IdentityInterface(
        fields=['fa', 'md']), name='outputnode')

    fsl2mrtrix = pe.Node(mrt.FSL2MRTrix(), name='fsl2mrtrix')
    dwi2tsr = pe.Node(mrt.DWI2Tensor(), name='DWI2Tensor')
    tsr2fa = pe.Node(mrt.Tensor2FractionalAnisotropy(), name='ComputeFA')
    fa2nii = pe.Node(mrt.MRConvert(extension='nii'), 'FA2Nifti')
    msk_fa = pe.Node(fs.ApplyMask(), name='MaskFA')
    tsr2adc = pe.Node(mrt.Tensor2ApparentDiffusion(), name='ComputeADC')
    adc2nii = pe.Node(mrt.MRConvert(extension='nii'), 'ADC2Nifti')
    msk_adc = pe.Node(fs.ApplyMask(), name='MaskADC')

    wf = pe.Workflow(name=name)
    wf.connect([
        (inputnode,    fsl2mrtrix, [('in_bvec', 'bvec_file'),
                                    ('in_bval', 'bval_file')]),
        (inputnode,       dwi2tsr, [('in_dwi', 'in_file')]),
        (inputnode,        msk_fa, [('in_mask', 'mask_file')]),
        (inputnode,       msk_adc, [('in_mask', 'mask_file')]),
        (fsl2mrtrix,      dwi2tsr, [('encoding_file', 'encoding_file')]),
        (dwi2tsr,          tsr2fa, [('tensor', 'in_file')]),
        (tsr2fa,           fa2nii, [('FA', 'in_file')]),
        (fa2nii,           msk_fa, [('converted', 'in_file')]),
        (dwi2tsr,         tsr2adc, [('tensor', 'in_file')]),
        (tsr2adc,         adc2nii, [('ADC', 'in_file')]),
        (adc2nii,         msk_adc, [('converted', 'in_file')]),
        (msk_fa,       outputnode, [('out_file', 'fa')]),
        (msk_adc,      outputnode, [('out_file', 'md')])
    ])

    return wf
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')
Ejemplo n.º 3
0
def create_mrtrix_dti_pipeline(name="dtiproc",
                               tractography_type='probabilistic'):
    """Creates a pipeline that does the same diffusion processing as in the
    :doc:`../../users/examples/dmri_mrtrix_dti` example script. Given a diffusion-weighted image,
    b-values, and b-vectors, the workflow will return the tractography
    computed from spherical deconvolution and probabilistic streamline tractography

    Example
    -------

    >>> dti = create_mrtrix_dti_pipeline("mrtrix_dti")
    >>> dti.inputs.inputnode.dwi = 'data.nii'
    >>> dti.inputs.inputnode.bvals = 'bvals'
    >>> dti.inputs.inputnode.bvecs = 'bvecs'
    >>> dti.run()                  # doctest: +SKIP

    Inputs::

        inputnode.dwi
        inputnode.bvecs
        inputnode.bvals

    Outputs::

        outputnode.fa
        outputnode.tdi
        outputnode.tracts_tck
        outputnode.tracts_trk
        outputnode.csdeconv

    """

    inputnode = pe.Node(
        interface=util.IdentityInterface(fields=["dwi", "bvecs", "bvals"]),
        name="inputnode")

    bet = pe.Node(interface=fsl.BET(), name="bet")
    bet.inputs.mask = True

    fsl2mrtrix = pe.Node(interface=mrtrix.FSL2MRTrix(), name='fsl2mrtrix')
    fsl2mrtrix.inputs.invert_y = True

    dwi2tensor = pe.Node(interface=mrtrix.DWI2Tensor(), name='dwi2tensor')

    tensor2vector = pe.Node(interface=mrtrix.Tensor2Vector(),
                            name='tensor2vector')
    tensor2adc = pe.Node(interface=mrtrix.Tensor2ApparentDiffusion(),
                         name='tensor2adc')
    tensor2fa = pe.Node(interface=mrtrix.Tensor2FractionalAnisotropy(),
                        name='tensor2fa')

    erode_mask_firstpass = pe.Node(interface=mrtrix.Erode(),
                                   name='erode_mask_firstpass')
    erode_mask_secondpass = pe.Node(interface=mrtrix.Erode(),
                                    name='erode_mask_secondpass')

    threshold_b0 = pe.Node(interface=mrtrix.Threshold(), name='threshold_b0')

    threshold_FA = pe.Node(interface=mrtrix.Threshold(), name='threshold_FA')
    threshold_FA.inputs.absolute_threshold_value = 0.7

    threshold_wmmask = pe.Node(interface=mrtrix.Threshold(),
                               name='threshold_wmmask')
    threshold_wmmask.inputs.absolute_threshold_value = 0.4

    MRmultiply = pe.Node(interface=mrtrix.MRMultiply(), name='MRmultiply')
    MRmult_merge = pe.Node(interface=util.Merge(2), name='MRmultiply_merge')

    median3d = pe.Node(interface=mrtrix.MedianFilter3D(), name='median3D')

    MRconvert = pe.Node(interface=mrtrix.MRConvert(), name='MRconvert')
    MRconvert.inputs.extract_at_axis = 3
    MRconvert.inputs.extract_at_coordinate = [0]

    csdeconv = pe.Node(interface=mrtrix.ConstrainedSphericalDeconvolution(),
                       name='csdeconv')

    gen_WM_mask = pe.Node(interface=mrtrix.GenerateWhiteMatterMask(),
                          name='gen_WM_mask')

    estimateresponse = pe.Node(interface=mrtrix.EstimateResponseForSH(),
                               name='estimateresponse')

    if tractography_type == 'probabilistic':
        CSDstreamtrack = pe.Node(
            interface=mrtrix.
            ProbabilisticSphericallyDeconvolutedStreamlineTrack(),
            name='CSDstreamtrack')
    else:
        CSDstreamtrack = pe.Node(
            interface=mrtrix.SphericallyDeconvolutedStreamlineTrack(),
            name='CSDstreamtrack')
    CSDstreamtrack.inputs.desired_number_of_tracks = 15000

    tracks2prob = pe.Node(interface=mrtrix.Tracks2Prob(), name='tracks2prob')
    tracks2prob.inputs.colour = True
    tck2trk = pe.Node(interface=mrtrix.MRTrix2TrackVis(), name='tck2trk')

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

    workflow.connect([(inputnode, fsl2mrtrix, [("bvecs", "bvec_file"),
                                               ("bvals", "bval_file")])])
    workflow.connect([(inputnode, dwi2tensor, [("dwi", "in_file")])])
    workflow.connect([(fsl2mrtrix, dwi2tensor, [("encoding_file",
                                                 "encoding_file")])])

    workflow.connect([
        (dwi2tensor, tensor2vector, [['tensor', 'in_file']]),
        (dwi2tensor, tensor2adc, [['tensor', 'in_file']]),
        (dwi2tensor, tensor2fa, [['tensor', 'in_file']]),
    ])

    workflow.connect([(inputnode, MRconvert, [("dwi", "in_file")])])
    workflow.connect([(MRconvert, threshold_b0, [("converted", "in_file")])])
    workflow.connect([(threshold_b0, median3d, [("out_file", "in_file")])])
    workflow.connect([(median3d, erode_mask_firstpass, [("out_file", "in_file")
                                                        ])])
    workflow.connect([(erode_mask_firstpass, erode_mask_secondpass,
                       [("out_file", "in_file")])])

    workflow.connect([(tensor2fa, MRmult_merge, [("FA", "in1")])])
    workflow.connect([(erode_mask_secondpass, MRmult_merge, [("out_file",
                                                              "in2")])])
    workflow.connect([(MRmult_merge, MRmultiply, [("out", "in_files")])])
    workflow.connect([(MRmultiply, threshold_FA, [("out_file", "in_file")])])
    workflow.connect([(threshold_FA, estimateresponse, [("out_file",
                                                         "mask_image")])])

    workflow.connect([(inputnode, bet, [("dwi", "in_file")])])
    workflow.connect([(inputnode, gen_WM_mask, [("dwi", "in_file")])])
    workflow.connect([(bet, gen_WM_mask, [("mask_file", "binary_mask")])])
    workflow.connect([(fsl2mrtrix, gen_WM_mask, [("encoding_file",
                                                  "encoding_file")])])

    workflow.connect([(inputnode, estimateresponse, [("dwi", "in_file")])])
    workflow.connect([(fsl2mrtrix, estimateresponse, [("encoding_file",
                                                       "encoding_file")])])

    workflow.connect([(inputnode, csdeconv, [("dwi", "in_file")])])
    workflow.connect([(gen_WM_mask, csdeconv, [("WMprobabilitymap",
                                                "mask_image")])])
    workflow.connect([(estimateresponse, csdeconv, [("response",
                                                     "response_file")])])
    workflow.connect([(fsl2mrtrix, csdeconv, [("encoding_file",
                                               "encoding_file")])])

    workflow.connect([(gen_WM_mask, threshold_wmmask, [("WMprobabilitymap",
                                                        "in_file")])])
    workflow.connect([(threshold_wmmask, CSDstreamtrack, [("out_file",
                                                           "seed_file")])])
    workflow.connect([(csdeconv, CSDstreamtrack, [("spherical_harmonics_image",
                                                   "in_file")])])

    if tractography_type == 'probabilistic':
        workflow.connect([(CSDstreamtrack, tracks2prob, [("tracked", "in_file")
                                                         ])])
        workflow.connect([(inputnode, tracks2prob, [("dwi", "template_file")])
                          ])

    workflow.connect([(CSDstreamtrack, tck2trk, [("tracked", "in_file")])])
    workflow.connect([(inputnode, tck2trk, [("dwi", "image_file")])])

    output_fields = ["fa", "tracts_trk", "csdeconv", "tracts_tck"]
    if tractography_type == 'probabilistic':
        output_fields.append("tdi")
    outputnode = pe.Node(
        interface=util.IdentityInterface(fields=output_fields),
        name="outputnode")

    workflow.connect([
        (CSDstreamtrack, outputnode, [("tracked", "tracts_tck")]),
        (csdeconv, outputnode, [("spherical_harmonics_image", "csdeconv")]),
        (tensor2fa, outputnode, [("FA", "fa")]),
        (tck2trk, outputnode, [("out_file", "tracts_trk")])
    ])
    if tractography_type == 'probabilistic':
        workflow.connect([(tracks2prob, outputnode, [("tract_image", "tdi")])])

    return workflow
Ejemplo n.º 4
0
    def build_core_nodes(self):
        """Build and connect the core nodes of the pipeline."""
        import os

        import nipype.interfaces.fsl as fsl
        import nipype.interfaces.mrtrix as mrtrix
        import nipype.interfaces.utility as nutil
        import nipype.pipeline.engine as npe
        from nipype.interfaces.ants import ApplyTransforms, RegistrationSynQuick
        from nipype.interfaces.mrtrix.preprocess import DWI2Tensor

        from clinica.lib.nipype.interfaces.mrtrix3.utils import TensorMetrics
        from clinica.utils.check_dependency import check_environment_variable

        from .dwi_dti_utils import (
            extract_bids_identifier_from_caps_filename,
            get_ants_transforms,
            get_caps_filenames,
            print_begin_pipeline,
            print_end_pipeline,
            statistics_on_atlases,
        )

        # Nodes creation
        # ==============
        get_bids_identifier = npe.Node(
            interface=nutil.Function(
                input_names=["caps_dwi_filename"],
                output_names=["bids_identifier"],
                function=extract_bids_identifier_from_caps_filename,
            ),
            name="0-Get_BIDS_Identifier",
        )

        get_caps_filenames = npe.Node(
            interface=nutil.Function(
                input_names=["caps_dwi_filename"],
                output_names=[
                    "bids_source",
                    "out_dti",
                    "out_fa",
                    "out_md",
                    "out_ad",
                    "out_rd",
                    "out_evec",
                ],
                function=get_caps_filenames,
            ),
            name="0-CAPS_Filenames",
        )

        convert_gradients = npe.Node(interface=mrtrix.FSL2MRTrix(),
                                     name="0-Convert_FSL_Gradient")

        dwi_to_dti = npe.Node(interface=DWI2Tensor(), name="1-Compute_DTI")

        dti_to_metrics = npe.Node(interface=TensorMetrics(),
                                  name="2-DTI-based_Metrics")

        register_fa = npe.Node(interface=RegistrationSynQuick(),
                               name="3a-Register_FA")
        fsl_dir = check_environment_variable("FSLDIR", "FSL")
        fa_map = os.path.join(fsl_dir, "data", "atlases", "JHU",
                              "JHU-ICBM-FA-1mm.nii.gz")
        register_fa.inputs.fixed_image = fa_map

        ants_transforms = npe.Node(
            interface=nutil.Function(
                input_names=[
                    "in_affine_transformation", "in_bspline_transformation"
                ],
                output_names=["transforms"],
                function=get_ants_transforms,
            ),
            name="combine_ants_transforms",
        )

        apply_ants_registration = npe.Node(interface=ApplyTransforms(),
                                           name="apply_ants_registration")
        apply_ants_registration.inputs.dimension = 3
        apply_ants_registration.inputs.input_image_type = 0
        apply_ants_registration.inputs.interpolation = "Linear"
        apply_ants_registration.inputs.reference_image = fa_map

        apply_ants_registration_for_md = apply_ants_registration.clone(
            "3b-Apply_ANTs_Registration_MD")
        apply_ants_registration_for_ad = apply_ants_registration.clone(
            "3b-Apply_ANTs_Registration_AD")
        apply_ants_registration_for_rd = apply_ants_registration.clone(
            "3b-Apply_ANTs_Registration_RD")

        thres_map = npe.Node(fsl.Threshold(thresh=0.0),
                             iterfield=["in_file"],
                             name="RemoveNegative")
        thres_norm_fa = thres_map.clone("3c-RemoveNegative_FA")
        thres_norm_md = thres_map.clone("3c-RemoveNegative_MD")
        thres_norm_ad = thres_map.clone("3c-RemoveNegative_AD")
        thres_norm_rd = thres_map.clone("3c-RemoveNegative_RD")

        scalar_analysis = npe.Node(
            interface=nutil.Function(
                input_names=["in_registered_map", "name_map", "prefix_file"],
                output_names=["atlas_statistics_list"],
                function=statistics_on_atlases,
            ),
            name="4-Scalar_Analysis",
        )
        scalar_analysis_fa = scalar_analysis.clone("4-Scalar_Analysis_FA")
        scalar_analysis_fa.inputs.name_map = "FA"
        scalar_analysis_md = scalar_analysis.clone("4-Scalar_Analysis_MD")
        scalar_analysis_md.inputs.name_map = "MD"
        scalar_analysis_ad = scalar_analysis.clone("4-Scalar_Analysis_AD")
        scalar_analysis_ad.inputs.name_map = "AD"
        scalar_analysis_rd = scalar_analysis.clone("4-Scalar_Analysis_RD")
        scalar_analysis_rd.inputs.name_map = "RD"

        thres_map = npe.Node(fsl.Threshold(thresh=0.0),
                             iterfield=["in_file"],
                             name="5-Remove_Negative")
        thres_fa = thres_map.clone("5-Remove_Negative_FA")
        thres_md = thres_map.clone("5-Remove_Negative_MD")
        thres_ad = thres_map.clone("5-Remove_Negative_AD")
        thres_rd = thres_map.clone("5-Remove_Negative_RD")
        thres_decfa = thres_map.clone("5-Remove_Negative_DECFA")

        print_begin_message = npe.Node(
            interface=nutil.Function(input_names=["in_bids_or_caps_file"],
                                     function=print_begin_pipeline),
            name="Write-Begin_Message",
        )

        print_end_message = npe.Node(
            interface=nutil.Function(
                input_names=[
                    "in_bids_or_caps_file", "final_file_1", "final_file_2"
                ],
                function=print_end_pipeline,
            ),
            name="Write-End_Message",
        )

        # Connection
        # ==========
        # fmt: off
        self.connect([
            (self.input_node, get_caps_filenames, [("preproc_dwi",
                                                    "caps_dwi_filename")]),
            # Print begin message
            (self.input_node, print_begin_message, [("preproc_dwi",
                                                     "in_bids_or_caps_file")]),
            # Get BIDS/CAPS identifier from filename
            (self.input_node, get_bids_identifier, [("preproc_dwi",
                                                     "caps_dwi_filename")]),
            # Convert FSL gradient files (bval/bvec) to MRtrix format
            (self.input_node, convert_gradients,
             [("preproc_bval", "bval_file"), ("preproc_bvec", "bvec_file")]),
            # Computation of the DTI model
            (self.input_node, dwi_to_dti, [("b0_mask", "mask"),
                                           ("preproc_dwi", "in_file")]),
            (convert_gradients, dwi_to_dti, [("encoding_file", "encoding_file")
                                             ]),
            (get_caps_filenames, dwi_to_dti, [("out_dti", "out_filename")]),
            # Computation of the different metrics from the DTI
            (get_caps_filenames, dti_to_metrics, [("out_fa", "out_fa")]),
            (get_caps_filenames, dti_to_metrics, [("out_md", "out_adc")]),
            (get_caps_filenames, dti_to_metrics, [("out_ad", "out_ad")]),
            (get_caps_filenames, dti_to_metrics, [("out_rd", "out_rd")]),
            (get_caps_filenames, dti_to_metrics, [("out_evec", "out_evec")]),
            (self.input_node, dti_to_metrics, [("b0_mask", "in_mask")]),
            (dwi_to_dti, dti_to_metrics, [("tensor", "in_file")]),
            # Registration of FA-map onto the atlas:
            (dti_to_metrics, register_fa, [("out_fa", "moving_image")]),
            # Apply deformation field on MD, AD & RD:
            (register_fa, ants_transforms, [("out_matrix",
                                             "in_affine_transformation")]),
            (register_fa, ants_transforms, [("forward_warp_field",
                                             "in_bspline_transformation")]),
            (dti_to_metrics, apply_ants_registration_for_md,
             [("out_adc", "input_image")]),
            (ants_transforms, apply_ants_registration_for_md,
             [("transforms", "transforms")]),
            (dti_to_metrics, apply_ants_registration_for_ad,
             [("out_ad", "input_image")]),
            (ants_transforms, apply_ants_registration_for_ad,
             [("transforms", "transforms")]),
            (dti_to_metrics, apply_ants_registration_for_rd,
             [("out_rd", "input_image")]),
            (ants_transforms, apply_ants_registration_for_rd,
             [("transforms", "transforms")]),
            # Remove negative values from the DTI maps:
            (register_fa, thres_norm_fa, [("warped_image", "in_file")]),
            (apply_ants_registration_for_md, thres_norm_md, [("output_image",
                                                              "in_file")]),
            (apply_ants_registration_for_rd, thres_norm_rd, [("output_image",
                                                              "in_file")]),
            (apply_ants_registration_for_ad, thres_norm_ad, [("output_image",
                                                              "in_file")]),
            # Generate regional TSV files
            (get_bids_identifier, scalar_analysis_fa, [("bids_identifier",
                                                        "prefix_file")]),
            (thres_norm_fa, scalar_analysis_fa, [("out_file",
                                                  "in_registered_map")]),
            (get_bids_identifier, scalar_analysis_md, [("bids_identifier",
                                                        "prefix_file")]),
            (thres_norm_md, scalar_analysis_md, [("out_file",
                                                  "in_registered_map")]),
            (get_bids_identifier, scalar_analysis_ad, [("bids_identifier",
                                                        "prefix_file")]),
            (thres_norm_ad, scalar_analysis_ad, [("out_file",
                                                  "in_registered_map")]),
            (get_bids_identifier, scalar_analysis_rd, [("bids_identifier",
                                                        "prefix_file")]),
            (thres_norm_rd, scalar_analysis_rd, [("out_file",
                                                  "in_registered_map")]),
            # Remove negative values from the DTI maps:
            (get_caps_filenames, thres_fa, [("out_fa", "out_file")]),
            (dti_to_metrics, thres_fa, [("out_fa", "in_file")]),
            (get_caps_filenames, thres_md, [("out_md", "out_file")]),
            (dti_to_metrics, thres_md, [("out_adc", "in_file")]),
            (get_caps_filenames, thres_ad, [("out_ad", "out_file")]),
            (dti_to_metrics, thres_ad, [("out_ad", "in_file")]),
            (get_caps_filenames, thres_rd, [("out_rd", "out_file")]),
            (dti_to_metrics, thres_rd, [("out_rd", "in_file")]),
            (get_caps_filenames, thres_decfa, [("out_evec", "out_file")]),
            (dti_to_metrics, thres_decfa, [("out_evec", "in_file")]),
            # Outputnode
            (dwi_to_dti, self.output_node, [("tensor", "dti")]),
            (thres_fa, self.output_node, [("out_file", "fa")]),
            (thres_md, self.output_node, [("out_file", "md")]),
            (thres_ad, self.output_node, [("out_file", "ad")]),
            (thres_rd, self.output_node, [("out_file", "rd")]),
            (thres_decfa, self.output_node, [("out_file", "decfa")]),
            (register_fa, self.output_node, [("out_matrix", "affine_matrix")]),
            (register_fa, self.output_node, [("forward_warp_field",
                                              "b_spline_transform")]),
            (thres_norm_fa, self.output_node, [("out_file", "registered_fa")]),
            (thres_norm_md, self.output_node, [("out_file", "registered_md")]),
            (thres_norm_ad, self.output_node, [("out_file", "registered_ad")]),
            (thres_norm_rd, self.output_node, [("out_file", "registered_rd")]),
            (scalar_analysis_fa, self.output_node, [("atlas_statistics_list",
                                                     "statistics_fa")]),
            (scalar_analysis_md, self.output_node, [("atlas_statistics_list",
                                                     "statistics_md")]),
            (scalar_analysis_ad, self.output_node, [("atlas_statistics_list",
                                                     "statistics_ad")]),
            (scalar_analysis_rd, self.output_node, [("atlas_statistics_list",
                                                     "statistics_rd")]),
            # Print end message
            (self.input_node, print_end_message, [("preproc_dwi",
                                                   "in_bids_or_caps_file")]),
            (thres_rd, print_end_message, [("out_file", "final_file_1")]),
            (scalar_analysis_rd, print_end_message, [("atlas_statistics_list",
                                                      "final_file_2")]),
        ])
Ejemplo n.º 5
0
"""
Diffusion processing nodes
--------------------------

.. seealso::

    dmri_connectivity_advanced.py
        Tutorial with further detail on using MRtrix tractography for connectivity analysis

    http://www.brain.org.au/software/mrtrix/index.html
        MRtrix's online documentation

b-values and b-vectors stored in FSL's format are converted into a single encoding file for MRTrix.
"""

fsl2mrtrix = pe.Node(interface=mrtrix.FSL2MRTrix(),name='fsl2mrtrix')

"""
Tensors are fitted to each voxel in the diffusion-weighted image and from these three maps are created:
	* Major eigenvector in each voxel
	* Apparent diffusion coefficient
	* Fractional anisotropy

"""

gunzip = pe.Node(interface=misc.Gunzip(), name='gunzip')
dwi2tensor = pe.Node(interface=mrtrix.DWI2Tensor(),name='dwi2tensor')
tensor2vector = pe.Node(interface=mrtrix.Tensor2Vector(),name='tensor2vector')
tensor2adc = pe.Node(interface=mrtrix.Tensor2ApparentDiffusion(),name='tensor2adc')
tensor2fa = pe.Node(interface=mrtrix.Tensor2FractionalAnisotropy(),name='tensor2fa')
Ejemplo n.º 6
0
def estimateMaxHarmOrder(bval_file):
    with open(bval_file,'r') as f:
        tmp = f.read()
        tmp = np.asarray(tmp.split())
    
    f.close()
    
    return np.count_nonzero(tmp > '0')


# ### MRTrix specific preprocessing

# In[6]:

# First convert the FSL-like input of bval and bvec into mrtrix format
fsl2mrtrixNode = Node(mrtrix.FSL2MRTrix(), name = 'fsl_2_mrtrix')

#Diffusion tensor images
dwi2tensorNode = Node(mrtrix.DWI2Tensor(), name = 'dwi_2_tensor')
#dwi2tensor dwi.mif -grad btable.b dt.mif

#Fractional anisotropy (FA) map
#tensor2FA dt.mif fa.mif
tensor2faNode = Node(mrtrix.Tensor2FractionalAnisotropy(), name = 'tensor_2_FA')

#Remove noisy background by multiplying the FA Image with the binary brainmask
#mrmult fa.mif wmmask.mif fa_corr.mif
mrmultNode = Node(fsl.BinaryMaths(), name = 'mrmult')
mrmultNode.inputs.operation = 'mul'

#Eigenvector (EV) map
def create_connectivity_pipeline(name="connectivity",
                                 parcellation_name='scale500'):
    inputnode_within = pe.Node(util.IdentityInterface(fields=[
        "subject_id", "dwi", "bvecs", "bvals", "subjects_dir",
        "resolution_network_file"
    ]),
                               name="inputnode_within")

    FreeSurferSource = pe.Node(interface=nio.FreeSurferSource(),
                               name='fssource')
    FreeSurferSourceLH = pe.Node(interface=nio.FreeSurferSource(),
                                 name='fssourceLH')
    FreeSurferSourceLH.inputs.hemi = 'lh'

    FreeSurferSourceRH = pe.Node(interface=nio.FreeSurferSource(),
                                 name='fssourceRH')
    FreeSurferSourceRH.inputs.hemi = 'rh'
    """
    Creating the workflow's nodes
    =============================
    """
    """
    Conversion nodes
    ----------------
    """
    """
    A number of conversion operations are required to obtain NIFTI files from the FreesurferSource for each subject.
    Nodes are used to convert the following:
        * Original structural image to NIFTI
        * Pial, white, inflated, and spherical surfaces for both the left and right hemispheres are converted to GIFTI for visualization in ConnectomeViewer
        * Parcellated annotation files for the left and right hemispheres are also converted to GIFTI

    """

    mri_convert_Brain = pe.Node(interface=fs.MRIConvert(),
                                name='mri_convert_Brain')
    mri_convert_Brain.inputs.out_type = 'nii'
    mri_convert_ROI_scale500 = mri_convert_Brain.clone(
        'mri_convert_ROI_scale500')

    mris_convertLH = pe.Node(interface=fs.MRIsConvert(), name='mris_convertLH')
    mris_convertLH.inputs.out_datatype = 'gii'
    mris_convertRH = mris_convertLH.clone('mris_convertRH')
    mris_convertRHwhite = mris_convertLH.clone('mris_convertRHwhite')
    mris_convertLHwhite = mris_convertLH.clone('mris_convertLHwhite')
    mris_convertRHinflated = mris_convertLH.clone('mris_convertRHinflated')
    mris_convertLHinflated = mris_convertLH.clone('mris_convertLHinflated')
    mris_convertRHsphere = mris_convertLH.clone('mris_convertRHsphere')
    mris_convertLHsphere = mris_convertLH.clone('mris_convertLHsphere')
    mris_convertLHlabels = mris_convertLH.clone('mris_convertLHlabels')
    mris_convertRHlabels = mris_convertLH.clone('mris_convertRHlabels')
    """
    Diffusion processing nodes
    --------------------------

    .. seealso::

        dmri_mrtrix_dti.py
            Tutorial that focuses solely on the MRtrix diffusion processing

        http://www.brain.org.au/software/mrtrix/index.html
            MRtrix's online documentation
    """
    """
    b-values and b-vectors stored in FSL's format are converted into a single encoding file for MRTrix.
    """

    fsl2mrtrix = pe.Node(interface=mrtrix.FSL2MRTrix(), name='fsl2mrtrix')
    """
    Distortions induced by eddy currents are corrected prior to fitting the tensors.
    The first image is used as a reference for which to warp the others.
    """

    eddycorrect = create_eddy_correct_pipeline(name='eddycorrect')
    eddycorrect.inputs.inputnode.ref_num = 1
    """
    Tensors are fitted to each voxel in the diffusion-weighted image and from these three maps are created:
        * Major eigenvector in each voxel
        * Apparent diffusion coefficient
        * Fractional anisotropy
    """

    dwi2tensor = pe.Node(interface=mrtrix.DWI2Tensor(), name='dwi2tensor')
    tensor2vector = pe.Node(interface=mrtrix.Tensor2Vector(),
                            name='tensor2vector')
    tensor2adc = pe.Node(interface=mrtrix.Tensor2ApparentDiffusion(),
                         name='tensor2adc')
    tensor2fa = pe.Node(interface=mrtrix.Tensor2FractionalAnisotropy(),
                        name='tensor2fa')
    MRconvert_fa = pe.Node(interface=mrtrix.MRConvert(), name='MRconvert_fa')
    MRconvert_fa.inputs.extension = 'nii'
    """

    These nodes are used to create a rough brain mask from the b0 image.
    The b0 image is extracted from the original diffusion-weighted image,
    put through a simple thresholding routine, and smoothed using a 3x3 median filter.
    """

    MRconvert = pe.Node(interface=mrtrix.MRConvert(), name='MRconvert')
    MRconvert.inputs.extract_at_axis = 3
    MRconvert.inputs.extract_at_coordinate = [0]
    threshold_b0 = pe.Node(interface=mrtrix.Threshold(), name='threshold_b0')
    median3d = pe.Node(interface=mrtrix.MedianFilter3D(), name='median3d')
    """
    The brain mask is also used to help identify single-fiber voxels.
    This is done by passing the brain mask through two erosion steps,
    multiplying the remaining mask with the fractional anisotropy map, and
    thresholding the result to obtain some highly anisotropic within-brain voxels.
    """

    erode_mask_firstpass = pe.Node(interface=mrtrix.Erode(),
                                   name='erode_mask_firstpass')
    erode_mask_secondpass = pe.Node(interface=mrtrix.Erode(),
                                    name='erode_mask_secondpass')
    MRmultiply = pe.Node(interface=mrtrix.MRMultiply(), name='MRmultiply')
    MRmult_merge = pe.Node(interface=util.Merge(2), name='MRmultiply_merge')
    threshold_FA = pe.Node(interface=mrtrix.Threshold(), name='threshold_FA')
    threshold_FA.inputs.absolute_threshold_value = 0.7
    """
    For whole-brain tracking we also require a broad white-matter seed mask.
    This is created by generating a white matter mask, given a brainmask, and
    thresholding it at a reasonably high level.
    """

    bet = pe.Node(interface=fsl.BET(mask=True), name='bet_b0')
    gen_WM_mask = pe.Node(interface=mrtrix.GenerateWhiteMatterMask(),
                          name='gen_WM_mask')
    threshold_wmmask = pe.Node(interface=mrtrix.Threshold(),
                               name='threshold_wmmask')
    threshold_wmmask.inputs.absolute_threshold_value = 0.4
    """
    The spherical deconvolution step depends on the estimate of the response function
    in the highly anisotropic voxels we obtained above.

    .. warning::

        For damaged or pathological brains one should take care to lower the maximum harmonic order of these steps.

    """

    estimateresponse = pe.Node(interface=mrtrix.EstimateResponseForSH(),
                               name='estimateresponse')
    estimateresponse.inputs.maximum_harmonic_order = 6
    csdeconv = pe.Node(interface=mrtrix.ConstrainedSphericalDeconvolution(),
                       name='csdeconv')
    csdeconv.inputs.maximum_harmonic_order = 6
    """
    Finally, we track probabilistically using the orientation distribution functions obtained earlier.
    The tracts are then used to generate a tract-density image, and they are also converted to TrackVis format.
    """

    probCSDstreamtrack = pe.Node(
        interface=mrtrix.ProbabilisticSphericallyDeconvolutedStreamlineTrack(),
        name='probCSDstreamtrack')
    probCSDstreamtrack.inputs.inputmodel = 'SD_PROB'
    probCSDstreamtrack.inputs.desired_number_of_tracks = 150000
    tracks2prob = pe.Node(interface=mrtrix.Tracks2Prob(), name='tracks2prob')
    tracks2prob.inputs.colour = True
    MRconvert_tracks2prob = MRconvert_fa.clone(name='MRconvert_tracks2prob')
    tck2trk = pe.Node(interface=mrtrix.MRTrix2TrackVis(), name='tck2trk')
    """
    Structural segmentation nodes
    -----------------------------
    """
    """
    The following node identifies the transformation between the diffusion-weighted
    image and the structural image. This transformation is then applied to the tracts
    so that they are in the same space as the regions of interest.
    """

    coregister = pe.Node(interface=fsl.FLIRT(dof=6), name='coregister')
    coregister.inputs.cost = ('normmi')
    """
    Parcellation is performed given the aparc+aseg image from Freesurfer.
    The CMTK Parcellation step subdivides these regions to return a higher-resolution parcellation scheme.
    The parcellation used here is entitled "scale500" and returns 1015 regions.
    """

    parcellate = pe.Node(interface=cmtk.Parcellate(), name="Parcellate")
    parcellate.inputs.parcellation_name = parcellation_name
    """
    The CreateMatrix interface takes in the remapped aparc+aseg image as well as the label dictionary and fiber tracts
    and outputs a number of different files. The most important of which is the connectivity network itself, which is stored
    as a 'gpickle' and can be loaded using Python's NetworkX package (see CreateMatrix docstring). Also outputted are various
    NumPy arrays containing detailed tract information, such as the start and endpoint regions, and statistics on the mean and
    standard deviation for the fiber length of each connection. These matrices can be used in the ConnectomeViewer to plot the
    specific tracts that connect between user-selected regions.

    Here we choose the Lausanne2008 parcellation scheme, since we are incorporating the CMTK parcellation step.
    """

    creatematrix = pe.Node(interface=cmtk.CreateMatrix(), name="CreateMatrix")
    creatematrix.inputs.count_region_intersections = True
    """
    Next we define the endpoint of this tutorial, which is the CFFConverter node, as well as a few nodes which use
    the Nipype Merge utility. These are useful for passing lists of the files we want packaged in our CFF file.
    The inspect.getfile command is used to package this script into the resulting CFF file, so that it is easy to
    look back at the processing parameters that were used.
    """

    CFFConverter = pe.Node(interface=cmtk.CFFConverter(), name="CFFConverter")
    CFFConverter.inputs.script_files = op.abspath(
        inspect.getfile(inspect.currentframe()))
    giftiSurfaces = pe.Node(interface=util.Merge(8), name="GiftiSurfaces")
    giftiLabels = pe.Node(interface=util.Merge(2), name="GiftiLabels")
    niftiVolumes = pe.Node(interface=util.Merge(3), name="NiftiVolumes")
    fiberDataArrays = pe.Node(interface=util.Merge(4), name="FiberDataArrays")
    """
    We also create a node to calculate several network metrics on our resulting file, and another CFF converter
    which will be used to package these networks into a single file.
    """

    networkx = create_networkx_pipeline(name='networkx')
    cmats_to_csv = create_cmats_to_csv_pipeline(name='cmats_to_csv')
    nfibs_to_csv = pe.Node(interface=misc.Matlab2CSV(), name='nfibs_to_csv')
    merge_nfib_csvs = pe.Node(interface=misc.MergeCSVFiles(),
                              name='merge_nfib_csvs')
    merge_nfib_csvs.inputs.extra_column_heading = 'Subject'
    merge_nfib_csvs.inputs.out_file = 'fibers.csv'
    NxStatsCFFConverter = pe.Node(interface=cmtk.CFFConverter(),
                                  name="NxStatsCFFConverter")
    NxStatsCFFConverter.inputs.script_files = op.abspath(
        inspect.getfile(inspect.currentframe()))
    """
    Connecting the workflow
    =======================
    Here we connect our processing pipeline.
    """
    """
    Connecting the inputs, FreeSurfer nodes, and conversions
    --------------------------------------------------------
    """

    mapping = pe.Workflow(name='mapping')
    """
    First, we connect the input node to the FreeSurfer input nodes.
    """

    mapping.connect([(inputnode_within, FreeSurferSource, [("subjects_dir",
                                                            "subjects_dir")])])
    mapping.connect([(inputnode_within, FreeSurferSource, [("subject_id",
                                                            "subject_id")])])

    mapping.connect([(inputnode_within, FreeSurferSourceLH,
                      [("subjects_dir", "subjects_dir")])])
    mapping.connect([(inputnode_within, FreeSurferSourceLH, [("subject_id",
                                                              "subject_id")])])

    mapping.connect([(inputnode_within, FreeSurferSourceRH,
                      [("subjects_dir", "subjects_dir")])])
    mapping.connect([(inputnode_within, FreeSurferSourceRH, [("subject_id",
                                                              "subject_id")])])

    mapping.connect([(inputnode_within, parcellate, [("subjects_dir",
                                                      "subjects_dir")])])
    mapping.connect([(inputnode_within, parcellate, [("subject_id",
                                                      "subject_id")])])
    mapping.connect([(parcellate, mri_convert_ROI_scale500, [('roi_file',
                                                              'in_file')])])
    """
    Nifti conversion for subject's stripped brain image from Freesurfer:
    """

    mapping.connect([(FreeSurferSource, mri_convert_Brain, [('brain',
                                                             'in_file')])])
    """
    Surface conversions to GIFTI (pial, white, inflated, and sphere for both hemispheres)
    """

    mapping.connect([(FreeSurferSourceLH, mris_convertLH, [('pial', 'in_file')
                                                           ])])
    mapping.connect([(FreeSurferSourceRH, mris_convertRH, [('pial', 'in_file')
                                                           ])])
    mapping.connect([(FreeSurferSourceLH, mris_convertLHwhite, [('white',
                                                                 'in_file')])])
    mapping.connect([(FreeSurferSourceRH, mris_convertRHwhite, [('white',
                                                                 'in_file')])])
    mapping.connect([(FreeSurferSourceLH, mris_convertLHinflated,
                      [('inflated', 'in_file')])])
    mapping.connect([(FreeSurferSourceRH, mris_convertRHinflated,
                      [('inflated', 'in_file')])])
    mapping.connect([(FreeSurferSourceLH, mris_convertLHsphere,
                      [('sphere', 'in_file')])])
    mapping.connect([(FreeSurferSourceRH, mris_convertRHsphere,
                      [('sphere', 'in_file')])])
    """
    The annotation files are converted using the pial surface as a map via the MRIsConvert interface.
    One of the functions defined earlier is used to select the lh.aparc.annot and rh.aparc.annot files
    specifically (rather than e.g. rh.aparc.a2009s.annot) from the output list given by the FreeSurferSource.
    """

    mapping.connect([(FreeSurferSourceLH, mris_convertLHlabels,
                      [('pial', 'in_file')])])
    mapping.connect([(FreeSurferSourceRH, mris_convertRHlabels,
                      [('pial', 'in_file')])])
    mapping.connect([(FreeSurferSourceLH, mris_convertLHlabels,
                      [(('annot', select_aparc_annot), 'annot_file')])])
    mapping.connect([(FreeSurferSourceRH, mris_convertRHlabels,
                      [(('annot', select_aparc_annot), 'annot_file')])])
    """
    Diffusion Processing
    --------------------
    Now we connect the tensor computations:
    """

    mapping.connect([(inputnode_within, fsl2mrtrix, [("bvecs", "bvec_file"),
                                                     ("bvals", "bval_file")])])
    mapping.connect([(inputnode_within, eddycorrect, [("dwi",
                                                       "inputnode.in_file")])])
    mapping.connect([(eddycorrect, dwi2tensor, [("outputnode.eddy_corrected",
                                                 "in_file")])])
    mapping.connect([(fsl2mrtrix, dwi2tensor, [("encoding_file",
                                                "encoding_file")])])

    mapping.connect([
        (dwi2tensor, tensor2vector, [['tensor', 'in_file']]),
        (dwi2tensor, tensor2adc, [['tensor', 'in_file']]),
        (dwi2tensor, tensor2fa, [['tensor', 'in_file']]),
    ])
    mapping.connect([(tensor2fa, MRmult_merge, [("FA", "in1")])])
    mapping.connect([(tensor2fa, MRconvert_fa, [("FA", "in_file")])])
    """

    This block creates the rough brain mask to be multiplied, mulitplies it with the
    fractional anisotropy image, and thresholds it to get the single-fiber voxels.
    """

    mapping.connect([(eddycorrect, MRconvert, [("outputnode.eddy_corrected",
                                                "in_file")])])
    mapping.connect([(MRconvert, threshold_b0, [("converted", "in_file")])])
    mapping.connect([(threshold_b0, median3d, [("out_file", "in_file")])])
    mapping.connect([(median3d, erode_mask_firstpass, [("out_file", "in_file")
                                                       ])])
    mapping.connect([(erode_mask_firstpass, erode_mask_secondpass,
                      [("out_file", "in_file")])])
    mapping.connect([(erode_mask_secondpass, MRmult_merge, [("out_file", "in2")
                                                            ])])
    mapping.connect([(MRmult_merge, MRmultiply, [("out", "in_files")])])
    mapping.connect([(MRmultiply, threshold_FA, [("out_file", "in_file")])])
    """
    Here the thresholded white matter mask is created for seeding the tractography.
    """

    mapping.connect([(eddycorrect, bet, [("outputnode.eddy_corrected",
                                          "in_file")])])
    mapping.connect([(eddycorrect, gen_WM_mask, [("outputnode.eddy_corrected",
                                                  "in_file")])])
    mapping.connect([(bet, gen_WM_mask, [("mask_file", "binary_mask")])])
    mapping.connect([(fsl2mrtrix, gen_WM_mask, [("encoding_file",
                                                 "encoding_file")])])
    mapping.connect([(gen_WM_mask, threshold_wmmask, [("WMprobabilitymap",
                                                       "in_file")])])
    """
    Next we estimate the fiber response distribution.
    """

    mapping.connect([(eddycorrect, estimateresponse,
                      [("outputnode.eddy_corrected", "in_file")])])
    mapping.connect([(fsl2mrtrix, estimateresponse, [("encoding_file",
                                                      "encoding_file")])])
    mapping.connect([(threshold_FA, estimateresponse, [("out_file",
                                                        "mask_image")])])
    """
    Run constrained spherical deconvolution.
    """

    mapping.connect([(eddycorrect, csdeconv, [("outputnode.eddy_corrected",
                                               "in_file")])])
    mapping.connect([(gen_WM_mask, csdeconv, [("WMprobabilitymap",
                                               "mask_image")])])
    mapping.connect([(estimateresponse, csdeconv, [("response",
                                                    "response_file")])])
    mapping.connect([(fsl2mrtrix, csdeconv, [("encoding_file", "encoding_file")
                                             ])])
    """
    Connect the tractography and compute the tract density image.
    """

    mapping.connect([(threshold_wmmask, probCSDstreamtrack, [("out_file",
                                                              "seed_file")])])
    mapping.connect([(csdeconv, probCSDstreamtrack,
                      [("spherical_harmonics_image", "in_file")])])
    mapping.connect([(probCSDstreamtrack, tracks2prob, [("tracked", "in_file")
                                                        ])])
    mapping.connect([(eddycorrect, tracks2prob, [("outputnode.eddy_corrected",
                                                  "template_file")])])
    mapping.connect([(tracks2prob, MRconvert_tracks2prob, [("tract_image",
                                                            "in_file")])])
    """
    Structural Processing
    ---------------------
    First, we coregister the diffusion image to the structural image
    """

    mapping.connect([(eddycorrect, coregister, [("outputnode.eddy_corrected",
                                                 "in_file")])])
    mapping.connect([(mri_convert_Brain, coregister, [('out_file', 'reference')
                                                      ])])
    """
    The MRtrix-tracked fibers are converted to TrackVis format (with voxel and data dimensions grabbed from the DWI).
    The connectivity matrix is created with the transformed .trk fibers and the parcellation file.
    """

    mapping.connect([(eddycorrect, tck2trk, [("outputnode.eddy_corrected",
                                              "image_file")])])
    mapping.connect([(mri_convert_Brain, tck2trk,
                      [("out_file", "registration_image_file")])])
    mapping.connect([(coregister, tck2trk, [("out_matrix_file", "matrix_file")
                                            ])])
    mapping.connect([(probCSDstreamtrack, tck2trk, [("tracked", "in_file")])])
    mapping.connect([(tck2trk, creatematrix, [("out_file", "tract_file")])])
    mapping.connect(inputnode_within, 'resolution_network_file', creatematrix,
                    'resolution_network_file')
    mapping.connect([(inputnode_within, creatematrix, [("subject_id",
                                                        "out_matrix_file")])])
    mapping.connect([(inputnode_within, creatematrix,
                      [("subject_id", "out_matrix_mat_file")])])
    mapping.connect([(parcellate, creatematrix, [("roi_file", "roi_file")])])
    """
    The merge nodes defined earlier are used here to create lists of the files which are
    destined for the CFFConverter.
    """

    mapping.connect([(mris_convertLH, giftiSurfaces, [("converted", "in1")])])
    mapping.connect([(mris_convertRH, giftiSurfaces, [("converted", "in2")])])
    mapping.connect([(mris_convertLHwhite, giftiSurfaces, [("converted", "in3")
                                                           ])])
    mapping.connect([(mris_convertRHwhite, giftiSurfaces, [("converted", "in4")
                                                           ])])
    mapping.connect([(mris_convertLHinflated, giftiSurfaces, [("converted",
                                                               "in5")])])
    mapping.connect([(mris_convertRHinflated, giftiSurfaces, [("converted",
                                                               "in6")])])
    mapping.connect([(mris_convertLHsphere, giftiSurfaces, [("converted",
                                                             "in7")])])
    mapping.connect([(mris_convertRHsphere, giftiSurfaces, [("converted",
                                                             "in8")])])

    mapping.connect([(mris_convertLHlabels, giftiLabels, [("converted", "in1")
                                                          ])])
    mapping.connect([(mris_convertRHlabels, giftiLabels, [("converted", "in2")
                                                          ])])

    mapping.connect([(parcellate, niftiVolumes, [("roi_file", "in1")])])
    mapping.connect([(eddycorrect, niftiVolumes, [("outputnode.eddy_corrected",
                                                   "in2")])])
    mapping.connect([(mri_convert_Brain, niftiVolumes, [("out_file", "in3")])])

    mapping.connect([(creatematrix, fiberDataArrays, [("endpoint_file", "in1")
                                                      ])])
    mapping.connect([(creatematrix, fiberDataArrays, [("endpoint_file_mm",
                                                       "in2")])])
    mapping.connect([(creatematrix, fiberDataArrays, [("fiber_length_file",
                                                       "in3")])])
    mapping.connect([(creatematrix, fiberDataArrays, [("fiber_label_file",
                                                       "in4")])])
    """
    This block actually connects the merged lists to the CFF converter. We pass the surfaces
    and volumes that are to be included, as well as the tracts and the network itself. The currently
    running pipeline (dmri_connectivity_advanced.py) is also scraped and included in the CFF file. This
    makes it easy for the user to examine the entire processing pathway used to generate the end
    product.
    """

    mapping.connect([(giftiSurfaces, CFFConverter, [("out", "gifti_surfaces")])
                     ])
    mapping.connect([(giftiLabels, CFFConverter, [("out", "gifti_labels")])])
    mapping.connect([(creatematrix, CFFConverter, [("matrix_files",
                                                    "gpickled_networks")])])
    mapping.connect([(niftiVolumes, CFFConverter, [("out", "nifti_volumes")])])
    mapping.connect([(fiberDataArrays, CFFConverter, [("out", "data_files")])])
    mapping.connect([(creatematrix, CFFConverter, [("filtered_tractography",
                                                    "tract_files")])])
    mapping.connect([(inputnode_within, CFFConverter, [("subject_id", "title")
                                                       ])])
    """
    The graph theoretical metrics which have been generated are placed into another CFF file.
    """

    mapping.connect([(inputnode_within, networkx,
                      [("subject_id", "inputnode.extra_field")])])
    mapping.connect([(creatematrix, networkx, [("intersection_matrix_file",
                                                "inputnode.network_file")])])

    mapping.connect([(networkx, NxStatsCFFConverter,
                      [("outputnode.network_files", "gpickled_networks")])])
    mapping.connect([(giftiSurfaces, NxStatsCFFConverter,
                      [("out", "gifti_surfaces")])])
    mapping.connect([(giftiLabels, NxStatsCFFConverter, [("out",
                                                          "gifti_labels")])])
    mapping.connect([(niftiVolumes, NxStatsCFFConverter, [("out",
                                                           "nifti_volumes")])])
    mapping.connect([(fiberDataArrays, NxStatsCFFConverter, [("out",
                                                              "data_files")])])
    mapping.connect([(inputnode_within, NxStatsCFFConverter, [("subject_id",
                                                               "title")])])

    mapping.connect([(inputnode_within, cmats_to_csv,
                      [("subject_id", "inputnode.extra_field")])])
    mapping.connect([(creatematrix, cmats_to_csv, [
        ("matlab_matrix_files", "inputnode.matlab_matrix_files")
    ])])
    mapping.connect([(creatematrix, nfibs_to_csv, [("stats_file", "in_file")])
                     ])
    mapping.connect([(nfibs_to_csv, merge_nfib_csvs, [("csv_files", "in_files")
                                                      ])])
    mapping.connect([(inputnode_within, merge_nfib_csvs, [("subject_id",
                                                           "extra_field")])])
    """
    Create a higher-level workflow
    --------------------------------------
    Finally, we create another higher-level workflow to connect our mapping workflow with the info and datagrabbing nodes
    declared at the beginning. Our tutorial can is now extensible to any arbitrary number of subjects by simply adding
    their names to the subject list and their data to the proper folders.
    """

    inputnode = pe.Node(interface=util.IdentityInterface(
        fields=["subject_id", "dwi", "bvecs", "bvals", "subjects_dir"]),
                        name="inputnode")

    outputnode = pe.Node(interface=util.IdentityInterface(fields=[
        "fa", "struct", "tracts", "tracks2prob", "connectome", "nxstatscff",
        "nxmatlab", "nxcsv", "fiber_csv", "cmatrices_csv", "nxmergedcsv",
        "cmatrix", "networks", "filtered_tracts", "rois", "odfs", "tdi",
        "mean_fiber_length", "median_fiber_length", "fiber_length_std"
    ]),
                         name="outputnode")

    connectivity = pe.Workflow(name="connectivity")
    connectivity.base_output_dir = name
    connectivity.base_dir = name

    connectivity.connect([(inputnode, mapping, [
        ("dwi", "inputnode_within.dwi"), ("bvals", "inputnode_within.bvals"),
        ("bvecs", "inputnode_within.bvecs"),
        ("subject_id", "inputnode_within.subject_id"),
        ("subjects_dir", "inputnode_within.subjects_dir")
    ])])

    connectivity.connect([(mapping, outputnode, [
        ("tck2trk.out_file", "tracts"),
        ("CFFConverter.connectome_file", "connectome"),
        ("NxStatsCFFConverter.connectome_file", "nxstatscff"),
        ("CreateMatrix.matrix_mat_file", "cmatrix"),
        ("CreateMatrix.mean_fiber_length_matrix_mat_file",
         "mean_fiber_length"),
        ("CreateMatrix.median_fiber_length_matrix_mat_file",
         "median_fiber_length"),
        ("CreateMatrix.fiber_length_std_matrix_mat_file", "fiber_length_std"),
        ("CreateMatrix.matrix_files", "networks"),
        ("CreateMatrix.filtered_tractographies", "filtered_tracts"),
        ("merge_nfib_csvs.csv_file", "fiber_csv"),
        ("mri_convert_ROI_scale500.out_file", "rois"),
        ("csdeconv.spherical_harmonics_image", "odfs"),
        ("mri_convert_Brain.out_file", "struct"),
        ("MRconvert_fa.converted", "fa"),
        ("MRconvert_tracks2prob.converted", "tracks2prob")
    ])])

    connectivity.connect([(cmats_to_csv, outputnode, [("outputnode.csv_file",
                                                       "cmatrices_csv")])])
    connectivity.connect([(networkx, outputnode, [("outputnode.csv_files",
                                                   "nxcsv")])])
    return connectivity
Ejemplo n.º 8
0
def create_precoth_pipeline_step2(name="precoth_step2", tractography_type='probabilistic'):
    inputnode = pe.Node(
        interface=util.IdentityInterface(fields=["subjects_dir",
                                                 "subject_id",
                                                 "dwi",
                                                 "bvecs",
                                                 "bvals",
                                                 "fdgpet",
                                                 "dose",
                                                 "weight",
                                                 "delay",
                                                 "glycemie",
                                                 "scan_time",
                                                 "single_fiber_mask",
                                                 "fa",
                                                 "rgb_fa",
                                                 "md",
                                                 "t1_brain",
                                                 "t1",
                                                 "wm_mask",
                                                 "term_mask",
                                                 "rois",
                                                 ]),
        name="inputnode")

    coregister = pe.Node(interface=fsl.FLIRT(dof=12), name = 'coregister')
    coregister.inputs.cost = ('normmi')

    invertxfm = pe.Node(interface=fsl.ConvertXFM(), name = 'invertxfm')
    invertxfm.inputs.invert_xfm = True

    WM_to_FA = pe.Node(interface=fsl.ApplyXfm(), name = 'WM_to_FA')
    WM_to_FA.inputs.interp = 'nearestneighbour'
    TermMask_to_FA = WM_to_FA.clone("TermMask_to_FA")

    rgb_fa_t1space = pe.Node(interface=fsl.ApplyXfm(), name = 'rgb_fa_t1space')
    md_to_T1 = pe.Node(interface=fsl.ApplyXfm(), name = 'md_to_T1')

    t1_dtispace = pe.Node(interface=fsl.ApplyXfm(), name = 't1_dtispace')

    fsl2mrtrix = pe.Node(interface=mrtrix.FSL2MRTrix(), name='fsl2mrtrix')
    fsl2mrtrix.inputs.invert_y = True

    fdgpet_regions = pe.Node(interface=RegionalValues(), name='fdgpet_regions')

    compute_cmr_glc_interface = util.Function(input_names=["in_file", "dose", "weight", "delay",
        "glycemie", "scan_time"], output_names=["out_file"], function=CMR_glucose)
    compute_cmr_glc = pe.Node(interface=compute_cmr_glc_interface, name='compute_cmr_glc')

    csdeconv = pe.Node(interface=mrtrix.ConstrainedSphericalDeconvolution(),
                       name='csdeconv')

    estimateresponse = pe.Node(interface=mrtrix.EstimateResponseForSH(),
                               name='estimateresponse')

    if tractography_type == 'probabilistic':
        CSDstreamtrack = pe.Node(
            interface=mrtrix.ProbabilisticSphericallyDeconvolutedStreamlineTrack(
            ),
            name='CSDstreamtrack')
    else:
        CSDstreamtrack = pe.Node(
            interface=mrtrix.SphericallyDeconvolutedStreamlineTrack(),
            name='CSDstreamtrack')

    CSDstreamtrack.inputs.minimum_tract_length = 50

    CSDstreamtrack.inputs.desired_number_of_tracks = 10000

    tck2trk = pe.Node(interface=mrtrix.MRTrix2TrackVis(), name='tck2trk')

    write_precoth_data_interface = util.Function(input_names=["dwi_network_file", "fdg_stats_file", "subject_id"],
                                         output_names=["out_file"],
                                         function=summarize_precoth)
    write_csv_data = pe.Node(
        interface=write_precoth_data_interface, name='write_csv_data')

    thalamus2precuneus2cortex = pe.Node(
        interface=cmtk.CreateMatrix(), name="thalamus2precuneus2cortex")
    thalamus2precuneus2cortex.inputs.count_region_intersections = True

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

    workflow.connect([(inputnode, fsl2mrtrix, [("bvecs", "bvec_file"),
                                               ("bvals", "bval_file")])])

    workflow.connect([(inputnode, fdgpet_regions, [("rois", "segmentation_file")])])
    workflow.connect([(inputnode, compute_cmr_glc, [("fdgpet", "in_file")])])
    workflow.connect([(inputnode, compute_cmr_glc, [("dose", "dose")])])
    workflow.connect([(inputnode, compute_cmr_glc, [("weight", "weight")])])
    workflow.connect([(inputnode, compute_cmr_glc, [("delay", "delay")])])
    workflow.connect([(inputnode, compute_cmr_glc, [("glycemie", "glycemie")])])
    workflow.connect([(inputnode, compute_cmr_glc, [("scan_time", "scan_time")])])
    workflow.connect([(compute_cmr_glc, fdgpet_regions, [("out_file", "in_files")])])

    workflow.connect([(inputnode, coregister,[("fa","in_file")])])
    workflow.connect([(inputnode, coregister,[('wm_mask','reference')])])
    workflow.connect([(inputnode, tck2trk,[("fa","image_file")])])
    
    workflow.connect([(inputnode, tck2trk,[("wm_mask","registration_image_file")])])
    workflow.connect([(coregister, tck2trk,[("out_matrix_file","matrix_file")])])
    
    workflow.connect([(coregister, invertxfm,[("out_matrix_file","in_file")])])

    workflow.connect([(inputnode, t1_dtispace,[("t1","in_file")])])
    workflow.connect([(invertxfm, t1_dtispace,[("out_file","in_matrix_file")])])
    workflow.connect([(inputnode, t1_dtispace,[("fa","reference")])])

    workflow.connect([(inputnode, rgb_fa_t1space,[("rgb_fa","in_file")])])
    workflow.connect([(coregister, rgb_fa_t1space,[("out_matrix_file","in_matrix_file")])])
    workflow.connect([(inputnode, rgb_fa_t1space,[('wm_mask','reference')])])

    workflow.connect([(inputnode, md_to_T1,[("md","in_file")])])
    workflow.connect([(coregister, md_to_T1,[("out_matrix_file","in_matrix_file")])])
    workflow.connect([(inputnode, md_to_T1,[('wm_mask','reference')])])

    workflow.connect([(invertxfm, WM_to_FA,[("out_file","in_matrix_file")])])
    workflow.connect([(inputnode, WM_to_FA,[("wm_mask","in_file")])])
    workflow.connect([(inputnode, WM_to_FA,[("fa","reference")])])
    
    workflow.connect([(invertxfm, TermMask_to_FA,[("out_file","in_matrix_file")])])
    workflow.connect([(inputnode, TermMask_to_FA,[("term_mask","in_file")])])
    workflow.connect([(inputnode, TermMask_to_FA,[("fa","reference")])])

    workflow.connect([(inputnode, estimateresponse, [("single_fiber_mask", "mask_image")])])

    workflow.connect([(inputnode, estimateresponse, [("dwi", "in_file")])])
    workflow.connect(
        [(fsl2mrtrix, estimateresponse, [("encoding_file", "encoding_file")])])

    workflow.connect([(inputnode, csdeconv, [("dwi", "in_file")])])
    #workflow.connect(
    #    [(TermMask_to_FA, csdeconv, [("out_file", "mask_image")])])
    workflow.connect(
        [(estimateresponse, csdeconv, [("response", "response_file")])])
    workflow.connect(
        [(fsl2mrtrix, csdeconv, [("encoding_file", "encoding_file")])])
    workflow.connect(
        [(WM_to_FA, CSDstreamtrack, [("out_file", "seed_file")])])
    workflow.connect(
        [(TermMask_to_FA, CSDstreamtrack, [("out_file", "mask_file")])])
    workflow.connect(
        [(csdeconv, CSDstreamtrack, [("spherical_harmonics_image", "in_file")])])

    workflow.connect([(CSDstreamtrack, tck2trk, [("tracked", "in_file")])])

    workflow.connect(
        [(tck2trk, thalamus2precuneus2cortex, [("out_file", "tract_file")])])
    workflow.connect(
        [(inputnode, thalamus2precuneus2cortex, [("subject_id", "out_matrix_file")])])
    workflow.connect(
        [(inputnode, thalamus2precuneus2cortex, [("subject_id", "out_matrix_mat_file")])])

    workflow.connect(
        [(inputnode, thalamus2precuneus2cortex, [("rois", "roi_file")])])
    workflow.connect(
        [(thalamus2precuneus2cortex, fdgpet_regions, [("intersection_matrix_file", "resolution_network_file")])])

    workflow.connect(
        [(inputnode, write_csv_data, [("subject_id", "subject_id")])])
    workflow.connect(
        [(fdgpet_regions, write_csv_data, [("stats_file", "fdg_stats_file")])])
    workflow.connect(
        [(thalamus2precuneus2cortex, write_csv_data, [("intersection_matrix_file", "dwi_network_file")])])

    output_fields = ["csdeconv", "tracts_tck", "summary", "filtered_tractographies",
        "matrix_file", "connectome", "CMR_nodes", "cmr_glucose", "fiber_labels_noorphans", "fiber_length_file",
        "fiber_label_file", "fa_t1space", "rgb_fa_t1space", "md_t1space", "fa_t1xform", "t1_dtispace",
        "intersection_matrix_mat_file", "dti_stats"]

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

    workflow.connect(
        [(CSDstreamtrack, outputnode, [("tracked", "tracts_tck")]),
         (csdeconv, outputnode,
          [("spherical_harmonics_image", "csdeconv")]),
         (coregister, outputnode, [("out_file", "fa_t1space")]),
         (rgb_fa_t1space, outputnode, [("out_file", "rgb_fa_t1space")]),
         (md_to_T1, outputnode, [("out_file", "md_t1space")]),
         (t1_dtispace, outputnode, [("out_file", "t1_dtispace")]),
         (coregister, outputnode, [("out_matrix_file", "fa_t1xform")]),
         (thalamus2precuneus2cortex, outputnode, [("filtered_tractographies", "filtered_tractographies")]),
         (thalamus2precuneus2cortex, outputnode, [("matrix_file", "connectome")]),
         (thalamus2precuneus2cortex, outputnode, [("fiber_labels_noorphans", "fiber_labels_noorphans")]),
         (thalamus2precuneus2cortex, outputnode, [("fiber_length_file", "fiber_length_file")]),
         (thalamus2precuneus2cortex, outputnode, [("fiber_label_file", "fiber_label_file")]),
         (thalamus2precuneus2cortex, outputnode, [("intersection_matrix_mat_file", "intersection_matrix_mat_file")]),
         (thalamus2precuneus2cortex, outputnode, [("stats_file", "dti_stats")]),
         (fdgpet_regions, outputnode, [("networks", "CMR_nodes")]),
         (write_csv_data, outputnode, [("out_file", "summary")]),
         (compute_cmr_glc, outputnode, [("out_file", "cmr_glucose")]),
         ])

    return workflow
Ejemplo n.º 9
0
def create_precoth_pipeline(name="precoth", tractography_type='probabilistic', reg_pet_T1=True):
    inputnode = pe.Node(
        interface=util.IdentityInterface(fields=["subjects_dir",
                                                 "subject_id",
                                                 "dwi",
                                                 "bvecs",
                                                 "bvals",
                                                 "fdgpet",
                                                 "dose",
                                                 "weight",
                                                 "delay",
                                                 "glycemie",
                                                 "scan_time"]),
        name="inputnode")

    nonlinfit_interface = util.Function(input_names=["dwi", "bvecs", "bvals", "base_name"],
    output_names=["tensor", "FA", "MD", "evecs", "evals", "rgb_fa", "norm", "mode", "binary_mask", "b0_masked"], function=nonlinfit_fn)

    nonlinfit_node = pe.Node(interface=nonlinfit_interface, name="nonlinfit_node")

    coregister = pe.Node(interface=fsl.FLIRT(dof=12), name = 'coregister')
    coregister.inputs.cost = ('normmi')

    invertxfm = pe.Node(interface=fsl.ConvertXFM(), name = 'invertxfm')
    invertxfm.inputs.invert_xfm = True

    WM_to_FA = pe.Node(interface=fsl.ApplyXfm(), name = 'WM_to_FA')
    WM_to_FA.inputs.interp = 'nearestneighbour'
    TermMask_to_FA = WM_to_FA.clone("TermMask_to_FA")

    mni_for_reg = op.join(os.environ["FSL_DIR"],"data","standard","MNI152_T1_1mm.nii.gz")
    reorientBrain = pe.Node(interface=fsl.FLIRT(dof=6), name = 'reorientBrain')
    reorientBrain.inputs.reference = mni_for_reg
    reorientROIs = pe.Node(interface=fsl.ApplyXfm(), name = 'reorientROIs')
    reorientROIs.inputs.interp = "nearestneighbour"
    reorientROIs.inputs.reference = mni_for_reg
    reorientRibbon = reorientROIs.clone("reorientRibbon")
    reorientRibbon.inputs.interp = "nearestneighbour"
    reorientT1 = reorientROIs.clone("reorientT1")
    reorientT1.inputs.interp = "trilinear"

    fsl2mrtrix = pe.Node(interface=mrtrix.FSL2MRTrix(), name='fsl2mrtrix')
    fsl2mrtrix.inputs.invert_y = True

    erode_mask_firstpass = pe.Node(interface=mrtrix.Erode(),
                                   name='erode_mask_firstpass')
    erode_mask_firstpass.inputs.out_filename = "b0_mask_median3D_erode.nii.gz"
    erode_mask_secondpass = pe.Node(interface=mrtrix.Erode(),
                                    name='erode_mask_secondpass')
    erode_mask_secondpass.inputs.out_filename = "b0_mask_median3D_erode_secondpass.nii.gz"
 
    threshold_FA = pe.Node(interface=fsl.ImageMaths(), name='threshold_FA')
    threshold_FA.inputs.op_string = "-thr 0.8 -uthr 0.99"
    threshold_mode = pe.Node(interface=fsl.ImageMaths(), name='threshold_mode')
    threshold_mode.inputs.op_string = "-thr 0.1 -uthr 0.99"    

    make_termination_mask = pe.Node(interface=fsl.ImageMaths(), name='make_termination_mask')
    make_termination_mask.inputs.op_string = "-bin"

    get_wm_mask = pe.Node(interface=fsl.ImageMaths(), name='get_wm_mask')
    get_wm_mask.inputs.op_string = "-thr 0.1"

    MRmultiply = pe.Node(interface=mrtrix.MRMultiply(), name='MRmultiply')
    MRmultiply.inputs.out_filename = "Eroded_FA.nii.gz"
    MRmult_merge = pe.Node(interface=util.Merge(2), name='MRmultiply_merge')

    median3d = pe.Node(interface=mrtrix.MedianFilter3D(), name='median3D')

    fdgpet_regions = pe.Node(interface=RegionalValues(), name='fdgpet_regions')

    compute_cmr_glc_interface = util.Function(input_names=["in_file", "dose", "weight", "delay",
        "glycemie", "scan_time"], output_names=["out_file"], function=CMR_glucose)
    compute_cmr_glc = pe.Node(interface=compute_cmr_glc_interface, name='compute_cmr_glc')

    csdeconv = pe.Node(interface=mrtrix.ConstrainedSphericalDeconvolution(),
                       name='csdeconv')

    estimateresponse = pe.Node(interface=mrtrix.EstimateResponseForSH(),
                               name='estimateresponse')

    if tractography_type == 'probabilistic':
        CSDstreamtrack = pe.Node(
            interface=mrtrix.ProbabilisticSphericallyDeconvolutedStreamlineTrack(
            ),
            name='CSDstreamtrack')
    else:
        CSDstreamtrack = pe.Node(
            interface=mrtrix.SphericallyDeconvolutedStreamlineTrack(),
            name='CSDstreamtrack')

    #CSDstreamtrack.inputs.desired_number_of_tracks = 10000
    CSDstreamtrack.inputs.minimum_tract_length = 50

    tck2trk = pe.Node(interface=mrtrix.MRTrix2TrackVis(), name='tck2trk')

    extract_PreCoTh_interface = util.Function(input_names=["in_file", "out_filename"],
                                         output_names=["out_file"],
                                         function=extract_PreCoTh)
    thalamus2precuneus2cortex_ROIs = pe.Node(
        interface=extract_PreCoTh_interface, name='thalamus2precuneus2cortex_ROIs')


    wm_mask_interface = util.Function(input_names=["in_file", "out_filename"],
                                         output_names=["out_file"],
                                         function=wm_labels_only)
    make_wm_mask = pe.Node(
        interface=wm_mask_interface, name='make_wm_mask')

    write_precoth_data_interface = util.Function(input_names=["dwi_network_file", "fdg_stats_file", "subject_id"],
                                         output_names=["out_file"],
                                         function=summarize_precoth)
    write_csv_data = pe.Node(
        interface=write_precoth_data_interface, name='write_csv_data')

    thalamus2precuneus2cortex = pe.Node(
        interface=cmtk.CreateMatrix(), name="thalamus2precuneus2cortex")
    thalamus2precuneus2cortex.inputs.count_region_intersections = True

    FreeSurferSource = pe.Node(
        interface=nio.FreeSurferSource(), name='fssource')
    mri_convert_Brain = pe.Node(
        interface=fs.MRIConvert(), name='mri_convert_Brain')
    mri_convert_Brain.inputs.out_type = 'niigz'
    mri_convert_Brain.inputs.no_change = True

    if reg_pet_T1:
        reg_pet_T1 = pe.Node(interface=fsl.FLIRT(dof=6), name = 'reg_pet_T1')
        reg_pet_T1.inputs.cost = ('corratio')
    
    reslice_fdgpet = mri_convert_Brain.clone("reslice_fdgpet")
    reslice_fdgpet.inputs.no_change = True

    mri_convert_Ribbon = mri_convert_Brain.clone("mri_convert_Ribbon")
    mri_convert_ROIs = mri_convert_Brain.clone("mri_convert_ROIs")
    mri_convert_T1 = mri_convert_Brain.clone("mri_convert_T1")

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

    workflow.connect(
        [(inputnode, FreeSurferSource, [("subjects_dir", "subjects_dir")])])
    workflow.connect(
        [(inputnode, FreeSurferSource, [("subject_id", "subject_id")])])

    workflow.connect(
        [(FreeSurferSource, mri_convert_T1, [('T1', 'in_file')])])
    workflow.connect(
        [(mri_convert_T1, reorientT1, [('out_file', 'in_file')])])

    workflow.connect(
        [(FreeSurferSource, mri_convert_Brain, [('brain', 'in_file')])])
    workflow.connect(
        [(mri_convert_Brain, reorientBrain, [('out_file', 'in_file')])])
    workflow.connect(
        [(reorientBrain, reorientROIs, [('out_matrix_file', 'in_matrix_file')])])
    workflow.connect(
        [(reorientBrain, reorientRibbon, [('out_matrix_file', 'in_matrix_file')])])
    workflow.connect(
        [(reorientBrain, reorientT1, [('out_matrix_file', 'in_matrix_file')])])

    workflow.connect(
        [(FreeSurferSource, mri_convert_ROIs, [(('aparc_aseg', select_aparc), 'in_file')])])
    workflow.connect(
        [(mri_convert_ROIs, reorientROIs, [('out_file', 'in_file')])])
    workflow.connect(
        [(reorientROIs, make_wm_mask, [('out_file', 'in_file')])])

    workflow.connect(
        [(FreeSurferSource, mri_convert_Ribbon, [(('ribbon', select_ribbon), 'in_file')])])
    workflow.connect(
        [(mri_convert_Ribbon, reorientRibbon, [('out_file', 'in_file')])])
    workflow.connect(
        [(reorientRibbon, make_termination_mask, [('out_file', 'in_file')])])

    workflow.connect([(inputnode, fsl2mrtrix, [("bvecs", "bvec_file"),
                                               ("bvals", "bval_file")])])

    workflow.connect(inputnode, 'dwi', nonlinfit_node, 'dwi')
    workflow.connect(inputnode, 'subject_id', nonlinfit_node, 'base_name')
    workflow.connect(inputnode, 'bvecs', nonlinfit_node, 'bvecs')
    workflow.connect(inputnode, 'bvals', nonlinfit_node, 'bvals')

    workflow.connect([(inputnode, compute_cmr_glc, [("dose", "dose")])])
    workflow.connect([(inputnode, compute_cmr_glc, [("weight", "weight")])])
    workflow.connect([(inputnode, compute_cmr_glc, [("delay", "delay")])])
    workflow.connect([(inputnode, compute_cmr_glc, [("glycemie", "glycemie")])])
    workflow.connect([(inputnode, compute_cmr_glc, [("scan_time", "scan_time")])])

    if reg_pet_T1:
        workflow.connect([(inputnode, reg_pet_T1, [("fdgpet", "in_file")])])
        workflow.connect(
            [(reorientBrain, reg_pet_T1, [("out_file", "reference")])])
        workflow.connect(
            [(reg_pet_T1, reslice_fdgpet, [("out_file", "in_file")])])
        workflow.connect(
            [(reorientROIs, reslice_fdgpet, [("out_file", "reslice_like")])])
        workflow.connect(
            [(reslice_fdgpet, compute_cmr_glc, [("out_file", "in_file")])])
    else:
        workflow.connect([(inputnode, reslice_fdgpet, [("fdgpet", "in_file")])])
        workflow.connect(
            [(reorientROIs, reslice_fdgpet, [("out_file", "reslice_like")])])
        workflow.connect(
            [(reslice_fdgpet, compute_cmr_glc, [("out_file", "in_file")])])
    workflow.connect(
        [(compute_cmr_glc, fdgpet_regions, [("out_file", "in_files")])])
    workflow.connect(
        [(thalamus2precuneus2cortex_ROIs, fdgpet_regions, [("out_file", "segmentation_file")])])

    workflow.connect([(nonlinfit_node, coregister,[("FA","in_file")])])
    workflow.connect([(make_wm_mask, coregister,[('out_file','reference')])])
    workflow.connect([(nonlinfit_node, tck2trk,[("FA","image_file")])])
    workflow.connect([(reorientBrain, tck2trk,[("out_file","registration_image_file")])])
    workflow.connect([(coregister, tck2trk,[("out_matrix_file","matrix_file")])])

    workflow.connect([(coregister, invertxfm,[("out_matrix_file","in_file")])])
    workflow.connect([(invertxfm, WM_to_FA,[("out_file","in_matrix_file")])])
    workflow.connect([(make_wm_mask, WM_to_FA,[("out_file","in_file")])])
    workflow.connect([(nonlinfit_node, WM_to_FA,[("FA","reference")])])
    
    workflow.connect([(invertxfm, TermMask_to_FA,[("out_file","in_matrix_file")])])
    workflow.connect([(make_termination_mask, TermMask_to_FA,[("out_file","in_file")])])
    workflow.connect([(nonlinfit_node, TermMask_to_FA,[("FA","reference")])])

    workflow.connect([(nonlinfit_node, median3d, [("binary_mask", "in_file")])])
    workflow.connect(
        [(median3d, erode_mask_firstpass, [("out_file", "in_file")])])
    workflow.connect(
        [(erode_mask_firstpass, erode_mask_secondpass, [("out_file", "in_file")])])

    workflow.connect([(nonlinfit_node, MRmult_merge, [("FA", "in1")])])
    workflow.connect(
        [(erode_mask_secondpass, MRmult_merge, [("out_file", "in2")])])
    workflow.connect([(MRmult_merge, MRmultiply, [("out", "in_files")])])
    workflow.connect([(MRmultiply, threshold_FA, [("out_file", "in_file")])])
    workflow.connect(
        [(threshold_FA, estimateresponse, [("out_file", "mask_image")])])

    workflow.connect([(inputnode, estimateresponse, [("dwi", "in_file")])])
    workflow.connect(
        [(fsl2mrtrix, estimateresponse, [("encoding_file", "encoding_file")])])

    workflow.connect([(inputnode, csdeconv, [("dwi", "in_file")])])
    #workflow.connect(
    #    [(TermMask_to_FA, csdeconv, [("out_file", "mask_image")])])
    workflow.connect(
        [(estimateresponse, csdeconv, [("response", "response_file")])])
    workflow.connect(
        [(fsl2mrtrix, csdeconv, [("encoding_file", "encoding_file")])])
    workflow.connect(
        [(WM_to_FA, CSDstreamtrack, [("out_file", "seed_file")])])
    workflow.connect(
        [(TermMask_to_FA, CSDstreamtrack, [("out_file", "mask_file")])])
    workflow.connect(
        [(csdeconv, CSDstreamtrack, [("spherical_harmonics_image", "in_file")])])
    
    workflow.connect([(CSDstreamtrack, tck2trk, [("tracked", "in_file")])])

    workflow.connect(
        [(tck2trk, thalamus2precuneus2cortex, [("out_file", "tract_file")])])
    workflow.connect(
        [(inputnode, thalamus2precuneus2cortex, [("subject_id", "out_matrix_file")])])
    workflow.connect(
        [(inputnode, thalamus2precuneus2cortex, [("subject_id", "out_matrix_mat_file")])])

    workflow.connect(
        [(reorientROIs, thalamus2precuneus2cortex_ROIs, [("out_file", "in_file")])])
    workflow.connect(
        [(thalamus2precuneus2cortex_ROIs, thalamus2precuneus2cortex, [("out_file", "roi_file")])])
    workflow.connect(
        [(thalamus2precuneus2cortex, fdgpet_regions, [("matrix_file", "resolution_network_file")])])

    workflow.connect(
        [(inputnode, write_csv_data, [("subject_id", "subject_id")])])
    workflow.connect(
        [(fdgpet_regions, write_csv_data, [("stats_file", "fdg_stats_file")])])
    workflow.connect(
        [(thalamus2precuneus2cortex, write_csv_data, [("intersection_matrix_file", "dwi_network_file")])])

    output_fields = ["fa", "rgb_fa", "md", "csdeconv", "tracts_tck", "rois", "t1",
        "t1_brain", "wmmask_dtispace", "fa_t1space", "summary", "filtered_tractographies",
        "matrix_file", "connectome", "CMR_nodes", "fiber_labels_noorphans", "fiber_length_file",
        "fiber_label_file", "intersection_matrix_mat_file"]

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

    workflow.connect(
        [(CSDstreamtrack, outputnode, [("tracked", "tracts_tck")]),
         (csdeconv, outputnode,
          [("spherical_harmonics_image", "csdeconv")]),
         (nonlinfit_node, outputnode, [("FA", "fa")]),
         (coregister, outputnode, [("out_file", "fa_t1space")]),
         (reorientBrain, outputnode, [("out_file", "t1_brain")]),
         (reorientT1, outputnode, [("out_file", "t1")]),
         (thalamus2precuneus2cortex_ROIs, outputnode, [("out_file", "rois")]),
         (thalamus2precuneus2cortex, outputnode, [("filtered_tractographies", "filtered_tractographies")]),
         (thalamus2precuneus2cortex, outputnode, [("matrix_file", "connectome")]),
         (thalamus2precuneus2cortex, outputnode, [("fiber_labels_noorphans", "fiber_labels_noorphans")]),
         (thalamus2precuneus2cortex, outputnode, [("fiber_length_file", "fiber_length_file")]),
         (thalamus2precuneus2cortex, outputnode, [("fiber_label_file", "fiber_label_file")]),
         (thalamus2precuneus2cortex, outputnode, [("intersection_matrix_mat_file", "intersection_matrix_mat_file")]),
         (fdgpet_regions, outputnode, [("networks", "CMR_nodes")]),
         (nonlinfit_node, outputnode, [("rgb_fa", "rgb_fa")]),
         (nonlinfit_node, outputnode, [("MD", "md")]),
         (write_csv_data, outputnode, [("out_file", "summary")]),
         ])

    return workflow
def anatomically_constrained_tracking(name="fiber_tracking", lmax=4):
    '''
    Define inputs and outputs of the workflow
    '''
    inputnode = pe.Node(interface=util.IdentityInterface(fields=[
        "subject_id",
        "dwi",
        "bvecs",
        "bvals",
        "single_fiber_mask",
        "wm_mask",
        "termination_mask",
        "registration_matrix_file",
        "registration_image_file",
    ]),
                        name="inputnode")

    outputnode = pe.Node(interface=util.IdentityInterface(
        fields=["fiber_odfs", "fiber_tracks_tck_dwi", "fiber_tracks_trk_t1"]),
                         name="outputnode")
    '''
    Define the nodes
    '''

    fsl2mrtrix = pe.Node(interface=mrtrix.FSL2MRTrix(), name='fsl2mrtrix')

    estimateresponse = pe.Node(interface=mrtrix.EstimateResponseForSH(),
                               name='estimateresponse')

    estimateresponse.inputs.maximum_harmonic_order = lmax

    csdeconv = pe.Node(interface=mrtrix.ConstrainedSphericalDeconvolution(),
                       name='csdeconv')
    csdeconv.inputs.maximum_harmonic_order = lmax

    CSDstreamtrack = pe.Node(
        interface=mrtrix.ProbabilisticSphericallyDeconvolutedStreamlineTrack(),
        name='CSDstreamtrack')

    CSDstreamtrack.inputs.desired_number_of_tracks = 100000
    CSDstreamtrack.inputs.minimum_tract_length = 10

    tck2trk = pe.Node(interface=mrtrix.MRTrix2TrackVis(), name='tck2trk')
    '''
    Connect the workflow
    '''
    workflow = pe.Workflow(name=name)
    workflow.base_dir = name
    '''
    Structural processing to create seed and termination masks
    '''

    # Might be worthwhile to use a smaller file? Could be faster to load but only
    # the dimensions of the "image_file" are using in this interface
    workflow.connect([(inputnode, fsl2mrtrix, [("bvecs", "bvec_file"),
                                               ("bvals", "bval_file")])])

    workflow.connect([(inputnode, tck2trk, [("dwi", "image_file")])])

    workflow.connect([(inputnode, tck2trk, [("registration_image_file",
                                             "registration_image_file")])])
    workflow.connect([(inputnode, tck2trk, [("registration_matrix_file",
                                             "matrix_file")])])

    workflow.connect([(inputnode, estimateresponse, [("single_fiber_mask",
                                                      "mask_image")])])

    workflow.connect([(inputnode, estimateresponse, [("dwi", "in_file")])])
    workflow.connect([(fsl2mrtrix, estimateresponse, [("encoding_file",
                                                       "encoding_file")])])

    workflow.connect([(inputnode, csdeconv, [("dwi", "in_file")])])

    #workflow.connect([(inputnode, csdeconv, [("termination_mask", "mask_image")])])

    workflow.connect([(inputnode, estimateresponse, [
        (('subject_id', add_subj_name_to_SFresponse), 'out_filename')
    ])])
    workflow.connect([(inputnode, csdeconv, [
        (('subject_id', add_subj_name_to_FODs), 'out_filename')
    ])])
    workflow.connect([(inputnode, CSDstreamtrack, [
        (('subject_id', add_subj_name_to_tracks), 'out_file')
    ])])
    workflow.connect([(inputnode, tck2trk, [
        (('subject_id', add_subj_name_to_trk_tracks), 'out_filename')
    ])])

    workflow.connect([(estimateresponse, csdeconv, [("response",
                                                     "response_file")])])
    workflow.connect([(fsl2mrtrix, csdeconv, [("encoding_file",
                                               "encoding_file")])])
    workflow.connect([(inputnode, CSDstreamtrack, [("wm_mask", "seed_file")])])
    workflow.connect([(inputnode, CSDstreamtrack, [("termination_mask",
                                                    "mask_file")])])
    workflow.connect([(csdeconv, CSDstreamtrack, [("spherical_harmonics_image",
                                                   "in_file")])])

    workflow.connect([(CSDstreamtrack, tck2trk, [("tracked", "in_file")])])

    workflow.connect([
        (CSDstreamtrack, outputnode, [("tracked", "fiber_tracks_tck_dwi")]),
        (csdeconv, outputnode, [("spherical_harmonics_image", "fiber_odfs")]),
        (tck2trk, outputnode, [("out_file", "fiber_tracks_trk_t1")]),
    ])

    return workflow
Ejemplo n.º 11
0
#Wraps the executable command ``modelfit``.
camino_ModelFit = pe.Node(interface=camino.ModelFit(), name='camino_ModelFit')

#Wraps the executable command ``vtkstreamlines``.
camino_VtkStreamlines = pe.Node(interface=camino.VtkStreamlines(),
                                name='camino_VtkStreamlines')

#Wraps the executable command ``dt2nii``.
camino_DT2NIfTI = pe.Node(interface=camino.DT2NIfTI(), name='camino_DT2NIfTI')

#Wraps the executable command ``erode``.
mrtrix_Erode = pe.Node(interface=mrtrix.Erode(), name='mrtrix_Erode')

#Converts separate b-values and b-vectors from text files (FSL style) into a
mrtrix_FSL2MRTrix = pe.Node(interface=mrtrix.FSL2MRTrix(),
                            name='mrtrix_FSL2MRTrix')

#Wraps the executable command ``mrconvert``.
mrtrix_MRConvert = pe.Node(interface=mrtrix.MRConvert(),
                           name='mrtrix_MRConvert')

#Use spm to perform slice timing correction.
spm_SliceTiming = pe.Node(interface=spm.SliceTiming(), name='spm_SliceTiming')

#uses  spm_reslice to resample in_file into space of space_defining
spm_Reslice = pe.Node(interface=spm.Reslice(), name='spm_Reslice')

#Create a workflow to connect all those nodes
analysisflow = nipype.Workflow('MyWorkflow')
Ejemplo n.º 12
0
    def build_core_nodes(self):
        """Build and connect the core nodes of the pipelines.
        """
        import clinica.pipelines.dwi_dti.dwi_dti_workflows as workflows
        import clinica.pipelines.dwi_dti.dwi_dti_utils as utils

        import nipype.interfaces.utility as nutil
        import nipype.pipeline.engine as npe
        import nipype.interfaces.fsl as fsl
        import nipype.interfaces.mrtrix as mrtrix
        from clinica.lib.nipype.interfaces.mrtrix3.utils import TensorMetrics
        from clinica.lib.nipype.interfaces.mrtrix.preprocess import DWI2Tensor

        # Nodes creation
        # ==============
        get_bids_identifier = npe.Node(interface=nutil.Function(
            input_names=['caps_dwi_filename'],
            output_names=['bids_identifier'],
            function=utils.extract_bids_identifier_from_caps_filename),
                                       name='0-Get_BIDS_Identifier')

        get_caps_filenames = npe.Node(interface=nutil.Function(
            input_names=['caps_dwi_filename'],
            output_names=[
                'bids_source', 'out_dti', 'out_fa', 'out_md', 'out_ad',
                'out_rd'
            ],
            function=utils.get_caps_filenames),
                                      name='0-CAPS_Filenames')

        convert_gradients = npe.Node(interface=mrtrix.FSL2MRTrix(),
                                     name='0-Convert_FSL_Gradient')

        dwi_to_dti = npe.Node(
            # interface=mrtrix.DWI2Tensor(),
            interface=DWI2Tensor(),
            name='1-Compute_DTI')

        dti_to_metrics = npe.Node(
            #            interface=mrtrix3.TensorMetrics(),
            interface=TensorMetrics(),
            name='2-DTI-based_Metrics')

        register_on_jhu_atlas = workflows.register_dti_maps_on_atlas(
            working_directory=self.base_dir, name="3-Register_DTI_Maps_On_JHU")

        scalar_analysis = npe.Node(interface=nutil.Function(
            input_names=['in_registered_map', 'name_map', 'prefix_file'],
            output_names=['atlas_statistics_list'],
            function=utils.statistics_on_atlases),
                                   name='4-Scalar_Analysis')
        scalar_analysis_fa = scalar_analysis.clone('4-Scalar_Analysis_FA')
        scalar_analysis_fa.inputs.name_map = 'FA'
        scalar_analysis_md = scalar_analysis.clone('4-Scalar_Analysis_MD')
        scalar_analysis_md.inputs.name_map = 'MD'
        scalar_analysis_ad = scalar_analysis.clone('4-Scalar_Analysis_AD')
        scalar_analysis_ad.inputs.name_map = 'AD'
        scalar_analysis_rd = scalar_analysis.clone('4-Scalar_Analysis_RD')
        scalar_analysis_rd.inputs.name_map = 'RD'

        thres_map = npe.Node(fsl.Threshold(thresh=0.0),
                             iterfield=['in_file'],
                             name='5-Remove_Negative')
        thres_fa = thres_map.clone('5-Remove_Negative_FA')
        thres_md = thres_map.clone('5-Remove_Negative_MD')
        thres_ad = thres_map.clone('5-Remove_Negative_AD')
        thres_rd = thres_map.clone('5-Remove_Negative_RD')

        print_begin_message = npe.Node(interface=nutil.Function(
            input_names=['in_bids_or_caps_file'],
            function=utils.print_begin_pipeline),
                                       name='Write-Begin_Message')

        print_end_message = npe.Node(interface=nutil.Function(
            input_names=[
                'in_bids_or_caps_file', 'final_file_1', 'final_file_2'
            ],
            function=utils.print_end_pipeline),
                                     name='Write-End_Message')

        # Connection
        # ==========
        self.connect([
            (self.input_node, get_caps_filenames,
             [('preproc_dwi', 'caps_dwi_filename')]),  # noqa
            # Print begin message
            (self.input_node, print_begin_message,
             [('preproc_dwi', 'in_bids_or_caps_file')]),  # noqa
            # Get BIDS/CAPS identifier from filename
            (self.input_node, get_bids_identifier,
             [('preproc_dwi', 'caps_dwi_filename')]),  # noqa
            # Convert FSL gradient files (bval/bvec) to MRtrix format
            (
                self.input_node,
                convert_gradients,
                [
                    ('preproc_bval', 'bval_file'),  # noqa
                    ('preproc_bvec', 'bvec_file')
                ]),  # noqa
            # Computation of the DTI model
            (
                self.input_node,
                dwi_to_dti,
                [
                    ('b0_mask', 'in_mask'),  # noqa
                    ('preproc_dwi', 'in_file')
                ]),  # noqa
            (convert_gradients, dwi_to_dti, [('encoding_file', 'encoding_file')
                                             ]),  # noqa
            (get_caps_filenames, dwi_to_dti, [('out_dti', 'out_filename')
                                              ]),  # noqa
            # Computation of the different metrics from the DTI
            (get_caps_filenames, dti_to_metrics, [('out_fa', 'out_fa')]
             ),  # noqa
            (get_caps_filenames, dti_to_metrics, [('out_md', 'out_adc')
                                                  ]),  # noqa
            (get_caps_filenames, dti_to_metrics, [('out_ad', 'out_ad')
                                                  ]),  # noqa
            (get_caps_filenames, dti_to_metrics, [('out_rd', 'out_rd')
                                                  ]),  # noqa
            (self.input_node, dti_to_metrics, [('b0_mask', 'in_mask')
                                               ]),  # noqa
            (dwi_to_dti, dti_to_metrics, [('tensor', 'in_file')]),  # noqa
            # Register DTI maps on JHU atlas
            (
                dti_to_metrics,
                register_on_jhu_atlas,
                [
                    ('out_fa', 'inputnode.in_fa'),  # noqa
                    ('out_adc', 'inputnode.in_md'),  # noqa
                    ('out_ad', 'inputnode.in_ad'),  # noqa
                    ('out_rd', 'inputnode.in_rd')
                ]),  # noqa
            # Generate regional TSV files
            (get_bids_identifier, scalar_analysis_fa,
             [('bids_identifier', 'prefix_file')]),  # noqa
            (register_on_jhu_atlas, scalar_analysis_fa,
             [('outputnode.out_norm_fa', 'in_registered_map')]),  # noqa
            (get_bids_identifier, scalar_analysis_md,
             [('bids_identifier', 'prefix_file')]),  # noqa
            (register_on_jhu_atlas, scalar_analysis_md,
             [('outputnode.out_norm_md', 'in_registered_map')]),  # noqa
            (get_bids_identifier, scalar_analysis_ad,
             [('bids_identifier', 'prefix_file')]),  # noqa
            (register_on_jhu_atlas, scalar_analysis_ad,
             [('outputnode.out_norm_ad', 'in_registered_map')]),  # noqa
            (get_bids_identifier, scalar_analysis_rd,
             [('bids_identifier', 'prefix_file')]),  # noqa
            (register_on_jhu_atlas, scalar_analysis_rd,
             [('outputnode.out_norm_rd', 'in_registered_map')]),  # noqa
            # Remove negative values from the DTI maps:
            (get_caps_filenames, thres_fa, [('out_fa', 'out_file')]),  # noqa
            (dti_to_metrics, thres_fa, [('out_fa', 'in_file')]),  # noqa
            (get_caps_filenames, thres_md, [('out_md', 'out_file')]),  # noqa
            (dti_to_metrics, thres_md, [('out_adc', 'in_file')]),  # noqa
            (get_caps_filenames, thres_ad, [('out_ad', 'out_file')]),  # noqa
            (dti_to_metrics, thres_ad, [('out_ad', 'in_file')]),  # noqa
            (get_caps_filenames, thres_rd, [('out_rd', 'out_file')]),  # noqa
            (dti_to_metrics, thres_rd, [('out_rd', 'in_file')]),  # noqa
            # Outputnode
            (dwi_to_dti, self.output_node, [('tensor', 'dti')]),  # noqa
            (thres_fa, self.output_node, [('out_file', 'fa')]),  # noqa
            (thres_md, self.output_node, [('out_file', 'md')]),  # noqa
            (thres_ad, self.output_node, [('out_file', 'ad')]),  # noqa
            (thres_rd, self.output_node, [('out_file', 'rd')]),  # noqa
            (dti_to_metrics, self.output_node, [('out_evec', 'decfa')
                                                ]),  # noqa
            (
                register_on_jhu_atlas,
                self.output_node,
                [
                    ('outputnode.out_norm_fa', 'registered_fa'),  # noqa
                    ('outputnode.out_norm_md', 'registered_md'),  # noqa
                    ('outputnode.out_norm_ad', 'registered_ad'),  # noqa
                    ('outputnode.out_norm_rd', 'registered_rd'),  # noqa
                    ('outputnode.out_affine_matrix', 'affine_matrix'),  # noqa
                    ('outputnode.out_b_spline_transform', 'b_spline_transform')
                ]),  # noqa
            (scalar_analysis_fa, self.output_node,
             [('atlas_statistics_list', 'statistics_fa')]),  # noqa
            (scalar_analysis_md, self.output_node,
             [('atlas_statistics_list', 'statistics_md')]),  # noqa
            (scalar_analysis_ad, self.output_node,
             [('atlas_statistics_list', 'statistics_ad')]),  # noqa
            (scalar_analysis_rd, self.output_node,
             [('atlas_statistics_list', 'statistics_rd')]),  # noqa
            # Print end message
            (self.input_node, print_end_message,
             [('preproc_dwi', 'in_bids_or_caps_file')]),  # noqa
            (thres_rd, print_end_message, [('out_file', 'final_file_1')
                                           ]),  # noqa
            (scalar_analysis_rd, print_end_message,
             [('atlas_statistics_list', 'final_file_2')]),  # noqa
        ])