コード例 #1
0
def create_dwi_pipeline(name="proc_dwi"):

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

    preprocess = create_dwi_preprocess_pipeline()

    estimate_bedpost = create_bedpostx_pipeline()

    dtifit = pe.Node(interface=fsl.DTIFit(), name='dtifit')

    pipeline = pe.Workflow(name=name)

    pipeline.connect([
        (inputnode, preprocess, [("dwi", "inputnode.dwi")]),
        (preprocess, dtifit, [('eddycorrect.outputnode.eddy_corrected', 'dwi'),
                              ("bet.mask_file", "mask")]),
        (inputnode, dtifit, [("bvals", "bvals"), ("bvecs", "bvecs")]),
        (preprocess, estimate_bedpost,
         [('eddycorrect.outputnode.eddy_corrected', 'inputnode.dwi'),
          ("bet.mask_file", "inputnode.mask")]),
        (inputnode, estimate_bedpost, [("bvals", "inputnode.bvals"),
                                       ("bvecs", "inputnode.bvecs")]),
    ])
    return pipeline
コード例 #2
0
    def DTI_fit(self):
        """

        gtab = gradient_table(bvals_file, bvecs_file)
        tenmodel = dti.TensorModel(gtab)
        tenfit = tenmodel.fit(self.mask_img)
        FA = fractional_anisotropy(tenfit.evals)
        :return:
        """
        os.chdir(r'/Users/ayam/Documents/PythonHackathon_Mos/Data/Stroke/files')
        dti = fsl.DTIFit()
        dti.inputs.dwi = 'DTI4D.nii'
        dti.inputs.bvecs = 'bvecs'
        dti.inputs.bvals = 'bvals'
        dti.inputs.base_name = 'TP'
        dti.inputs.mask = 'nodif_brain_mask.nii'
        dti.inputs.output_type = 'NIFTI'
        dti.run()
コード例 #3
0
"""

bet = pe.Node(interface=fsl.BET(), name='bet')
bet.inputs.mask = True
bet.inputs.frac = 0.34
"""
correct the diffusion weighted images for eddy_currents
"""

eddycorrect = create_eddy_correct_pipeline('eddycorrect')
eddycorrect.inputs.inputnode.ref_num = 0
"""
compute the diffusion tensor in each voxel
"""

dtifit = pe.Node(interface=fsl.DTIFit(), name='dtifit')
"""
connect all the nodes for this workflow
"""

computeTensor.connect(
    [(fslroi, bet, [('roi_file', 'in_file')]),
     (eddycorrect, dtifit, [('outputnode.eddy_corrected', 'dwi')]),
     (infosource, dtifit,
      [['subject_id', 'base_name']]), (bet, dtifit, [('mask_file', 'mask')])])
"""
Setup for Tracktography
-----------------------

Here we will create a workflow to enable probabilistic tracktography
and hard segmentation of the seed region
コード例 #4
0
def create_dti():
    # main workflow for preprocessing diffusion data
    # fsl output type
    fsl.FSLCommand.set_default_output_type('NIFTI_GZ')
    # Initiation of a workflow
    dwi_preproc = Workflow(name="dwi_preproc")
    # inputnode
    inputnode = Node(IdentityInterface(fields=[
        'subject_id', 'freesurfer_dir', 'aseg', 'dwi', 'dwi_ap', 'dwi_pa',
        'bvals', 'bvecs'
    ]),
                     name='inputnode')
    # output node
    outputnode = Node(IdentityInterface(fields=[
        'dwi_denoised', "dwi_unringed", "topup_corr", "topup_field",
        "topup_fieldcoef", "eddy_corr", "rotated_bvecs", 'total_movement_rms',
        'shell_params', 'cnr_maps', 'residuals', 'outlier_report',
        'shell_params', 'dti_fa', 'dti_md', 'dti_l1', 'dti_l2', 'dti_l3',
        'dti_v1', 'dti_v2', 'dti_v3', 'fa2anat', 'fa2anat_mat', 'fa2anat_dat'
    ]),
                      name='outputnode')
    '''
    workflow to run distortion correction
    -------------------------------------
    '''
    distor_corr = create_distortion_correct()

    #''
    ## upsampling #TODO: upsample with eddy directly, waiting for Alfred for the method
    #''
    #flirt = Node(fsl.FLIRT(), name='flirt')
    #flirt.inputs.apply_isoxfm = 1
    #TODO: to use this for dtifit, needed to creat another brain mask
    '''
    getting first bval/bvec files
    '''

    get_bvalsvecs = Node(util.Function(input_names=["bvals", "bvecs", "dwi"],
                                       output_names=["bval_file", "bvec_file"],
                                       function=return_list_element),
                         name="get_bvalsvecs")
    '''
    tensor fitting
    --------------
    '''
    dti = Node(fsl.DTIFit(), name='dti')

    #connecting the nodes
    dwi_preproc.connect([
        (inputnode, distor_corr, [('dwi', 'inputnode.dwi')]),
        (inputnode, distor_corr, [('dwi_ap', 'inputnode.dwi_ap')]),
        (inputnode, distor_corr, [('dwi_pa', 'inputnode.dwi_pa')]),
        (inputnode, get_bvalsvecs, [("bvals", "bvals")]),
        (inputnode, get_bvalsvecs, [("bvecs", "bvecs")]),
        (inputnode, get_bvalsvecs, [("dwi", "dwi")]),
        (get_bvalsvecs, distor_corr, [("bval_file", "inputnode.bvals")]),
        (get_bvalsvecs, distor_corr, [("bvec_file", "inputnode.bvecs")]),
        (get_bvalsvecs, dti, [("bval_file", "bvals")]),
        (distor_corr, outputnode, [('outputnode.bo_brain', 'bo_brain')]),
        (distor_corr, outputnode, [('outputnode.bo_brainmask', 'bo_brainmask')
                                   ]),
        (distor_corr, outputnode, [('outputnode.noise', 'noise')]),
        (distor_corr, outputnode, [('outputnode.dwi_denoised', 'dwi_denoised')
                                   ]),
        (distor_corr, outputnode, [('outputnode.dwi_unringed', 'dwi_unringed')
                                   ]),
        (distor_corr, outputnode, [('outputnode.topup_corr', 'topup_corr')]),
        (distor_corr, outputnode, [('outputnode.topup_field', 'topup_field')]),
        (distor_corr, outputnode, [('outputnode.topup_fieldcoef',
                                    'topup_fieldcoef')]),
        (distor_corr, outputnode, [('outputnode.eddy_corr', 'eddy_corr')]),
        (distor_corr, outputnode, [('outputnode.rotated_bvecs',
                                    'rotated_bvecs')]),
        (distor_corr, outputnode, [('outputnode.total_movement_rms',
                                    'total_movement_rms')]),
        (distor_corr, outputnode, [('outputnode.cnr_maps', 'cnr_maps')]),
        (distor_corr, outputnode, [('outputnode.residuals', 'residuals')]),
        (distor_corr, outputnode, [('outputnode.shell_params', 'shell_params')
                                   ]),
        (distor_corr, outputnode, [('outputnode.outlier_report',
                                    'outlier_report')]),
        (distor_corr, dti, [("outputnode.rotated_bvecs", "bvecs")]),
        (distor_corr, dti, [('outputnode.bo_brainmask', 'mask')]),
        #(distor_corr, flirt, [('outputnode.eddy_corr', 'in_file')]),
        #(distor_corr, flirt, [('outputnode.eddy_corr', 'reference')]),
        #(flirt, dti, [('out_file', 'dwi')]),
        (distor_corr, dti, [('outputnode.eddy_corr', 'dwi')]),
        (dti, outputnode, [('FA', 'dti_fa')]),
        (dti, outputnode, [('MD', 'dti_md')]),
        (dti, outputnode, [('L1', 'dti_l1')]),
        (dti, outputnode, [('L2', 'dti_l2')]),
        (dti, outputnode, [('L3', 'dti_l3')]),
        (dti, outputnode, [('V1', 'dti_v1')]),
        (dti, outputnode, [('V2', 'dti_v2')]),
        (dti, outputnode, [('V3', 'dti_v3')])
    ])
    '''
    coregistration of FA and T1
    ------------------------------------
    '''

    # linear registration with bbregister
    bbreg = Node(fs.BBRegister(contrast_type='t1',
                               out_fsl_file='fa2anat.mat',
                               out_reg_file='fa2anat.dat',
                               registered_file='fa2anat_bbreg.nii.gz',
                               init='fsl'),
                 name='bbregister')

    # connecting the nodes
    dwi_preproc.connect([
        (inputnode, bbreg, [('subject_id', 'subject_id')]),
        (inputnode, bbreg, [('freesurfer_dir', 'subjects_dir')]),
        (dti, bbreg, [("FA", "source_file")]),
        (bbreg, outputnode, [('out_fsl_file', 'fa2anat_mat'),
                             ('out_reg_file', 'fa2anat_dat'),
                             ('registered_file', 'fa2anat')])
    ])

    return dwi_preproc
コード例 #5
0
    def _run_interface(self, runtime):

        # Loading required packages
        from additional_interfaces import AdditionalDTIMeasures
        from additional_interfaces import DipyDenoise
        import nipype.interfaces.fsl as fsl
        import nipype.interfaces.io as nio
        import nipype.pipeline.engine as pe
        import nipype.interfaces.utility as util
        import os

        # ==============================================================
        # Processing of diffusion-weighted data
        # Extract b0 image
        fslroi = pe.Node(interface=fsl.ExtractROI(), name='extract_b0')
        fslroi.inputs.in_file = self.inputs.dwi
        fslroi.inputs.t_min = 0
        fslroi.inputs.t_size = 1

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

        # Eddy-current and motion correction
        eddy = pe.Node(interface=fsl.epi.Eddy(args='-v'), name='eddy')
        eddy.inputs.in_acqp  = self.inputs.acqparams
        eddy.inputs.in_bvec  = self.inputs.bvecs
        eddy.inputs.in_bval  = self.inputs.bvals
        eddy.inputs.in_file = self.inputs.dwi
        eddy.inputs.in_index = self.inputs.index_file

        # Denoising
        dwi_denoise = pe.Node(interface=DipyDenoise(), name='dwi_denoise')
        dwi_denoise.inputs.in_file = self.inputs.dwi

        # Fitting the diffusion tensor model
        dtifit = pe.Node(interface=fsl.DTIFit(), name='dtifit')
        dtifit.inputs.base_name = self.inputs.subject_id
        dtifit.inputs.dwi = self.inputs.dwi
        dtifit.inputs.bvecs = self.inputs.bvecs
        dtifit.inputs.bvals = self.inputs.bvals

        # Getting AD and RD
        get_rd = pe.Node(interface=AdditionalDTIMeasures(), name='get_rd')

        # DataSink
        datasink = pe.Node(interface=nio.DataSink(), name='datasink')
        datasink.inputs.parameterization = False
        datasink.inputs.base_directory = self.inputs.out_directory + '/_subject_id_' + self.inputs.subject_id + '/dwi_preproc/'

        # Renaming the outputs for consistency
        AD_rename = pe.Node(interface=util.Rename(keep_ext = True), name='AD_rename')
        AD_rename.inputs.format_string = self.inputs.subject_id + '_AD'

        b0_rename = pe.Node(interface=util.Rename(keep_ext = True), name='b0_rename')
        b0_rename.inputs.format_string = self.inputs.subject_id + '_b0'

        dwi_rename = pe.Node(interface=util.Rename(keep_ext = True), name='dwi_rename')
        dwi_rename.inputs.format_string = self.inputs.subject_id + '_dwi'

        mask_rename = pe.Node(interface=util.Rename(keep_ext = True), name='mask_rename')
        mask_rename.inputs.format_string = self.inputs.subject_id + '_mask'

        RD_rename = pe.Node(interface=util.Rename(keep_ext = True), name='RD_rename')
        RD_rename.inputs.format_string = self.inputs.subject_id + '_RD'


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

        # Diffusion data
        # Preprocessing
        dwi_preproc.connect(fslroi, 'roi_file', bet, 'in_file')
        dwi_preproc.connect(bet, 'mask_file', eddy, 'in_mask')
        dwi_preproc.connect(eddy, 'out_corrected', dwi_denoise, 'in_file')

        # Calculate diffusion measures
        dwi_preproc.connect(dwi_denoise, 'out_file', dtifit, 'dwi')
        dwi_preproc.connect(bet, 'mask_file', dtifit, 'mask')
        dwi_preproc.connect(dtifit, 'L1', get_rd, 'L1')
        dwi_preproc.connect(dtifit, 'L2', get_rd, 'L2')
        dwi_preproc.connect(dtifit, 'L3', get_rd, 'L3')

        # Renaming same outputs
        dwi_preproc.connect(dwi_denoise, 'out_file', dwi_rename, 'in_file')
        dwi_preproc.connect(bet, 'out_file', b0_rename, 'in_file')
        dwi_preproc.connect(bet, 'mask_file', mask_rename, 'in_file')
        dwi_preproc.connect(get_rd, 'AD', AD_rename, 'in_file')
        dwi_preproc.connect(get_rd, 'RD', RD_rename, 'in_file')

        # Connecting to the datasink
        dwi_preproc.connect(dwi_rename, 'out_file', datasink, 'preprocessed.@dwi')
        dwi_preproc.connect(b0_rename, 'out_file', datasink, 'preprocessed.@b0')
        dwi_preproc.connect(mask_rename, 'out_file', datasink, 'preprocessed.@mask')
        dwi_preproc.connect(dtifit, 'FA', datasink, 'preprocessed.@FA')
        dwi_preproc.connect(dtifit, 'MD', datasink, 'preprocessed.@MD')
        dwi_preproc.connect(AD_rename, 'out_file', datasink, 'preprocessed.@AD')
        dwi_preproc.connect(RD_rename, 'out_file', datasink, 'preprocessed.@RD')

        # ==============================================================
        # Running the workflow
        dwi_preproc.base_dir = os.path.abspath(self.inputs.out_directory + '_subject_id_' + self.inputs.subject_id)
        dwi_preproc.write_graph()
        dwi_preproc.write_graph()
        dwi_preproc.run()

        return runtime
コード例 #6
0
def create_prep(use_fieldmap):

    from nipype.workflows.smri.freesurfer import create_getmask_flow
    import nipype.interfaces.fsl as fsl          # fsl
    import nipype.interfaces.utility as util     # utility
    import nipype.pipeline.engine as pe          # pypeline engine
    fsl.FSLCommand.set_default_output_type('NIFTI')
    import bips.utils.reportsink.io as io
    inputspec = pe.Node(interface=util.IdentityInterface(fields=['dwi',
                                                                 'bvec',
                                                                 'bval',
                                                                 'subject_id',
                                                                 'subjects_dir',
                                                                 'magnitude_image',
                                                                 'phase_image',
                                                                 'echo_spacing',
                                                                 'TE_diff',
                                                                 'sigma',
                                                                 'rotate',
                                                                 'report_directory']),
                        name='inputspec')
    
    gen_fa = pe.Workflow(name="gen_fa")

    eddy_correct = create_eddy_correct_pipeline()
    gen_fa.connect(inputspec, 'dwi', eddy_correct, 'inputnode.in_file')
    gen_fa.connect(inputspec,'bval', eddy_correct, 'inputnode.bvals')

    getmask = create_getmask_flow()
    gen_fa.connect(inputspec,'subject_id',getmask,'inputspec.subject_id')
    gen_fa.connect(inputspec,'subjects_dir',getmask,'inputspec.subjects_dir')
    getmask.inputs.inputspec.contrast_type = 't2'

    outputnode = pe.Node(interface=util.IdentityInterface(fields=['FA',
                                                                  'MD',
                                                                  'reg_file',
                                                                  'FM_unwarped_mean',
                                                                  'FM_unwarped_epi',
                                                                  'eddy_corrected',
                                                                  'mask',
                                                                  'bvecs',
                                                                  'bvals',
                                                                  "mean"]),
        name='outputspec')
    dtifit = pe.MapNode(interface=fsl.DTIFit(), name='dtifit', iterfield=['dwi',"mask","bvecs","bvals"])

    if use_fieldmap:
        fieldmap = pe.Node(interface=fsl.utils.EPIDeWarp(), name='fieldmap_unwarp')
        dewarper = pe.MapNode(interface=fsl.FUGUE(),iterfield=['in_file'],name='dewarper')
        gen_fa.connect(inputspec,'TE_diff',
            fieldmap, 'tediff')
        gen_fa.connect(inputspec,'echo_spacing',
            fieldmap,'esp')
        gen_fa.connect(inputspec,'sigma',
            fieldmap, 'sigma')
        gen_fa.connect(eddy_correct, 'outputnode.eddy_corrected',
            dewarper, 'in_file')
        gen_fa.connect(fieldmap, 'exf_mask',
            dewarper, 'mask_file')
        gen_fa.connect(fieldmap, 'vsm_file',
            dewarper, 'shift_in_file')
        gen_fa.connect(eddy_correct, 'outputnode.mean_image',
            fieldmap, 'exf_file')
        gen_fa.connect(inputspec, 'phase_image',
            fieldmap, 'dph_file')
        gen_fa.connect(inputspec, 'magnitude_image',
            fieldmap, 'mag_file')
        gen_fa.connect(fieldmap, 'exfdw',
            getmask, 'inputspec.source_file')
        gen_fa.connect(fieldmap, 'exfdw',
            outputnode, 'FM_unwarped_mean')
        gen_fa.connect(fieldmap, 'exfdw',
            outputnode, 'mean')
        gen_fa.connect(dewarper,'unwarped_file',dtifit,'dwi')
        gen_fa.connect(dewarper, 'unwarped_file',
            outputnode, 'FM_unwarped_epi')
        #gen_fa.connect(fieldmap,'exf_mask',dtifit,'mask')

    else:
        gen_fa.connect(eddy_correct,'outputnode.mean_image',
            getmask,'inputspec.source_file')
        gen_fa.connect(eddy_correct,'outputnode.mean_image',
            outputnode,'mean')
        gen_fa.connect(eddy_correct, 'outputnode.eddy_corrected', dtifit, 'dwi')
        gen_fa.connect(eddy_correct, 'outputnode.eddy_corrected', outputnode, 'eddy_corrected')

    gen_fa.connect(getmask,('outputspec.mask_file',pickfirst), dtifit, 'mask')
    gen_fa.connect(getmask,('outputspec.mask_file',pickfirst), outputnode, 'mask')

    gen_fa.connect(inputspec,'subject_id',dtifit,'base_name')

    rotate = pe.MapNode(util.Function(input_names=['bvecs','motion_vecs','rotate'],
                                      output_names=['rotated_bvecs'],
                                      function=rotate_bvecs),
        name='rotate_bvecs', iterfield=["bvecs", "motion_vecs"])

    gen_fa.connect(inputspec,'bvec', rotate, 'bvecs')
    gen_fa.connect(eddy_correct,'outputnode.coreg_mat_files',rotate,'motion_vecs')
    gen_fa.connect(inputspec,'rotate', rotate, 'rotate')
    gen_fa.connect(rotate,'rotated_bvecs', dtifit, 'bvecs')

    gen_fa.connect(inputspec, 'bval', dtifit, 'bvals')
    gen_fa.connect(inputspec, 'bval', outputnode, 'bvals')

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

    plotmotion = pe.MapNode(util.Function(input_names=["motion_parameters"],
                                          output_names=["fname_t","fname_r"],
                                          function=plot_motion),
        name="plot_motion",iterfield="motion_parameters")

    gen_fa.connect(eddy_correct,'outputnode.coreg_mat_files',getmotion,'flirt_out_mats')
    gen_fa.connect(getmotion,"motion_params", plotmotion, "motion_parameters")

    reportnode = pe.Node(io.ReportSink(orderfields=["Introduction",
                                                    "In_Files",
                                                    "Translations",
                                                    "Rotations"]),name="Diffusion_Preprocessing_Report")
    reportnode.inputs.Introduction = "Quality Assurance Report for Diffusion preprocessing."
    reportnode.inputs.report_name = "Diffusion_Preprocessing_Report"

    gen_fa.connect(getmask,'outputspec.reg_file',
        outputnode, 'reg_file')

    gen_fa.connect(plotmotion, "fname_t", reportnode, "Translations")
    gen_fa.connect(plotmotion, "fname_r", reportnode, "Rotations")
    gen_fa.connect(inputspec, "dwi", reportnode, "In_Files")
    gen_fa.connect(inputspec,"subject_id", reportnode, "container")
    gen_fa.connect(inputspec,"report_directory", reportnode,"base_directory")
    gen_fa.connect(rotate,'rotated_bvecs', outputnode, 'bvecs')
    gen_fa.connect(dtifit, 'FA', outputnode, 'FA')
    gen_fa.connect(dtifit, 'MD', outputnode, 'MD')
    return gen_fa
コード例 #7
0
def create_dti():
    # main workflow for preprocessing diffusion data
    # fsl output type
    fsl.FSLCommand.set_default_output_type('NIFTI_GZ')
    # Initiation of a workflow
    dwi_preproc = Workflow(name="dwi_preproc")
    # inputnode
    inputnode = Node(IdentityInterface(fields=[
        'subject_id',
        'freesurfer_dir',
        'aseg',
        'dwi',
        'dwi_ap',
        'dwi_pa',
        'bvals',
        'bvecs'
    ]),
        name='inputnode')
    # output node
    outputnode = Node(IdentityInterface(fields=[
        'dwi_denoised',
        "dwi_unringed",
        "topup_corr",
        "topup_field",
        "bo_brain",
        "bo_brainmask",
        "topup_fieldcoef",
        "eddy_corr",
        "eddy_params",
        "rotated_bvecs",
        "total_movement_rms",
        "shell_alignment_parameters",
        'outlier_report',
        "cnr_maps",
        "residuals",
        'dti_fa',
        'dti_md',
        'dti_l1',
        'dti_l2',
        'dti_l3',
        'dti_v1',
        'dti_v2',
        'dti_v3',
        'fa2anat',
        'fa2anat_mat',
        'fa2anat_dat'
    ]),
        name='outputnode')

    
    '''
    workflow to run distortion correction
    -------------------------------------
    '''
    distor_corr = create_distortion_correct()


    '''
    tensor fitting
    --------------
    '''
    dti = Node(fsl.DTIFit(), name='dti')

    #connecting the nodes
    dwi_preproc.connect([

        (inputnode, distor_corr, [('dwi', 'inputnode.dwi')]),
        (inputnode, distor_corr, [('dwi_ap', 'inputnode.dwi_ap')]),
        (inputnode, distor_corr, [('dwi_pa', 'inputnode.dwi_pa')]),
        (inputnode, distor_corr, [("bvals", "inputnode.bvals")]),
        (inputnode, distor_corr, [("bvecs", "inputnode.bvecs")]),
        (inputnode, dti, [("bvals", "bvals")]),
        (distor_corr, outputnode, [('outputnode.bo_brain', 'bo_brain')]),
        (distor_corr, outputnode, [('outputnode.bo_brainmask', 'bo_brainmask')]),
        (distor_corr, outputnode, [('outputnode.noise', 'noise')]),
        (distor_corr, outputnode, [('outputnode.dwi_denoised', 'dwi_denoised')]),
        (distor_corr, outputnode, [('outputnode.dwi_unringed', 'dwi_unringed')]),
        (distor_corr, outputnode, [('outputnode.topup_corr', 'topup_corr')]),
        (distor_corr, outputnode, [('outputnode.topup_field', 'topup_field')]),
        (distor_corr, outputnode, [('outputnode.topup_fieldcoef', 'topup_fieldcoef')]),
        (distor_corr, outputnode, [('outputnode.eddy_corr', 'eddy_corr')]),
        (distor_corr, outputnode, [('outputnode.rotated_bvecs', 'rotated_bvecs')]),
        (distor_corr, outputnode, [('outputnode.total_movement_rms', 'total_movement_rms')]),
        (distor_corr, outputnode, [('outputnode.outlier_report', 'outlier_report')]),
        (distor_corr, outputnode, [('outputnode.shell_params', "shell_alignment_parameters",)]),
        (distor_corr, outputnode, [('outputnode.cnr_maps', 'cnr_maps')]),
        (distor_corr, outputnode, [('outputnode.residuals', 'residuals')]),
        (distor_corr, outputnode, [('outputnode.eddy_params', 'eddy_params')]),
        (distor_corr, dti, [("outputnode.rotated_bvecs", "bvecs")]),
        (distor_corr, dti, [('outputnode.bo_brainmask', 'mask')]),
        #(distor_corr, flirt, [('outputnode.eddy_corr', 'in_file')]),
        #(distor_corr, flirt, [('outputnode.eddy_corr', 'reference')]),
        #(flirt, dti, [('out_file', 'dwi')]),
        (distor_corr, dti, [('outputnode.eddy_corr', 'dwi')]),
        (dti, outputnode, [('FA', 'dti_fa')]),
        (dti, outputnode, [('MD', 'dti_md')]),
        (dti, outputnode, [('L1', 'dti_l1')]),
        (dti, outputnode, [('L2', 'dti_l2')]),
        (dti, outputnode, [('L3', 'dti_l3')]),
        (dti, outputnode, [('V1', 'dti_v1')]),
        (dti, outputnode, [('V2', 'dti_v2')]),
        (dti, outputnode, [('V3', 'dti_v3')])

    ])


    '''
    coregistration of FA and T1
    ------------------------------------
    '''
    #have to rename subject for fu (but now structural wf is connected to dwi
    #and its not necessary to rename again.)
    #def rename_subject_for_fu(input_id):
    #    output_id=input_id+"_fu"
    #    return output_id

    #modify subject name so it can be saved in the same folder as other LIFE- freesurfer data
    #rename=Node(util.Function(input_names=['input_id'],
    #                        output_names=['output_id'],
    #                        function = rename_subject_for_fu), name="rename")
    
    # linear registration with bbregister
    bbreg = Node(fs.BBRegister(contrast_type='t1',
    out_fsl_file='fa2anat.mat',
    out_reg_file='fa2anat.dat',
    registered_file='fa2anat_bbreg.nii.gz',
    init='fsl'
    ),
    name='bbregister')

    # connecting the nodes
    dwi_preproc.connect([

        (inputnode, bbreg, [('subject_id', 'subject_id')]),
        (inputnode, bbreg, [('freesurfer_dir', 'subjects_dir')]),
        (dti, bbreg, [("FA", "source_file")]),
        (bbreg, outputnode, [('out_fsl_file', 'fa2anat_mat'),
                             ('out_reg_file', 'fa2anat_dat'),
                             ('registered_file', 'fa2anat')])

    ])

    return dwi_preproc
コード例 #8
0
    def dwi_preproc(acqparams, base_directory, index_file, out_directory,
                    subject_list):

        # Loading required packages
        from BrainTypes_additional_interfaces import ants_QuickSyN
        import nipype.interfaces.fsl as fsl
        import nipype.interfaces.io as nio
        import nipype.pipeline.engine as pe
        from nipype import SelectFiles
        import nipype.interfaces.utility as util
        import os

        # ==============================================================
        # Processing of diffusion-weighted data
        infosource = pe.Node(
            interface=util.IdentityInterface(fields=['subject_id']),
            name='infosource')
        infosource.iterables = ('subject_id', subject_list)

        # Getting the relevant 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)

        # Extract b0 image
        fslroi = pe.Node(interface=fsl.ExtractROI(), name='fslroi')
        fslroi.inputs.t_min = 0
        fslroi.inputs.t_size = 1

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

        # Eddy-current and motion correction
        eddy = pe.Node(interface=fsl.epi.Eddy(args='-v'), name='eddy')
        eddy.inputs.in_acqp = acqparams
        eddy.inputs.in_index = index_file

        # Fitting the diffusion tensor model
        dtifit = pe.Node(interface=fsl.DTIFit(), name='dtifit')

        # Moving files to MNI space
        reg = pe.Node(interface=ants_QuickSyN(), name='reg')
        reg.inputs.fixed_image = os.environ[
            'FSLDIR'] + '/data/standard/FMRIB58_FA_1mm.nii.gz'
        reg.inputs.image_dimensions = 3
        reg.inputs.transform_type = 's'

        # ==============================================================
        # Setting up the workflow
        dwi_preproc = pe.Workflow(name='dwi_preproc')
        dwi_preproc.connect(infosource, 'subject_id', selectfiles,
                            'subject_id')

        # Diffusion data
        # Preprocessing
        dwi_preproc.connect(selectfiles, 'dwi', fslroi, 'in_file')
        dwi_preproc.connect(fslroi, 'roi_file', bet, 'in_file')
        dwi_preproc.connect(bet, 'mask_file', eddy, 'in_mask')
        dwi_preproc.connect(selectfiles, 'dwi', eddy, 'in_file')
        dwi_preproc.connect(selectfiles, 'bvec', eddy, 'in_bvec')
        dwi_preproc.connect(selectfiles, 'bval', eddy, 'in_bval')

        # Calculate diffusion measures
        dwi_preproc.connect(eddy, 'out_corrected', dtifit, 'dwi')
        dwi_preproc.connect(bet, 'mask_file', dtifit, 'mask')
        dwi_preproc.connect(infosource, 'subject_id', dtifit, 'base_name')
        dwi_preproc.connect(selectfiles, 'bvec', dtifit, 'bvecs')
        dwi_preproc.connect(selectfiles, 'bval', dtifit, 'bvals')
        dwi_preproc.connect(dtifit, 'FA', reg, 'moving_image')
        dwi_preproc.connect(infosource, 'subject_id', reg, 'output_prefix')

        # ==============================================================
        # Running the workflow
        dwi_preproc.base_dir = os.path.abspath(out_directory)
        dwi_preproc.write_graph()
        dwi_preproc.run()
Study_Template = '/home/in/aeed/Work/October_Acquistion/FA_Template_Cluster.nii.gz'
#-----------------------------------------------------------------------------------------------------
# In[7]:
#Eddy Current correction using the new function Eddy instead of Eddy_correct

eddy = Node (fsl.Eddy(), name = 'eddy')
eddy.inputs.in_acqp  = acqparams
eddy.inputs.in_bval  = bval
eddy.inputs.in_bvec  = bvec
eddy.inputs.in_index = index
eddy.inputs.niter = 10
#-----------------------------------------------------------------------------------------------------
# In[7]:
#Fit the tensor

fit_tensor = Node (fsl.DTIFit(), name = 'fit_tensor')
fit_tensor.inputs.bvals = '/home/in/aeed/Work/October_Acquistion/bval_20'
fit_tensor.inputs.bvecs = '/home/in/aeed/Work/October_Acquistion/bvec_20'
fit_tensor.inputs.save_tensor = True
# fit_tensor.inputs.wls = True #Fit the tensor with wighted least squares, try this one
#-----------------------------------------------------------------------------------------------------
# In[7]:
#Get the radial diffusivity by taking the first, the sum of L2 and L3

l2_l3_sum = Node(fsl.BinaryMaths(), name = 'l2_l3_sum')
l2_l3_sum.inputs.operation = 'add'

#-----------------------------------------------------------------------------------------------------
# In[7]:
#Now the average
コード例 #10
0
def create_dti():
    # main workflow for preprocessing diffusion data
    # fsl output type
    fsl.FSLCommand.set_default_output_type('NIFTI_GZ')
    # Initiation of a workflow
    dwi_preproc = Workflow(name="dwi_preproc")
    # inputnode
    inputnode = Node(IdentityInterface(fields=[
        'subject_id', 'freesurfer_dir', 'aseg', 'dwi', 'dwi_b0', 'dwi_mag',
        'dwi_ph', 'bvals', 'bvecs', 'dwi_dwelltime', 'te_diff'
    ]),
                     name='inputnode')
    # output node
    outputnode = Node(IdentityInterface(fields=[
        'bo_brain', "bo_brainmask", 'dwi_denoised', 'dwi_unringed',
        "mag2b0mat", "mag2b0", "fmap", "eddy_corr", "rotated_bvecs",
        "total_movement_rms", "outlier_report", "cnr_maps", "residuals",
        "shell_params", "eddy_params", 'dti_fa', 'dti_md', 'dti_l1', 'dti_l2',
        'dti_l3', 'dti_v1', 'dti_v2', 'dti_v3', 'fa2anat', 'fa2anat_mat',
        'fa2anat_dat'
    ]),
                      name='outputnode')
    '''
    workflow to run distortion correction
    -------------------------------------
    '''
    distor_corr = create_distortion_correct()
    '''
    tensor fitting
    --------------
    '''
    dti = Node(fsl.DTIFit(), name='dti')

    #connecting the nodes
    dwi_preproc.connect([
        (inputnode, distor_corr, [('dwi', 'inputnode.dwi')]),
        (inputnode, distor_corr, [('dwi_b0', 'inputnode.dwi_b0')]),
        (inputnode, distor_corr, [('dwi_mag', 'inputnode.dwi_mag')]),
        (inputnode, distor_corr, [('dwi_ph', 'inputnode.dwi_ph')]),
        (inputnode, distor_corr, [("bvals", "inputnode.bvals")]),
        (inputnode, distor_corr, [("bvecs", "inputnode.bvecs")]),
        (inputnode, distor_corr, [("dwi_dwelltime", "inputnode.dwi_dwelltime")
                                  ]),
        (inputnode, distor_corr, [("te_diff", "inputnode.te_diff")]),
        (distor_corr, outputnode, [('outputnode.bo_brain', 'bo_brain')]),
        (distor_corr, outputnode, [('outputnode.bo_brainmask', 'bo_brainmask')
                                   ]),
        (distor_corr, outputnode, [('outputnode.dwi_denoised', 'dwi_denoised')
                                   ]),
        (distor_corr, outputnode, [('outputnode.dwi_unringed', 'dwi_unringed')
                                   ]),
        (distor_corr, outputnode, [('outputnode.fmap', 'fmap')]),
        (distor_corr, outputnode, [('outputnode.mag2b0mat', 'mag2b0mat')]),
        (distor_corr, outputnode, [('outputnode.mag2b0', 'mag2b0')]),
        (distor_corr, outputnode, [('outputnode.eddy_corr', 'eddy_corr')]),
        (distor_corr, outputnode, [('outputnode.rotated_bvecs',
                                    'rotated_bvecs')]),
        (distor_corr, outputnode, [('outputnode.total_movement_rms',
                                    'total_movement_rms')]),
        (distor_corr, outputnode, [('outputnode.cnr_maps', 'cnr_maps')]),
        (distor_corr, outputnode, [('outputnode.residuals', 'residuals')]),
        (distor_corr, outputnode, [('outputnode.shell_params', 'shell_params')
                                   ]),
        (distor_corr, outputnode, [('outputnode.eddy_params', 'eddy_params')]),
        (distor_corr, outputnode, [('outputnode.outlier_report',
                                    'outlier_report')]),
        (distor_corr, dti, [("outputnode.rotated_bvecs", "bvecs")]),
        (distor_corr, dti, [('outputnode.bo_brainmask', 'mask')]),
        (distor_corr, dti, [('outputnode.eddy_corr', 'dwi')]),
        (distor_corr, dti, [("outputnode.bvals", "bvals")]),
        (dti, outputnode, [('FA', 'dti_fa')]),
        (dti, outputnode, [('MD', 'dti_md')]),
        (dti, outputnode, [('L1', 'dti_l1')]),
        (dti, outputnode, [('L2', 'dti_l2')]),
        (dti, outputnode, [('L3', 'dti_l3')]),
        (dti, outputnode, [('V1', 'dti_v1')]),
        (dti, outputnode, [('V2', 'dti_v2')]),
        (dti, outputnode, [('V3', 'dti_v3')])
    ])
    '''
    coregistration of FA and T1
    ------------------------------------
    '''

    # linear registration with bbregister
    bbreg = Node(fs.BBRegister(contrast_type='t1',
                               out_fsl_file='fa2anat.mat',
                               out_reg_file='fa2anat.dat',
                               registered_file='fa2anat_bbreg.nii.gz',
                               init='fsl'),
                 name='bbregister')

    # connecting the nodes
    dwi_preproc.connect([
        (inputnode, bbreg, [('subject_id', 'subject_id')]),
        (inputnode, bbreg, [('freesurfer_dir', 'subjects_dir')]),
        (dti, bbreg, [("FA", "source_file")]),
        (bbreg, outputnode, [('out_fsl_file', 'fa2anat_mat'),
                             ('out_reg_file', 'fa2anat_dat'),
                             ('registered_file', 'fa2anat')])
    ])

    return dwi_preproc
コード例 #11
0
def create_conductivity_tensor_mesh_workflow(name="add_conductivity"):
    inputnode = pe.Node(interface=util.IdentityInterface(fields=[
        "dwi", "bvecs", "bvals", "struct", "t1_fsl_space", "mesh_file"
    ]),
                        name="inputnode")
    outputnode = pe.Node(interface=util.IdentityInterface(fields=[
        "mesh_file", "diff_V1", "cond_V1", "fa_t1_space", "mean_conductivity"
    ]),
                         name="outputnode")

    conform_T1 = pe.Node(interface=fs.MRIConvert(), name='conform_T1')
    conform_T1.inputs.conform = True
    bet_T1 = pe.Node(interface=fsl.BET(), name='bet_T1')

    bet_b0 = pe.Node(interface=fsl.BET(), name='bet_b0')
    bet_b0.inputs.frac = 0.2
    bet_b0.inputs.mask = True

    dtifit = pe.Node(interface=fsl.DTIFit(), name='dtifit')
    dtifit.inputs.save_tensor = True

    threshold_FA = pe.Node(interface=fsl.ImageMaths(), name='threshold_FA')
    threshold_FA.inputs.op_string = '-thr 0.2 -uthr 0.99'

    affine_register = pe.Node(interface=fsl.FLIRT(), name='affine_register')
    affine_register.inputs.dof = 6
    #affine_register.inputs.cost = ('normmi')

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

    register_tensor = pe.Node(interface=fsl.VecReg(), name='register_tensor')

    decompose_tensor = pe.Node(interface=fsl.DecomposeTensor(),
                               name='decompose_tensor')
    decompose_conductivity = decompose_tensor.clone("decompose_conductivity")
    decompose_conductivity.inputs.base_name = "cond"
    decompose_diff_tensor_fslspace = decompose_tensor.clone(
        "decompose_diff_tensor_fslspace")
    decompose_diff_tensor_fslspace.inputs.base_name = "tensor_reg"

    fast_segment = pe.Node(interface=fsl.FAST(), name='fast_segment')
    fast_segment.inputs.segments = True

    conductivity_mapping = pe.Node(interface=dipy.EstimateConductivity(),
                                   name='conductivity_mapping')
    conductivity_mapping.inputs.lower_triangular_input = False
    conductivity_mapping.inputs.lower_triangular_output = False

    concat_affine_xform = pe.Node(interface=fsl.ConvertXFM(),
                                  name='concat_affine_xform')
    concat_affine_xform.inputs.in_file2 = op.join(os.environ["FWD_DIR"],
                                                  "etc/fs2fsl_conform.mat")
    concat_affine_xform.inputs.concat_xfm = True

    diff_tensor_to_fsl_space = pe.Node(interface=fsl.VecReg(),
                                       name='diff_tensor_to_fsl_space')

    add_tensors_to_mesh_interface = util.Function(
        input_names=[
            "mesh_file", "tensor_file", "mask_file", "mask_threshold",
            "lower_triangular"
        ],
        output_names=["out_file"],
        function=include_gmsh_tensor_elements)
    add_conductivity_tensor_to_mesh = pe.Node(
        interface=add_tensors_to_mesh_interface,
        name='add_conductivity_tensor_to_mesh')

    add_conductivity_tensor_to_mesh.inputs.lower_triangular = False
    add_conductivity_tensor_to_mesh.inputs.mask_threshold = 0.1
    """
    Define the Workflow
    -------------------
    """

    workflow = pe.Workflow(name='workflow')
    scale_factor_workflow = create_get_scale_factor_workflow(
        "scale_factor_workflow")

    workflow.connect([(inputnode, dtifit, [
        ('dwi', 'dwi'),
        ('bvals', 'bvals'),
        ('bvecs', 'bvecs'),
    ])])

    workflow.connect([(inputnode, bet_b0, [('dwi', 'in_file')])])
    workflow.connect([(bet_b0, dtifit, [('mask_file', 'mask')])])

    workflow.connect([(inputnode, conform_T1, [('struct', 'in_file')])])
    workflow.connect([(conform_T1, bet_T1, [('out_file', 'in_file')])])
    workflow.connect([(bet_T1, fast_segment, [("out_file", "in_files")])])
    workflow.connect([(fast_segment, affine_register,
                       [(('tissue_class_files', select_WM), 'reference')])])

    workflow.connect([(dtifit, threshold_FA, [('FA', 'in_file')])])
    workflow.connect([(threshold_FA, affine_register, [('out_file', 'in_file')
                                                       ])])

    workflow.connect([(affine_register, transform_FA, [('out_matrix_file',
                                                        'in_matrix_file')])])
    workflow.connect([(dtifit, transform_FA, [('FA', 'in_file')])])
    workflow.connect([(fast_segment, transform_FA,
                       [(('tissue_class_files', select_WM), 'reference')])])

    workflow.connect([(dtifit, register_tensor, [('tensor', 'in_file')])])
    workflow.connect([(bet_T1, register_tensor, [('out_file', 'ref_vol')])])
    workflow.connect([(affine_register, concat_affine_xform,
                       [('out_matrix_file', 'in_file')])])

    workflow.connect([(affine_register, register_tensor, [('out_matrix_file',
                                                           'affine_mat')])])
    workflow.connect([(register_tensor, decompose_tensor, [('out_file',
                                                            'in_file')])])

    workflow.connect([(fast_segment, scale_factor_workflow, [
        ("tissue_class_files", "inputnode.tissue_class_files")
    ])])
    workflow.connect([(decompose_tensor, scale_factor_workflow, [
        ('L1', 'inputnode.L1'),
        ('L2', 'inputnode.L2'),
        ('L3', 'inputnode.L3'),
    ])])

    workflow.connect([(scale_factor_workflow, conductivity_mapping, [
        ("calc_scale_factor.scale_factor", "eigenvalue_scaling_factor")
    ])])

    workflow.connect([(dtifit, diff_tensor_to_fsl_space, [("tensor", "in_file")
                                                          ])])
    workflow.connect([(concat_affine_xform, diff_tensor_to_fsl_space,
                       [("out_file", "affine_mat")])])
    workflow.connect([(inputnode, diff_tensor_to_fsl_space, [("t1_fsl_space",
                                                              "ref_vol")])])

    workflow.connect([(decompose_diff_tensor_fslspace,
                       add_conductivity_tensor_to_mesh, [("FA", "mask_file")])
                      ])

    workflow.connect([(inputnode, add_conductivity_tensor_to_mesh,
                       [("mesh_file", "mesh_file")])])
    workflow.connect([(add_conductivity_tensor_to_mesh, outputnode,
                       [("out_file", "mesh_file")])])

    workflow.connect([(diff_tensor_to_fsl_space,
                       decompose_diff_tensor_fslspace, [("out_file", "in_file")
                                                        ])])
    workflow.connect([(diff_tensor_to_fsl_space, conductivity_mapping,
                       [("out_file", "in_file")])])
    workflow.connect([(conductivity_mapping, decompose_conductivity,
                       [("out_file", "in_file")])])
    workflow.connect([(conductivity_mapping, add_conductivity_tensor_to_mesh,
                       [("out_file", "tensor_file")])])
    workflow.connect([(decompose_diff_tensor_fslspace, outputnode,
                       [("V1", "diff_V1")])])
    workflow.connect([(decompose_conductivity, outputnode, [("V1", "cond_V1")])
                      ])
    workflow.connect([(decompose_conductivity, outputnode,
                       [("MD", "mean_conductivity")])])
    workflow.connect([(transform_FA, outputnode, [("out_file", "fa_t1_space")])
                      ])
    return workflow