def MNI_reorient(structural_nifti_file, out_file):
    """This function swaps the dimensions of the file by doing 90, 180, 0r 270 degree
    rotations. The final product is in the RAS+ orientation (Right, Anterior, and Superior parts of the brain
    are the positive values).

    - in order to swap the dimensions, fsl.Reorient2Std calls fsl.SwapDimensions. In other words,
    it is a specified version of Reorient2Std. For more info on Reorient2Std, look at RPI_reorient.py


    input
    ------
    structural_nifti_file: nifti/nifti.gz file
    The original T1 weighted anatomical file

    output
    ------
    out_file: nifti.gz file
    an MNI reoriented image in the RAS+ orientation

    """

    MNI = fsl.Reorient2Std()
    MNI.inputs.in_file = structural_nifti_file
    MNI.inputs.out_file = out_file
    MNI_results = MNI.run()
    return MNI_results
    def make_segment(self):
        # Ref: http://nipype.readthedocs.io/en/0.12.1/interfaces/generated/nipype.interfaces.fsl.utils.html#reorient2std
        ro = Node(interface=fsl.Reorient2Std(), name='ro')

        # Ref: http://nipype.readthedocs.io/en/latest/interfaces/generated/interfaces.spm/preprocess.html#segment
        seg = Node(interface=spm.NewSegment(channel_info=(0.0001, 60, (True,
                                                                       True))),
                   name="seg")

        spm_tissues_split = Node(Function(['in_list'], ['gm', 'wm', 'csf'],
                                          self.spm_tissues),
                                 name='spm_tissues_split')

        gzip = Node(Function(['in_list'], ['out_list'], self.gzip_spm),
                    name='gzip')

        segment = Workflow(name='Segment', base_dir=self.temp_dir)

        gunzip = Node(interface=Gunzip(), name='gunzip')
        # for new segment
        segment.connect(ro, 'out_file', gunzip, 'in_file')
        segment.connect(gunzip, 'out_file', seg, 'channel_files')
        segment.connect(seg, 'native_class_images', spm_tissues_split,
                        'in_list')
        return segment
Ejemplo n.º 3
0
def reorient_img(in_file, out_dir):
    out_file = os.path.join(out_dir, 'T1w_reorient.nii.gz')
    # Ensure in standard orientation
    reorient = fsl.Reorient2Std()
    reorient.inputs.in_file = in_file
    reorient.inputs.out_file = out_file
    reorient.run()
Ejemplo n.º 4
0
def create_converter_diffusion_pipeline(working_dir,
                                        ds_dir,
                                        name='converter_diffusion'):
    # initiate workflow
    converter_wf = Workflow(name=name)
    converter_wf.base_dir = os.path.join(working_dir, 'LeiCA_resting')

    # set fsl output
    fsl.FSLCommand.set_default_output_type('NIFTI_GZ')

    # inputnode
    inputnode = Node(util.IdentityInterface(fields=['dMRI_dicom']),
                     name='inputnode')

    outputnode = Node(util.IdentityInterface(fields=['dMRI']),
                      name='outputnode')

    niftisink = Node(nio.DataSink(), name='niftisink')
    niftisink.inputs.base_directory = os.path.join(ds_dir, 'raw_niftis')

    #######

    converter_dMRI = Node(Dcm2nii(), name="converter_dMRI")
    converter_dMRI.inputs.gzip_output = True
    converter_dMRI.inputs.nii_output = True
    converter_dMRI.inputs.anonymize = False
    converter_dMRI.plugin_args = {'submit_specs': 'request_memory = 2000'}
    converter_wf.connect(inputnode, 'dMRI_dicom', converter_dMRI,
                         'source_names')

    dMRI_rename = Node(util.Rename(format_string='DTI_mx_137.nii.gz'),
                       name='dMRI_rename')
    converter_wf.connect(converter_dMRI, 'converted_files', dMRI_rename,
                         'in_file')

    bvecs_rename = Node(util.Rename(format_string='DTI_mx_137.bvecs'),
                        name='bvecs_rename')
    converter_wf.connect(converter_dMRI, 'bvecs', bvecs_rename, 'in_file')

    bvals_rename = Node(util.Rename(format_string='DTI_mx_137.bvals'),
                        name='bvals_rename')
    converter_wf.connect(converter_dMRI, "bvals", bvals_rename, 'in_file')

    # reorient to standard orientation
    reor_2_std = Node(fsl.Reorient2Std(), name='reor_2_std')
    converter_wf.connect(dMRI_rename, 'out_file', reor_2_std, 'in_file')
    converter_wf.connect(reor_2_std, 'out_file', outputnode, 'dMRI')

    # save original niftis
    converter_wf.connect(reor_2_std, 'out_file', niftisink, 'dMRI.@dwi')
    converter_wf.connect(bvals_rename, 'out_file', niftisink, 'dMRI.@bvals')
    converter_wf.connect(bvecs_rename, 'out_file', niftisink, 'dMRI.@bvecs')

    converter_wf.write_graph(dotfilename='converter_struct',
                             graph2use='flat',
                             format='pdf')
    return converter_wf
Ejemplo n.º 5
0
def results(cenc_participant_id,  cenc_participant_dir, cenc_freesurfer_dir,cenc_results_dir, verbose):

     util.mkcd_dir( [ cenc_results_dir ], True)

     files_to_convert = [ os.path.join( cenc_freesurfer_dir, cenc_participant_id, 'mri', 'nu.mgz'),
                          os.path.join( cenc_freesurfer_dir, cenc_participant_id, 'mri', 'aseg.mgz'),
                          os.path.join( cenc_freesurfer_dir, cenc_participant_id, 'mri', 'brainmask.mgz'),
                          os.path.join( cenc_freesurfer_dir, cenc_participant_id, 'mri', 'aparc.a2009s+aseg.mgz'),
                          os.path.join( cenc_freesurfer_dir, cenc_participant_id, 'mri', 'wmparc.mgz')
                          ]

     # Check if files exist

     print files_to_convert

     if util.check_files(files_to_convert, True) == False:
          sys.exit()

     # Create link to directory

     freesurfer_results_dir =  os.path.abspath(os.path.join( cenc_participant_dir, 'freesurfer','results'))

     if not os.path.exists(freesurfer_results_dir):
          util.force_symbolic_link( os.path.join( cenc_freesurfer_dir,  cenc_participant_id ), freesurfer_results_dir)

     # TODO use input node to run this instead of a loop. The trick part is to have the files named correctly. 

     for ii in files_to_convert:
          mc = fs.MRIConvert( in_file  = ii,
                              out_file = os.path.join( cenc_results_dir, str.replace( os.path.basename(ii),'.mgz','.nii.gz')),
                              out_type = 'niigz'
                              )
          mc.run()

          
          reorient = fsl.Reorient2Std( in_file = mc.inputs.out_file, out_file = mc.inputs.out_file)
          reorient.run()
     
     # Create final brain mask. 

     cenc.create_mask( os.path.join( cenc_results_dir, 'brainmask.nii.gz'),         
                       os.path.join( cenc_results_dir, 'aparc.a2009s+aseg.nii.gz'), 
                       os.path.join( cenc_results_dir, 'mask.nii.gz')
                       )

     # Extract labels for Further processing

     cenc_results_labels_dir = os.path.join(cenc_results_dir, 'labels')
     util.mkcd_dir( cenc_results_labels_dir, 'labels') )
Ejemplo n.º 6
0
def results(cenc_participant_id,  cenc_participant_dir, cenc_freesurfer_dir,cenc_results_dir, verbose):

     util.mkcd_dir( [ cenc_results_dir ], True)

     files_to_convert = [ os.path.join( cenc_freesurfer_dir, cenc_participant_id, 'mri', 'nu.mgz'),
                          os.path.join( cenc_freesurfer_dir, cenc_participant_id, 'mri', 'aseg.mgz'),
                          os.path.join( cenc_freesurfer_dir, cenc_participant_id, 'mri', 'brainmask.mgz'),
                          os.path.join( cenc_freesurfer_dir, cenc_participant_id, 'mri', 'aparc.a2009s+aseg.mgz'),
                          os.path.join( cenc_freesurfer_dir, cenc_participant_id, 'mri', 'wmparc.mgz')
                          ]

     # Check if files exist

     print files_to_convert

     if util.check_files(files_to_convert, True) == False:
          sys.exit()

     # Create link to directory

     freesurfer_results_dir =  os.path.abspath(os.path.join( cenc_participant_dir, 'freesurfer','results'))

     if not os.path.exists(freesurfer_results_dir):
          util.force_symbolic_link( os.path.join( cenc_freesurfer_dir,  cenc_participant_id ), freesurfer_results_dir)

     # TODO use input node to run this instead of a loop

     mc = Node( fs.MRIConvert( out_type = 'niigz'
                               ),
                name="mri_convert"
                )  
       
     mc.iterables = ( "in_file", files_to_convert )

     reorient = Node( fsl.Reorient2Std(), name="reorient" )

     workflow_convert = Workflow(name='cenc_freesurfer_nipype_workflow')
     workflow_convert.base_dir = cenc_results_dir
     
     workflow_convert.connect( [ (mc,       reorient, [('out_file', 'in_file')] )]
                               )    
     workflow_convert.run()
     
     # Create final brain mask. This takes forever. Speeding it up would be helpful. 

     cenc.create_mask( os.path.join( cenc_results_dir, 'brainmask.nii.gz'),         
                       os.path.join( cenc_results_dir, 'aparc.a2009s+aseg.nii.gz'), 
                       os.path.join( cenc_results_dir, 'mask.nii.gz')
                       )
def create_images_workflow():
    # Correct for the sphinx position and use reorient to standard.
    workflow = Workflow(name='minimal_proc')

    inputs = Node(IdentityInterface(fields=['images']), name="in")
    outputs = Node(IdentityInterface(fields=['images']), name="out")

    sphinx = MapNode(fs.MRIConvert(sphinx=True),
                     iterfield=['in_file'],
                     name='sphinx')

    workflow.connect(inputs, 'images', sphinx, 'in_file')

    ro = MapNode(fsl.Reorient2Std(), iterfield=['in_file'], name='ro')

    workflow.connect(sphinx, 'out_file', ro, 'in_file')
    workflow.connect(ro, 'out_file', outputs, 'images')

    return workflow
Ejemplo n.º 8
0
def create_converter_structural_pipeline(working_dir,
                                         ds_dir,
                                         name='converter_struct'):
    # initiate workflow
    converter_wf = Workflow(name=name)
    converter_wf.base_dir = os.path.join(working_dir, 'LeiCA_resting')

    # set fsl output
    fsl.FSLCommand.set_default_output_type('NIFTI_GZ')

    # inputnode
    inputnode = Node(util.IdentityInterface(fields=['t1w_dicom']),
                     name='inputnode')

    outputnode = Node(util.IdentityInterface(fields=['t1w']),
                      name='outputnode')

    niftisink = Node(nio.DataSink(), name='niftisink')
    niftisink.inputs.base_directory = os.path.join(ds_dir, 'raw_niftis')

    # convert to nifti
    # todo check if geometry bugs attac. use dcm2nii?
    converter_t1w = Node(DcmStack(embed_meta=True), name='converter_t1w')
    converter_t1w.plugin_args = {'submit_specs': 'request_memory = 2000'}
    converter_t1w.inputs.out_format = 't1w'

    converter_wf.connect(inputnode, 't1w_dicom', converter_t1w, 'dicom_files')

    # reorient to standard orientation
    reor_2_std = Node(fsl.Reorient2Std(), name='reor_2_std')
    converter_wf.connect(converter_t1w, 'out_file', reor_2_std, 'in_file')

    converter_wf.connect(reor_2_std, 'out_file', outputnode, 't1w')

    # save original niftis
    converter_wf.connect(reor_2_std, 'out_file', niftisink, 'sMRI')

    converter_wf.write_graph(dotfilename='converter_struct',
                             graph2use='flat',
                             format='pdf')
    return converter_wf
Ejemplo n.º 9
0
def nipype_reconall(t1path, t2path=None):
    splitpath = t1path.split(os.sep)

    # Reorientation using FSL
    reodir = os.path.join(BIDS_DATA_DIR, "derivatives",
                          "reorient_{0}".format(splitpath[-3]), splitpath[-4])
    if not os.path.isdir(reodir):
        os.makedirs(reodir)
    reopath = []
    for path in (t1path, t2path):
        if path is not None:
            reopath.append(os.path.join(reodir, os.path.basename(path)))
        else:
            reopath.append(None)
            continue
        reorient = fsl.Reorient2Std(in_file=path, out_file=reopath[-1])
        if PROCESS:
            reorient.run()
    t1path, t2path = reopath

    # Segmentation using FreeSurfer
    fsdir = os.path.join(BIDS_DATA_DIR, "derivatives",
                         "freesurfer_{0}".format(splitpath[-3]))
    if not os.path.isdir(fsdir):
        os.makedirs(fsdir)
    reconall = freesurfer.ReconAll(subject_id=splitpath[-4],
                                   directive="all",
                                   subjects_dir=fsdir,
                                   T1_files=t1path)
    if t2path is not None:
        reconall.inputs.T2_file = t2path
        reconall.inputs.use_T2 = True
    if PROCESS:
        reconall.run()

    return reconall.cmdline
Ejemplo n.º 10
0
def do_pipe3_projection(subject_ID,
                        freesurfer_dir,
                        workflow_dir,
                        output_dir,
                        tract_number,
                        use_sample=False):
    """
    Packages and Data Setup
    =======================
    Import necessary modules from nipype.
    """

    import nipype.interfaces.io as io  # Data i/o
    import nipype.interfaces.utility as util  # utility
    import nipype.pipeline.engine as pe  # pipeline engine
    import nipype.interfaces.fsl as fsl
    import nipype.interfaces.freesurfer as fsurf  # freesurfer
    import nipype.interfaces.ants as ants
    import os.path as op  # system functions

    from nipype.interfaces.utility import Function

    from dmri_pipe_aux import get_connectivity_matrix
    from dmri_pipe_aux import surf2file
    from dmri_pipe_aux import voxels2nii
    from dmri_pipe_aux import normalize_matrix
    from dmri_pipe_aux import interface2surf
    from dmri_pipe_aux import read_voxels
    from dmri_pipe_aux import downsample_matrix
    from dmri_pipe_aux import merge_matrices
    """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """
    Point to the freesurfer subjects directory (Recon-all must have been run on the subjects)
    """ """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """"""

    subjects_dir = op.abspath(freesurfer_dir)
    fsurf.FSCommand.set_default_subjects_dir(subjects_dir)
    fsl.FSLCommand.set_default_output_type('NIFTI')
    """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """
    define the workflow
    """ """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """"""

    dmripipeline = pe.Workflow(name='pipe3_projection')
    """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """
    Use datasource node to perform the actual data grabbing.
    Templates for the associated images are used to obtain the correct images.
    """ """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """"""

    data_template = subject_ID + "/%s/" + "%s" + "%s"

    info = dict(
        wm=[['fa_masking', subject_ID, '_mask_wm.nii']],
        seeds_left=[['fa_masking', subject_ID, '_interface_left_voxels.txt']],
        seeds_right=[['fa_masking', subject_ID,
                      '_interface_right_voxels.txt']],
        index_left=[['fa_masking', subject_ID, '_interface_left_index.nii']],
        index_right=[['fa_masking', subject_ID, '_interface_right_index.nii']],
        fa=[['fa_masking', subject_ID, '_fa_masked.nii']],
        t1=[['anatomy', subject_ID, '_t1_masked.nii']],
        inv_flirt_mat=[['anatomy', '', 'flirt_t1_2_fa_inv.mat']],
        warp=[['anatomy', '', 'ants_fa_2_regt1_Warp.nii.gz']])

    datasource = pe.Node(interface=io.DataGrabber(outfields=info.keys()),
                         name='datasource')
    datasource.inputs.template = data_template
    datasource.inputs.base_directory = output_dir
    datasource.inputs.template_args = info
    datasource.inputs.sort_filelist = True
    datasource.run_without_submitting = True

    tracts_left_source = pe.Node(
        interface=io.DataGrabber(outfields=['tracts_left']),
        name='tracts_left_source')
    tracts_left_source.inputs.template = subject_ID + '/raw_tracts/lh/probtract_*.nii'
    tracts_left_source.inputs.base_directory = output_dir
    tracts_left_source.inputs.sort_filelist = True
    tracts_left_source.run_without_submitting = True

    tracts_right_source = pe.Node(
        interface=io.DataGrabber(outfields=['tracts_right']),
        name='tracts_right_source')
    tracts_right_source.inputs.template = subject_ID + '/raw_tracts/rh/probtract_*.nii'
    tracts_right_source.inputs.base_directory = output_dir
    tracts_right_source.inputs.sort_filelist = True
    tracts_right_source.run_without_submitting = True
    """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """
    The input node declared here will be the main
    conduits for the raw data to the rest of the processing pipeline.
    """ """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """"""

    inputnode = pe.Node(interface=util.IdentityInterface(fields=[
        "wm", "seeds_left", "seeds_right", "index_left", "index_right", "fa",
        "t1", "inv_flirt_mat", "warp", "tracts_left", "tracts_right"
    ]),
                        name="inputnode")
    """
    read seed coordinates
    """

    interface_voxels_left = pe.Node(interface=Function(
        input_names=["seed_file", "use_sample"],
        output_names=["seed_list"],
        function=read_voxels),
                                    name='70_interface_voxels_left')
    interface_voxels_left.inputs.use_sample = use_sample
    dmripipeline.connect(inputnode, "seeds_left", interface_voxels_left,
                         "seed_file")

    interface_voxels_right = interface_voxels_left.clone(
        name='70_interface_voxels_right')
    dmripipeline.connect(inputnode, "seeds_right", interface_voxels_right,
                         "seed_file")
    """
    Get the direct connectivity matrix
    """

    connectivity_matrix = pe.Node(interface=Function(
        input_names=[
            "tract_list_left", "tract_list_right", "voxel_list_left",
            "voxel_list_right", "max_value"
        ],
        output_names=[
            "submatrix_left_left", "submatrix_left_right",
            "submatrix_right_left", "submatrix_right_right", "exclusion_list"
        ],
        function=get_connectivity_matrix),
                                  name='71_direct_connect_array')
    connectivity_matrix.inputs.max_value = tract_number
    connectivity_matrix.run_without_submitting = True
    #    connectivity_matrix.plugin_args={'override_specs': 'requirements = Machine == "kalifornien.cbs.mpg.de"'}
    dmripipeline.connect(inputnode, "tracts_left", connectivity_matrix,
                         "tract_list_left")
    dmripipeline.connect(inputnode, "tracts_right", connectivity_matrix,
                         "tract_list_right")
    dmripipeline.connect(interface_voxels_left, "seed_list",
                         connectivity_matrix, "voxel_list_left")
    dmripipeline.connect(interface_voxels_right, "seed_list",
                         connectivity_matrix, "voxel_list_right")

    tract_exclusion_mask = pe.Node(interface=Function(
        input_names=["voxel_list", "ref_image", "outfile"],
        output_names=["outfile"],
        function=voxels2nii),
                                   name='72_tract_exclusion_mask')
    tract_exclusion_mask.inputs.outfile = subject_ID + '_tractseed_exclusion_mask.nii'
    dmripipeline.connect(inputnode, "wm", tract_exclusion_mask, "ref_image")
    dmripipeline.connect(connectivity_matrix, "exclusion_list",
                         tract_exclusion_mask, "voxel_list")

    submatrix_left_left = pe.Node(interface=Function(
        input_names=["in_array", "max_value", "outfile_prefix"],
        output_names=[
            "mat_matrix_nat", "mat_matrix_log", "nii_matrix_nat",
            "nii_matrix_log"
        ],
        function=normalize_matrix),
                                  name='73_submatrix_left_left')
    submatrix_left_left.run_without_submitting = True
    submatrix_left_left.inputs.max_value = tract_number
    submatrix_left_left.inputs.outfile_prefix = 'directconnect_left_left'
    dmripipeline.connect(connectivity_matrix, "submatrix_left_left",
                         submatrix_left_left, "in_array")

    submatrix_left_right = submatrix_left_left.clone(
        name='73_submatrix_left_right')
    submatrix_left_right.inputs.outfile_prefix = 'directconnect_left_right'
    dmripipeline.connect(connectivity_matrix, "submatrix_left_right",
                         submatrix_left_right, "in_array")

    submatrix_right_left = submatrix_left_left.clone(
        name='73_submatrix_right_left')
    submatrix_right_left.inputs.outfile_prefix = 'directconnect_right_left'
    dmripipeline.connect(connectivity_matrix, "submatrix_right_left",
                         submatrix_right_left, "in_array")

    submatrix_right_right = submatrix_left_left.clone(
        name='73_submatrix_right_right')
    submatrix_right_right.inputs.outfile_prefix = 'directconnect_right_right'
    dmripipeline.connect(connectivity_matrix, "submatrix_right_right",
                         submatrix_right_right, "in_array")

    #     full_matrix_nat = pe.Node(interface=Function(input_names=["sm_left_left", "sm_left_right","sm_right_left", "sm_right_right", "out_filename"], output_names=["out_file"], function=merge_matrices), name='73_full_matrix_nat')
    #     full_matrix_nat.inputs.out_filename = 'directconnect_full_nat.mat'
    #     full_matrix_nat.run_without_submitting = True
    #     dmripipeline.connect(submatrix_left_left, "nii_matrix_nat", full_matrix_nat, "sm_left_left")
    #     dmripipeline.connect(submatrix_left_right, "nii_matrix_nat", full_matrix_nat, "sm_left_right")
    #     dmripipeline.connect(submatrix_right_left, "nii_matrix_nat", full_matrix_nat, "sm_right_left")
    #     dmripipeline.connect(submatrix_right_right, "nii_matrix_nat", full_matrix_nat, "sm_right_right")
    #
    #     full_matrix_log = full_matrix_nat.clone(name='73_full_matrix_log')
    #     full_matrix_log.inputs.out_filename = 'directconnect_full_log.mat'
    #     full_matrix_log.run_without_submitting = True
    #     dmripipeline.connect(submatrix_left_left, "nii_matrix_log", full_matrix_log, "sm_left_left")
    #     dmripipeline.connect(submatrix_left_right, "nii_matrix_log", full_matrix_log, "sm_left_right")
    #     dmripipeline.connect(submatrix_right_left, "nii_matrix_log", full_matrix_log, "sm_right_left")
    #     dmripipeline.connect(submatrix_right_right, "nii_matrix_log", full_matrix_log, "sm_right_right")
    """
    # invert and binarize tract exclusion mask and remove those voxels from the index interfaces
    """
    tract_denoise_mask = pe.Node(interface=fsl.maths.MathsCommand(),
                                 name='74_tract_denoise_mask')
    tract_denoise_mask.inputs.args = '-binv'
    tract_denoise_mask.run_without_submitting = True
    dmripipeline.connect(tract_exclusion_mask, "outfile", tract_denoise_mask,
                         "in_file")

    index_pruned_left = pe.Node(interface=fsl.maths.ApplyMask(),
                                name='75_interface_pruned_left')
    index_pruned_left.inputs.out_file = subject_ID + '_interface_pruned_left.nii'
    index_pruned_left.run_without_submitting = True
    dmripipeline.connect(inputnode, "index_left", index_pruned_left, "in_file")
    dmripipeline.connect(tract_denoise_mask, "out_file", index_pruned_left,
                         "mask_file")

    index_pruned_right = index_pruned_left.clone(
        name='75_interface_pruned_right')
    index_pruned_right.inputs.out_file = subject_ID + '_interface_pruned_right.nii'
    dmripipeline.connect(inputnode, "index_right", index_pruned_right,
                         "in_file")
    dmripipeline.connect(tract_denoise_mask, "out_file", index_pruned_right,
                         "mask_file")
    """
    # warp index image to t1 space
    """
    index_warped_2_t1_left = pe.Node(interface=ants.WarpImageMultiTransform(),
                                     name='76_index_warped_2_t1_left')
    index_warped_2_t1_left.inputs.use_nearest = True
    index_warped_2_t1_left.run_without_submitting = True
    dmripipeline.connect([(index_pruned_left, index_warped_2_t1_left,
                           [('out_file', 'input_image')])])
    dmripipeline.connect([(inputnode, index_warped_2_t1_left,
                           [('fa', 'reference_image')])])
    dmripipeline.connect([(inputnode, index_warped_2_t1_left,
                           [('warp', 'transformation_series')])])

    index_warped_2_t1_right = index_warped_2_t1_left.clone(
        name='76_index_warped_2_t1_right')
    dmripipeline.connect([(index_pruned_right, index_warped_2_t1_right,
                           [('out_file', 'input_image')])])
    dmripipeline.connect([(inputnode, index_warped_2_t1_right,
                           [('fa', 'reference_image')])])
    dmripipeline.connect([(inputnode, index_warped_2_t1_right,
                           [('warp', 'transformation_series')])])

    index_final_2_t1_left = pe.Node(interface=fsl.ApplyXfm(),
                                    name='77_index_final_2_t1_left')
    index_final_2_t1_left.inputs.apply_xfm = True
    index_final_2_t1_left.run_without_submitting = True
    index_final_2_t1_left.inputs.interp = 'nearestneighbour'
    index_final_2_t1_left.inputs.out_file = subject_ID + '_index_seedt1_left.nii'
    dmripipeline.connect([(index_warped_2_t1_left, index_final_2_t1_left,
                           [("output_image", "in_file")])])
    dmripipeline.connect([(inputnode, index_final_2_t1_left,
                           [("inv_flirt_mat", "in_matrix_file")])])
    dmripipeline.connect([(inputnode, index_final_2_t1_left, [("t1",
                                                               "reference")])])

    index_final_2_t1_right = index_final_2_t1_left.clone(
        name='77_index_final_2_t1_right')
    index_final_2_t1_right.inputs.out_file = subject_ID + '_index_seedt1_right.nii'
    dmripipeline.connect([(index_warped_2_t1_right, index_final_2_t1_right,
                           [("output_image", "in_file")])])
    dmripipeline.connect([(inputnode, index_final_2_t1_right,
                           [("inv_flirt_mat", "in_matrix_file")])])
    dmripipeline.connect([(inputnode, index_final_2_t1_right,
                           [("t1", "reference")])])
    """
    extra processing
    """

    index_vol2surf_left = pe.Node(interface=fsurf.SampleToSurface(),
                                  name='78_index_vol2surf_left')
    index_vol2surf_left.inputs.hemi = 'lh'
    index_vol2surf_left.inputs.subject_id = subject_ID
    index_vol2surf_left.inputs.reg_header = True
    index_vol2surf_left.inputs.interp_method = 'nearest'
    index_vol2surf_left.inputs.sampling_method = 'point'
    index_vol2surf_left.inputs.sampling_range = 0
    index_vol2surf_left.inputs.sampling_units = 'frac'
    index_vol2surf_left.inputs.surface = 'orig'
    #index_vol2surf_left.inputs.cortex_mask = True
    index_vol2surf_left.inputs.terminal_output = 'file'
    index_vol2surf_left.inputs.out_file = subject_ID + '_index_seedt1_2surf_left.mgz'
    index_vol2surf_left.run_without_submitting = True
    dmripipeline.connect([(index_final_2_t1_left, index_vol2surf_left,
                           [('out_file', 'source_file')])])

    index_vol2surf_right = index_vol2surf_left.clone(
        name='78_index_vol2surf_right')
    index_vol2surf_right.inputs.hemi = 'rh'
    index_vol2surf_right.inputs.out_file = subject_ID + '_index_seedt1_2surf_right.mgz'
    dmripipeline.connect([(index_final_2_t1_right, index_vol2surf_right,
                           [('out_file', 'source_file')])])

    index_2_t1_reorient_left = pe.Node(interface=fsl.Reorient2Std(),
                                       name='79_next_2_t1_reorient_left')
    index_2_t1_reorient_left.inputs.out_file = subject_ID + '_index_seedt1_reorient_left.nii'
    index_2_t1_reorient_left.run_without_submitting = True
    dmripipeline.connect(index_final_2_t1_left, 'out_file',
                         index_2_t1_reorient_left, 'in_file')

    index_2_t1_reorient_right = index_2_t1_reorient_left.clone(
        name='79_next_2_t1_reorient_right')
    index_2_t1_reorient_right.inputs.out_file = subject_ID + '_index_seedt1_reorient_right.nii'
    dmripipeline.connect(index_final_2_t1_right, 'out_file',
                         index_2_t1_reorient_right, 'in_file')

    index_interface2surf_left = pe.Node(interface=Function(
        input_names=[
            "interface_image", "surface_file", "cortex_label", "ref_mgz",
            "out_file"
        ],
        output_names=["out_file"],
        function=interface2surf),
                                        name='80_index_interface2surf_left')
    index_interface2surf_left.inputs.surface_file = subjects_dir + '/' + subject_ID + '/surf/lh.orig'
    index_interface2surf_left.inputs.cortex_label = subjects_dir + '/' + subject_ID + '/label/lh.cortex.label'
    index_interface2surf_left.inputs.out_file = subject_ID + '_index_seedt1_2surf_left.mgz'
    dmripipeline.connect(index_2_t1_reorient_left, 'out_file',
                         index_interface2surf_left, 'interface_image')
    dmripipeline.connect(index_vol2surf_left, 'out_file',
                         index_interface2surf_left, 'ref_mgz')

    index_interface2surf_right = index_interface2surf_left.clone(
        name='80_index_interface2surf_right')
    index_interface2surf_right.inputs.surface_file = subjects_dir + '/' + subject_ID + '/surf/rh.orig'
    index_interface2surf_right.inputs.cortex_label = subjects_dir + '/' + subject_ID + '/label/rh.cortex.label'
    index_interface2surf_right.inputs.out_file = subject_ID + '_index_seedt1_2surf_right.mgz'
    dmripipeline.connect(index_2_t1_reorient_right, 'out_file',
                         index_interface2surf_right, 'interface_image')
    dmripipeline.connect(index_vol2surf_right, 'out_file',
                         index_interface2surf_right, 'ref_mgz')

    fs_indexlist_left = pe.Node(interface=Function(
        input_names=["in_surface_values", "cortex_label", "out_file"],
        output_names=["out_file"],
        function=surf2file),
                                name='81_index_fsnative_left')
    fs_indexlist_left.inputs.cortex_label = op.join(
        freesurfer_dir, subject_ID + '/label/lh.cortex.label')
    fs_indexlist_left.inputs.out_file = subject_ID + '_seed_index_fsnative_left.txt'
    fs_indexlist_left.run_without_submitting = True
    dmripipeline.connect([(index_interface2surf_left, fs_indexlist_left,
                           [("out_file", "in_surface_values")])])

    fs_indexlist_right = fs_indexlist_left.clone(
        name='81_index_fsnative_right')
    fs_indexlist_right.inputs.cortex_label = op.join(
        freesurfer_dir, subject_ID + '/label/rh.cortex.label')
    fs_indexlist_right.inputs.out_file = subject_ID + '_seed_index_fsnative_right.txt'
    dmripipeline.connect([(index_interface2surf_right, fs_indexlist_right,
                           [("out_file", "in_surface_values")])])
    """""" """""" """""" """""" """
    """ """""" """""" """""" """"""

    index_fsaverage5_left = pe.Node(interface=fsurf.SurfaceTransform(),
                                    name='81_index_fsaverage5_left')
    index_fsaverage5_left.inputs.hemi = 'lh'
    index_fsaverage5_left.inputs.source_subject = subject_ID
    index_fsaverage5_left.inputs.target_subject = 'fsaverage5'
    index_fsaverage5_left.inputs.args = '--mapmethod nnf --label-src lh.cortex.label --label-trg lh.cortex.label'
    index_fsaverage5_left.inputs.out_file = subject_ID + '_index_seedt1_fsaverage5_left.mgz'
    #index_fsaverage5_left.run_without_submitting = True
    dmripipeline.connect([(index_interface2surf_left, index_fsaverage5_left,
                           [('out_file', 'source_file')])])

    index_fsaverage5_right = index_fsaverage5_left.clone(
        name='81_index_fsaverage5_right')
    index_fsaverage5_right.inputs.hemi = 'rh'
    index_fsaverage5_left.inputs.args = '--mapmethod nnf --label-src rh.cortex.label --label-trg rh.cortex.label'
    index_fsaverage5_right.inputs.out_file = subject_ID + '_index_seedt1_fsaverage5_right.mgz'
    dmripipeline.connect([(index_interface2surf_right, index_fsaverage5_right,
                           [('out_file', 'source_file')])])

    fs5_indexlist_left = pe.Node(interface=Function(
        input_names=["in_surface_values", "cortex_label", "out_file"],
        output_names=["out_file"],
        function=surf2file),
                                 name='82_index_fsav5_left')
    fs5_indexlist_left.inputs.cortex_label = op.join(
        freesurfer_dir, 'fsaverage5/label/lh.cortex.label')
    fs5_indexlist_left.inputs.out_file = subject_ID + '_seed_index_fs5_left.txt'
    #fs5_indexlist_left.run_without_submitting = True
    dmripipeline.connect([(index_fsaverage5_left, fs5_indexlist_left,
                           [("out_file", "in_surface_values")])])

    fs5_indexlist_right = fs5_indexlist_left.clone(name='82_index_fsav5_right')
    fs5_indexlist_right.inputs.cortex_label = op.join(
        freesurfer_dir, 'fsaverage5/label/rh.cortex.label')
    fs5_indexlist_right.inputs.out_file = subject_ID + '_seed_index_fs5_right.txt'
    dmripipeline.connect([(index_fsaverage5_right, fs5_indexlist_right,
                           [("out_file", "in_surface_values")])])

    index_fsaverage4_left = pe.Node(interface=fsurf.SurfaceTransform(),
                                    name='81_index_fsaverage4_left')
    index_fsaverage4_left.inputs.hemi = 'lh'
    index_fsaverage4_left.inputs.source_subject = subject_ID
    index_fsaverage4_left.inputs.target_subject = 'fsaverage4'
    index_fsaverage4_left.inputs.args = '--mapmethod nnf --label-src lh.cortex.label --label-trg lh.cortex.label'
    index_fsaverage4_left.inputs.out_file = subject_ID + '_index_seedt1_fsaverage4_left.mgz'
    #index_fsaverage4_left.run_without_submitting = True
    dmripipeline.connect([(index_interface2surf_left, index_fsaverage4_left,
                           [('out_file', 'source_file')])])

    index_fsaverage4_right = index_fsaverage4_left.clone(
        name='81_index_fsaverage4_right')
    index_fsaverage4_right.inputs.hemi = 'rh'
    index_fsaverage4_left.inputs.args = '--mapmethod nnf --label-src rh.cortex.label --label-trg rh.cortex.label'
    index_fsaverage4_right.inputs.out_file = subject_ID + '_index_seedt1_fsaverage4_right.mgz'
    dmripipeline.connect([(index_interface2surf_right, index_fsaverage4_right,
                           [('out_file', 'source_file')])])

    fs4_indexlist_left = pe.Node(interface=Function(
        input_names=["in_surface_values", "cortex_label", "out_file"],
        output_names=["out_file"],
        function=surf2file),
                                 name='82_index_fsav4_left')
    fs4_indexlist_left.inputs.cortex_label = op.join(
        freesurfer_dir, 'fsaverage4/label/lh.cortex.label')
    fs4_indexlist_left.inputs.out_file = subject_ID + '_seed_index_fs4_left.txt'
    #fs4_indexlist_left.run_without_submitting = True
    dmripipeline.connect([(index_fsaverage4_left, fs4_indexlist_left,
                           [("out_file", "in_surface_values")])])

    fs4_indexlist_right = fs4_indexlist_left.clone(name='82_index_fsav4_right')
    fs4_indexlist_right.inputs.cortex_label = op.join(
        freesurfer_dir, 'fsaverage4/label/rh.cortex.label')
    fs4_indexlist_right.inputs.out_file = subject_ID + '_seed_index_fs4_right.txt'
    dmripipeline.connect([(index_fsaverage4_right, fs4_indexlist_right,
                           [("out_file", "in_surface_values")])])
    """
    downsample matrices according to fsaverage projections
    """
    if (not use_sample):
        connect_mat_fs4_nat_left_left = pe.Node(
            interface=Function(input_names=[
                "index_row_file", "index_col_file", "matrix_file",
                "out_prefix", "dist2sim"
            ],
                               output_names=["out_mat", "out_nii"],
                               function=downsample_matrix),
            name='83_connect_mat_fs4_nat_left_left')
        connect_mat_fs4_nat_left_left.inputs.out_prefix = subject_ID + '_connect_fs4_nat_left_left'
        connect_mat_fs4_nat_left_left.inputs.dist2sim = False
        dmripipeline.connect(fs4_indexlist_left, "out_file",
                             connect_mat_fs4_nat_left_left, "index_row_file")
        dmripipeline.connect(fs4_indexlist_left, "out_file",
                             connect_mat_fs4_nat_left_left, "index_col_file")
        dmripipeline.connect(submatrix_left_left, "mat_matrix_nat",
                             connect_mat_fs4_nat_left_left, "matrix_file")

        connect_mat_fs4_nat_left_right = connect_mat_fs4_nat_left_left.clone(
            name='83_connect_mat_fs4_nat_left_right')
        connect_mat_fs4_nat_left_right.inputs.out_prefix = subject_ID + '_connect_fs4_nat_left_right'
        dmripipeline.connect(fs4_indexlist_left, "out_file",
                             connect_mat_fs4_nat_left_right, "index_row_file")
        dmripipeline.connect(fs4_indexlist_right, "out_file",
                             connect_mat_fs4_nat_left_right, "index_col_file")
        dmripipeline.connect(submatrix_left_right, "mat_matrix_nat",
                             connect_mat_fs4_nat_left_right, "matrix_file")

        connect_mat_fs4_nat_right_left = connect_mat_fs4_nat_left_left.clone(
            name='83_connect_mat_fs4_nat_right_left')
        connect_mat_fs4_nat_right_left.inputs.out_prefix = subject_ID + '_connect_fs4_nat_right_left'
        dmripipeline.connect(fs4_indexlist_right, "out_file",
                             connect_mat_fs4_nat_right_left, "index_row_file")
        dmripipeline.connect(fs4_indexlist_left, "out_file",
                             connect_mat_fs4_nat_right_left, "index_col_file")
        dmripipeline.connect(submatrix_right_left, "mat_matrix_nat",
                             connect_mat_fs4_nat_right_left, "matrix_file")

        connect_mat_fs4_nat_right_right = connect_mat_fs4_nat_left_left.clone(
            name='83_connect_mat_fs4_nat_right_right')
        connect_mat_fs4_nat_right_right.inputs.out_prefix = subject_ID + '_connect_fs4_nat_right_right'
        dmripipeline.connect(fs4_indexlist_right, "out_file",
                             connect_mat_fs4_nat_right_right, "index_row_file")
        dmripipeline.connect(fs4_indexlist_right, "out_file",
                             connect_mat_fs4_nat_right_right, "index_col_file")
        dmripipeline.connect(submatrix_right_right, "mat_matrix_nat",
                             connect_mat_fs4_nat_right_right, "matrix_file")

        connect_mat_fs4_log_left_left = connect_mat_fs4_nat_left_left.clone(
            name='83_connect_mat_fs4_log_left_left')
        connect_mat_fs4_log_left_left.inputs.out_prefix = subject_ID + '_connect_fs4_log_left_left'
        dmripipeline.connect(fs4_indexlist_left, "out_file",
                             connect_mat_fs4_log_left_left, "index_row_file")
        dmripipeline.connect(fs4_indexlist_left, "out_file",
                             connect_mat_fs4_log_left_left, "index_col_file")
        dmripipeline.connect(submatrix_left_left, "mat_matrix_log",
                             connect_mat_fs4_log_left_left, "matrix_file")

        connect_mat_fs4_log_left_right = connect_mat_fs4_log_left_left.clone(
            name='83_connect_mat_fs4_log_left_right')
        connect_mat_fs4_log_left_right.inputs.out_prefix = subject_ID + '_connect_fs4_log_left_right'
        dmripipeline.connect(fs4_indexlist_left, "out_file",
                             connect_mat_fs4_log_left_right, "index_row_file")
        dmripipeline.connect(fs4_indexlist_right, "out_file",
                             connect_mat_fs4_log_left_right, "index_col_file")
        dmripipeline.connect(submatrix_left_right, "mat_matrix_log",
                             connect_mat_fs4_log_left_right, "matrix_file")

        connect_mat_fs4_log_right_left = connect_mat_fs4_log_left_left.clone(
            name='83_connect_mat_fs4_log_right_left')
        connect_mat_fs4_log_right_left.inputs.out_prefix = subject_ID + '_connect_fs4_log_right_left'
        dmripipeline.connect(fs4_indexlist_right, "out_file",
                             connect_mat_fs4_log_right_left, "index_row_file")
        dmripipeline.connect(fs4_indexlist_left, "out_file",
                             connect_mat_fs4_log_right_left, "index_col_file")
        dmripipeline.connect(submatrix_right_left, "mat_matrix_log",
                             connect_mat_fs4_log_right_left, "matrix_file")

        connect_mat_fs4_log_right_right = connect_mat_fs4_log_left_left.clone(
            name='83_connect_mat_fs4_log_right_right')
        connect_mat_fs4_log_right_right.inputs.out_prefix = subject_ID + '_connect_fs4_log_right_right'
        dmripipeline.connect(fs4_indexlist_right, "out_file",
                             connect_mat_fs4_log_right_right, "index_row_file")
        dmripipeline.connect(fs4_indexlist_right, "out_file",
                             connect_mat_fs4_log_right_right, "index_col_file")
        dmripipeline.connect(submatrix_right_right, "mat_matrix_log",
                             connect_mat_fs4_log_right_right, "matrix_file")

        #         connect_mat_fs4_nat_full = pe.Node(interface=Function(input_names=["sm_left_left", "sm_left_right","sm_right_left", "sm_right_right", "out_filename"], output_names=["out_file"], function=merge_matrices), name='83_connect_mat_fs4_nat_full')
        #         connect_mat_fs4_nat_full.inputs.out_filename = subject_ID + '_connect_fs4_nat_full.mat'
        #         connect_mat_fs4_nat_full.run_without_submitting = True
        #         dmripipeline.connect(connect_mat_fs4_nat_left_left, "out_nii", connect_mat_fs4_nat_full, "sm_left_left")
        #         dmripipeline.connect(connect_mat_fs4_nat_left_right, "out_nii", connect_mat_fs4_nat_full, "sm_left_right")
        #         dmripipeline.connect(connect_mat_fs4_nat_right_left, "out_nii", connect_mat_fs4_nat_full, "sm_right_left")
        #         dmripipeline.connect(connect_mat_fs4_nat_right_right, "out_nii", connect_mat_fs4_nat_full, "sm_right_right")
        #
        #         connect_mat_fs4_log_full = connect_mat_fs4_nat_full.clone(name='83_connect_mat_fs4_log_full')
        #         connect_mat_fs4_log_full.inputs.outfile_prefix = subject_ID + '_connect_fs4_log_full.mat'
        #         connect_mat_fs4_log_full.run_without_submitting = True
        #         dmripipeline.connect(connect_mat_fs4_log_left_left, "out_nii", connect_mat_fs4_log_full, "sm_left_left")
        #         dmripipeline.connect(connect_mat_fs4_log_left_right, "out_nii", connect_mat_fs4_log_full, "sm_left_right")
        #         dmripipeline.connect(connect_mat_fs4_log_right_left, "out_nii", connect_mat_fs4_log_full, "sm_right_left")
        #         dmripipeline.connect(connect_mat_fs4_log_right_right, "out_nii", connect_mat_fs4_log_full, "sm_right_right")

        connect_mat_fs5_nat_left_left = connect_mat_fs4_nat_left_left.clone(
            name='83_connect_mat_fs5_nat_left_left')
        connect_mat_fs5_nat_left_left.inputs.out_prefix = subject_ID + '_connect_fs5_nat_left_left'
        dmripipeline.connect(fs5_indexlist_left, "out_file",
                             connect_mat_fs5_nat_left_left, "index_row_file")
        dmripipeline.connect(fs5_indexlist_left, "out_file",
                             connect_mat_fs5_nat_left_left, "index_col_file")
        dmripipeline.connect(submatrix_left_left, "mat_matrix_nat",
                             connect_mat_fs5_nat_left_left, "matrix_file")

        connect_mat_fs5_nat_left_right = connect_mat_fs5_nat_left_left.clone(
            name='83_connect_mat_fs5_nat_left_right')
        connect_mat_fs5_nat_left_right.inputs.out_prefix = subject_ID + '_connect_fs5_nat_left_right'
        dmripipeline.connect(fs5_indexlist_left, "out_file",
                             connect_mat_fs5_nat_left_right, "index_row_file")
        dmripipeline.connect(fs5_indexlist_right, "out_file",
                             connect_mat_fs5_nat_left_right, "index_col_file")
        dmripipeline.connect(submatrix_left_right, "mat_matrix_nat",
                             connect_mat_fs5_nat_left_right, "matrix_file")

        connect_mat_fs5_nat_right_left = connect_mat_fs5_nat_left_left.clone(
            name='83_connect_mat_fs5_nat_right_left')
        connect_mat_fs5_nat_right_left.inputs.out_prefix = subject_ID + '_connect_fs5_nat_right_left'
        dmripipeline.connect(fs5_indexlist_right, "out_file",
                             connect_mat_fs5_nat_right_left, "index_row_file")
        dmripipeline.connect(fs5_indexlist_left, "out_file",
                             connect_mat_fs5_nat_right_left, "index_col_file")
        dmripipeline.connect(submatrix_right_left, "mat_matrix_nat",
                             connect_mat_fs5_nat_right_left, "matrix_file")

        connect_mat_fs5_nat_right_right = connect_mat_fs5_nat_left_left.clone(
            name='83_connect_mat_fs5_nat_right_right')
        connect_mat_fs5_nat_right_right.inputs.out_prefix = subject_ID + '_connect_fs5_nat_right_right'
        dmripipeline.connect(fs5_indexlist_right, "out_file",
                             connect_mat_fs5_nat_right_right, "index_row_file")
        dmripipeline.connect(fs5_indexlist_right, "out_file",
                             connect_mat_fs5_nat_right_right, "index_col_file")
        dmripipeline.connect(submatrix_right_right, "mat_matrix_nat",
                             connect_mat_fs5_nat_right_right, "matrix_file")

        connect_mat_fs5_log_left_left = connect_mat_fs5_nat_left_left.clone(
            name='83_connect_mat_fs5_log_left_left')
        connect_mat_fs5_log_left_left.inputs.out_prefix = subject_ID + '_connect_fs5_log_left_left'
        dmripipeline.connect(fs5_indexlist_left, "out_file",
                             connect_mat_fs5_log_left_left, "index_row_file")
        dmripipeline.connect(fs5_indexlist_left, "out_file",
                             connect_mat_fs5_log_left_left, "index_col_file")
        dmripipeline.connect(submatrix_left_left, "mat_matrix_log",
                             connect_mat_fs5_log_left_left, "matrix_file")

        connect_mat_fs5_log_left_right = connect_mat_fs5_log_left_left.clone(
            name='83_connect_mat_fs5_log_left_right')
        connect_mat_fs5_log_left_right.inputs.out_prefix = subject_ID + '_connect_fs5_log_left_right'
        dmripipeline.connect(fs5_indexlist_left, "out_file",
                             connect_mat_fs5_log_left_right, "index_row_file")
        dmripipeline.connect(fs5_indexlist_right, "out_file",
                             connect_mat_fs5_log_left_right, "index_col_file")
        dmripipeline.connect(submatrix_left_right, "mat_matrix_log",
                             connect_mat_fs5_log_left_right, "matrix_file")

        connect_mat_fs5_log_right_left = connect_mat_fs5_log_left_left.clone(
            name='83_connect_mat_fs5_log_right_left')
        connect_mat_fs5_log_right_left.inputs.out_prefix = subject_ID + '_connect_fs5_log_right_left'
        dmripipeline.connect(fs5_indexlist_right, "out_file",
                             connect_mat_fs5_log_right_left, "index_row_file")
        dmripipeline.connect(fs5_indexlist_left, "out_file",
                             connect_mat_fs5_log_right_left, "index_col_file")
        dmripipeline.connect(submatrix_right_left, "mat_matrix_log",
                             connect_mat_fs5_log_right_left, "matrix_file")

        connect_mat_fs5_log_right_right = connect_mat_fs5_log_left_left.clone(
            name='83_connect_mat_fs5_log_right_right')
        connect_mat_fs5_log_right_right.inputs.out_prefix = subject_ID + '_connect_fs5_log_right_right'
        dmripipeline.connect(fs5_indexlist_right, "out_file",
                             connect_mat_fs5_log_right_right, "index_row_file")
        dmripipeline.connect(fs5_indexlist_right, "out_file",
                             connect_mat_fs5_log_right_right, "index_col_file")
        dmripipeline.connect(submatrix_right_right, "mat_matrix_log",
                             connect_mat_fs5_log_right_right, "matrix_file")

#         connect_mat_fs5_nat_full = connect_mat_fs4_nat_full.clone(name='83_connect_mat_fs5_nat_full')
#         connect_mat_fs5_nat_full.inputs.outfile_prefix = subject_ID + '_connect_fs5_nat_full.mat'
#         connect_mat_fs5_nat_full.run_without_submitting = True
#         dmripipeline.connect(connect_mat_fs5_nat_left_left, "out_nii", connect_mat_fs5_nat_full, "sm_left_left")
#         dmripipeline.connect(connect_mat_fs5_nat_left_right, "out_nii", connect_mat_fs5_nat_full, "sm_left_right")
#         dmripipeline.connect(connect_mat_fs5_nat_right_left, "out_nii", connect_mat_fs5_nat_full, "sm_right_left")
#         dmripipeline.connect(connect_mat_fs5_nat_right_right, "out_nii", connect_mat_fs5_nat_full, "sm_right_right")
#
#         connect_mat_fs5_log_full = connect_mat_fs5_nat_full.clone(name='83_connect_mat_fs5_log_full')
#         connect_mat_fs5_log_full.inputs.out_filename = subject_ID + '_connect_fs5_log_full.mat'
#         connect_mat_fs5_log_full.run_without_submitting = True
#         dmripipeline.connect(connect_mat_fs5_log_left_left, "out_nii", connect_mat_fs5_log_full, "sm_left_left")
#         dmripipeline.connect(connect_mat_fs5_log_left_right, "out_nii", connect_mat_fs5_log_full, "sm_left_right")
#         dmripipeline.connect(connect_mat_fs5_log_right_left, "out_nii", connect_mat_fs5_log_full, "sm_right_left")
#         dmripipeline.connect(connect_mat_fs5_log_right_right, "out_nii", connect_mat_fs5_log_full, "sm_right_right")
#
    """
    use a sink to save outputs
    """

    datasink = pe.Node(io.DataSink(), name='99_datasink')
    datasink.inputs.base_directory = output_dir
    datasink.inputs.container = subject_ID
    datasink.inputs.parameterization = True
    #datasink.run_without_submitting = True

    dmripipeline.connect(index_pruned_left, 'out_file', datasink,
                         'interface_index.@3')
    dmripipeline.connect(index_pruned_right, 'out_file', datasink,
                         'interface_index.@4')
    dmripipeline.connect(index_final_2_t1_left, 'out_file', datasink,
                         'interface_index.@5')
    dmripipeline.connect(index_final_2_t1_right, 'out_file', datasink,
                         'interface_index.@6')
    dmripipeline.connect(index_interface2surf_left, 'out_file', datasink,
                         'interface_index.@7')
    dmripipeline.connect(index_interface2surf_right, 'out_file', datasink,
                         'interface_index.@8')
    dmripipeline.connect(index_fsaverage5_left, 'out_file', datasink,
                         'interface_index.@9')
    dmripipeline.connect(index_fsaverage5_right, 'out_file', datasink,
                         'interface_index.@10')
    dmripipeline.connect(fs5_indexlist_left, 'out_file', datasink,
                         'interface_index.@11')
    dmripipeline.connect(fs5_indexlist_right, 'out_file', datasink,
                         'interface_index.@12')
    dmripipeline.connect(index_fsaverage4_left, 'out_file', datasink,
                         'interface_index.@13')
    dmripipeline.connect(index_fsaverage4_right, 'out_file', datasink,
                         'interface_index.@14')
    dmripipeline.connect(fs4_indexlist_left, 'out_file', datasink,
                         'interface_index.@15')
    dmripipeline.connect(fs4_indexlist_right, 'out_file', datasink,
                         'interface_index.@16')
    dmripipeline.connect(fs_indexlist_left, 'out_file', datasink,
                         'interface_index.@17')
    dmripipeline.connect(fs_indexlist_right, 'out_file', datasink,
                         'interface_index.@18')
    dmripipeline.connect(tract_exclusion_mask, 'outfile', datasink,
                         'interface_index.@19')

    #    dmripipeline.connect(submatrix_left_left, 'mat_matrix_nat', datasink, 'connect_matrix.native.mat')
    #    dmripipeline.connect(submatrix_left_left, 'mat_matrix_log', datasink, 'connect_matrix.native.mat.@2')
    dmripipeline.connect(submatrix_left_left, 'nii_matrix_nat', datasink,
                         'connect_matrix.native.@3')
    dmripipeline.connect(submatrix_left_left, 'nii_matrix_log', datasink,
                         'connect_matrix.native.@4')
    #    dmripipeline.connect(submatrix_right_right, 'mat_matrix_nat', datasink, 'connect_matrix.native.mat.@5')
    #    dmripipeline.connect(submatrix_right_right, 'mat_matrix_log', datasink, 'connect_matrix.native.mat.@6')
    dmripipeline.connect(submatrix_right_right, 'nii_matrix_nat', datasink,
                         'connect_matrix.native.@7')
    dmripipeline.connect(submatrix_right_right, 'nii_matrix_log', datasink,
                         'connect_matrix.native.@8')
    #    dmripipeline.connect(submatrix_left_right, 'mat_matrix_nat', datasink, 'connect_matrix.native.mat')
    #    dmripipeline.connect(submatrix_left_right, 'mat_matrix_log', datasink, 'connect_matrix.native.mat.@2')
    dmripipeline.connect(submatrix_left_right, 'nii_matrix_nat', datasink,
                         'connect_matrix.native.@9')
    dmripipeline.connect(submatrix_left_right, 'nii_matrix_log', datasink,
                         'connect_matrix.native.@10')
    #    dmripipeline.connect(submatrix_right_left, 'mat_matrix_nat', datasink, 'connect_matrix.native.mat')
    #    dmripipeline.connect(submatrix_right_left, 'mat_matrix_log', datasink, 'connect_matrix.native.mat.@2')
    dmripipeline.connect(submatrix_right_left, 'nii_matrix_nat', datasink,
                         'connect_matrix.native.@11')
    dmripipeline.connect(submatrix_right_left, 'nii_matrix_log', datasink,
                         'connect_matrix.native.@12')

    #     dmripipeline.connect(full_matrix_nat, 'out_file', datasink, 'connect_matrix.native.@9')
    #     dmripipeline.connect(full_matrix_log, 'out_file', datasink, 'connect_matrix.native.@11')

    if (not use_sample):
        #        dmripipeline.connect(connect_mat_fs4_nat_left_left, 'out_mat', datasink, 'connect_matrix.fs4.mat.@1')
        #        dmripipeline.connect(connect_mat_fs4_log_left_left, 'out_mat', datasink, 'connect_matrix.fs4.mat.@2')
        #        dmripipeline.connect(connect_mat_fs4_nat_right_right, 'out_mat', datasink, 'connect_matrix.fs4.mat.@3')
        #        dmripipeline.connect(connect_mat_fs4_log_right_right, 'out_mat', datasink, 'connect_matrix.fs4.mat.@4')
        #        dmripipeline.connect(connect_mat_fs4_nat_left_right, 'out_mat', datasink, 'connect_matrix.fs4.mat.@5')
        #        dmripipeline.connect(connect_mat_fs4_log_left_right, 'out_mat', datasink, 'connect_matrix.fs4.mat.@6')
        #        dmripipeline.connect(connect_mat_fs4_nat_right_left, 'out_mat', datasink, 'connect_matrix.fs4.mat.@7')
        #        dmripipeline.connect(connect_mat_fs4_log_right_left, 'out_mat', datasink, 'connect_matrix.fs4.mat.@8')

        dmripipeline.connect(connect_mat_fs4_nat_left_left, 'out_nii',
                             datasink, 'connect_matrix.fs4.@1')
        dmripipeline.connect(connect_mat_fs4_log_left_left, 'out_nii',
                             datasink, 'connect_matrix.fs4.@2')
        dmripipeline.connect(connect_mat_fs4_nat_right_right, 'out_nii',
                             datasink, 'connect_matrix.fs4.@3')
        dmripipeline.connect(connect_mat_fs4_log_right_right, 'out_nii',
                             datasink, 'connect_matrix.fs4.@4')
        dmripipeline.connect(connect_mat_fs4_nat_left_right, 'out_nii',
                             datasink, 'connect_matrix.fs4.@5')
        dmripipeline.connect(connect_mat_fs4_log_left_right, 'out_nii',
                             datasink, 'connect_matrix.fs4.@6')
        dmripipeline.connect(connect_mat_fs4_nat_right_left, 'out_nii',
                             datasink, 'connect_matrix.fs4.@7')
        dmripipeline.connect(connect_mat_fs4_log_right_left, 'out_nii',
                             datasink, 'connect_matrix.fs4.@8')

        #         dmripipeline.connect(connect_mat_fs4_nat_full, 'out_file', datasink, 'connect_matrix.@28')
        #         dmripipeline.connect(connect_mat_fs4_log_full, 'out_file', datasink, 'connect_matrix.@30')

        #        dmripipeline.connect(connect_mat_fs5_nat_left_left, 'out_mat', datasink, 'connect_matrix.fs5.mat.@1')
        #        dmripipeline.connect(connect_mat_fs5_log_left_left, 'out_mat', datasink, 'connect_matrix.fs5.mat.@2')
        #        dmripipeline.connect(connect_mat_fs5_nat_right_right, 'out_mat', datasink, 'connect_matrix.fs5.mat.@3')
        #        dmripipeline.connect(connect_mat_fs5_log_right_right, 'out_mat', datasink, 'connect_matrix.fs5.mat.@4')
        #        dmripipeline.connect(connect_mat_fs5_nat_left_right, 'out_mat', datasink, 'connect_matrix.fs5.mat.@5')
        #        dmripipeline.connect(connect_mat_fs5_log_left_right, 'out_mat', datasink, 'connect_matrix.fs5.mat.@6')
        #        dmripipeline.connect(connect_mat_fs5_nat_right_left, 'out_mat', datasink, 'connect_matrix.fs5.mat.@7')
        #        dmripipeline.connect(connect_mat_fs5_log_right_left, 'out_mat', datasink, 'connect_matrix.fs5.mat.@8')

        dmripipeline.connect(connect_mat_fs5_nat_left_left, 'out_nii',
                             datasink, 'connect_matrix.fs5.@1')
        dmripipeline.connect(connect_mat_fs5_log_left_left, 'out_nii',
                             datasink, 'connect_matrix.fs5.@2')
        dmripipeline.connect(connect_mat_fs5_nat_right_right, 'out_nii',
                             datasink, 'connect_matrix.fs5.@3')
        dmripipeline.connect(connect_mat_fs5_log_right_right, 'out_nii',
                             datasink, 'connect_matrix.fs5.@4')
        dmripipeline.connect(connect_mat_fs5_nat_left_right, 'out_nii',
                             datasink, 'connect_matrix.fs5.@5')
        dmripipeline.connect(connect_mat_fs5_log_left_right, 'out_nii',
                             datasink, 'connect_matrix.fs5.@6')
        dmripipeline.connect(connect_mat_fs5_nat_right_left, 'out_nii',
                             datasink, 'connect_matrix.fs5.@7')
        dmripipeline.connect(connect_mat_fs5_log_right_left, 'out_nii',
                             datasink, 'connect_matrix.fs5.@8')

#         dmripipeline.connect(connect_mat_fs5_nat_full, 'out_file', datasink, 'connect_matrix.@40')
#         dmripipeline.connect(connect_mat_fs5_log_full, 'out_file', datasink, 'connect_matrix.@42')
    """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """
    ===============================================================================
    Connecting the workflow
    ===============================================================================
    """ """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """"""
    """
    Create a higher-level workflow
    ------------------------------
    Finally, we create another higher-level workflow to connect our dmripipeline workflow with the info and datagrabbing nodes
    declared at the beginning. Our tutorial 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.
    """

    connectprepro = pe.Workflow(name="dmri_pipe3_projection")

    connectprepro.base_dir = op.abspath(workflow_dir + "/workflow_" +
                                        subject_ID)
    connectprepro.connect([(datasource, dmripipeline,
                            [('wm', 'inputnode.wm'),
                             ('seeds_left', 'inputnode.seeds_left'),
                             ('seeds_right', 'inputnode.seeds_right'),
                             ('t1', 'inputnode.t1'),
                             ('warp', 'inputnode.warp'),
                             ('inv_flirt_mat', 'inputnode.inv_flirt_mat'),
                             ('fa', 'inputnode.fa'),
                             ('index_left', 'inputnode.index_left'),
                             ('index_right', 'inputnode.index_right')]),
                           (tracts_left_source, dmripipeline,
                            [('tracts_left', 'inputnode.tracts_left')]),
                           (tracts_right_source, dmripipeline,
                            [('tracts_right', 'inputnode.tracts_right')])])

    return connectprepro
Ejemplo n.º 11
0
output_dir = 'datasink'
working_dir = '/media/harryzhang/VolumeWD/'

# list of subject identifiers
patient_list = ['540335']

# list of session identifiers
task_list = ['DWI', 'ADC', 'FLAIR', 'TTP']

# Smoothing widths to apply
fwhm = [2, 3, 4]

# main workflow

# Reorient
reorient = Node(fsl.Reorient2Std(output_type='NIFTI_GZ',
                                 ignore_exception=True),
                name='reorient')

# Bias Field Correction
N4_BFC = Node(ants.N4BiasFieldCorrection(dimension=3), name='N4_BFC')

# Smooth - image smoothing
smooth = Node(Smooth(), name="smooth")
smooth.iterables = ("fwhm", fwhm)


# coregistration Workflow
def coreg_workflow():

    # BET - Skull-stripping
    bet_anat = Node(fsl.BET(frac=0.2,
infosource_baseline = Node(interface=IdentityInterface(fields=['idvi']),
                           name="infosource_baseline")
infosource_baseline.iterables = ('idvi', idvi_baseline_list)

# get full path to MRI corresponding to idvi
getmusemri_baseline = Node(Function(input_names=['key', 'dict'],
                                    output_names=['musemri'],
                                    function=get_value),
                           name='getmusemri_baseline')
getmusemri_baseline.inputs.dict = musemri_dict

# Step 1: Spatial normalization of baseline MPRAGE onto study-specific template

# Reorient: this simply applies 90, 180, or 270 degree rotations about each axis to make the image orientation
# the same as the FSL standard
reorient = Node(interface=fsl.Reorient2Std(output_type='NIFTI'),
                name="reorient")

# Use antsRegistration to compute registration between subject's baseline MPRAGE and study-specific template
antsreg = Node(ants.Registration(
    args='--float',
    collapse_output_transforms=True,
    fixed_image=blsa_template,
    initial_moving_transform_com=True,
    num_threads=1,
    output_inverse_warped_image=True,
    output_warped_image=True,
    smoothing_sigmas=[[3, 2, 1, 0]] * 3,
    sigma_units=['vox'] * 3,
    transforms=['Rigid', 'Affine', 'SyN'],
    terminal_output='file',
Ejemplo n.º 13
0
    def preprocess_channels_pipeline(self, **name_maps):
        pipeline = self.new_pipeline(
            'preprocess_channels',
            name_maps=name_maps,
            desc=("Convert channel signals in complex coords to polar coords "
                  "and combine"))

        if (self.provided('header_image') or
                self.branch('reorient_to_std') or
                self.parameter('force_channel_flip') is not None):
            # Read channel files reorient them into standard space and then
            # write back to directory
            list_channels = pipeline.add(
                'list_channels',
                ListDir(),
                inputs={
                    'directory': ('channels', multi_nifti_gz_format)})

            if self.parameter('force_channel_flip') is not None:
                force_flip = pipeline.add(
                    'flip_dims',
                    fsl.SwapDimensions(
                        new_dims=tuple(self.parameter('force_channel_flip'))),
                    inputs={
                        'in_file': (list_channels, 'files')},
                    iterfield=['in_file'])
                geom_dest_file = (force_flip, 'out_file')
            else:
                geom_dest_file = (list_channels, 'files')

            if self.provided('header_image'):
                # If header image is provided stomp its geometry over the
                # acquired channels
                copy_geom = pipeline.add(
                    'qsm_copy_geometry',
                    fsl.CopyGeom(
                        output_type='NIFTI_GZ'),
                    inputs={
                        'in_file': ('header_image', nifti_gz_format),
                        'dest_file': geom_dest_file},
                    iterfield=(['dest_file']),
                    requirements=[fsl_req.v('5.0.8')])
                reorient_in_file = (copy_geom, 'out_file')
            else:
                reorient_in_file = geom_dest_file

            if self.branch('reorient_to_std'):
                reorient = pipeline.add(
                    'reorient_channel',
                    fsl.Reorient2Std(
                        output_type='NIFTI_GZ'),
                    inputs={
                        'in_file': reorient_in_file},
                    iterfield=['in_file'],
                    requirements=[fsl_req.v('5.0.8')])
                copy_to_dir_in_files = (reorient, 'out_file')
            else:
                copy_to_dir_in_files = reorient_in_file

            copy_to_dir = pipeline.add(
                'copy_to_dir',
                CopyToDir(),
                inputs={
                    'in_files': copy_to_dir_in_files,
                    'file_names': (list_channels, 'files')})
            to_polar_in_dir = (copy_to_dir, 'out_dir')
        else:
            to_polar_in_dir = ('channels', multi_nifti_gz_format)

        pipeline.add(
            'to_polar',
            ToPolarCoords(
                in_fname_re=self.parameter('channel_fname_regex'),
                real_label=self.parameter('channel_real_label'),
                imaginary_label=self.parameter('channel_imag_label')),
            inputs={
                'in_dir': to_polar_in_dir},
            outputs={
                'mag_channels': ('magnitudes_dir', multi_nifti_gz_format),
                'phase_channels': ('phases_dir', multi_nifti_gz_format)})

        return pipeline
Ejemplo n.º 14
0
	

	# Initialize workflow
	workflow = pe.Workflow(name='anat')
	workflow.base_dir = '.'

	# Reference brain images
	ref_brain = '/usr/share/fsl/5.0/data/standard/MNI152_T1_2mm_brain.nii.gz'
	ref_mask = '/usr/share/fsl/5.0/data/standard/MNI152_T1_2mm_brain_mask.nii.gz'
	reference_skull = '/usr/share/fsl/5.0/data/standard/MNI152_T1_2mm.nii.gz'
	fnirt_config = '/usr/share/fsl/5.0/etc/flirtsch/T1_2_MNI152_2mm.cnf'
	anat = data_path + subj_dirs[k] + '/session1/lesion_seg.nii.gz'

	# Reorient to FSL standard orientation
	#deoblique = pe.Node(interface=afni.Warp(in_file=anat, deoblique=True, outputtype='NIFTI_GZ'), name='deoblique')
	reorient = pe.Node(interface=fsl.Reorient2Std(in_file=anat, output_type='NIFTI_GZ'), name='reorient')
	#workflow.connect(deoblique, 'out_file', reorient, 'in_file')

	# AFNI skullstrip
	#skullstrip = pe.Node(interface=afni.SkullStrip(args='-no_use_edge -ld 20', outputtype='NIFTI_GZ'), name='skullstrip')
	#workflow.connect(reorient, 'out_file', skullstrip, 'in_file')

	# Segment with FSL FAST
	#tissue priors
	#tissue_path = '/usr/share/fsl/5.0/data/standard/tissuepriors/2mm/'
	#csf_prior = tissue_path + 'avg152T1_csf_bin.nii.gz'
	#white_prior = tissue_path + 'avg152T1_white_bin.nii.gz'
	#gray_prior = tissue_path + 'avg152T1_gray_bin.nii.gz'

	#segmentation = pe.Node(interface=fsl.FAST(number_classes=3, use_priors=True, img_type=1), name='segmentation')
	#workflow.connect(skullstrip, 'out_file', segmentation, 'in_files')
Ejemplo n.º 15
0
def define_template_workflow(info, subjects, qc=True):

    # --- Workflow parameterization

    subject_source = Node(IdentityInterface(["subject"]),
                          name="subject_source",
                          iterables=("subject", subjects))

    # Data input
    template_input = Node(TemplateInput(data_dir=info.data_dir),
                          "template_input")

    # --- Definition of functional template space

    crop_image = Node(fs.ApplyMask(args="-bb 4"), "crop_image")

    zoom_image = Node(fs.MRIConvert(resample_type="cubic",
                                    out_type="niigz",
                                    vox_size=info.voxel_size,
                                    ),
                      "zoom_image")

    reorient_image = Node(fsl.Reorient2Std(out_file="anat.nii.gz"),
                          "reorient_image")

    generate_reg = Node(fs.Tkregister2(fsl_out="anat2func.mat",
                                       reg_file="anat2func.dat",
                                       reg_header=True),
                        "generate_reg")

    invert_reg = Node(fs.Tkregister2(reg_file="func2anat.dat",
                                     reg_header=True),
                      "invert_reg")

    # --- Identification of surface vertices

    hemi_source = Node(IdentityInterface(["hemi"]), "hemi_source",
                       iterables=("hemi", ["lh", "rh"]))

    tag_surf = Node(fs.Surface2VolTransform(surf_name="graymid",
                                            transformed_file="ribbon.nii.gz",
                                            vertexvol_file="vertices.nii.gz",
                                            mkmask=True),
                    "tag_surf")

    mask_cortex = Node(MaskWithLabel(fill_value=-1), "mask_cortex")

    combine_hemis = JoinNode(fsl.Merge(dimension="t",
                                       merged_file="surf.nii.gz"),
                             name="combine_hemis",
                             joinsource="hemi_source",
                             joinfield="in_files")

    make_ribbon = Node(MakeRibbon(), "make_ribbon")

    # --- Segementation of anatomical tissue in functional space

    transform_wmparc = Node(fs.ApplyVolTransform(inverse=True,
                                                 interp="nearest",
                                                 args="--keep-precision"),
                            "transform_wmparc")

    anat_segment = Node(AnatomicalSegmentation(), "anat_segment")

    # --- Template QC

    template_qc = Node(TemplateReport(), "template_qc")

    # --- Workflow ouptut

    save_info = Node(SaveInfo(info_dict=info.trait_get()), "save_info")

    template_output = Node(DataSink(base_directory=info.proc_dir,
                                    parameterization=False),
                           "template_output")

    # === Assemble pipeline

    workflow = Workflow(name="template", base_dir=info.cache_dir)

    processing_edges = [

        (subject_source, template_input,
            [("subject", "subject")]),
        (template_input, crop_image,
            [("norm_file", "in_file"),
             ("wmparc_file", "mask_file")]),
        (crop_image, zoom_image,
            [("out_file", "in_file")]),
        (zoom_image, reorient_image,
            [("out_file", "in_file")]),

        (subject_source, generate_reg,
            [("subject", "subject_id")]),
        (template_input, generate_reg,
            [("norm_file", "moving_image")]),
        (reorient_image, generate_reg,
            [("out_file", "target_image")]),

        (subject_source, invert_reg,
            [("subject", "subject_id")]),
        (template_input, invert_reg,
            [("norm_file", "target_image")]),
        (reorient_image, invert_reg,
            [("out_file", "moving_image")]),

        (hemi_source, tag_surf,
            [("hemi", "hemi")]),
        (invert_reg, tag_surf,
            [("reg_file", "reg_file")]),
        (reorient_image, tag_surf,
            [("out_file", "template_file")]),
        (template_input, mask_cortex,
            [("label_files", "label_files")]),
        (hemi_source, mask_cortex,
            [("hemi", "hemi")]),
        (tag_surf, mask_cortex,
            [("vertexvol_file", "in_file")]),
        (mask_cortex, combine_hemis,
            [("out_file", "in_files")]),
        (combine_hemis, make_ribbon,
            [("merged_file", "in_file")]),

        (reorient_image, transform_wmparc,
            [("out_file", "source_file")]),
        (template_input, transform_wmparc,
            [("wmparc_file", "target_file")]),
        (invert_reg, transform_wmparc,
            [("reg_file", "reg_file")]),
        (reorient_image, anat_segment,
            [("out_file", "anat_file")]),
        (transform_wmparc, anat_segment,
            [("transformed_file", "wmparc_file")]),
        (combine_hemis, anat_segment,
            [("merged_file", "surf_file")]),

        (template_input, template_output,
            [("output_path", "container")]),
        (reorient_image, template_output,
            [("out_file", "@anat")]),
        (generate_reg, template_output,
            [("fsl_file", "@anat2func")]),
        (anat_segment, template_output,
            [("seg_file", "@seg"),
             ("lut_file", "@lut"),
             ("edge_file", "@edge"),
             ("mask_file", "@mask")]),
        (combine_hemis, template_output,
            [("merged_file", "@surf")]),
        (make_ribbon, template_output,
            [("out_file", "@ribon")]),

    ]
    workflow.connect(processing_edges)

    # Optionally connect QC nodes

    qc_edges = [

        (reorient_image, template_qc,
            [("out_file", "anat_file")]),
        (combine_hemis, template_qc,
            [("merged_file", "surf_file")]),
        (anat_segment, template_qc,
            [("lut_file", "lut_file"),
             ("seg_file", "seg_file"),
             ("edge_file", "edge_file"),
             ("mask_file", "mask_file")]),

        (subject_source, save_info,
            [("subject", "parameterization")]),
        (save_info, template_output,
            [("info_file", "qc.@info_json")]),

        (template_qc, template_output,
            [("seg_plot", "qc.@seg_plot"),
             ("mask_plot", "qc.@mask_plot"),
             ("edge_plot", "qc.@edge_plot"),
             ("surf_plot", "qc.@surf_plot"),
             ("anat_plot", "qc.@anat_plot")]),

    ]
    if qc:
        workflow.connect(qc_edges)

    return workflow
Ejemplo n.º 16
0
from nipype.pipeline.engine import Workflow, Node, MapNode
import nipype.interfaces.fsl as fsl
import nipype.interfaces.spm as spm

#Matlab and SPM configuration
# Set the way matlab should be called
# mlab.MatlabCommand.set_default_matlab_cmd("matlab -nodesktop -nosplash -nojvm -noFigureWindows")
spm_path = '/opt/spm12'
mlab.MatlabCommand.set_default_matlab_cmd("matlab -nodesktop -nosplash")
mlab.MatlabCommand.set_default_paths(spm_path)

# Nodes

ro = Node(interface=fsl.Reorient2Std(output_type='NIFTI'), name='ro')
seg = Node(interface=spm.Segment(csf_output_type=[False, False, True],
                                 gm_output_type=[False, False, True],
                                 wm_output_type=[False, False, True],
                                 save_bias_corrected=True),
           name="segment")

# Connections:
segment = Workflow(name='Segment', base_dir='./')
segment.connect(ro, 'out_file', seg, 'data')

# Example connection to the main Workflow:
# main = Workflow(name='main', base_dir=w_dir)
# main.connect(infosource, 'subject_id', datasource, 'subject_id')
# main.connect(datasource, 'nii', segment, 'ro.in_file')
# main.connect(segment, 'seg.bias_corrected_image', sink, '@bias_corr')
# main.connect(segment, 'seg.native_csf_image', sink, '@csf')
# main.connect(segment, 'seg. native_gm_image', sink, '@gm')
Ejemplo n.º 17
0
    def make_workflow(self):
        # Infosource: Iterate through subject names
        infosource = Node(interface=IdentityInterface(fields=['subject_str']),
                          name="infosource")
        infosource.iterables = ('subject_str', self.subject_list)

        # Infosource: Iterate through subject names
        #imgsrc = Node(interface=IdentityInterface(fields=['img']), name="imgsrc")
        #imgsrc.iterables = ('img', ['uni'])

        parse_scanner_dir = Node(
            interface=ParseScannerDir(raw_data_dir=self.raw_data_dir),
            name='parse_scanner_dir')

        ro = Node(interface=fsl.Reorient2Std(), name='ro')

        mv_uni = Node(interface=Rename(format_string='uni_'), name='mv_uni')
        mv_uniden = Node(interface=Rename(format_string='uniden'),
                         name='mv_uniden')
        mv_flair = Node(interface=Rename(format_string='flair'),
                        name='mv_flair')
        mv_bold = Node(interface=Rename(format_string='bold_'), name='mv_bold')
        mv_boldmag1 = Node(interface=Rename(format_string='boldmag1'),
                           name='mv_boldmag1')
        mv_boldmag2 = Node(interface=Rename(format_string='boldmag2'),
                           name='mv_boldmag2')
        mv_phasediff = Node(interface=Rename(format_string='boldphdiff'),
                            name='mv_phasediff')
        sink = Node(interface=DataSink(), name='sink')
        sink.inputs.base_directory = self.bids_root
        #sink.inputs.substitutions = [('mp2rage075iso', '{}'.format(str(sink.inputs._outputs.keys()))),
        #                              ('uni', 'uni.nii.gz')]#,
        #                              ('_uniden_DEN', ''),
        #                              ('DEN_mp2rage_orig_reoriented_masked_maths', 'mUNIbrain_DENskull_SPMmasked'),
        #                              ('_mp2rage_orig_reoriented_maths_maths_bin', '_brain_bin')]
        sink.inputs.regexp_substitutions = [
            (r'_subject_str_2(?P<subid>[0-9][0-9][0-9])T(?P<sesid>[0-9])/uni_',
             r'sub-NeuroMET\g<subid>/ses-0\g<sesid>/anat/sub-NeuroMET\g<subid>_ses-0\g<sesid>_T1w.nii.gz'
             ),
            (r'_subject_str_2(?P<subid>[0-9][0-9][0-9])T(?P<sesid>[0-9])/uniden',
             r'/derivatives/Siemens/sub-NeuroMET\g<subid>/ses-0\g<sesid>/anat/sub-NeuroMET\g<subid>_ses-0\g<sesid>_desc-UNIDEN.nii.gz'
             ),
            (r'_subject_str_2(?P<subid>[0-9][0-9][0-9])T(?P<sesid>[0-9])/flair',
             r'sub-NeuroMET\g<subid>/ses-0\g<sesid>/anat/sub-NeuroMET\g<subid>_ses-0\g<sesid>_FLAIR.nii.gz'
             ),
            (r'_subject_str_2(?P<subid>[0-9][0-9][0-9])T(?P<sesid>[0-9])/bold_',
             r'sub-NeuroMET\g<subid>/ses-0\g<sesid>/func/sub-NeuroMET\g<subid>_ses-0\g<sesid>_task-rest_bold.nii.gz'
             ),
            (r'_subject_str_2(?P<subid>[0-9][0-9][0-9])T(?P<sesid>[0-9])/boldmag1',
             r'sub-NeuroMET\g<subid>/ses-0\g<sesid>/fmap/sub-NeuroMET\g<subid>_ses-0\g<sesid>_magnitude1.nii.gz'
             ),
            (r'_subject_str_2(?P<subid>[0-9][0-9][0-9])T(?P<sesid>[0-9])/boldmag2',
             r'sub-NeuroMET\g<subid>/ses-0\g<sesid>/fmap/sub-NeuroMET\g<subid>_ses-0\g<sesid>_magnitude2.nii.gz'
             ),
            (r'_subject_str_2(?P<subid>[0-9][0-9][0-9])T(?P<sesid>[0-9])/boldphdiff',
             r'sub-NeuroMET\g<subid>/ses-0\g<sesid>/fmap/sub-NeuroMET\g<subid>_ses-0\g<sesid>_phasediff.nii.gz'
             ),
        ]
        #    (r'c1{prefix}(.*).UNI_brain_bin.nii.gz'.format(prefix=self.project_prefix),
        #                                      r'{prefix}\1.UNI_brain_bin.nii.gz'.format(prefix=self.project_prefix)),
        #                                     (r'c1{prefix}(.*).DEN_brain_bin.nii.gz'.format(prefix=self.project_prefix),
        #                                      r'{prefix}\1.DEN_brain_bin.nii.gz'.format(prefix=self.project_prefix))]

        scanner_to_bids = Workflow(name='scanner_to_bids',
                                   base_dir=self.temp_dir)
        #scanner_to_bids.connect(imgsrc, 'img', mv, 'format_string')
        scanner_to_bids.connect(infosource, 'subject_str', parse_scanner_dir,
                                'subject_id')
        scanner_to_bids.connect(parse_scanner_dir, 'uni', mv_uni, 'in_file')
        scanner_to_bids.connect(parse_scanner_dir, 'uniden', mv_uniden,
                                'in_file')
        scanner_to_bids.connect(parse_scanner_dir, 'flair', mv_flair,
                                'in_file')
        scanner_to_bids.connect(parse_scanner_dir, 'bold', mv_bold, 'in_file')
        scanner_to_bids.connect(parse_scanner_dir, 'boldmag1', mv_boldmag1,
                                'in_file')
        scanner_to_bids.connect(parse_scanner_dir, 'boldmag2', mv_boldmag2,
                                'in_file')
        scanner_to_bids.connect(parse_scanner_dir, 'boldphdiff', mv_phasediff,
                                'in_file')
        scanner_to_bids.connect(mv_uni, 'out_file', sink, '@uni')
        scanner_to_bids.connect(mv_uniden, 'out_file', sink, '@uniden')
        scanner_to_bids.connect(mv_flair, 'out_file', sink, '@flair')
        scanner_to_bids.connect(mv_bold, 'out_file', sink, '@bold')
        scanner_to_bids.connect(mv_boldmag1, 'out_file', sink, '@boldmag1')
        scanner_to_bids.connect(mv_boldmag2, 'out_file', sink, '@boldmag2')
        scanner_to_bids.connect(mv_phasediff, 'out_file', sink, '@phasediff')

        return scanner_to_bids
Ejemplo n.º 18
0
subject = input('Please enter the subject ID: ')

home = '/Volumes/iang/active/BABIES/BABIES_MAMA'

t1w = home + '/' + subject + '/t1w'
dest = home + '/' + subject + '/anat'
func1 = home + '/' + subject + '/func/run1'
func2 = home + '/' + subject + '/func/run2'

copyfile((t1w + '/t1w_raw.nii.gz'), (dest + '/t1w_raw.nii.gz'))

# In[10]:

reorient = Node(fsl.Reorient2Std(in_file=(dest + '/t1w_raw.nii.gz'),
                                 out_file=(dest + '/spgrorient.nii.gz'),
                                 output_type='NIFTI_GZ'),
                name='reorient')
reorient.run()

# In[11]:

skullstrip = Node(fsl.BET(in_file=(dest + '/spgrorient.nii.gz'),
                          out_file=(dest + '/spgrbrain.nii.gz'),
                          robust=True,
                          frac=0.5,
                          vertical_gradient=0),
                  name='skullstrip')
skullstrip.run()

# In[13]:
Ejemplo n.º 19
0
def create_resting():

    # main workflow
    func_preproc = Workflow(name='resting')

    inputnode = Node(util.IdentityInterface(fields=[
        'subject_id', 'out_dir', 'freesurfer_dir', 'func', 'rs_mag', 'rs_ph',
        'anat_head', 'anat_brain', 'anat_brain_mask', 'wmseg', 'csfseg',
        'vol_to_remove', 'TR', 'highpass_freq', 'epi_resolution', 'echo_space',
        'te_diff', 'fwhm', 'pe_dir', 'composite_transform', 'standard_brain',
        'standard_downsampled'
    ]),
                     name='inputnode')

    #Use correct subject ID from long timepoint for bbregister
    def change_subject_id(subject):
        import re
        [subj, ses] = re.split("_", subject)

        new_subject_id = subject + '.long.' + subj
        return new_subject_id

    change_subject_id = Node(util.Function(input_names=["subject"],
                                           output_names=["new_subject_id"],
                                           function=change_subject_id),
                             name="change_subject_id")

    outputnode = Node(util.IdentityInterface(fields=[
        'brain', 'brainmask', 'anat2std_transforms', 'std2anat_transforms',
        'anat2std', 'anat_head', 'wmseg', 'csfseg', 'wmedge', 'subject_id'
    ]),
                      name='outputnode')

    ##PREPROCESSING FOR AROMA (Steps 1 - 7)
    def merge_if_list(in_file):
        if type(in_file) == list:
            import numpy as np
            import nibabel as nb
            import os
            from nipype.utils.filemanip import split_filename
            nii1 = nb.load(in_file[0])
            nii1d = nii1.get_data()
            nii2 = nb.load(in_file[1])
            nii2d = nii2.get_data()
            x = np.concatenate((nii1d, nii2d), axis=3)
            new_nii = nb.Nifti1Image(x, nii1.get_affine(), nii1.get_header())
            new_nii.set_data_dtype(np.float32)
            _, base, _ = split_filename(in_file[0])
            nb.save(new_nii, base + "_merged.nii.gz")
            return os.path.abspath(base + "_merged.nii.gz")
        else:
            return in_file

    #if rsfmri is a list -> merge files, otherwise return single list.
    merge_rs = Node(util.Function(input_names=['in_file'],
                                  output_names=["out_file"],
                                  function=merge_if_list),
                    name='merge_rs')

    # node to remove first volumes
    remove_vol = Node(util.Function(input_names=['in_file', 't_min'],
                                    output_names=["out_file"],
                                    function=strip_rois_func),
                      name='remove_vol')

    # workflow for motion correction
    moco = create_moco_pipeline()

    # workflow for fieldmap correction and coregistration
    fmap_coreg = create_fmap_coreg_pipeline()

    # workflow for applying transformations to timeseries
    transform_ts = create_transform_pipeline()

    #mean intensity normalization
    meanintensnorm = Node(fsl.ImageMaths(op_string='-ing 10000'),
                          name='meanintensnorm')

    smoothing = create_smoothing_pipeline()

    # connections
    func_preproc.connect([
        (inputnode, merge_rs, [('func', 'in_file')]),
        (merge_rs, remove_vol, [('out_file', 'in_file')]),
        (inputnode, remove_vol, [('vol_to_remove', 't_min')]),
        (inputnode, moco, [('anat_brain_mask', 'inputnode.brainmask')]),
        (remove_vol, moco, [('out_file', 'inputnode.epi')]),
        (inputnode, change_subject_id, [('subject_id', 'subject')]),
        (change_subject_id, fmap_coreg, [('new_subject_id',
                                          'inputnode.fs_subject_id')]),
        (inputnode, fmap_coreg, [('rs_mag', 'inputnode.mag'),
                                 ('rs_ph', 'inputnode.phase'),
                                 ('freesurfer_dir',
                                  'inputnode.fs_subjects_dir'),
                                 ('echo_space', 'inputnode.echo_space'),
                                 ('te_diff', 'inputnode.te_diff'),
                                 ('pe_dir', 'inputnode.pe_dir'),
                                 ('anat_head', 'inputnode.anat_head'),
                                 ('anat_brain', 'inputnode.anat_brain')]),
        (moco, fmap_coreg, [('outputnode.epi_mean', 'inputnode.epi_mean')]),
        (remove_vol, transform_ts, [('out_file', 'inputnode.orig_ts')]),
        (inputnode, transform_ts, [('anat_head', 'inputnode.anat_head')]),
        (inputnode, transform_ts, [('anat_brain_mask', 'inputnode.brain_mask')
                                   ]),
        (inputnode, transform_ts, [('epi_resolution', 'inputnode.resolution')
                                   ]),
        (moco, transform_ts, [('outputnode.mat_moco', 'inputnode.mat_moco')]),
        (fmap_coreg, transform_ts, [('outputnode.fmap_fullwarp',
                                     'inputnode.fullwarp')]),
        (transform_ts, meanintensnorm, [('outputnode.trans_ts', 'in_file')]),
        (meanintensnorm, smoothing, [('out_file', 'inputnode.ts_transformed')
                                     ]),
        (inputnode, smoothing, [('fwhm', 'inputnode.fwhm')])
    ])

    ##CALCULATE TRANSFORM from anatomical to standard space with FSL tools
    # Anat > Standard
    # register high-resolution to standard template with non-linear transform
    # flirt serves as preparation for fnirt)

    #reorient brain to standard (because Freesurfer space can cause problems)
    reorient2std = Node(fsl.Reorient2Std(), name="reorient2std")

    reorient2std_rs = Node(fsl.Reorient2Std(), name="reorient2std_rs")
    reorient2std_mask = Node(fsl.Reorient2Std(), name="reorient2std_mask")

    flirt_prep = Node(fsl.FLIRT(cost_func='mutualinfo', interp='trilinear'),
                      name='flirt_prep')
    flirt_prep.inputs.interp = 'trilinear'
    flirt_prep.inputs.dof = 12

    fnirt = Node(fsl.FNIRT(), name='fnirt')
    fnirt.inputs.field_file = True
    fnirt.inputs.fieldcoeff_file = True

    func_preproc.connect([
        (inputnode, reorient2std, [('anat_brain', 'in_file')]),
        (reorient2std, flirt_prep, [('out_file', 'in_file')]),
        #(inputnode, flirt_prep,  [('anat_brain', 'in_file')]),
        (inputnode, flirt_prep, [('standard_brain', 'reference')]),
        (flirt_prep, fnirt, [('out_matrix_file', 'affine_file')]),
        (reorient2std, fnirt, [('out_file', 'in_file')]),
        (inputnode, fnirt, [('standard_brain', 'ref_file')]),
    ])

    def getcwd(subject_id):
        import os
        tmp = os.getcwd()
        tmp = tmp[:-6]
        tmp = tmp + 'ica_aroma/out'  #%(subject_id)
        return tmp

    get_wd = Node(util.Function(input_names=['subject_id'],
                                output_names=["d"],
                                function=getcwd),
                  name='get_wd')

    ica_aroma = Node(ICA_AROMA(), name="ica_aroma")
    ica_aroma.inputs.denoise_type = 'both'
    #ica_aroma.inputs.out_dir = os.getcwd()

    func_preproc.connect([
        (moco, ica_aroma, [('outputnode.par_moco', 'motion_parameters')]),
        (smoothing, reorient2std_rs, [('outputnode.ts_smoothed', 'in_file')]),
        (reorient2std_rs, ica_aroma, [('out_file', 'in_file')]),
        (fnirt, ica_aroma, [('field_file', 'fnirt_warp_file')]),
        (transform_ts, reorient2std_mask, [('outputnode.comb_mask_resamp',
                                            'in_file')]),
        (reorient2std_mask, ica_aroma, [('out_file', 'mask')]),
        (inputnode, get_wd, [('subject_id', 'subject_id')]),
        (get_wd, ica_aroma, [('d', 'out_dir')])
    ])

    ##POSTPROCESSING
    postprocess = create_denoise_pipeline()

    func_preproc.connect([
        (reorient2std_mask, postprocess, [
            ('out_file', 'inputnode.brain_mask')
        ]),  #use the correctly oriented mask                           
        (ica_aroma, postprocess, [
            ('nonaggr_denoised_file', 'inputnode.epi_coreg')
        ]),  #use the nonaggr_denoised_file
        (inputnode, postprocess, [('TR', 'inputnode.tr')]),
        (inputnode, postprocess, [('highpass_freq', 'inputnode.highpass_freq')
                                  ]),
        (inputnode, postprocess, [('wmseg', 'inputnode.wmseg')]),
        (inputnode, postprocess, [('csfseg', 'inputnode.csfseg')]),
    ])

    #outputnode
    outputnode = Node(util.IdentityInterface(fields=[
        'par', 'rms', 'mean_epi', 'tsnr', 'stddev_file', 'realigned_ts',
        'fmap', 'unwarped_mean_epi2fmap', 'coregistered_epi2fmap',
        'fmap_fullwarp', 'epi2anat', 'epi2anat_mat', 'epi2anat_dat',
        'epi2anat_mincost', 'full_transform_ts', 'full_transform_mean',
        'resamp_t1', 'comb_mask_resamp', 'dvars_file', 'out_flirt_prep',
        'out_matrix_flirt_prep', 'out_warped', 'out_warp_field',
        'aggr_denoised_file', 'nonaggr_denoised_file', 'out_dir', 'wmcsf_mask',
        'combined_motion', 'comp_regressor', 'comp_F', 'comp_pF', 'out_betas',
        'ts_fullspectrum', 'ts_filtered'
    ]),
                      name='outputnode')

    # connections
    func_preproc.connect([
        (
            moco,
            outputnode,
            [  #('outputnode.epi_moco', 'realign.@realigned_ts'),
                ('outputnode.par_moco', 'par'),
                ('outputnode.rms_moco', 'rms'),
                ('outputnode.epi_moco', 'realigned_ts'),
                ('outputnode.epi_mean', 'mean_epi'),
                ('outputnode.tsnr_file', 'tsnr'),
                ('outputnode.stddev_file', 'stddev'),
            ]),
        (fmap_coreg, outputnode,
         [('outputnode.fmap', 'fmap'),
          ('outputnode.unwarped_mean_epi2fmap', 'unwarped_mean_epi2fmap'),
          ('outputnode.epi2fmap', 'coregistered_epi2fmap'),
          ('outputnode.fmap_fullwarp', 'fmap_fullwarp'),
          ('outputnode.epi2anat', 'epi2anat'),
          ('outputnode.epi2anat_mat', 'epi2anat_mat'),
          ('outputnode.epi2anat_dat', 'epi2anat_dat'),
          ('outputnode.epi2anat_mincost', 'epi2anat_mincost')]),
        (transform_ts, outputnode,
         [('outputnode.trans_ts', 'full_transform_ts'),
          ('outputnode.trans_ts_mean', 'full_transform_mean'),
          ('outputnode.resamp_t1', 'resamp_t1'),
          ('outputnode.comb_mask_resamp', 'comb_mask_resamp'),
          ('outputnode.out_dvars', 'dvars_file')]),
        (flirt_prep, outputnode, [('out_file', 'out_flirt_prep'),
                                  ('out_matrix_file', 'out_matrix_flirt_prep')
                                  ]),
        (fnirt, outputnode, [('warped_file', 'out_warped'),
                             ('field_file', 'out_warp_field')]),
        (ica_aroma, outputnode, [('aggr_denoised_file', 'aggr_denoised_file'),
                                 ('nonaggr_denoised_file',
                                  'nonaggr_denoised_file'),
                                 ('out_dir', 'out_dir')]),
        (postprocess, outputnode,
         [('outputnode.wmcsf_mask', 'wmcsf_mask'),
          ('outputnode.combined_motion', 'combined_motion'),
          ('outputnode.comp_regressor', 'comp_regressor'),
          ('outputnode.comp_F', 'comp_F'), ('outputnode.comp_pF', 'comp_pF'),
          ('outputnode.out_betas', 'out_betas'),
          ('outputnode.ts_fullspectrum', 'ts_fullspectrum'),
          ('outputnode.ts_filtered', 'ts_filtered')])
    ])

    return func_preproc
Ejemplo n.º 20
0
def create_converter_functional_pipeline(working_dir,
                                         ds_dir,
                                         name='converter_funct'):
    # initiate workflow
    converter_wf = Workflow(name=name)
    converter_wf.base_dir = os.path.join(working_dir, 'LeiCA_resting')

    # set fsl output
    fsl.FSLCommand.set_default_output_type('NIFTI_GZ')

    # I/O NODE
    inputnode = Node(
        util.IdentityInterface(fields=['epi_dicom', 'out_format']),
        name='inputnode')

    outputnode = Node(util.IdentityInterface(fields=['epi', 'TR_ms']),
                      name='outputnode')

    niftisink = Node(nio.DataSink(), name='niftisink')
    niftisink.inputs.base_directory = os.path.join(ds_dir, 'raw_niftis')
    niftisink.inputs.substitutions = [('_TR_id_', 'TR_')]

    # convert to nifti
    # todo check if geometry bugs attac. use dcm2nii?
    converter_epi = Node(DcmStack(embed_meta=True), name='converter_epi')
    converter_epi.plugin_args = {'submit_specs': 'request_memory = 2000'}

    def reformat_filename_fct(TR_str):
        return 'rsfMRI_' + TR_str

    reformat_filename = Node(util.Function(input_names=['TR_str'],
                                           output_names=['filename'],
                                           function=reformat_filename_fct),
                             name='reformat_filename')

    converter_wf.connect(inputnode, 'out_format', reformat_filename, 'TR_str')
    converter_wf.connect(inputnode, 'epi_dicom', converter_epi, 'dicom_files')
    converter_wf.connect(reformat_filename, 'filename', converter_epi,
                         'out_format')

    # reorient to standard orientation
    reor_2_std = Node(fsl.Reorient2Std(), name='reor_2_std')
    converter_wf.connect(converter_epi, 'out_file', reor_2_std, 'in_file')

    converter_wf.connect(reor_2_std, 'out_file', outputnode, 'epi')

    # save original niftis
    converter_wf.connect(reor_2_std, 'out_file', niftisink, 'rsfMRI')

    # GET TR FROM .nii
    def check_TR_fct(TR):
        print ' '
        print 'check_TR_fct checks validity of TR'
        print('imported TR is %s' % TR)
        print '  '
        try:
            float(TR)
        except ValueError:
            isvalid_TR = 0
            raise Exception(
                'ERROR: TR COULD NOT AUTOMATICALLY BE EXTRACTED FROM EPI.\nEXECUTION STOPPED'
            )
        else:
            isvalid_TR = 1
            print 'TR is valid'
        if isvalid_TR:
            if float(TR <= 0):
                raise Exception(
                    'ERROR: TR NOT VALID (<=0).\nEXECUTION STOPPED')
        return float(TR)

    get_TR = Node(ImageInfo(), name='get_TR')
    converter_wf.connect(reor_2_std, 'out_file', get_TR, 'in_file')

    check_TR = Node(util.Function(input_names=['TR'],
                                  output_names=['TR_ms'],
                                  function=check_TR_fct),
                    name='check_TR')

    converter_wf.connect(get_TR, 'TR', check_TR, 'TR')
    converter_wf.connect(check_TR, 'TR_ms', outputnode, 'TR_ms')

    converter_wf.write_graph(dotfilename=converter_wf.name,
                             graph2use='flat',
                             format='pdf')

    return converter_wf
Ejemplo n.º 21
0
def create_preprocessing_workflow(analysis_params, name='yesno_3T'):
    import os.path as op
    import nipype.pipeline as pe
    from nipype.interfaces import fsl
    from nipype.interfaces.utility import Function, Merge, IdentityInterface
    from nipype.interfaces.io import SelectFiles, DataSink
    from IPython import embed as shell

    # Importing of custom nodes from spynoza packages; assumes that spynoza is installed:
    # pip install git+https://github.com/spinoza-centre/spynoza.git@develop
    from spynoza.utils import get_scaninfo, pickfirst, average_over_runs, set_nifti_intercept_slope
    from spynoza.uniformization.workflows import create_non_uniformity_correct_4D_file
    from spynoza.unwarping.b0.workflows import create_B0_workflow
    from spynoza.motion_correction.workflows import create_motion_correction_workflow
    from spynoza.registration.workflows import create_registration_workflow
    from spynoza.filtering.nodes import sgfilter
    from spynoza.conversion.nodes import psc
    from spynoza.denoising.retroicor.workflows import create_retroicor_workflow
    from spynoza.masking.workflows import create_masks_from_surface_workflow
    from spynoza.glm.nodes import fit_nuisances

    ########################################################################################
    # nodes
    ########################################################################################

    input_node = pe.Node(
        IdentityInterface(fields=[
            'task',  # main
            'sub_id',  # main
            'ses_id',  # main
            'raw_data_dir',  # main
            'output_directory',  # main
            'sub_FS_id',  # main
            'FS_subject_dir',  # motion correction
            'RepetitionTime',  # motion correction
            'which_file_is_EPI_space',  # motion correction
            'standard_file',  # registration
            'topup_conf_file',  # unwarping
            'EchoTimeDiff',  # unwarping
            'EpiFactor',  # unwarping
            'SenseFactor',  # unwarping
            'WaterFatShift',  # unwarping
            'PhaseEncodingDirection',  # unwarping
            'EchoSpacing'  # unwarping
            'psc_func',  # percent signal change
            'sg_filter_window_length',  # temporal filtering
            'sg_filter_order',  # temporal filtering
            'SliceEncodingDirection',  # retroicor
            'PhysiologySampleRate',  # retroicor
            'SliceTiming',  # retroicor
            'SliceOrder',  # retroicor
            'NumberDummyScans',  # retroicor
            'MultiBandFactor',  # retroicor
            'hr_rvt',  # retroicor
            'av_func',  # extra
            'EchoTime',  # extra
            'bd_design_matrix_file',  # extra
        ]),
        name='inputspec')

    for param in analysis_params:
        exec('input_node.inputs.{} = analysis_params[param]'.format(param))

    # i/o node
    datasource_templates = dict(
        func=
        '{sub_id}/{ses_id}/func/{sub_id}_{ses_id}_task-{task}*_bold.nii.gz',
        magnitude='{sub_id}/{ses_id}/fmap/{sub_id}_{ses_id}*magnitude.nii.gz',
        phasediff='{sub_id}/{ses_id}/fmap/{sub_id}_{ses_id}*phasediff.nii.gz',
        #physio='{sub_id}/{ses_id}/func/*{task}*physio.*',
        #events='{sub_id}/{ses_id}/func/*{task}*_events.pickle',
        #eye='{sub_id}/{ses_id}/func/*{task}*_eyedata.edf'
    )
    datasource = pe.Node(SelectFiles(datasource_templates,
                                     sort_filelist=True,
                                     raise_on_empty=False),
                         name='datasource')

    output_node = pe.Node(IdentityInterface(
        fields=(['temporal_filtered_files', 'percent_signal_change_files'])),
                          name='outputspec')

    # nodes for setting the slope/intercept of incoming niftis to (1, 0)
    # this is apparently necessary for the B0 map files
    int_slope_B0_magnitude = pe.Node(Function(
        input_names=['in_file'],
        output_names=['out_file'],
        function=set_nifti_intercept_slope),
                                     name='int_slope_B0_magnitude')
    int_slope_B0_phasediff = pe.Node(Function(
        input_names=['in_file'],
        output_names=['out_file'],
        function=set_nifti_intercept_slope),
                                     name='int_slope_B0_phasediff')

    # reorient nodes
    reorient_epi = pe.MapNode(interface=fsl.Reorient2Std(),
                              name='reorient_epi',
                              iterfield=['in_file'])
    reorient_B0_magnitude = pe.Node(interface=fsl.Reorient2Std(),
                                    name='reorient_B0_magnitude')
    reorient_B0_phasediff = pe.Node(interface=fsl.Reorient2Std(),
                                    name='reorient_B0_phasediff')

    # bet_epi = pe.MapNode(interface=
    #     fsl.BET(frac=analysis_parameters['bet_f_value'], vertical_gradient = analysis_parameters['bet_g_value'],
    #             functional=True, mask = True), name='bet_epi', iterfield=['in_file'])

    datasink = pe.Node(DataSink(), name='sinker')
    datasink.inputs.parameterization = False

    ########################################################################################
    # workflow
    ########################################################################################

    # the actual top-level workflow
    preprocessing_workflow = pe.Workflow(name=name)
    preprocessing_workflow.base_dir = op.join(analysis_params['base_dir'],
                                              'temp/')

    # data source
    preprocessing_workflow.connect(input_node, 'raw_data_dir', datasource,
                                   'base_directory')
    preprocessing_workflow.connect(input_node, 'sub_id', datasource, 'sub_id')
    preprocessing_workflow.connect(input_node, 'ses_id', datasource, 'ses_id')
    preprocessing_workflow.connect(input_node, 'task', datasource, 'task')

    # and data sink
    preprocessing_workflow.connect(input_node, 'output_directory', datasink,
                                   'base_directory')

    # BET (we don't do this, because we expect the raw data in the bids folder to be betted
    # already for anonymization purposes)
    # preprocessing_workflow.connect(datasource, 'func', bet_epi, 'in_file')

    # non-uniformity correction
    # preprocessing_workflow.connect(bet_epi, 'out_file', nuc, 'in_file')
    # preprocessing_workflow.connect(datasource, 'func', nuc, 'in_file')

    # reorient images
    preprocessing_workflow.connect(datasource, 'func', reorient_epi, 'in_file')
    preprocessing_workflow.connect(datasource, 'magnitude',
                                   reorient_B0_magnitude, 'in_file')
    preprocessing_workflow.connect(datasource, 'phasediff',
                                   reorient_B0_phasediff, 'in_file')
    preprocessing_workflow.connect(reorient_epi, 'out_file', datasink,
                                   'reorient')

    #B0 field correction:
    if analysis_params['B0_or_topup'] == 'B0':
        # set slope/intercept to unity for B0 map
        preprocessing_workflow.connect(reorient_B0_magnitude, 'out_file',
                                       int_slope_B0_magnitude, 'in_file')
        preprocessing_workflow.connect(reorient_B0_phasediff, 'out_file',
                                       int_slope_B0_phasediff, 'in_file')
        #B0 field correction:
        if 'EchoSpacing' in analysis_params:
            B0_wf = create_B0_workflow(name='B0', scanner='siemens')
            preprocessing_workflow.connect(input_node, 'EchoSpacing', B0_wf,
                                           'inputspec.echo_spacing')
        else:
            B0_wf = create_B0_workflow(name='B0', scanner='philips')
            preprocessing_workflow.connect(input_node, 'WaterFatShift', B0_wf,
                                           'inputspec.wfs')
            preprocessing_workflow.connect(input_node, 'EpiFactor', B0_wf,
                                           'inputspec.epi_factor')
        preprocessing_workflow.connect(input_node, 'SenseFactor', B0_wf,
                                       'inputspec.acceleration')
        preprocessing_workflow.connect(reorient_epi, 'out_file', B0_wf,
                                       'inputspec.in_files')
        preprocessing_workflow.connect(int_slope_B0_magnitude, 'out_file',
                                       B0_wf, 'inputspec.fieldmap_mag')
        preprocessing_workflow.connect(int_slope_B0_phasediff, 'out_file',
                                       B0_wf, 'inputspec.fieldmap_pha')
        preprocessing_workflow.connect(input_node, 'EchoTimeDiff', B0_wf,
                                       'inputspec.te_diff')
        preprocessing_workflow.connect(input_node, 'PhaseEncodingDirection',
                                       B0_wf,
                                       'inputspec.phase_encoding_direction')
        preprocessing_workflow.connect(B0_wf, 'outputspec.field_coefs',
                                       datasink, 'B0.fieldcoef')
        preprocessing_workflow.connect(B0_wf, 'outputspec.out_files', datasink,
                                       'B0')

    # motion correction
    motion_proc = create_motion_correction_workflow(
        'moco', method=analysis_params['moco_method'])
    if analysis_params['B0_or_topup'] == 'B0':
        preprocessing_workflow.connect(B0_wf, 'outputspec.out_files',
                                       motion_proc, 'inputspec.in_files')
    elif analysis_params['B0_or_topup'] == 'neither':
        preprocessing_workflow.connect(bet_epi, 'out_file', motion_proc,
                                       'inputspec.in_files')
    preprocessing_workflow.connect(input_node, 'RepetitionTime', motion_proc,
                                   'inputspec.tr')
    preprocessing_workflow.connect(input_node, 'output_directory', motion_proc,
                                   'inputspec.output_directory')
    preprocessing_workflow.connect(input_node, 'which_file_is_EPI_space',
                                   motion_proc,
                                   'inputspec.which_file_is_EPI_space')

    # registration
    reg = create_registration_workflow(analysis_params, name='reg')
    preprocessing_workflow.connect(input_node, 'output_directory', reg,
                                   'inputspec.output_directory')
    preprocessing_workflow.connect(motion_proc, 'outputspec.EPI_space_file',
                                   reg, 'inputspec.EPI_space_file')
    preprocessing_workflow.connect(input_node, 'sub_FS_id', reg,
                                   'inputspec.freesurfer_subject_ID')
    preprocessing_workflow.connect(input_node, 'FS_subject_dir', reg,
                                   'inputspec.freesurfer_subject_dir')
    preprocessing_workflow.connect(input_node, 'standard_file', reg,
                                   'inputspec.standard_file')

    # temporal filtering
    preprocessing_workflow.connect(input_node, 'sg_filter_window_length',
                                   sgfilter, 'window_length')
    preprocessing_workflow.connect(input_node, 'sg_filter_order', sgfilter,
                                   'polyorder')
    preprocessing_workflow.connect(motion_proc,
                                   'outputspec.motion_corrected_files',
                                   sgfilter, 'in_file')
    preprocessing_workflow.connect(sgfilter, 'out_file', datasink, 'tf')

    # node for percent signal change
    preprocessing_workflow.connect(input_node, 'psc_func', psc, 'func')
    preprocessing_workflow.connect(sgfilter, 'out_file', psc, 'in_file')
    preprocessing_workflow.connect(psc, 'out_file', datasink, 'psc')

    # # retroicor functionality
    # if analysis_params['perform_physio'] == 1:
    #     retr = create_retroicor_workflow(name = 'retroicor', order_or_timing = analysis_params['retroicor_order_or_timing'])
    #
    #     # # retroicor can take the crudest form of epi file, so that it proceeds quickly
    #     preprocessing_workflow.connect(datasource, 'func', retr, 'inputspec.in_files')
    #     preprocessing_workflow.connect(datasource, 'physio', retr, 'inputspec.phys_files')
    #     preprocessing_workflow.connect(input_node, 'analysis_params.nr_dummies', retr, 'inputspec.nr_dummies')
    #     preprocessing_workflow.connect(input_node, 'analysis_params.MultiBandFactor', retr, 'inputspec.MB_factor')
    #     preprocessing_workflow.connect(input_node, 'analysis_params.tr', retr, 'inputspec.tr')
    #     preprocessing_workflow.connect(input_node, 'analysis_params.SliceEncodingDirection', retr, 'inputspec.slice_direction')
    #     preprocessing_workflow.connect(input_node, 'analysis_params.SliceTiming', retr, 'inputspec.slice_timing')
    #     preprocessing_workflow.connect(input_node, 'analysis_params.SliceOrder', retr, 'inputspec.slice_order')
    #     preprocessing_workflow.connect(input_node, 'analysis_params.PhysiologySampleRate', retr, 'inputspec.phys_sample_rate')
    #     preprocessing_workflow.connect(input_node, 'analysis_params.hr_rvt', retr, 'inputspec.hr_rvt')
    #
    #     # fit nuisances from retroicor
    #     # preprocessing_workflow.connect(retr, 'outputspec.evs', fit_nuis, 'slice_regressor_list')
    #     # preprocessing_workflow.connect(motion_proc, 'outputspec.extended_motion_correction_parameters', fit_nuis, 'vol_regressors')
    #     # preprocessing_workflow.connect(psc, 'out_file', fit_nuis, 'in_file')
    #
    #     # preprocessing_workflow.connect(fit_nuis, 'res_file', av_r, 'in_files')
    #
    #     preprocessing_workflow.connect(retr, 'outputspec.new_phys', datasink, 'phys.log')
    #     preprocessing_workflow.connect(retr, 'outputspec.fig_file', datasink, 'phys.figs')
    #     preprocessing_workflow.connect(retr, 'outputspec.evs', datasink, 'phys.evs')
    #     # preprocessing_workflow.connect(fit_nuis, 'res_file', datasink, 'phys.res')
    #     # preprocessing_workflow.connect(fit_nuis, 'rsq_file', datasink, 'phys.rsq')
    #     # preprocessing_workflow.connect(fit_nuis, 'beta_file', datasink, 'phys.betas')
    #
    #     # preprocessing_workflow.connect(av_r, 'out_file', datasink, 'av_r')

    #
    # ########################################################################################
    # # masking stuff if doing mri analysis
    # ########################################################################################
    #
    #     all_mask_opds = ['dc'] + analysis_parameters[u'avg_subject_RS_label_folders']
    #     all_mask_lds = [''] + analysis_parameters[u'avg_subject_RS_label_folders']
    #
    #     # loop across different folders to mask
    #     # untested as yet.
    #     masking_list = []
    #     dilate_list = []
    #     for opd, label_directory in zip(all_mask_opds,all_mask_lds):
    #         dilate_list.append(
    #             pe.MapNode(interface=fsl.maths.DilateImage(
    #                 operation = 'mean', kernel_shape = 'sphere', kernel_size = analysis_parameters['dilate_kernel_size']),
    #                 name='dilate_'+label_directory, iterfield=['in_file']))
    #
    #         masking_list.append(create_masks_from_surface_workflow(name = 'masks_from_surface_'+label_directory))
    #
    #         masking_list[-1].inputs.inputspec.label_directory = label_directory
    #         masking_list[-1].inputs.inputspec.fill_thresh = 0.005
    #         masking_list[-1].inputs.inputspec.re = '*.label'
    #
    #         preprocessing_workflow.connect(motion_proc, 'outputspec.EPI_space_file', masking_list[-1], 'inputspec.EPI_space_file')
    #         preprocessing_workflow.connect(input_node, 'output_directory', masking_list[-1], 'inputspec.output_directory')
    #         preprocessing_workflow.connect(input_node, 'FS_subject_dir', masking_list[-1], 'inputspec.freesurfer_subject_dir')
    #         preprocessing_workflow.connect(input_node, 'FS_ID', masking_list[-1], 'inputspec.freesurfer_subject_ID')
    #         preprocessing_workflow.connect(reg, 'rename_register.out_file', masking_list[-1], 'inputspec.reg_file')
    #
    #         preprocessing_workflow.connect(masking_list[-1], 'outputspec.masks', dilate_list[-1], 'in_file')
    #         preprocessing_workflow.connect(dilate_list[-1], 'out_file', datasink, 'masks.'+opd)
    #
    #     # # surface-based label import in to EPI space, but now for RS labels
    #     # these should have been imported to the subject's FS folder,
    #     # see scripts/annot_conversion.sh
    #     RS_masks_from_surface = create_masks_from_surface_workflow(name = 'RS_masks_from_surface')
    #     RS_masks_from_surface.inputs.inputspec.label_directory = analysis_parameters['avg_subject_label_folder']
    #     RS_masks_from_surface.inputs.inputspec.fill_thresh = 0.005
    #     RS_masks_from_surface.inputs.inputspec.re = '*.label'
    #
    #     preprocessing_workflow.connect(motion_proc, 'outputspec.EPI_space_file', RS_masks_from_surface, 'inputspec.EPI_space_file')
    #     preprocessing_workflow.connect(input_node, 'output_directory', RS_masks_from_surface, 'inputspec.output_directory')
    #     preprocessing_workflow.connect(input_node, 'FS_subject_dir', RS_masks_from_surface, 'inputspec.freesurfer_subject_dir')
    #     preprocessing_workflow.connect(input_node, 'FS_ID', RS_masks_from_surface, 'inputspec.freesurfer_subject_ID')
    #     preprocessing_workflow.connect(reg, 'rename_register.out_file', RS_masks_from_surface, 'inputspec.reg_file')
    #
    #     preprocessing_workflow.connect(RS_masks_from_surface, 'outputspec.masks', RS_dilate_cortex, 'in_file')
    #     preprocessing_workflow.connect(RS_dilate_cortex, 'out_file', datasink, 'masks.'+analysis_parameters['avg_subject_label_folder'])

    ########################################################################################
    # wrapping up, sending data to datasink
    ########################################################################################

    # preprocessing_workflow.connect(bet_epi, 'out_file', datasink, 'bet.epi')
    # preprocessing_workflow.connect(bet_epi, 'mask_file', datasink, 'bet.epimask')
    # preprocessing_workflow.connect(bet_topup, 'out_file', datasink, 'bet.topup')
    # preprocessing_workflow.connect(bet_topup, 'mask_file', datasink, 'bet.topupmask')

    # preprocessing_workflow.connect(nuc, 'out_file', datasink, 'nuc')
    # preprocessing_workflow.connect(sgfilter, 'out_file', datasink, 'tf')
    # preprocessing_workflow.connect(psc, 'out_file', datasink, 'psc')
    # preprocessing_workflow.connect(datasource, 'physio', datasink, 'phys')

    return preprocessing_workflow
Ejemplo n.º 22
0
def create_pipeline_SS_TV(bids_dir,
                          work_dir,
                          out_dir,
                          subjects,
                          sessions,
                          mag_match_pattern,
                          phase_match_pattern,
                          mask_match_pattern,
                          keep_unnecessary_outputs,
                          FAST_bias_iters,
                          FAST_bias_lowpass,
                          FAST_num_classes,
                          skip_fast,
                          brain_extract_method,
                          BET_frac,
                          single_subject_custom_mask,
                          freq_weights__snr_window_sz,
                          truncate_echo,
                          SS_TV_lagrange_parameter,
                          B0_dir,
                          scnd_diff_reliability_thresh_noise,
                          trim_radius_sz,
                          scnd_diff_reliability_thresh_trim,
                          skip_qsm,
                          skip_r2star,
                          matlab_executable,
                          mcr_location,
                          run_mode):
    layout = BIDSLayout(bids_dir)

    ### CREATE PIPELINE OBJECT
    pipelineDir = work_dir
    wf = pe.Workflow(name="SS_TV")
    wf.base_dir = pipelineDir
    wf.config['execution']['remove_unnecessary_outputs'] = not keep_unnecessary_outputs

    ### GET MULTI-ECHO DATA
    # can we do this more elegantly?
    first_echo_files = []
    for subject in subjects:
        if layout.get_sessions(subject=subject) == []:
            if sessions == ['.*']:
                first_echo_files = first_echo_files + layout.get(subject=subject, modality='anat',
                                                                 extensions='.*part-phase.*echo-0*1.*.nii.*', )
            else:
                print(
                    "Warning: Session filter applied, but subject " + subject + " has no bids session information. This subject has been ignored.")
        else:
            for session in sessions:
                first_echo_files = first_echo_files + layout.get(subject=subject, session=session, modality='anat',
                                                                 extensions='.*part-phase.*echo-0*1.*.nii.*', )
    anat_folders = []
    for img in first_echo_files:
        full_dirname = os.path.dirname(img.filename)
        remove_base_dir = full_dirname.replace(bids_dir, '')
        remove_leading_slash = remove_base_dir.lstrip(os.sep)
        anat_folders.append(remove_leading_slash)

    anat_folders = list(set(anat_folders))
    anat_folders.sort()

    # IdentityInterface is useful for passing subject directory structure to datasink
    infosource = pe.Node(niu.IdentityInterface(fields=['subject_id']), name="infosource")
    infosource.iterables = ('subject_id', anat_folders)

    ### NODES AND PARAMETERS
    if brain_extract_method == BrainExtractMethod.BIDS:
        datasource = pe.Node(
            nio.DataGrabber(infields=['subject_id'],
                            outfields=['phase_images', 'mag_images', 'phase_jsons', 'mag_jsons', 'brain_mask']),
            name='datasource')
        datasource.inputs.field_template = dict(
            phase_images='%s/' + phase_match_pattern + '.nii*',
            phase_jsons='%s/' + phase_match_pattern + '.json',
            mag_images='%s/' + mag_match_pattern + '.nii*',
            mag_jsons='%s/' + mag_match_pattern + '.json',
            brain_mask='%s/' + mask_match_pattern + '.nii*',
        )
    else:
        datasource = pe.Node(
            nio.DataGrabber(infields=['subject_id'],
                            outfields=['phase_images', 'mag_images', 'phase_jsons', 'mag_jsons']),
            name='datasource')
        datasource.inputs.field_template = dict(
            phase_images='%s/' + phase_match_pattern + '.nii*',
            phase_jsons='%s/' + phase_match_pattern + '.json',
            mag_images='%s/' + mag_match_pattern + '.nii*',
            mag_jsons='%s/' + mag_match_pattern + '.json',
        )
    datasource.inputs.sort_filelist = True
    datasource.inputs.template = "*"
    datasource.inputs.base_directory = bids_dir

    # this node must change depending on the scanner vendor
    susc_phase_preprocess = pe.Node(SiemensPhasePreprocess(), name='susc_phase_preprocess')

    avg_and_freq_estimate_weights = pe.Node(GetAvgAndSNRMap(), name='avg_and_freq_estimate_weights')
    avg_and_freq_estimate_weights.inputs.snr_window_sz = freq_weights__snr_window_sz
    avg_and_freq_estimate_weights.inputs.avg_out_filename = "avg.nii.gz"
    avg_and_freq_estimate_weights.inputs.snr_map_out_filename = "weights.nii.gz"

    wf.connect([
        (infosource, datasource, [('subject_id', 'subject_id')]),
        (datasource, avg_and_freq_estimate_weights, [('mag_images', 'mag')]),
        (datasource, susc_phase_preprocess, [('phase_images', 'infiles')])
    ])

    if brain_extract_method == BrainExtractMethod.BET:
        brain_extract = pe.Node(fsl.BET(), name='brain_extract_bet')
        brain_extract.inputs.frac = BET_frac
        brain_extract.inputs.mask = True
        brain_extract.inputs.robust = True

        if skip_fast:
            # connect avg directly to bet (skip FAST if image uniform enough for brain extraction)
            wf.connect([
                (avg_and_freq_estimate_weights, brain_extract, [('avg_out_filename', 'in_file')])
            ])
        else:
            # connect avg to nu correction, connect nu correction to bet
            """
            #spm worked better for varian 7T data
            #if using spm, these prameters are needed
            bias_regularization=.001
            sampling_distance=2.0
            bias_fwhm=30

            nonuniformityCorrect_spm=pe.Node(spm.preprocess.Segment(),name='nonuniformityCorrect_spm')
            nonuniformityCorrect_spm.inputs.bias_regularization=bias_regularization
            nonuniformityCorrect_spm.inputs.sampling_distance=sampling_distance
            nonuniformityCorrect_spm.inputs.bias_fwhm=bias_fwhm
            nonuniformityCorrect_spm.inputs.save_bias_corrected=True
            """
            nonuniformity_correct_fsl = pe.Node(fsl.FAST(), name='nonuniformity_correct_fsl')
            nonuniformity_correct_fsl.inputs.img_type = 2  # 1 for t1, 2 for t2
            nonuniformity_correct_fsl.inputs.bias_iters = FAST_bias_iters  # higher for larger nonuniformity
            nonuniformity_correct_fsl.inputs.bias_lowpass = FAST_bias_lowpass  # spm uses 30
            nonuniformity_correct_fsl.inputs.number_classes = FAST_num_classes  # spm uses 5
            nonuniformity_correct_fsl.inputs.output_biasfield = True
            nonuniformity_correct_fsl.inputs.output_biascorrected = True
            nonuniformity_correct_fsl.interface.estimated_memory_gb = 10

            wf.connect([
                # spm requires matlab
                # (avg_and_freq_estimate_weights, nonuniformityCorrect_spm, [('avgOutFilename', 'data')]),
                # (nonuniformityCorrect_spm, brain_extract, [('bias_corrected_image', 'in_file')]),
                (avg_and_freq_estimate_weights, nonuniformity_correct_fsl, [('avg_out_filename', 'in_files')]),
                (nonuniformity_correct_fsl, brain_extract, [('restored_image', 'in_file')])
            ])
    elif brain_extract_method == BrainExtractMethod.BIDS:
        brain_extract = pe.Node(
            nio.DataGrabber(infields=['subject_id'],
                            outfields=['mask_file']),
            name='bids_brain_mask')
        brain_extract.inputs.field_template = dict(
            mask_file='%s/' + mask_match_pattern + '.nii*',
        )
        brain_extract.inputs.sort_filelist = False
        brain_extract.inputs.template = "*"
        brain_extract.inputs.base_directory = bids_dir
        wf.connect([
            (infosource, brain_extract, [('subject_id', 'subject_id')]),
        ])

    elif brain_extract_method == BrainExtractMethod.SINGLE_SUBJECT_FULL_PATH:
        brain_extract = pe.Node(niu.IdentityInterface(fields=['mask_file']), name="fullpath_brain_mask")
        brain_extract.inputs.mask_file = single_subject_custom_mask

    freq_est = pe.Node(EstimateFrequencyFromWrappedPhase(), 'freq_est')
    freq_est.inputs.truncate_echo = truncate_echo
    freq_est.inputs.freq_filename = "freq_est.nii.gz"
    freq_est.interface.estimated_memory_gb = 4

    fieldmap_reorient = pe.Node(fsl.Reorient2Std(), name='fieldmap_reorient')

    datasink = pe.Node(nio.DataSink(), name="datasink")
    datasink.inputs.base_directory = out_dir + '/qsm_sstv/'
    datasink.inputs.parameterization = False

    rename_infosource = pe.Node(replace_slash, "rename_infosource")
    rename_fieldmap = pe.Node(niu.Rename(format_string="%(subject_id)s-fieldmap", keep_ext=True), "rename_fieldmap")

    wf.connect([
        (susc_phase_preprocess, freq_est, [('outfiles', 'phase')]),
        (datasource, freq_est, [('phase_jsons', 'json')]),
        (brain_extract, freq_est, [('mask_file', 'mask')]),
        (avg_and_freq_estimate_weights, freq_est, [('snr_map_out_filename', 'weight')]),
        (freq_est, fieldmap_reorient, [('freq_filename', 'in_file')]),
        # rename files and data sink
        (infosource, rename_infosource, [('subject_id', 'filename')]),
        # fieldmap
        (rename_infosource, rename_fieldmap, [('renamed', 'subject_id')]),
        (fieldmap_reorient, rename_fieldmap, [('out_file', 'in_file')]),
        (rename_fieldmap, datasink, [('out_file', '@')]),
        (infosource, datasink, [('subject_id', 'container')]),
    ])

    if not (skip_qsm and skip_r2star):
        trim_mask = pe.Node(TrimMaskUsingReliability(), name='trim_mask')
        trim_mask.inputs.erosion_sz = trim_radius_sz  # in mm
        trim_mask.inputs.threshold = scnd_diff_reliability_thresh_trim
        trim_mask.inputs.trimmed_mask_filename = "trim_mask.nii.gz"
        trim_mask.inputs.reliability_filename = "unreliableMap.nii.gz"
        trim_mask.interface.estimated_memory_gb = 25

        wf.connect([
            (freq_est, trim_mask, [('freq_filename', 'phase')]),
            (brain_extract, trim_mask, [('mask_file', 'mask')])
        ])

    if not skip_qsm:
        unreliable_fieldmap_voxels = pe.Node(CalculateReliabilityMask(), name='unreliable_fieldmap_voxels')
        unreliable_fieldmap_voxels.inputs.threshold = scnd_diff_reliability_thresh_noise
        unreliable_fieldmap_voxels.inputs.reliability_mask_filename = "unreliableMask.nii.gz"
        unreliable_fieldmap_voxels.inputs.reliability_filename = "unreliableMap.nii.gz"

        CF_value = pe.Node(GetCFFromJson, name='CFValue')

        susceptibility = pe.Node(SS_TV(run_mode, matlab_executable, mcr_location), name='susceptibility')
        susceptibility.inputs.alpha = SS_TV_lagrange_parameter
        susceptibility.inputs.B0_dir = B0_dir
        susceptibility.inputs.susceptibility_filename = 'susceptibilityMap.nii.gz'
        susceptibility.interface.estimated_memory_gb = 10

        QSM_reorient = pe.Node(fsl.Reorient2Std(), name='QSM_reorient')
        QSM_brain_mask_reorient = pe.Node(fsl.Reorient2Std(), name='QSM_brain_mask_reorient')
        QSM_noise_mask_reorient = pe.Node(fsl.Reorient2Std(), name='QSM_noise_mask_reorient')

        rename_QSM = pe.Node(niu.Rename(format_string="%(subject_id)s-QSM", keep_ext=True), "rename_QSM")
        rename_QSM_brain_mask = pe.Node(niu.Rename(format_string="%(subject_id)s-QSM_brainMask", keep_ext=True),
                                        "rename_QSM_brain_mask")
        rename_QSM_noise_mask = pe.Node(niu.Rename(format_string="%(subject_id)s-QSM_noiseMask", keep_ext=True),
                                        "rename_QSM_noise_mask")
        wf.connect([
            (freq_est, unreliable_fieldmap_voxels, [('freq_filename', 'phase')]),
            (brain_extract, unreliable_fieldmap_voxels, [('mask_file', 'mask')]),
            (freq_est, susceptibility, [('freq_filename', 'freq_loc')]),
            (datasource, CF_value, [('mag_jsons', 'filename')]),
            (unreliable_fieldmap_voxels, susceptibility, [('reliability_mask_filename', 'reliability_mask_loc')]),
            (trim_mask, susceptibility, [('trimmed_mask_filename', 'mask_loc')]),
            (CF_value, susceptibility, [('CF_value', 'CF')]),

            (susceptibility, QSM_reorient, [('susceptibility_filename', 'in_file')]),
            (trim_mask, QSM_brain_mask_reorient, [('trimmed_mask_filename', 'in_file')]),
            (unreliable_fieldmap_voxels, QSM_noise_mask_reorient, [('reliability_mask_filename', 'in_file')]),

            # qsm
            (rename_infosource, rename_QSM, [('renamed', 'subject_id')]),
            (QSM_reorient, rename_QSM, [('out_file', 'in_file')]),
            (rename_QSM, datasink, [('out_file', '@.@qsm')]),
            # qsm brain mask
            (rename_infosource, rename_QSM_brain_mask, [('renamed', 'subject_id')]),
            (QSM_brain_mask_reorient, rename_QSM_brain_mask, [('out_file', 'in_file')]),
            (rename_QSM_brain_mask, datasink, [('out_file', '@.@qsm_brain')]),
            # qsm noisey voxels in fieldmap
            (rename_infosource, rename_QSM_noise_mask, [('renamed', 'subject_id')]),
            (QSM_noise_mask_reorient, rename_QSM_noise_mask, [('out_file', 'in_file')]),
            (rename_QSM_noise_mask, datasink, [('out_file', '@.@qsm_noise')]),
        ])

    if not skip_r2star:
        R2Star = pe.Node(CalcR2Star(), 'R2Star')
        R2Star.inputs.R2star = 'R2star.nii.gz'
        R2Star.inputs.neg_mask = 'negMask.nii.gz'
        R2Star.inputs.nan_mask = 'nanMask.nii.gz'
        # R2Star.interface.estimated_memory_gb = 5

        R2star_reorient = pe.Node(fsl.Reorient2Std(), name='R2star_reorient')
        R2star_fit_reorient = pe.Node(fsl.Reorient2Std(), name='R2star_fit_reorient')
        R2star_neg_mask_reorient = pe.Node(fsl.Reorient2Std(), name='R2star_neg_mask_reorient')

        rename_R2star = pe.Node(niu.Rename(format_string="%(subject_id)s-R2star", keep_ext=True), "rename_R2star")
        rename_R2star_fit = pe.Node(niu.Rename(format_string="%(subject_id)s-R2star_fit", keep_ext=True),
                                    "rename_R2star_fit")
        rename_R2star_neg_mask = pe.Node(niu.Rename(format_string="%(subject_id)s-R2star_negMask", keep_ext=True),
                                         "rename_R2star_neg_mask")

        wf.connect([
            (datasource, R2Star, [('mag_images', 'mag')]),
            (susc_phase_preprocess, R2Star, [('outfiles', 'phase')]),
            (freq_est, R2Star, [('freq_filename', 'freq_loc')]),
            (trim_mask, R2Star, [('trimmed_mask_filename', 'mask')]),
            (datasource, R2Star, [('mag_jsons', 'json')]),
            (R2Star, R2star_reorient, [('R2star', 'in_file')]),
            (R2Star, R2star_fit_reorient, [('R2star_fit', 'in_file')]),
            (R2Star, R2star_neg_mask_reorient, [('neg_mask', 'in_file')]),
            # r2star
            (rename_infosource, rename_R2star, [('renamed', 'subject_id')]),
            (R2star_reorient, rename_R2star, [('out_file', 'in_file')]),
            (rename_R2star, datasink, [('out_file', '@.@r2star')]),
            # r2star fit map
            (rename_infosource, rename_R2star_fit, [('renamed', 'subject_id')]),
            (R2star_fit_reorient, rename_R2star_fit, [('out_file', 'in_file')]),
            (rename_R2star_fit, datasink, [('out_file', '@.@r2starfit')]),
            # r2star negative values that were set to 0
            (rename_infosource, rename_R2star_neg_mask, [('renamed', 'subject_id')]),
            (R2star_neg_mask_reorient, rename_R2star_neg_mask, [('out_file', 'in_file')]),
            (rename_R2star_neg_mask, datasink, [('out_file', '@.@r2starneg')]),
        ])

    return wf
Ejemplo n.º 23
0
        inputnode.inputs.source_file = func2

    # Motion correction + slice timing correction
    realign4d = pe.Node(interface=SpaceTimeRealigner(), name='realign4d')
    realign4d.inputs.ignore_exception = True
    realign4d.inputs.slice_times = 'asc_alt_siemens'
    realign4d.inputs.slice_info = 2
    realign4d.inputs.tr = 2.00

    workflow1.connect(inputnode, 'source_file', realign4d, 'in_file')
    workflow1.connect(realign4d, 'par_file', outputnode, 'move_par')

    # Reorient
    #deoblique = pe.Node(interface=afni.Warp(deoblique=True, outputtype='NIFTI_GZ'), name='deoblique')
    #workflow1.connect(realign4d, 'out_file', deoblique, 'in_file')
    reorient = pe.Node(interface=fsl.Reorient2Std(output_type='NIFTI_GZ'),
                       name='reorient')
    workflow1.connect(realign4d, 'out_file', reorient, 'in_file')
    workflow1.connect(reorient, 'out_file', outputnode, 'out_file')

    # Run workflow1
    workflow1.write_graph()
    workflow1.run()

    # Initialize DRIFTER
    if data == 'func1':
        #check is physiological signals exist, if not, then None
        infile = results_path + '/' + data + '_1/reorient/corr_epi_reoriented.nii.gz'
        physsig_a = physsig1
        if not os.path.isfile(physsig1):
            print "MISSING PULS DATA!"
def prepro_func(i):
    try:
        subj = i
        for s in (['session2']):

            # Define input files: 2xfMRI + 1xMPRAGE
            func1 = data_path + subj + '/Functional_scans/' + s[:-2] + s[
                -1] + '_a/epi.nii.gz'  #choose this for patients
            func2 = data_path + subj + '/Functional_scans/' + s[:-2] + s[
                -1] + '_b/epi.nii.gz'  #choose this for patients
            #anat = glob.glob(anat_path + subj +'/'+ s + '/anat/reorient/anat_*.nii.gz') #choose this for session 1
            lesion_mask_file = anat_path + subj + '/session1/anat/reorient/lesion_seg.nii.gz'
            old_lesion_mask_file = glob.glob(
                anat_path + subj +
                '/session1/anat/reorient/old_lesion_seg.nii.gz'
            )  #choose this for ones with no old lesion
            #old_lesion_mask_file = anat_path + subj +'/session1/anat/reorient/old_lesion_seg.nii.gz' #choose this for ones with old lesion
            anat = glob.glob(anat_path + subj + '/' + s +
                             '/anat/anat2hr/anat_*.nii.gz'
                             )  #choose this for sessions 2 and 3
            anat_CSF = glob.glob(
                anat_path + subj +
                '/session1/seg_anat/segmentation/anat_*_pve_0.nii.gz'
            )  # don't change, same for all sessions
            anat_WM = glob.glob(
                anat_path + subj +
                '/session1/seg_anat/segmentation/anat_*_pve_2.nii.gz'
            )  # don't change, same for all sessions
            anat_GM = glob.glob(
                anat_path + subj +
                '/session1/seg_anat/segmentation/anat_*_pve_1.nii.gz'
            )  # don't change, same for all sessions
            anat2MNI_fieldwarp = glob.glob(
                anat_path + subj +
                '/session1/anat/nonlinear_reg/anat_*_fieldwarp.nii.gz'
            )  # don't change, same for all sessions

            if not os.path.isdir(data_path + subj + '/' + s):  # No data exists
                continue

            if not os.path.isfile(func1):
                print '1. functional file ' + func1 + ' not found. Skipping!'
                continue

            if not os.path.isfile(func2):
                print '2. functional file ' + func2 + ' not found. Skipping!'
                continue

            if not anat:
                print 'Preprocessed anatomical file not found. Skipping!'
                continue
            if len(anat) > 1:
                print 'WARNING: found multiple files of preprocessed anatomical image!'
                continue
            anat = anat[0]

            if not anat2MNI_fieldwarp:
                print 'Anatomical registration to MNI152-space field file not found. Skipping!'
                continue
            if len(anat2MNI_fieldwarp) > 1:
                print 'WARNING: found multiple files of anat2MNI fieldwarp!'
                continue
            anat2MNI_fieldwarp = anat2MNI_fieldwarp[0]

            if not anat_CSF:
                anat_CSF = glob.glob(
                    anat_path + subj + '/' + s +
                    '/seg_anat/segmentation/anat_*_pve_0.nii.gz')
                if not anat_CSF:
                    print 'Anatomical segmentation CSF file not found. Skipping!'
                    continue
            if len(anat_CSF) > 1:
                print 'WARNING: found multiple files of anatomical CSF file!'
                continue
            anat_CSF = anat_CSF[0]

            if not anat_WM:
                anat_WM = glob.glob(
                    anat_path + subj + '/' + s +
                    '/seg_anat/segmentation/anat_*_pve_2.nii.gz')
                if not anat_WM:
                    print 'Anatomical segmentation WM file not found. Skipping!'
                    continue
            if len(anat_WM) > 1:
                print 'WARNING: found multiple files of anatomical WM file!'
                continue
            anat_WM = anat_WM[0]

            if not anat_GM:
                anat_GM = glob.glob(
                    anat_path + subj + '/' + s +
                    '/seg_anat/segmentation/anat_*_pve_1.nii.gz')
                if not anat_GM:
                    print 'Anatomical segmentation GM file not found. Skipping!'
                    continue
            if len(anat_GM) > 1:
                print 'WARNING: found multiple files of anatomical GM file!'
                continue
            anat_GM = anat_GM[0]

            if not os.path.isdir(results_path + subj):
                os.mkdir(results_path + subj)

            if not os.path.isdir(results_path + subj + '/' + s):
                os.mkdir(results_path + subj + '/' + s)

            for data in acquisitions:

                os.chdir(results_path + subj + '/' + s)
                print "Currently processing subject: " + subj + '/' + s + ' ' + data

                #Initialize workflows
                workflow = pe.Workflow(name=data)

                workflow.base_dir = '.'
                inputnode = pe.Node(
                    interface=util.IdentityInterface(fields=['source_file']),
                    name='inputspec')
                outputnode = pe.Node(
                    interface=util.IdentityInterface(fields=['result_func']),
                    name='outputspec')

                if data == 'func1':
                    inputnode.inputs.source_file = func1
                else:
                    inputnode.inputs.source_file = func2

                # Remove n_dummies first volumes
                trim = pe.Node(interface=Trim(begin_index=n_dummies),
                               name='trim')
                workflow.connect(inputnode, 'source_file', trim, 'in_file')

                # Motion correction + slice timing correction
                realign4d = pe.Node(interface=SpaceTimeRealigner(),
                                    name='realign4d')
                #realign4d.inputs.ignore_exception=True
                realign4d.inputs.slice_times = 'asc_alt_siemens'

                realign4d.inputs.slice_info = 2  # horizontal slices
                realign4d.inputs.tr = mytr  # TR in seconds
                workflow.connect(trim, 'out_file', realign4d, 'in_file')

                # Reorient
                #deoblique = pe.Node(interface=afni.Warp(deoblique=True, outputtype='NIFTI_GZ'), name='deoblique') #leave out if you don't need this
                #workflow.connect(realign4d, 'out_file', deoblique, 'in_file')
                reorient = pe.Node(
                    interface=fsl.Reorient2Std(output_type='NIFTI_GZ'),
                    name='reorient')
                workflow.connect(realign4d, 'out_file', reorient, 'in_file')

                # AFNI skullstrip and mean image skullstrip
                tstat1 = pe.Node(interface=afni.TStat(args='-mean',
                                                      outputtype="NIFTI_GZ"),
                                 name='tstat1')
                automask = pe.Node(interface=afni.Automask(
                    dilate=1, outputtype="NIFTI_GZ"),
                                   name='automask')
                skullstrip = pe.Node(interface=afni.Calc(
                    expr='a*b', outputtype="NIFTI_GZ"),
                                     name='skullstrip')
                tstat2 = pe.Node(interface=afni.TStat(args='-mean',
                                                      outputtype="NIFTI_GZ"),
                                 name='tstat2')

                workflow.connect(reorient, 'out_file', tstat1, 'in_file')
                workflow.connect(tstat1, 'out_file', automask, 'in_file')
                workflow.connect(automask, 'out_file', skullstrip, 'in_file_b')
                workflow.connect(reorient, 'out_file', skullstrip, 'in_file_a')
                workflow.connect(skullstrip, 'out_file', tstat2, 'in_file')

                # Register to anatomical space #can be changed
                #mean2anat = pe.Node(fsl.FLIRT(bins=40, cost='normmi', dof=7, interp='nearestneighbour', searchr_x=[-180,180], searchr_y=[-180,180], searchr_z=[-180,180]), name='mean2anat')
                mean2anat = pe.Node(fsl.FLIRT(bins=40,
                                              cost='normmi',
                                              dof=7,
                                              interp='nearestneighbour'),
                                    name='mean2anat')
                #mean2anat = pe.Node(fsl.FLIRT(no_search=True), name='mean2anat')
                mean2anat.inputs.reference = anat
                workflow.connect(tstat2, 'out_file', mean2anat, 'in_file')

                # Transform mean functional image
                warpmean = pe.Node(interface=fsl.ApplyWarp(), name='warpmean')
                warpmean.inputs.ref_file = MNI_brain
                warpmean.inputs.field_file = anat2MNI_fieldwarp
                workflow.connect(mean2anat, 'out_matrix_file', warpmean,
                                 'premat')
                workflow.connect(tstat2, 'out_file', warpmean, 'in_file')

                # ----- inversion matrix and eroded brain mask for regression -----

                # create inverse matrix from mean2anat registration
                invmat = pe.Node(fsl.ConvertXFM(), name='invmat')
                invmat.inputs.invert_xfm = True
                workflow.connect(mean2anat, 'out_matrix_file', invmat,
                                 'in_file')

                # erode functional brain mask
                erode_brain = pe.Node(fsl.ImageMaths(), name='erode_brain')
                erode_brain.inputs.args = '-kernel boxv 3 -ero'
                workflow.connect(automask, 'out_file', erode_brain, 'in_file')

                # register GM mask to functional image space, this is done for quality control
                reg_GM = pe.Node(fsl.preprocess.ApplyXFM(), name='register_GM')
                reg_GM.inputs.apply_xfm = True
                reg_GM.inputs.in_file = anat_GM
                workflow.connect(tstat2, 'out_file', reg_GM, 'reference')
                workflow.connect(invmat, 'out_file', reg_GM, 'in_matrix_file')

                # --------- motion regression and censor signals ------------------

                # normalize motion parameters
                norm_motion = pe.Node(interface=Function(
                    input_names=['in_file'],
                    output_names=['out_file'],
                    function=normalize_motion_data),
                                      name='normalize_motion')
                workflow.connect(realign4d, 'par_file', norm_motion, 'in_file')

                # create censor file, for censoring motion
                get_censor = pe.Node(afni.OneDToolPy(), name='motion_censors')
                get_censor.inputs.set_nruns = 1
                get_censor.inputs.censor_motion = (censor_thr, 'motion')
                get_censor.inputs.show_censor_count = True
                if overwrite: get_censor.inputs.args = '-overwrite'
                workflow.connect(norm_motion, 'out_file', get_censor,
                                 'in_file')

                # compute motion parameter derivatives (for use in regression)
                deriv_motion = pe.Node(afni.OneDToolPy(), name='deriv_motion')
                deriv_motion.inputs.set_nruns = 1
                deriv_motion.inputs.derivative = True
                if overwrite: deriv_motion.inputs.args = '-overwrite'
                deriv_motion.inputs.out_file = 'motion_derivatives.txt'
                workflow.connect(norm_motion, 'out_file', deriv_motion,
                                 'in_file')

                # scale motion parameters and get quadratures
                quadr_motion = pe.Node(interface=Function(
                    input_names=['in_file', 'multicol'],
                    output_names=['out_file', 'out_quadr_file'],
                    function=scale_and_quadrature),
                                       name='quadr_motion')
                quadr_motion.inputs.multicol = True
                workflow.connect(norm_motion, 'out_file', quadr_motion,
                                 'in_file')

                # scale motion derivatives and get quadratures
                quadr_motion_deriv = pe.Node(interface=Function(
                    input_names=['in_file', 'multicol'],
                    output_names=['out_file', 'out_quadr_file'],
                    function=scale_and_quadrature),
                                             name='quadr_motion_deriv')
                quadr_motion_deriv.inputs.multicol = True
                workflow.connect(deriv_motion, 'out_file', quadr_motion_deriv,
                                 'in_file')

                # -------- CSF regression signals ---------------

                # threshold and erode CSF mask
                erode_CSF_mask = pe.Node(fsl.ImageMaths(),
                                         name='erode_CSF_mask')
                erode_CSF_mask.inputs.args = '-thr 0.5 -kernel boxv 3 -ero'
                erode_CSF_mask.inputs.in_file = anat_CSF

                # register CSF mask to functional image space
                reg_CSF_mask = pe.Node(fsl.preprocess.ApplyXFM(),
                                       name='register_CSF_mask')
                reg_CSF_mask.inputs.apply_xfm = True
                workflow.connect(tstat2, 'out_file', reg_CSF_mask, 'reference')
                workflow.connect(invmat, 'out_file', reg_CSF_mask,
                                 'in_matrix_file')

                # inverse lesion mask and remove it from CSF mask #remove this if you don't have a lesion mask
                inverse_lesion_mask = pe.Node(fsl.ImageMaths(),
                                              name='inverse_lesion_mask')
                inverse_lesion_mask.inputs.args = '-add 1 -rem 2'
                inverse_lesion_mask.inputs.in_file = lesion_mask_file
                rem_lesion = pe.Node(fsl.ImageMaths(), name='remove_lesion')
                workflow.connect(erode_CSF_mask, 'out_file', rem_lesion,
                                 'in_file')
                workflow.connect(inverse_lesion_mask, 'out_file', rem_lesion,
                                 'mask_file')
                '''
			# Transform lesion mask to MNI152 space #remove if lesion masks are already in MNI152 space
		        warp_lesion = pe.Node(interface=fsl.ApplyWarp(), name='warp_lesion')
		        warp_lesion.inputs.ref_file = MNI_brain
		        warp_lesion.inputs.field_file = anat2MNI_fieldwarp
			warp_lesion.inputs.in_file = lesion_mask_file
			warp_lesion.inputs.out_file = anat_path + subj +'/'+ s + '/anat/nonlinear_reg/lesion_seg_warp.nii.gz'
			warp_lesion.run()
			'''

                # inverse old lesion mask and remove it from CSF mask #remove this if you don't have a lesion mask
                if old_lesion_mask_file:
                    inverse_old_lesion_mask = pe.Node(
                        fsl.ImageMaths(), name='inverse_old_lesion_mask')
                    inverse_old_lesion_mask.inputs.args = '-add 1 -rem 3'
                    #inverse_old_lesion_mask.inputs.in_file = old_lesion_mask_file[0]
                    inverse_old_lesion_mask.inputs.in_file = old_lesion_mask_file
                    rem_old_lesion = pe.Node(fsl.ImageMaths(),
                                             name='remove_old_lesion')
                    workflow.connect(rem_lesion, 'out_file', rem_old_lesion,
                                     'in_file')
                    workflow.connect(inverse_old_lesion_mask, 'out_file',
                                     rem_old_lesion, 'mask_file')
                    workflow.connect(rem_old_lesion, 'out_file', reg_CSF_mask,
                                     'in_file')
                    '''
			    # Transform old lesion mask to MNI152 space #remove if lesion masks are already in MNI152 space
		            warp_old_lesion = pe.Node(interface=fsl.ApplyWarp(), name='warp_old_lesion')
		            warp_old_lesion.inputs.ref_file = MNI_brain
		            warp_old_lesion.inputs.field_file = anat2MNI_fieldwarp
			    warp_old_lesion.inputs.in_file = old_lesion_mask_file
			    warp_old_lesion.inputs.out_file = anat_path + subj +'/'+ s + '/anat/nonlinear_reg/old_lesion_seg_warp.nii.gz'
			    warp_old_lesion.run()
			    '''

                else:
                    workflow.connect(rem_lesion, 'out_file', reg_CSF_mask,
                                     'in_file')

                # threshold CSF mask and intersect with functional brain mask
                thr_CSF_mask = pe.Node(fsl.ImageMaths(),
                                       name='threshold_CSF_mask')
                thr_CSF_mask.inputs.args = '-thr 0.25'
                workflow.connect(reg_CSF_mask, 'out_file', thr_CSF_mask,
                                 'in_file')
                workflow.connect(erode_brain, 'out_file', thr_CSF_mask,
                                 'mask_file')

                # extract CSF values
                get_CSF_noise = pe.Node(fsl.ImageMeants(),
                                        name='get_CSF_noise')
                workflow.connect(skullstrip, 'out_file', get_CSF_noise,
                                 'in_file')
                workflow.connect(thr_CSF_mask, 'out_file', get_CSF_noise,
                                 'mask')

                # compute CSF noise derivatives
                deriv_CSF = pe.Node(afni.OneDToolPy(), name='deriv_CSF')
                deriv_CSF.inputs.set_nruns = 1
                deriv_CSF.inputs.derivative = True
                if overwrite: deriv_CSF.inputs.args = '-overwrite'
                deriv_CSF.inputs.out_file = 'CSF_derivatives.txt'
                workflow.connect(get_CSF_noise, 'out_file', deriv_CSF,
                                 'in_file')

                # scale SCF noise and get quadratures
                quadr_CSF = pe.Node(interface=Function(
                    input_names=['in_file', 'multicol'],
                    output_names=['out_file', 'out_quadr_file'],
                    function=scale_and_quadrature),
                                    name='quadr_CSF')
                quadr_CSF.inputs.multicol = False
                workflow.connect(get_CSF_noise, 'out_file', quadr_CSF,
                                 'in_file')

                # scale CSF noise derivatives and get quadratures
                quadr_CSF_deriv = pe.Node(interface=Function(
                    input_names=['in_file', 'multicol'],
                    output_names=['out_file', 'out_quadr_file'],
                    function=scale_and_quadrature),
                                          name='quadr_CSF_deriv')
                quadr_CSF_deriv.inputs.multicol = False
                workflow.connect(deriv_CSF, 'out_file', quadr_CSF_deriv,
                                 'in_file')

                # -------- WM regression signals -----------------

                # threshold and erode WM mask
                erode_WM_mask = pe.Node(fsl.ImageMaths(), name='erode_WM_mask')
                erode_WM_mask.inputs.args = '-thr 0.5 -kernel boxv 7 -ero'
                erode_WM_mask.inputs.in_file = anat_WM

                # registrer WM mask to functional image space
                reg_WM_mask = pe.Node(fsl.preprocess.ApplyXFM(),
                                      name='register_WM_mask')
                reg_WM_mask.inputs.apply_xfm = True
                workflow.connect(tstat2, 'out_file', reg_WM_mask, 'reference')
                workflow.connect(invmat, 'out_file', reg_WM_mask,
                                 'in_matrix_file')
                workflow.connect(erode_WM_mask, 'out_file', reg_WM_mask,
                                 'in_file')

                # create inverse nonlinear registration MNI2anat
                invwarp = pe.Node(fsl.InvWarp(output_type='NIFTI_GZ'),
                                  name='invwarp')
                invwarp.inputs.warp = anat2MNI_fieldwarp
                invwarp.inputs.reference = anat

                # transform ventricle mask to functional space
                reg_ventricles = pe.Node(fsl.ApplyWarp(),
                                         name='register_ventricle_mask')
                reg_ventricles.inputs.in_file = ventricle_mask
                workflow.connect(tstat2, 'out_file', reg_ventricles,
                                 'ref_file')
                workflow.connect(invwarp, 'inverse_warp', reg_ventricles,
                                 'field_file')
                workflow.connect(invmat, 'out_file', reg_ventricles, 'postmat')

                # threshold WM mask and intersect with functional brain mask
                thr_WM_mask = pe.Node(fsl.ImageMaths(),
                                      name='threshold_WM_mask')
                thr_WM_mask.inputs.args = '-thr 0.25'
                workflow.connect(reg_WM_mask, 'out_file', thr_WM_mask,
                                 'in_file')
                workflow.connect(erode_brain, 'out_file', thr_WM_mask,
                                 'mask_file')

                # remove ventricles from WM mask
                exclude_ventricles = pe.Node(fsl.ImageMaths(),
                                             name='exclude_ventricles')
                workflow.connect(thr_WM_mask, 'out_file', exclude_ventricles,
                                 'in_file')
                workflow.connect(reg_ventricles, 'out_file',
                                 exclude_ventricles, 'mask_file')

                # check that WM is collected from both hemispheres
                check_WM_bilat = pe.Node(interface=Function(
                    input_names=['in_file'],
                    output_names=['errors'],
                    function=check_bilateralism),
                                         name='check_WM_bilateralism')
                workflow.connect(exclude_ventricles, 'out_file',
                                 check_WM_bilat, 'in_file')

                # extract WM values
                get_WM_noise = pe.Node(fsl.ImageMeants(), name='get_WM_noise')
                workflow.connect(skullstrip, 'out_file', get_WM_noise,
                                 'in_file')
                workflow.connect(exclude_ventricles, 'out_file', get_WM_noise,
                                 'mask')

                # compute WM noise derivatives
                deriv_WM = pe.Node(afni.OneDToolPy(), name='deriv_WM')
                deriv_WM.inputs.set_nruns = 1
                deriv_WM.inputs.derivative = True
                if overwrite: deriv_WM.inputs.args = '-overwrite'
                deriv_WM.inputs.out_file = 'WM_derivatives.txt'
                workflow.connect(get_WM_noise, 'out_file', deriv_WM, 'in_file')

                # scale WM noise and get quadratures
                quadr_WM = pe.Node(interface=Function(
                    input_names=['in_file', 'multicol'],
                    output_names=['out_file', 'out_quadr_file'],
                    function=scale_and_quadrature),
                                   name='quadr_WM')
                quadr_WM.inputs.multicol = False
                workflow.connect(get_WM_noise, 'out_file', quadr_WM, 'in_file')

                # scale WM noise derivatives and get quadratures
                quadr_WM_deriv = pe.Node(interface=Function(
                    input_names=['in_file', 'multicol'],
                    output_names=['out_file', 'out_quadr_file'],
                    function=scale_and_quadrature),
                                         name='quadr_WM_deriv')
                quadr_WM_deriv.inputs.multicol = False
                workflow.connect(deriv_WM, 'out_file', quadr_WM_deriv,
                                 'in_file')

                # ---------- global regression signals ----------------

                if global_reg:
                    # register anatomical whole brain mask to functional image space
                    reg_glob_mask = pe.Node(fsl.preprocess.ApplyXFM(),
                                            name='register_global_mask')
                    reg_glob_mask.inputs.apply_xfm = True
                    reg_glob_mask.inputs.in_file = anat
                    workflow.connect(tstat2, 'out_file', reg_glob_mask,
                                     'reference')
                    workflow.connect(invmat, 'out_file', reg_glob_mask,
                                     'in_matrix_file')

                    # threshold anatomical brain mask and intersect with functional brain mask
                    thr_glob_mask = pe.Node(fsl.ImageMaths(),
                                            name='threshold_global_mask')
                    thr_glob_mask.inputs.args = '-thr -0.1'
                    workflow.connect(reg_glob_mask, 'out_file', thr_glob_mask,
                                     'in_file')
                    workflow.connect(erode_brain, 'out_file', thr_glob_mask,
                                     'mask_file')

                    # extract global signal values
                    get_glob_noise = pe.Node(fsl.ImageMeants(),
                                             name='get_global_noise')
                    workflow.connect(skullstrip, 'out_file', get_glob_noise,
                                     'in_file')
                    workflow.connect(thr_glob_mask, 'out_file', get_glob_noise,
                                     'mask')

                    # compute global noise derivative
                    deriv_glob = pe.Node(afni.OneDToolPy(),
                                         name='deriv_global')
                    deriv_glob.inputs.set_nruns = 1
                    deriv_glob.inputs.derivative = True
                    if overwrite: deriv_glob.inputs.args = '-overwrite'
                    deriv_glob.inputs.out_file = 'global_derivatives.txt'
                    workflow.connect(get_glob_noise, 'out_file', deriv_glob,
                                     'in_file')

                    # scale global noise and get quadratures
                    quadr_glob = pe.Node(interface=Function(
                        input_names=['in_file', 'multicol'],
                        output_names=['out_file', 'out_quadr_file'],
                        function=scale_and_quadrature),
                                         name='quadr_glob')
                    quadr_glob.inputs.multicol = False
                    workflow.connect(get_glob_noise, 'out_file', quadr_glob,
                                     'in_file')

                    # scale global noise derivatives and get quadratures
                    quadr_glob_deriv = pe.Node(interface=Function(
                        input_names=['in_file', 'multicol'],
                        output_names=['out_file', 'out_quadr_file'],
                        function=scale_and_quadrature),
                                               name='quadr_glob_deriv')
                    quadr_glob_deriv.inputs.multicol = False
                    workflow.connect(deriv_glob, 'out_file', quadr_glob_deriv,
                                     'in_file')

                # ---------- regression matrix ----------

                # create bandpass regressors, can not be easily implemented to workflow
                get_bandpass = pe.Node(interface=Function(
                    input_names=['minf', 'maxf', 'example_file', 'tr'],
                    output_names=['out_tuple'],
                    function=bandpass),
                                       name='bandpass_regressors')
                get_bandpass.inputs.minf = myminf
                get_bandpass.inputs.maxf = mymaxf
                get_bandpass.inputs.tr = mytr
                workflow.connect(norm_motion, 'out_file', get_bandpass,
                                 'example_file')

                # concatenate regressor time series
                cat_reg_name = 'cat_regressors'
                if global_reg: cat_reg_name = cat_reg_name + '_global'
                cat_reg = pe.Node(interface=Function(
                    input_names=[
                        'mot', 'motd', 'motq', 'motdq', 'CSF', 'CSFd', 'CSFq',
                        'CSFdq', 'WM', 'WMd', 'WMq', 'WMdq', 'include_global',
                        'glob', 'globd', 'globq', 'globdq'
                    ],
                    output_names=['reg_file_args'],
                    function=concatenate_regressors),
                                  name=cat_reg_name)
                cat_reg.inputs.include_global = global_reg
                workflow.connect(quadr_motion, 'out_file', cat_reg, 'mot')
                workflow.connect(quadr_motion_deriv, 'out_file', cat_reg,
                                 'motd')
                workflow.connect(quadr_motion, 'out_quadr_file', cat_reg,
                                 'motq')
                workflow.connect(quadr_motion_deriv, 'out_quadr_file', cat_reg,
                                 'motdq')
                workflow.connect(quadr_CSF, 'out_file', cat_reg, 'CSF')
                workflow.connect(quadr_CSF_deriv, 'out_file', cat_reg, 'CSFd')
                workflow.connect(quadr_CSF, 'out_quadr_file', cat_reg, 'CSFq')
                workflow.connect(quadr_CSF_deriv, 'out_quadr_file', cat_reg,
                                 'CSFdq')
                workflow.connect(quadr_WM, 'out_file', cat_reg, 'WM')
                workflow.connect(quadr_WM_deriv, 'out_file', cat_reg, 'WMd')
                workflow.connect(quadr_WM, 'out_quadr_file', cat_reg, 'WMq')
                workflow.connect(quadr_WM_deriv, 'out_quadr_file', cat_reg,
                                 'WMdq')
                if global_reg:
                    workflow.connect(quadr_glob, 'out_file', cat_reg, 'glob')
                    workflow.connect(quadr_glob_deriv, 'out_file', cat_reg,
                                     'globd')
                    workflow.connect(quadr_glob, 'out_quadr_file', cat_reg,
                                     'globq')
                    workflow.connect(quadr_glob_deriv, 'out_quadr_file',
                                     cat_reg, 'globdq')
                else:
                    cat_reg.inputs.glob = None
                    cat_reg.inputs.globd = None
                    cat_reg.inputs.globq = None
                    cat_reg.inputs.globdq = None

# create regression matrix
                deconvolve_name = 'deconvolve'
                if global_reg: deconvolve_name = deconvolve_name + '_global'
                deconvolve = pe.Node(afni.Deconvolve(), name=deconvolve_name)
                deconvolve.inputs.polort = 2  # contstant, linear and quadratic background signals removed
                deconvolve.inputs.fout = True
                deconvolve.inputs.tout = True
                deconvolve.inputs.x1D_stop = True
                deconvolve.inputs.force_TR = mytr
                workflow.connect(cat_reg, 'reg_file_args', deconvolve, 'args')
                workflow.connect(get_bandpass, 'out_tuple', deconvolve,
                                 'ortvec')
                workflow.connect([(skullstrip, deconvolve,
                                   [(('out_file', str2list), 'in_files')])])

                # regress out motion and other unwanted signals
                tproject_name = 'tproject'
                if global_reg: tproject_name = tproject_name + '_global'
                tproject = pe.Node(afni.TProject(outputtype="NIFTI_GZ"),
                                   name=tproject_name)
                tproject.inputs.TR = mytr
                tproject.inputs.polort = 0  # use matrix created with 3dDeconvolve, higher order polynomials not needed
                tproject.inputs.cenmode = 'NTRP'  # interpolate removed time points
                workflow.connect(get_censor, 'out_file', tproject, 'censor')
                workflow.connect(skullstrip, 'out_file', tproject, 'in_file')
                workflow.connect(automask, 'out_file', tproject, 'mask')
                workflow.connect(deconvolve, 'x1D', tproject, 'ort')

                # Transform all images
                warpall_name = 'warpall'
                if global_reg: warpall_name = warpall_name + '_global'
                warpall = pe.Node(interface=fsl.ApplyWarp(), name=warpall_name)
                warpall.inputs.ref_file = MNI_brain
                warpall.inputs.field_file = anat2MNI_fieldwarp
                workflow.connect(mean2anat, 'out_matrix_file', warpall,
                                 'premat')
                workflow.connect(tproject, 'out_file', warpall, 'in_file')
                workflow.connect(warpall, 'out_file', outputnode,
                                 'result_func')

                # Run workflow
                workflow.write_graph()
                workflow.run()

        print "FUNCTIONAL PREPROCESSING DONE! Results in ", results_path + subj + '/' + s
    except:
        print "Error with patient: ", subj
        traceback.print_exc()
Ejemplo n.º 25
0
def native_to_tal_fsl(
        path_to_img,
        force_new_transform=False,
        dof=6,
        output_folder='/home/gustav/Desktop/data_processed/mta_data/native',
        guid='',
        remove_tmp_files=True):
    '''
    path_to_img - input image in native space
    force_new_transform - if True, the native image will be transformed regardless of if 
    a transformed image exists
    returns ac/pc alinged imaged by taliarach transformation with voxel size of 1x1x1mm3
    Function that inputs a native image of the brain and 
        1) conforms it to 1x1x1mm3 voxel size + lrflip if needed
        2) performs rigid talariach transformation for ac/pc-alignment and centering of brain.
        3) if to_nifti: convert to nii
    '''
    native_img = os.path.basename(path_to_img)
    if not guid:  # if no output guid soecified
        if 'nii.gz' in native_img:
            guid = os.path.splitext(os.path.splitext(native_img)[0])[0]
        else:
            guid = os.path.splitext(native_img)[0]
    tal_img = guid + '_mni_dof_' + str(dof) + '.nii'
    bet_img = guid + '_bet.nii'
    bet_img_cp = guid + '_bet_cp.nii'
    tmp_img = guid + '_tmp.nii'
    path_to_folder = os.path.dirname(path_to_img)
    tmp_img_path = os.path.join(output_folder, tmp_img)
    tal_img_path = os.path.join(output_folder, tal_img)
    bet_img_path = os.path.join(output_folder, bet_img)
    bet_img_path_cp = os.path.join(output_folder, bet_img_cp)

    xfm_path = os.path.join(output_folder,
                            guid + '_mni_dof_' + str(dof) + '.mat')
    xfm_path_cp = os.path.join(output_folder,
                               guid + '_mni_dof_' + str(dof) + '_cp.mat')

    xfm_path2 = os.path.join(output_folder,
                             guid + '_mni_dof_' + str(dof) + '_2.mat')

    try:
        fsl_path = os.environ['FSLDIR']
    except:
        fsl_path = '/usr/local/fsl'
        print('please install fsl and test $FSLDIR. Trying default path: ' +
              fsl_path)
    template_img = os.path.join(fsl_path, 'data', 'standard',
                                'MNI152_T1_1mm.nii.gz')
    tal_img_exist = os.path.exists(tal_img_path)
    xfm_exist = os.path.exists(xfm_path)
    fsl_1 = fsl.FLIRT()
    fsl_2 = fsl.FLIRT()
    fsl_pre = fsl.Reorient2Std()

    if not tal_img_exist or force_new_transform:

        # pre-reorient first images
        fsl_pre.inputs.in_file = path_to_img
        fsl_pre.inputs.out_file = tmp_img_path

        fsl_pre.inputs.output_type = 'NIFTI'
        fsl_pre.run()

        # run skull strip to calculate transformation matrix
        btr = fsl.BET()
        btr.inputs.in_file = tmp_img_path
        btr.inputs.frac = 0.7
        btr.inputs.out_file = bet_img_path
        btr.inputs.output_type = 'NIFTI'
        #btr.inputs.reduce_bias = True
        btr.inputs.robust = True
        btr.cmdline
        btr.run()

        # calculate transformation matrix - 1st attempt
        fsl_1.inputs.in_file = bet_img_path
        fsl_1.inputs.reference = template_img
        fsl_1.inputs.out_file = bet_img_path
        fsl_1.inputs.output_type = 'NIFTI'
        fsl_1.inputs.dof = dof
        fsl_1.inputs.out_matrix_file = xfm_path
        fsl_1.run()

        # read .mat file to assess if AC-PC alignment failed completely by looking at the diagonal elements (should be close to 1's)
        f = open(xfm_path, 'r')
        l = [[num for num in line.split('  ')] for line in f]
        matrix_1 = np.zeros((4, 4))
        for m in range(4):
            for n in range(4):
                matrix_1[m, n] = float(l[m][n])

        dist_1 = np.sum(np.square(np.diag(matrix_1) - 1))
        print('Dist (below 0.01 generally OK): ' + str(dist_1))
        print('Transformation matrix path: ' + xfm_path)
        dist_lim = .01
        translate_lim = 30
        if dist_1 > dist_lim or matrix_1[
                2, 3] > translate_lim:  # if ac-PC failed, run without bet
            # copy bet files for debuging
            copyfile(bet_img_path, bet_img_path_cp)
            copyfile(xfm_path, xfm_path_cp)

            print('------ Rerunning registration without bet ---')
            fsl_1.inputs.in_file = tmp_img_path
            fsl_1.run()

            f = open(xfm_path, 'r')
            l = [[num for num in line.split('  ')] for line in f]
            matrix_2 = np.zeros((4, 4))
            for m in range(4):
                for n in range(4):
                    matrix_2[m, n] = float(l[m][n])

            dist_2 = np.sum(np.square(np.diag(matrix_2) - 1))
            print([dist_1, dist_2])
            if (dist_1 < dist_lim and dist_2 < dist_lim):
                if matrix_1[2, 3] < matrix_2[2, 3]:
                    # use the transform from the bet image if that was "better"
                    xfm_path = xfm_path_cp
                    print(
                        'Using bet transform, both below dist and translate smaller'
                    )
            elif dist_1 < dist_2:
                xfm_path = xfm_path_cp
                print('Using bet transform, bet dist smaller')

        # apply transform
        fsl_2.inputs.in_file = tmp_img_path
        fsl_2.inputs.reference = template_img
        fsl_2.inputs.out_file = tal_img_path
        fsl_2.inputs.output_type = 'NIFTI'
        fsl_2.inputs.in_matrix_file = xfm_path
        fsl_2.inputs.apply_xfm = True
        fsl_2.inputs.out_matrix_file = xfm_path2
        fsl_2.run()
        if remove_tmp_files:
            for img in [
                    tmp_img_path, bet_img_path, xfm_path2, bet_img_path_cp,
                    xfm_path_cp
            ]:  #,xfm_path
                if os.path.exists(img):
                    os.remove(img)
        else:
            print('OBS: NOT REMOVING TEMPORARY TRANSFORM FILES ')
Ejemplo n.º 26
0
preproc.connect(datasource, 'fm_pos', inputnode, 'fm_pos')
preproc.connect(datasource, 'fm_neg', inputnode, 'fm_neg')







# ------------- prepare anatomical data -------------

prep_anatomicals = pe.Workflow(name='prep_anatomicals')
prep_anatomicals.base_dir = os.path.abspath('./nipype')

# reorient t1 to standard
T1_to_standard = pe.Node(interface=fsl.Reorient2Std(output_type = "NIFTI_GZ"), name='T1_to_standard') 
preproc.connect(inputnode, 't1', T1_to_standard, 'in_file')


# reorient t2 to standard
T2_to_standard = pe.Node(interface=fsl.Reorient2Std(output_type = "NIFTI_GZ"), name='T2_to_standard') 
preproc.connect(inputnode, 't2', T2_to_standard, 'in_file')


# coreg t2 to t1
t2tot1 = pe.Node(interface=fsl.FLIRT(dof=6, output_type = "NIFTI_GZ"), name='t2tot1')
preproc.connect(T2_to_standard, 'out_file', t2tot1, 'in_file')
preproc.connect(T1_to_standard, 'out_file', t2tot1, 'reference')
    

# downsample caltech atlas t1 to t1/t2 resolution
Ejemplo n.º 27
0
]

TissueList = [os.path.abspath(Atlas2) + '/' + tissue for tissue in tissuelist]

config.set('execution', 'crashdump_dir', parent_dir)

cropT2 = pe.Node(interface=fsl.ExtractROI(), name='cropT2')
cropT2.inputs.x_min = cfg['T2_crop_box'][0]
cropT2.inputs.x_size = cfg['T2_crop_box'][1] - cfg['T2_crop_box'][0]
cropT2.inputs.y_min = cfg['T2_crop_box'][2]
cropT2.inputs.y_size = cfg['T2_crop_box'][3] - cfg['T2_crop_box'][2]
cropT2.inputs.z_min = cfg['T2_crop_box'][4]
cropT2.inputs.z_size = cfg['T2_crop_box'][5] - cfg['T2_crop_box'][4]
cropT2.inputs.in_file = cfg['T2_struct']

reorientT2 = pe.Node(interface=fsl.Reorient2Std(), name='reorientT2')

betT2 = pe.Node(interface=fsl.BET(), name='betT2')
betT2.inputs.frac = 0.2
#betT2.inputs.robust=True
#betT2.inputs.center = cfg['T2_center']

FastSeg = pe.Node(interface=fsl.FAST(), name='FastSeg')
#FastSeg.inputs.terminal_output = 'stream'
FastSeg.inputs.output_biascorrected = True
FastSeg.inputs.img_type = 2

get_T2_template = pe.Node(interface=fsl.ExtractROI(), name='get_T2_template')
get_T2_template.inputs.t_size = 1
get_T2_template.inputs.in_file = T2_Template
## ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ INPUTS ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ##
# placeholder Node to enable iteration over scans
infosource_baseline = Node(interface=IdentityInterface(fields=['idvi']), name="infosource_baseline")
infosource_baseline.iterables = ('idvi', idvi_baseline_list)

# get full path to MRI corresponding to idvi
getmusemri_baseline = Node(Function(input_names=['key','dict'],output_names=['musemri'],function=get_value),
                           name='getmusemri_baseline')
getmusemri_baseline.inputs.dict = musemri_dict

# Step 1: Spatial normalization of baseline 1.5T MRI onto study-specific template

# Reorient: this simply applies 90, 180, or 270 degree rotations about each axis to make the image orientation
# the same as the FSL standard
reorient = Node(interface=fsl.Reorient2Std(output_type='NIFTI'), name="reorient")

# Use antsRegistration to compute registration between subject's baseline 1.5T MRI and study-specific template
antsreg = Node(ants.Registration(args='--float',
                                 collapse_output_transforms=True,
                                 fixed_image=blsa_template,
                                 initial_moving_transform_com=True,
                                 num_threads=1,
                                 output_inverse_warped_image=True,
                                 output_warped_image=True,
                                 smoothing_sigmas=[[3, 2, 1, 0]]*3,
                                 sigma_units=['vox']*3,
                                 transforms=['Rigid', 'Affine', 'SyN'],
                                 terminal_output='file',
                                 winsorize_lower_quantile=0.005,
                                 winsorize_upper_quantile=0.995,
Ejemplo n.º 29
0
def img2img_register(
        img_file,
        ref_file,
        wf_base_dir,
        wf_name,
        input_reorient2std=False,
        ref_reorient2std=False,
        method='linear',
        flirt_out_reg_file='linear_reg.mat',
        flirt_out_file='img2img_linear.nii.gz',
        fnirt_out_file='img2img_nonlinear.nii.gz',
        fnirt_fieldcoeff_file='img2img_nonlinear_fieldcoeff.nii.gz'):

    img_file = os.path.abspath(img_file)
    ref_file = os.path.abspath(ref_file)
    wf_base_dir = os.path.abspath(wf_base_dir)

    if not img_file.endswith(('.nii', '.nii.gz')):
        raise ("input file should be in nifti format (.nii or .nii.gz)!")
    if not ref_file.endswith(('.nii', '.nii.gz')):
        raise (
            "destination file (ref_file) should be in nifti format (.nii or .nii.gz)!"
        )

    ### reorient2std

    ### reorient img_file
    if input_reorient2std:
        reorient = fsl.Reorient2Std()
        reorient.inputs.in_file = img_file
        reorient.inputs.out_file = 'input_img_reorient2std.nii.gz'
        reorient_Node = pe.Node(reorient, 'input_file')
        wf = pe.Workflow(name='reorient2std', base_dir=wf_base_dir)
        wf.add_nodes([reorient_Node])
        wf.run()
        img_file = os.path.join(wf_base_dir, 'reorient2std', 'input_file',
                                'input_img_reorient2std.nii.gz')

    ### reorient ref_file if config is not MNI
    if ref_reorient2std and config != 'MNI':
        reorient = fsl.Reorient2Std()
        reorient.inputs.in_file = ref_file
        reorient.inputs.out_file = 'ref_img_reorient2std.nii.gz'
        reorient_Node = pe.Node(reorient, 'ref_file')
        wf = pe.Workflow(name='reorient2std', base_dir=wf_base_dir)
        wf.add_nodes([reorient_Node])
        wf.run()
        ref_file = os.path.join(wf_base_dir, 'reorient2std', 'ref_file',
                                'ref_img_reorient2std.nii.gz')

    if method == 'linear':

        flirt = pe.Node(interface=fsl.FLIRT(in_file=img_file,
                                            reference=ref_file,
                                            out_matrix_file=flirt_out_reg_file,
                                            out_file=flirt_out_file),
                        name='linear')

        wf = pe.Workflow(name=wf_name, base_dir=wf_base_dir)

        wf.add_nodes([flirt])
        wf.run()

    if method == 'nonlinear':
        flirt = pe.Node(interface=fsl.FLIRT(in_file=img_file,
                                            reference=ref_file,
                                            out_matrix_file=flirt_out_reg_file,
                                            out_file=flirt_out_file),
                        name='linear')

        fnirt = pe.Node(interface=fsl.FNIRT(
            in_file=img_file,
            ref_file=ref_file,
            warped_file=fnirt_out_file,
            fieldcoeff_file=fnirt_fieldcoeff_file),
                        name='nonlinear')

        wf = pe.Workflow(name=wf_name, base_dir=wf_base_dir)

        ## adding nodes to workflows
        wf.add_nodes([flirt, fnirt])
        wf.connect([(flirt, fnirt, [('out_matrix_file', 'affine_file')])])
        wf.run()

    linear_reg_file = os.path.join(wf_base_dir, wf_name, method,
                                   flirt_out_reg_file)
    nonlinear_warp_field_file = os.path.join(wf_base_dir, wf_name, method,
                                             fnirt_fieldcoeff_file)

    return {
        'img_file': img_file,
        'ref_file': ref_file,
        'linear_reg_file': linear_reg_file,
        'warp_field_file': nonlinear_warp_field_file
    }
Ejemplo n.º 30
0
# Infosource - function free node to iterate over the list of subject names (and/or sessions)
infosource = Node(IdentityInterface(fields=['subject_id']), name="infosource")
infosource.iterables = [('subject_id', subject_list)]

# SelectFiles - uses glob and regex to find your files
templates = dict(struct='{subject_id}/structural/structural.nii.gz',
                 func='{subject_id}/functional/*.nii.gz')
selectfiles = Node(SelectFiles(templates), "selectfiles")
selectfiles.inputs.base_directory = DATA_DIR

# Node which might come in handy when piping data to interfaces that are incompatible with gzipped format
gunzip_struct = Node(Gunzip(), name="gunzip_struct")

# Reorient images to match approximate orientation of the standard template images (MNI152)
reorient_func = Node(fsl.Reorient2Std(output_type='NIFTI_GZ'),
                     name='reorient_func')
reorient_struct = Node(fsl.Reorient2Std(output_type='NIFTI_GZ'),
                       name='reorient_struct')

# Convert functional images to float representation (FLOAT32)
img2float = Node(fsl.ImageMaths(out_data_type='float',
                                op_string='',
                                suffix='_dtype'),
                 name='img2float')


# Return the volume index of a file
def select_volume(filename, which):
    from nibabel import load
    import numpy as np