Exemple #1
0
def fmri_bmsk_workflow(name='fMRIBrainMask', use_bet=False):
    """Comute brain mask of an fmri dataset"""

    workflow = pe.Workflow(name=name)
    inputnode = pe.Node(niu.IdentityInterface(fields=['in_file']),
                        name='inputnode')
    outputnode = pe.Node(niu.IdentityInterface(fields=['out_file']),
                         name='outputnode')

    if not use_bet:
        afni_msk = pe.Node(afp.Automask(outputtype='NIFTI_GZ'),
                           name='afni_msk')

        # Connect brain mask extraction
        workflow.connect([(inputnode, afni_msk, [('in_file', 'in_file')]),
                          (afni_msk, outputnode, [('out_file', 'out_file')])])

    else:
        from nipype.interfaces.fsl import BET, ErodeImage
        bet_msk = pe.Node(BET(mask=True, functional=True), name='bet_msk')
        erode = pe.Node(ErodeImage(kernel_shape='box', kernel_size=1.0),
                        name='erode')

        # Connect brain mask extraction
        workflow.connect([(inputnode, bet_msk, [('in_file', 'in_file')]),
                          (bet_msk, erode, [('mask_file', 'in_file')]),
                          (erode, outputnode, [('out_file', 'out_file')])])

    return workflow
Exemple #2
0
def create_bo_func_preproc(slice_timing_correction = False, wf_name = 'bo_func_preproc'):
    """
    
    The main purpose of this workflow is to process functional data. Raw rest file is deobliqued and reoriented 
    into RPI. Then take the mean intensity values over all time points for each voxel and use this image 
    to calculate motion parameters. The image is then skullstripped, normalized and a processed mask is 
    obtained to use it further in Image analysis.
    
    Parameters
    ----------
    
    slice_timing_correction : boolean
        Slice timing Correction option
    wf_name : string
        Workflow name
    
    Returns 
    -------
    func_preproc : workflow object
        Functional Preprocessing workflow object
    
    Notes
    -----
    
    `Source <https://github.com/FCP-INDI/C-PAC/blob/master/CPAC/func_preproc/func_preproc.py>`_
    
    Workflow Inputs::
    
        inputspec.rest : func/rest file or a list of func/rest nifti file 
            User input functional(T2) Image, in any of the 8 orientations
            
        inputspec.start_idx : string 
            Starting volume/slice of the functional image (optional)
            
        inputspec.stop_idx : string
            Last volume/slice of the functional image (optional)
            
        scan_params.tr : string
            Subject TR
        
        scan_params.acquistion : string
            Acquisition pattern (interleaved/sequential, ascending/descending)
    
        scan_params.ref_slice : integer
            Reference slice for slice timing correction
            
    Workflow Outputs::
    
        outputspec.drop_tr : string (nifti file)
            Path to Output image with the initial few slices dropped
          
        outputspec.slice_time_corrected : string (nifti file)
            Path to Slice time corrected image
          
        outputspec.refit : string (nifti file)
            Path to deobliqued anatomical data 
        
        outputspec.reorient : string (nifti file)
            Path to RPI oriented anatomical data 
        
        outputspec.motion_correct_ref : string (nifti file)
             Path to Mean intensity Motion corrected image 
             (base reference image for the second motion correction run)
        
        outputspec.motion_correct : string (nifti file)
            Path to motion corrected output file
        
        outputspec.max_displacement : string (Mat file)
            Path to maximum displacement (in mm) for brain voxels in each volume
        
        outputspec.movement_parameters : string (Mat file)
            Path to 1D file containing six movement/motion parameters(3 Translation, 3 Rotations) 
            in different columns (roll pitch yaw dS  dL  dP)
        
        outputspec.skullstrip : string (nifti file)
            Path to skull stripped Motion Corrected Image 
        
        outputspec.mask : string (nifti file)
            Path to brain-only mask
            
        outputspec.example_func : string (nifti file)
            Mean, Skull Stripped, Motion Corrected output T2 Image path
            (Image with mean intensity values across voxels) 
        
        outputpsec.preprocessed : string (nifti file)
            output skull stripped, motion corrected T2 image 
            with normalized intensity values 

        outputspec.preprocessed_mask : string (nifti file)
           Mask obtained from normalized preprocessed image
           
    
    Order of commands:
    
    - Get the start and the end volume index of the functional run. If not defined by the user, return the first and last volume.
    
        get_idx(in_files, stop_idx, start_idx)
        
    - Dropping the initial TRs. For details see `3dcalc <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dcalc.html>`_::
        
        3dcalc -a rest.nii.gz[4..299] 
               -expr 'a' 
               -prefix rest_3dc.nii.gz
               
    - Slice timing correction. For details see `3dshift <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dTshift.html>`_::
    
        3dTshift -TR 2.1s 
                 -slice 18 
                 -tpattern alt+z 
                 -prefix rest_3dc_shift.nii.gz rest_3dc.nii.gz

    - Deobliqing the scans.  For details see `3drefit <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3drefit.html>`_::
    
        3drefit -deoblique rest_3dc.nii.gz
        
    - Re-orienting the Image into Right-to-Left Posterior-to-Anterior Inferior-to-Superior (RPI) orientation. For details see `3dresample <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dresample.html>`_::
    
        3dresample -orient RPI 
                   -prefix rest_3dc_RPI.nii.gz 
                   -inset rest_3dc.nii.gz
        
    - Calculate voxel wise statistics. Get the RPI Image with mean intensity values over all timepoints for each voxel. For details see `3dTstat <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dTstat.html>`_::
    
        3dTstat -mean 
                -prefix rest_3dc_RPI_3dT.nii.gz 
                rest_3dc_RPI.nii.gz
    
    - Motion Correction. For details see `3dvolreg <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dvolreg.html>`_::  
       
        3dvolreg -Fourier 
                 -twopass 
                 -base rest_3dc_RPI_3dT.nii.gz/
                 -zpad 4 
                 -maxdisp1D rest_3dc_RPI_3dvmd1D.1D 
                 -1Dfile rest_3dc_RPI_3dv1D.1D 
                 -prefix rest_3dc_RPI_3dv.nii.gz 
                 rest_3dc_RPI.nii.gz
                 
      The base image or the reference image is the mean intensity RPI image obtained in the above the step.For each volume 
      in RPI-oriented T2 image, the command, aligns the image with the base mean image and calculates the motion, displacement 
      and movement parameters. It also outputs the aligned 4D volume and movement and displacement parameters for each volume.
                 
    - Calculate voxel wise statistics. Get the motion corrected output Image from the above step, with mean intensity values over all timepoints for each voxel. 
      For details see `3dTstat <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dTstat.html>`_::
    
        3dTstat -mean 
                -prefix rest_3dc_RPI_3dv_3dT.nii.gz 
                rest_3dc_RPI_3dv.nii.gz
    
    - Motion Correction and get motion, movement and displacement parameters. For details see `3dvolreg <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dvolreg.html>`_::   

        3dvolreg -Fourier 
                 -twopass 
                 -base rest_3dc_RPI_3dv_3dT.nii.gz 
                 -zpad 4 
                 -maxdisp1D rest_3dc_RPI_3dvmd1D.1D 
                 -1Dfile rest_3dc_RPI_3dv1D.1D 
                 -prefix rest_3dc_RPI_3dv.nii.gz 
                 rest_3dc_RPI.nii.gz
        
      The base image or the reference image is the mean intensity motion corrected image obtained from the above the step (first 3dvolreg run). 
      For each volume in RPI-oriented T2 image, the command, aligns the image with the base mean image and calculates the motion, displacement 
      and movement parameters. It also outputs the aligned 4D volume and movement and displacement parameters for each volume.
    
    - Unwarp the motion corrected using a regularized B0 field map that is in RPI space, one of the outputs from the calib_preproc using FSL FUGUE
    
    	fugue --nocheck=on 
		-i rest_3dc_RPI_3dv.nii.gz 
		--loadfmap=cal_reg_bo_RPI 
		--unwarpdir=x 
		--dwell=1 
		-u rest_3dc_RPI_3dv_unwarped.nii.gz
    
    
    - Create a  brain-only mask. For details see `3dautomask <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dAutomask.html>`_::
    
        3dAutomask  
                   -prefix rest_3dc_RPI_3dv_unwarped_automask.nii.gz 
                   rest_3dc_RPI_3dv_unwarped.nii.gz

    - Edge Detect(remove skull) and get the brain only. For details see `3dcalc <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dcalc.html>`_::
    
        3dcalc -a rest_3dc_RPI_3dv_unwarped.nii.gz 
               -b rest_3dc_RPI_3dv_unwarped_automask.nii.gz 
               -expr 'a*b' 
               -prefix rest_3dc_RPI_3dv_unwarped_3dc.nii.gz
    
    - Normalizing the image intensity values. For details see `fslmaths <http://www.fmrib.ox.ac.uk/fsl/avwutils/index.html>`_::
      
        fslmaths rest_3dc_RPI_3dv_unwarped_3dc.nii.gz 
                 -ing 10000 rest_3dc_RPI_3dv_unwarped_3dc_maths.nii.gz 
                 -odt float
                 
      Normalized intensity = (TrueValue*10000)/global4Dmean
                 
    - Calculate mean of skull stripped image. For details see `3dTstat <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dTstat.html>`_::
        
        3dTstat -mean -prefix rest_3dc_RPI_3dv_unwarped_3dc_3dT.nii.gz rest_3dc_RPI_3dv_unwarped_3dc.nii.gz
        
    - Create Mask (Generate mask from Normalized data). For details see `fslmaths <http://www.fmrib.ox.ac.uk/fsl/avwutils/index.html>`_::
        
        fslmaths rest_3dc_RPI_3dv_unwarped_3dc_maths.nii.gz 
               -Tmin -bin rest_3dc_RPI_3dv_unwarped_3dc_maths_maths.nii.gz 
               -odt char

    High Level Workflow Graph:
    
    .. image:: ../images/func_preproc.dot.png
       :width: 1000
    
    
    Detailed Workflow Graph:
    
    .. image:: ../images/func_preproc_detailed.dot.png
       :width: 1000

    Examples
    --------
    
    >>> from func_preproc import *
    >>> preproc = create_func_preproc(slice_timing_correction=True)
    >>> preproc.inputs.inputspec.func='sub1/func/rest.nii.gz'
    >>> preproc.inputs.scan_params.TR = '2.0'
    >>> preproc.inputs.scan_params.ref_slice = 19
    >>> preproc.inputs.scan_params.acquisition = 'alt+z2'
    >>> preproc.run() #doctest: +SKIP


    >>> from func_preproc import *
    >>> preproc = create_func_preproc(slice_timing_correction=False)
    >>> preproc.inputs.inputspec.func='sub1/func/rest.nii.gz'
    >>> preproc.inputs.inputspec.start_idx = 4
    >>> preproc.inputs.inputspec.stop_idx = 250
    >>> preproc.run() #doctest: +SKIP
    
    """

    preproc = pe.Workflow(name=wf_name)
    inputNode = pe.Node(util.IdentityInterface(fields=['rest',
						       'calib_reg_bo_RPI',
                                                       'start_idx',
                                                       'stop_idx']),
                        name='inputspec')
    
    scan_params = pe.Node(util.IdentityInterface(fields=['tr',
                                                         'acquisition',
                                                         'ref_slice']),
                          name = 'scan_params')

    outputNode = pe.Node(util.IdentityInterface(fields=['drop_tr',
                                                        'refit',
                                                        'reorient',
                                                        'reorient_mean',
                                                        'motion_correct',
                                                        'motion_correct_ref',
                                                        'movement_parameters',
                                                        'max_displacement',
                                                        'bo_unwarped',
                                                        'mask',
							'mask_preunwarp',
                                                        'skullstrip',
                                                        'example_func',
                                                        'preprocessed',
                                                        'preprocessed_mask',
                                                        'slice_time_corrected']),

                          name='outputspec')

    func_get_idx = pe.Node(util.Function(input_names=['in_files', 
                                                      'stop_idx', 
                                                      'start_idx'],
                               output_names=['stopidx', 
                                             'startidx'],
                 function=get_idx), name='func_get_idx')
    
    preproc.connect(inputNode, 'rest',
                    func_get_idx, 'in_files')
		    		    
    preproc.connect(inputNode, 'start_idx',
                    func_get_idx, 'start_idx')
    preproc.connect(inputNode, 'stop_idx',
                    func_get_idx, 'stop_idx')
    
    
    func_drop_trs = pe.Node(interface=preprocess.Calc(),
                           name='func_drop_trs')
    func_drop_trs.inputs.expr = 'a'
    func_drop_trs.inputs.outputtype = 'NIFTI_GZ'
    
    preproc.connect(inputNode, 'rest',
                    func_drop_trs, 'in_file_a')
    preproc.connect(func_get_idx, 'startidx',
                    func_drop_trs, 'start_idx')
    preproc.connect(func_get_idx, 'stopidx',
                    func_drop_trs, 'stop_idx')
    
    preproc.connect(func_drop_trs, 'out_file',
                    outputNode, 'drop_tr')
    
    
    func_slice_timing_correction = pe.Node(interface=preprocess.TShift(),
                                           name = 'func_slice_timing_correction')
    func_slice_timing_correction.inputs.outputtype = 'NIFTI_GZ'
    
    func_deoblique = pe.Node(interface=preprocess.Refit(),
                            name='func_deoblique')
    func_deoblique.inputs.deoblique = True
    
    
    if slice_timing_correction:
        preproc.connect(func_drop_trs, 'out_file',
                        func_slice_timing_correction,'in_file')
        preproc.connect(scan_params, 'tr',
                        func_slice_timing_correction, 'tr')
        preproc.connect(scan_params, 'acquisition',
                        func_slice_timing_correction, 'tpattern')
        preproc.connect(scan_params, 'ref_slice',
                        func_slice_timing_correction, 'tslice')
        
        preproc.connect(func_slice_timing_correction, 'out_file',
                        func_deoblique, 'in_file')
        
        preproc.connect(func_slice_timing_correction, 'out_file',
                        outputNode, 'slice_time_corrected')
    else:
        preproc.connect(func_drop_trs, 'out_file',
                        func_deoblique, 'in_file')
    
    preproc.connect(func_deoblique, 'out_file',
                    outputNode, 'refit')

    func_reorient = pe.Node(interface=preprocess.Resample(),
                               name='func_reorient')
    func_reorient.inputs.orientation = 'RPI'
    func_reorient.inputs.outputtype = 'NIFTI_GZ'

    preproc.connect(func_deoblique, 'out_file',
                    func_reorient, 'in_file')
    
    preproc.connect(func_reorient, 'out_file',
                    outputNode, 'reorient')
    
    func_get_mean_RPI = pe.Node(interface=preprocess.TStat(),
                            name='func_get_mean_RPI')
    func_get_mean_RPI.inputs.options = '-mean'
    func_get_mean_RPI.inputs.outputtype = 'NIFTI_GZ'
    
    preproc.connect(func_reorient, 'out_file',
                    func_get_mean_RPI, 'in_file')
        
    #calculate motion parameters
    func_motion_correct = pe.Node(interface=preprocess.Volreg(),
                             name='func_motion_correct')
    func_motion_correct.inputs.args = '-Fourier -twopass'
    func_motion_correct.inputs.zpad = 4
    func_motion_correct.inputs.outputtype = 'NIFTI_GZ'
    
    preproc.connect(func_reorient, 'out_file',
                    func_motion_correct, 'in_file')
    preproc.connect(func_get_mean_RPI, 'out_file',
                    func_motion_correct, 'basefile')

    
    func_get_mean_motion = func_get_mean_RPI.clone('func_get_mean_motion')
    preproc.connect(func_motion_correct, 'out_file',
                    func_get_mean_motion, 'in_file')
    
    preproc.connect(func_get_mean_motion, 'out_file',
                    outputNode, 'motion_correct_ref')
    
    
    func_motion_correct_A = func_motion_correct.clone('func_motion_correct_A')
    func_motion_correct_A.inputs.md1d_file = 'max_displacement.1D'
    
    preproc.connect(func_reorient, 'out_file',
                    func_motion_correct_A, 'in_file')
    preproc.connect(func_get_mean_motion, 'out_file',
                    func_motion_correct_A, 'basefile')
    
    
    
    
    
    preproc.connect(func_motion_correct_A, 'out_file',
                    outputNode, 'motion_correct')
    preproc.connect(func_motion_correct_A, 'md1d_file',
                    outputNode, 'max_displacement')
    preproc.connect(func_motion_correct_A, 'oned_file',
                    outputNode, 'movement_parameters')


    
    func_get_brain_mask = pe.Node(interface=preprocess.Automask(),
                               name='func_get_brain_mask')
#    func_get_brain_mask.inputs.dilate = 1
    func_get_brain_mask.inputs.outputtype = 'NIFTI_GZ'

#-------------------------

    func_bo_unwarp = pe.Node(interface=fsl.FUGUE(),name='bo_unwarp')
    #func_bo_unwarp.inputs.in_file='lfo_mc'
    func_bo_unwarp.inputs.args='--nocheck=on'
    #func_bo_unwarp.inputs.fmap_in_file='calib'
    func_bo_unwarp.inputs.dwell_time=1.0
    func_bo_unwarp.inputs.unwarp_direction='x'
    
    preproc.connect(inputNode, 'calib_reg_bo_RPI',
                    func_bo_unwarp, 'fmap_in_file')
    
        
    preproc.connect(func_motion_correct_A, 'out_file',
                    func_bo_unwarp, 'in_file')
    
    preproc.connect(func_bo_unwarp, 'unwarped_file',
                    outputNode, 'bo_unwarped')
    
    
    preproc.connect(func_bo_unwarp, 'unwarped_file',
                    func_get_brain_mask, 'in_file')
    

#--------------------------

    preproc.connect(func_get_brain_mask, 'out_file',
                    outputNode, 'mask')
        
#------------ ALSO give the example_func_preunwarp

    func_get_brain_mask_A = func_get_brain_mask.clone('func_get_brain_mask_A')
    
    preproc.connect(func_motion_correct_A, 'out_file',
                    func_get_brain_mask_A, 'in_file')
    	    
    preproc.connect(func_get_brain_mask_A, 'out_file',
                    outputNode, 'mask_preunwarp')
    
    
    
    
    
    
    
    func_edge_detect = pe.Node(interface=preprocess.Calc(),
                            name='func_edge_detect')
    func_edge_detect.inputs.expr = 'a*b'
    func_edge_detect.inputs.outputtype = 'NIFTI_GZ'

    preproc.connect(func_bo_unwarp, 'unwarped_file',
                    func_edge_detect, 'in_file_a')
    preproc.connect(func_get_brain_mask, 'out_file',
                    func_edge_detect, 'in_file_b')

    preproc.connect(func_edge_detect, 'out_file',
                    outputNode, 'skullstrip')

    
    func_mean_skullstrip = pe.Node(interface=preprocess.TStat(),
                           name='func_mean_skullstrip')
    func_mean_skullstrip.inputs.options = '-mean'
    func_mean_skullstrip.inputs.outputtype = 'NIFTI_GZ'

    preproc.connect(func_edge_detect, 'out_file',
                    func_mean_skullstrip, 'in_file')
    
    preproc.connect(func_mean_skullstrip, 'out_file',
                    outputNode, 'example_func')
    
    
    func_normalize = pe.Node(interface=fsl.ImageMaths(),
                            name='func_normalize')
    func_normalize.inputs.op_string = '-ing 10000'
    func_normalize.inputs.out_data_type = 'float'

    preproc.connect(func_edge_detect, 'out_file',
                    func_normalize, 'in_file')
    
    preproc.connect(func_normalize, 'out_file',
                    outputNode, 'preprocessed')
    
    
    func_mask_normalize = pe.Node(interface=fsl.ImageMaths(),
                           name='func_mask_normalize')
    func_mask_normalize.inputs.op_string = '-Tmin -bin'
    func_mask_normalize.inputs.out_data_type = 'char'

    preproc.connect(func_normalize, 'out_file',
                    func_mask_normalize, 'in_file')
    
    preproc.connect(func_mask_normalize, 'out_file',
                    outputNode, 'preprocessed_mask')

    return preproc
def functional_brain_mask_workflow(workflow, resource_pool, config):

    # resource pool should have:
    #     func_motion_correct

    import os
    import sys

    import nipype.interfaces.io as nio
    import nipype.pipeline.engine as pe

    import nipype.interfaces.utility as util
    import nipype.interfaces.fsl as fsl

    from nipype.interfaces.afni import preprocess

    #check_input_resources(resource_pool, "func_motion_correct")

    if "use_bet" not in config.keys():
        config["use_bet"] = False

    if "func_motion_correct" not in resource_pool.keys():

        from functional_preproc import func_motion_correct_workflow

        workflow, resource_pool = \
            func_motion_correct_workflow(workflow, resource_pool, config)

    if config["use_bet"] == False:

        func_get_brain_mask = pe.Node(interface=preprocess.Automask(),
                                      name='func_get_brain_mask')

        func_get_brain_mask.inputs.outputtype = 'NIFTI_GZ'

    else:

        func_get_brain_mask = pe.Node(interface=fsl.BET(),
                                      name='func_get_brain_mask_BET')

        func_get_brain_mask.inputs.mask = True
        func_get_brain_mask.inputs.functional = True

        erode_one_voxel = pe.Node(interface=fsl.ErodeImage(),
                                  name='erode_one_voxel')

        erode_one_voxel.inputs.kernel_shape = 'box'
        erode_one_voxel.inputs.kernel_size = 1.0

    #if isinstance(tuple, resource_pool["func_motion_correct"]):

    if len(resource_pool["func_motion_correct"]) == 2:
        node, out_file = resource_pool["func_motion_correct"]
        workflow.connect(node, out_file, func_get_brain_mask, 'in_file')
    else:
        func_get_brain_mask.inputs.in_file = \
            resource_pool["func_motion_correct"]

    if config["use_bet"] == False:

        resource_pool["functional_brain_mask"] = (func_get_brain_mask, \
                                                     'out_file')

    else:

        workflow.connect(func_get_brain_mask, 'mask_file', erode_one_voxel,
                         'in_file')

        resource_pool["functional_brain_mask"] = (erode_one_voxel, 'out_file')

    return workflow, resource_pool
Exemple #4
0
def create_func_preproc(use_bet=False, wf_name='func_preproc'):
    """

    The main purpose of this workflow is to process functional data. Raw rest file is deobliqued and reoriented
    into RPI. Then take the mean intensity values over all time points for each voxel and use this image
    to calculate motion parameters. The image is then skullstripped, normalized and a processed mask is
    obtained to use it further in Image analysis.

    Parameters
    ----------

    wf_name : string
        Workflow name

    Returns
    -------
    func_preproc : workflow object
        Functional Preprocessing workflow object

    Notes
    -----

    `Source <https://github.com/FCP-INDI/C-PAC/blob/master/CPAC/func_preproc/func_preproc.py>`_

    Workflow Inputs::

        inputspec.rest : func/rest file or a list of func/rest nifti file
            User input functional(T2) Image, in any of the 8 orientations

        scan_params.tr : string
            Subject TR

        scan_params.acquistion : string
            Acquisition pattern (interleaved/sequential, ascending/descending)

        scan_params.ref_slice : integer
            Reference slice for slice timing correction

    Workflow Outputs::

        outputspec.refit : string (nifti file)
            Path to deobliqued anatomical data

        outputspec.reorient : string (nifti file)
            Path to RPI oriented anatomical data

        outputspec.motion_correct_ref : string (nifti file)
             Path to Mean intensity Motion corrected image
             (base reference image for the second motion correction run)

        outputspec.motion_correct : string (nifti file)
            Path to motion corrected output file

        outputspec.max_displacement : string (Mat file)
            Path to maximum displacement (in mm) for brain voxels in each volume

        outputspec.movement_parameters : string (Mat file)
            Path to 1D file containing six movement/motion parameters(3 Translation, 3 Rotations)
            in different columns (roll pitch yaw dS  dL  dP)

        outputspec.skullstrip : string (nifti file)
            Path to skull stripped Motion Corrected Image

        outputspec.mask : string (nifti file)
            Path to brain-only mask

        outputspec.example_func : string (nifti file)
            Mean, Skull Stripped, Motion Corrected output T2 Image path
            (Image with mean intensity values across voxels)

        outputpsec.preprocessed : string (nifti file)
            output skull stripped, motion corrected T2 image
            with normalized intensity values

        outputspec.preprocessed_mask : string (nifti file)
           Mask obtained from normalized preprocessed image

    Order of commands:

    - Deobliqing the scans.  For details see `3drefit <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3drefit.html>`_::

        3drefit -deoblique rest_3dc.nii.gz

    - Re-orienting the Image into Right-to-Left Posterior-to-Anterior Inferior-to-Superior (RPI) orientation. For details see `3dresample <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dresample.html>`_::

        3dresample -orient RPI
                   -prefix rest_3dc_RPI.nii.gz
                   -inset rest_3dc.nii.gz

    - Calculate voxel wise statistics. Get the RPI Image with mean intensity values over all timepoints for each voxel. For details see `3dTstat <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dTstat.html>`_::

        3dTstat -mean
                -prefix rest_3dc_RPI_3dT.nii.gz
                rest_3dc_RPI.nii.gz

    - Motion Correction. For details see `3dvolreg <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dvolreg.html>`_::

        3dvolreg -Fourier
                 -twopass
                 -base rest_3dc_RPI_3dT.nii.gz/
                 -zpad 4
                 -maxdisp1D rest_3dc_RPI_3dvmd1D.1D
                 -1Dfile rest_3dc_RPI_3dv1D.1D
                 -prefix rest_3dc_RPI_3dv.nii.gz
                 rest_3dc_RPI.nii.gz

      The base image or the reference image is the mean intensity RPI image obtained in the above the step.For each volume
      in RPI-oriented T2 image, the command, aligns the image with the base mean image and calculates the motion, displacement
      and movement parameters. It also outputs the aligned 4D volume and movement and displacement parameters for each volume.

    - Calculate voxel wise statistics. Get the motion corrected output Image from the above step, with mean intensity values over all timepoints for each voxel.
      For details see `3dTstat <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dTstat.html>`_::

        3dTstat -mean
                -prefix rest_3dc_RPI_3dv_3dT.nii.gz
                rest_3dc_RPI_3dv.nii.gz

    - Motion Correction and get motion, movement and displacement parameters. For details see `3dvolreg <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dvolreg.html>`_::

        3dvolreg -Fourier
                 -twopass
                 -base rest_3dc_RPI_3dv_3dT.nii.gz
                 -zpad 4
                 -maxdisp1D rest_3dc_RPI_3dvmd1D.1D
                 -1Dfile rest_3dc_RPI_3dv1D.1D
                 -prefix rest_3dc_RPI_3dv.nii.gz
                 rest_3dc_RPI.nii.gz

      The base image or the reference image is the mean intensity motion corrected image obtained from the above the step (first 3dvolreg run).
      For each volume in RPI-oriented T2 image, the command, aligns the image with the base mean image and calculates the motion, displacement
      and movement parameters. It also outputs the aligned 4D volume and movement and displacement parameters for each volume.

    - Create a brain-only mask. For details see `3dautomask <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dAutomask.html>`_::

        3dAutomask
                   -prefix rest_3dc_RPI_3dv_automask.nii.gz
                   rest_3dc_RPI_3dv.nii.gz

    - Edge Detect(remove skull) and get the brain only. For details see `3dcalc <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dcalc.html>`_::

        3dcalc -a rest_3dc_RPI_3dv.nii.gz
               -b rest_3dc_RPI_3dv_automask.nii.gz
               -expr 'a*b'
               -prefix rest_3dc_RPI_3dv_3dc.nii.gz

    - Normalizing the image intensity values. For details see `fslmaths <http://www.fmrib.ox.ac.uk/fsl/avwutils/index.html>`_::

        fslmaths rest_3dc_RPI_3dv_3dc.nii.gz
                 -ing 10000 rest_3dc_RPI_3dv_3dc_maths.nii.gz
                 -odt float

      Normalized intensity = (TrueValue*10000)/global4Dmean

    - Calculate mean of skull stripped image. For details see `3dTstat <http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dTstat.html>`_::

        3dTstat -mean -prefix rest_3dc_RPI_3dv_3dc_3dT.nii.gz rest_3dc_RPI_3dv_3dc.nii.gz

    - Create Mask (Generate mask from Normalized data). For details see `fslmaths <http://www.fmrib.ox.ac.uk/fsl/avwutils/index.html>`_::

        fslmaths rest_3dc_RPI_3dv_3dc_maths.nii.gz
               -Tmin -bin rest_3dc_RPI_3dv_3dc_maths_maths.nii.gz
               -odt char

    High Level Workflow Graph:

    .. image:: ../images/func_preproc.dot.png
       :width: 1000


    Detailed Workflow Graph:

    .. image:: ../images/func_preproc_detailed.dot.png
       :width: 1000

    Examples
    --------

    >>> import func_preproc
    >>> preproc = create_func_preproc(bet=True)
    >>> preproc.inputs.inputspec.func='sub1/func/rest.nii.gz'
    >>> preproc.run() #doctest: +SKIP


    >>> import func_preproc
    >>> preproc = create_func_preproc(bet=False)
    >>> preproc.inputs.inputspec.func='sub1/func/rest.nii.gz'
    >>> preproc.run() #doctest: +SKIP

    """

    preproc = pe.Workflow(name=wf_name)
    inputNode = pe.Node(util.IdentityInterface(fields=['func']),
                        name='inputspec')

    outputNode = pe.Node(
        util.IdentityInterface(fields=[
            'refit',
            'reorient',
            'reorient_mean',
            'motion_correct',
            'motion_correct_ref',
            'movement_parameters',
            'max_displacement',
            # 'xform_matrix',
            'mask',
            'skullstrip',
            'example_func',
            'preprocessed',
            'preprocessed_mask',
            'slice_time_corrected',
            'oned_matrix_save'
        ]),
        name='outputspec')

    try:
        from nipype.interfaces.afni import utils as afni_utils
        func_deoblique = pe.Node(interface=afni_utils.Refit(),
                                 name='func_deoblique')
    except ImportError:
        func_deoblique = pe.Node(interface=preprocess.Refit(),
                                 name='func_deoblique')
    func_deoblique.inputs.deoblique = True

    preproc.connect(inputNode, 'func', func_deoblique, 'in_file')

    try:
        func_reorient = pe.Node(interface=afni_utils.Resample(),
                                name='func_reorient')
    except UnboundLocalError:
        func_reorient = pe.Node(interface=preprocess.Resample(),
                                name='func_reorient')

    func_reorient.inputs.orientation = 'RPI'
    func_reorient.inputs.outputtype = 'NIFTI_GZ'

    preproc.connect(func_deoblique, 'out_file', func_reorient, 'in_file')

    preproc.connect(func_reorient, 'out_file', outputNode, 'reorient')

    try:
        func_get_mean_RPI = pe.Node(interface=afni_utils.TStat(),
                                    name='func_get_mean_RPI')
    except UnboundLocalError:
        func_get_mean_RPI = pe.Node(interface=preprocess.TStat(),
                                    name='func_get_mean_RPI')

    func_get_mean_RPI.inputs.options = '-mean'
    func_get_mean_RPI.inputs.outputtype = 'NIFTI_GZ'

    preproc.connect(func_reorient, 'out_file', func_get_mean_RPI, 'in_file')

    # calculate motion parameters
    func_motion_correct = pe.Node(interface=preprocess.Volreg(),
                                  name='func_motion_correct')
    func_motion_correct.inputs.args = '-Fourier -twopass'
    func_motion_correct.inputs.zpad = 4
    func_motion_correct.inputs.outputtype = 'NIFTI_GZ'

    preproc.connect(func_reorient, 'out_file', func_motion_correct, 'in_file')
    preproc.connect(func_get_mean_RPI, 'out_file', func_motion_correct,
                    'basefile')

    func_get_mean_motion = func_get_mean_RPI.clone('func_get_mean_motion')
    preproc.connect(func_motion_correct, 'out_file', func_get_mean_motion,
                    'in_file')

    preproc.connect(func_get_mean_motion, 'out_file', outputNode,
                    'motion_correct_ref')

    func_motion_correct_A = func_motion_correct.clone('func_motion_correct_A')
    func_motion_correct_A.inputs.md1d_file = 'max_displacement.1D'

    preproc.connect(func_reorient, 'out_file', func_motion_correct_A,
                    'in_file')
    preproc.connect(func_get_mean_motion, 'out_file', func_motion_correct_A,
                    'basefile')

    preproc.connect(func_motion_correct_A, 'out_file', outputNode,
                    'motion_correct')
    preproc.connect(func_motion_correct_A, 'md1d_file', outputNode,
                    'max_displacement')
    preproc.connect(func_motion_correct_A, 'oned_file', outputNode,
                    'movement_parameters')
    preproc.connect(func_motion_correct_A, 'oned_matrix_save', outputNode,
                    'oned_matrix_save')

    if not use_bet:

        func_get_brain_mask = pe.Node(interface=preprocess.Automask(),
                                      name='func_get_brain_mask')

        func_get_brain_mask.inputs.outputtype = 'NIFTI_GZ'

        preproc.connect(func_motion_correct_A, 'out_file', func_get_brain_mask,
                        'in_file')

        preproc.connect(func_get_brain_mask, 'out_file', outputNode, 'mask')

    else:

        func_get_brain_mask = pe.Node(interface=fsl.BET(),
                                      name='func_get_brain_mask_BET')

        func_get_brain_mask.inputs.mask = True
        func_get_brain_mask.inputs.functional = True

        erode_one_voxel = pe.Node(interface=fsl.ErodeImage(),
                                  name='erode_one_voxel')

        erode_one_voxel.inputs.kernel_shape = 'box'
        erode_one_voxel.inputs.kernel_size = 1.0

        preproc.connect(func_motion_correct_A, 'out_file', func_get_brain_mask,
                        'in_file')

        preproc.connect(func_get_brain_mask, 'mask_file', erode_one_voxel,
                        'in_file')

        preproc.connect(erode_one_voxel, 'out_file', outputNode, 'mask')

    try:
        func_edge_detect = pe.Node(interface=afni_utils.Calc(),
                                   name='func_edge_detect')
    except UnboundLocalError:
        func_edge_detect = pe.Node(interface=preprocess.Calc(),
                                   name='func_edge_detect')

    func_edge_detect.inputs.expr = 'a*b'
    func_edge_detect.inputs.outputtype = 'NIFTI_GZ'

    preproc.connect(func_motion_correct_A, 'out_file', func_edge_detect,
                    'in_file_a')

    if not use_bet:
        preproc.connect(func_get_brain_mask, 'out_file', func_edge_detect,
                        'in_file_b')
    else:
        preproc.connect(erode_one_voxel, 'out_file', func_edge_detect,
                        'in_file_b')

    preproc.connect(func_edge_detect, 'out_file', outputNode, 'skullstrip')

    try:
        func_mean_skullstrip = pe.Node(interface=afni_utils.TStat(),
                                       name='func_mean_skullstrip')
    except UnboundLocalError:
        func_mean_skullstrip = pe.Node(interface=preprocess.TStat(),
                                       name='func_mean_skullstrip')

    func_mean_skullstrip.inputs.options = '-mean'
    func_mean_skullstrip.inputs.outputtype = 'NIFTI_GZ'

    preproc.connect(func_edge_detect, 'out_file', func_mean_skullstrip,
                    'in_file')

    preproc.connect(func_mean_skullstrip, 'out_file', outputNode,
                    'example_func')

    func_normalize = pe.Node(interface=fsl.ImageMaths(), name='func_normalize')
    func_normalize.inputs.op_string = '-ing 10000'
    func_normalize.inputs.out_data_type = 'float'

    preproc.connect(func_edge_detect, 'out_file', func_normalize, 'in_file')

    preproc.connect(func_normalize, 'out_file', outputNode, 'preprocessed')

    func_mask_normalize = pe.Node(interface=fsl.ImageMaths(),
                                  name='func_mask_normalize')
    func_mask_normalize.inputs.op_string = '-Tmin -bin'
    func_mask_normalize.inputs.out_data_type = 'char'

    preproc.connect(func_normalize, 'out_file', func_mask_normalize, 'in_file')

    preproc.connect(func_mask_normalize, 'out_file', outputNode,
                    'preprocessed_mask')

    return preproc
Exemple #5
0
def skullstrip_functional(skullstrip_tool='afni',
                          anatomical_mask_dilation=False,
                          wf_name='skullstrip_functional'):

    skullstrip_tool = skullstrip_tool.lower()
    if skullstrip_tool != 'afni' and skullstrip_tool != 'fsl' and skullstrip_tool != 'fsl_afni' and skullstrip_tool != 'anatomical_refined':
        raise Exception(
            "\n\n[!] Error: The 'tool' parameter of the "
            "'skullstrip_functional' workflow must be either "
            "'afni' or 'fsl' or 'fsl_afni' or 'anatomical_refined'.\n\nTool input: "
            "{0}\n\n".format(skullstrip_tool))

    wf = pe.Workflow(name=wf_name)

    input_node = pe.Node(util.IdentityInterface(
        fields=['func', 'anatomical_brain_mask', 'anat_skull']),
                         name='inputspec')

    output_node = pe.Node(
        util.IdentityInterface(fields=['func_brain', 'func_brain_mask']),
        name='outputspec')

    if skullstrip_tool == 'afni':
        func_get_brain_mask = pe.Node(interface=preprocess.Automask(),
                                      name='func_get_brain_mask_AFNI')
        func_get_brain_mask.inputs.outputtype = 'NIFTI_GZ'

        wf.connect(input_node, 'func', func_get_brain_mask, 'in_file')

        wf.connect(func_get_brain_mask, 'out_file', output_node,
                   'func_brain_mask')

    elif skullstrip_tool == 'fsl':
        func_get_brain_mask = pe.Node(interface=fsl.BET(),
                                      name='func_get_brain_mask_BET')

        func_get_brain_mask.inputs.mask = True
        func_get_brain_mask.inputs.functional = True

        erode_one_voxel = pe.Node(interface=fsl.ErodeImage(),
                                  name='erode_one_voxel')

        erode_one_voxel.inputs.kernel_shape = 'box'
        erode_one_voxel.inputs.kernel_size = 1.0

        wf.connect(input_node, 'func', func_get_brain_mask, 'in_file')

        wf.connect(func_get_brain_mask, 'mask_file', erode_one_voxel,
                   'in_file')

        wf.connect(erode_one_voxel, 'out_file', output_node, 'func_brain_mask')

    elif skullstrip_tool == 'fsl_afni':
        skullstrip_first_pass = pe.Node(fsl.BET(frac=0.2,
                                                mask=True,
                                                functional=True),
                                        name='skullstrip_first_pass')
        bet_dilate = pe.Node(fsl.DilateImage(operation='max',
                                             kernel_shape='sphere',
                                             kernel_size=6.0,
                                             internal_datatype='char'),
                             name='skullstrip_first_dilate')
        bet_mask = pe.Node(fsl.ApplyMask(), name='skullstrip_first_mask')
        unifize = pe.Node(afni_utils.Unifize(
            t2=True,
            outputtype='NIFTI_GZ',
            args='-clfrac 0.2 -rbt 18.3 65.0 90.0',
            out_file="uni.nii.gz"),
                          name='unifize')
        skullstrip_second_pass = pe.Node(preprocess.Automask(
            dilate=1, outputtype='NIFTI_GZ'),
                                         name='skullstrip_second_pass')
        combine_masks = pe.Node(fsl.BinaryMaths(operation='mul'),
                                name='combine_masks')

        wf.connect([
            (input_node, skullstrip_first_pass, [('func', 'in_file')]),
            (skullstrip_first_pass, bet_dilate, [('mask_file', 'in_file')]),
            (bet_dilate, bet_mask, [('out_file', 'mask_file')]),
            (skullstrip_first_pass, bet_mask, [('out_file', 'in_file')]),
            (bet_mask, unifize, [('out_file', 'in_file')]),
            (unifize, skullstrip_second_pass, [('out_file', 'in_file')]),
            (skullstrip_first_pass, combine_masks, [('mask_file', 'in_file')]),
            (skullstrip_second_pass, combine_masks, [('out_file',
                                                      'operand_file')]),
            (combine_masks, output_node, [('out_file', 'func_brain_mask')])
        ])

    # Refine functional mask by registering anatomical mask to functional space
    elif skullstrip_tool == 'anatomical_refined':

        # Get functional mean to use later as reference, when transform anatomical mask to functional space
        func_skull_mean = pe.Node(interface=afni_utils.TStat(),
                                  name='func_skull_mean')
        func_skull_mean.inputs.options = '-mean'
        func_skull_mean.inputs.outputtype = 'NIFTI_GZ'

        wf.connect(input_node, 'func', func_skull_mean, 'in_file')

        # Register func to anat
        linear_reg_func_to_anat = pe.Node(interface=fsl.FLIRT(),
                                          name='linear_reg_func_to_anat')
        linear_reg_func_to_anat.inputs.cost = 'mutualinfo'
        linear_reg_func_to_anat.inputs.dof = 6

        wf.connect(func_skull_mean, 'out_file', linear_reg_func_to_anat,
                   'in_file')
        wf.connect(input_node, 'anat_skull', linear_reg_func_to_anat,
                   'reference')

        # Inverse func to anat affine
        inv_func_to_anat_affine = pe.Node(interface=fsl.ConvertXFM(),
                                          name='inv_func_to_anat_affine')
        inv_func_to_anat_affine.inputs.invert_xfm = True

        wf.connect(linear_reg_func_to_anat, 'out_matrix_file',
                   inv_func_to_anat_affine, 'in_file')

        # Transform anatomical mask to functional space
        linear_trans_mask_anat_to_func = pe.Node(
            interface=fsl.FLIRT(), name='linear_trans_mask_anat_to_func')
        linear_trans_mask_anat_to_func.inputs.apply_xfm = True
        linear_trans_mask_anat_to_func.inputs.cost = 'mutualinfo'
        linear_trans_mask_anat_to_func.inputs.dof = 6
        linear_trans_mask_anat_to_func.inputs.interp = 'nearestneighbour'

        # Dialate anatomical mask, if 'anatomical_mask_dilation : True' in config file
        if anatomical_mask_dilation:
            anat_mask_dilate = pe.Node(interface=afni.MaskTool(),
                                       name='anat_mask_dilate')
            anat_mask_dilate.inputs.dilate_inputs = '1'
            anat_mask_dilate.inputs.outputtype = 'NIFTI_GZ'

            wf.connect(input_node, 'anatomical_brain_mask', anat_mask_dilate,
                       'in_file')
            wf.connect(anat_mask_dilate, 'out_file',
                       linear_trans_mask_anat_to_func, 'in_file')

        else:
            wf.connect(input_node, 'anatomical_brain_mask',
                       linear_trans_mask_anat_to_func, 'in_file')

        wf.connect(func_skull_mean, 'out_file', linear_trans_mask_anat_to_func,
                   'reference')
        wf.connect(inv_func_to_anat_affine, 'out_file',
                   linear_trans_mask_anat_to_func, 'in_matrix_file')
        wf.connect(linear_trans_mask_anat_to_func, 'out_file', output_node,
                   'func_brain_mask')

    func_edge_detect = pe.Node(interface=afni_utils.Calc(),
                               name='func_extract_brain')

    func_edge_detect.inputs.expr = 'a*b'
    func_edge_detect.inputs.outputtype = 'NIFTI_GZ'

    wf.connect(input_node, 'func', func_edge_detect, 'in_file_a')

    if skullstrip_tool == 'afni':
        wf.connect(func_get_brain_mask, 'out_file', func_edge_detect,
                   'in_file_b')
    elif skullstrip_tool == 'fsl':
        wf.connect(erode_one_voxel, 'out_file', func_edge_detect, 'in_file_b')
    elif skullstrip_tool == 'fsl_afni':
        wf.connect(combine_masks, 'out_file', func_edge_detect, 'in_file_b')
    elif skullstrip_tool == 'anatomical_refined':
        wf.connect(linear_trans_mask_anat_to_func, 'out_file',
                   func_edge_detect, 'in_file_b')

    wf.connect(func_edge_detect, 'out_file', output_node, 'func_brain')

    return wf
Exemple #6
0
def skullstrip_functional(tool='afni', wf_name='skullstrip_functional'):

    tool = tool.lower()
    if tool != 'afni' and tool != 'fsl' and tool != 'fsl_afni':
        raise Exception("\n\n[!] Error: The 'tool' parameter of the "
                        "'skullstrip_functional' workflow must be either "
                        "'afni' or 'fsl'.\n\nTool input: "
                        "{0}\n\n".format(tool))

    wf = pe.Workflow(name=wf_name)

    input_node = pe.Node(util.IdentityInterface(fields=['func']),
                         name='inputspec')

    output_node = pe.Node(
        util.IdentityInterface(fields=['func_brain', 'func_brain_mask']),
        name='outputspec')

    if tool == 'afni':
        func_get_brain_mask = pe.Node(interface=preprocess.Automask(),
                                      name='func_get_brain_mask_AFNI')
        func_get_brain_mask.inputs.outputtype = 'NIFTI_GZ'

        wf.connect(input_node, 'func', func_get_brain_mask, 'in_file')

        wf.connect(func_get_brain_mask, 'out_file', output_node,
                   'func_brain_mask')

    elif tool == 'fsl':
        func_get_brain_mask = pe.Node(interface=fsl.BET(),
                                      name='func_get_brain_mask_BET')

        func_get_brain_mask.inputs.mask = True
        func_get_brain_mask.inputs.functional = True

        erode_one_voxel = pe.Node(interface=fsl.ErodeImage(),
                                  name='erode_one_voxel')

        erode_one_voxel.inputs.kernel_shape = 'box'
        erode_one_voxel.inputs.kernel_size = 1.0

        wf.connect(input_node, 'func', func_get_brain_mask, 'in_file')

        wf.connect(func_get_brain_mask, 'mask_file', erode_one_voxel,
                   'in_file')

        wf.connect(erode_one_voxel, 'out_file', output_node, 'func_brain_mask')

    elif tool == 'fsl_afni':
        skullstrip_first_pass = pe.Node(fsl.BET(frac=0.2,
                                                mask=True,
                                                functional=True),
                                        name='skullstrip_first_pass')
        bet_dilate = pe.Node(fsl.DilateImage(operation='max',
                                             kernel_shape='sphere',
                                             kernel_size=6.0,
                                             internal_datatype='char'),
                             name='skullstrip_first_dilate')
        bet_mask = pe.Node(fsl.ApplyMask(), name='skullstrip_first_mask')
        unifize = pe.Node(afni_utils.Unifize(
            t2=True,
            outputtype='NIFTI_GZ',
            args='-clfrac 0.2 -rbt 18.3 65.0 90.0',
            out_file="uni.nii.gz"),
                          name='unifize')
        skullstrip_second_pass = pe.Node(preprocess.Automask(
            dilate=1, outputtype='NIFTI_GZ'),
                                         name='skullstrip_second_pass')
        combine_masks = pe.Node(fsl.BinaryMaths(operation='mul'),
                                name='combine_masks')

        wf.connect([
            (input_node, skullstrip_first_pass, [('func', 'in_file')]),
            (skullstrip_first_pass, bet_dilate, [('mask_file', 'in_file')]),
            (bet_dilate, bet_mask, [('out_file', 'mask_file')]),
            (skullstrip_first_pass, bet_mask, [('out_file', 'in_file')]),
            (bet_mask, unifize, [('out_file', 'in_file')]),
            (unifize, skullstrip_second_pass, [('out_file', 'in_file')]),
            (skullstrip_first_pass, combine_masks, [('mask_file', 'in_file')]),
            (skullstrip_second_pass, combine_masks, [('out_file',
                                                      'operand_file')]),
            (combine_masks, output_node, [('out_file', 'func_brain_mask')])
        ])

    func_edge_detect = pe.Node(interface=afni_utils.Calc(),
                               name='func_extract_brain')

    func_edge_detect.inputs.expr = 'a*b'
    func_edge_detect.inputs.outputtype = 'NIFTI_GZ'

    wf.connect(input_node, 'func', func_edge_detect, 'in_file_a')

    if tool == 'afni':
        wf.connect(func_get_brain_mask, 'out_file', func_edge_detect,
                   'in_file_b')
    elif tool == 'fsl':
        wf.connect(erode_one_voxel, 'out_file', func_edge_detect, 'in_file_b')
    elif tool == 'fsl_afni':
        wf.connect(combine_masks, 'out_file', func_edge_detect, 'in_file_b')

    wf.connect(func_edge_detect, 'out_file', output_node, 'func_brain')

    return wf
Exemple #7
0
def functional_brain_mask_workflow(workflow, resource_pool, config, name="_"):
    """Build and run a Nipype workflow to generate a functional brain mask
    using AFNI's 3dAutomask.

    - If any resources/outputs required by this workflow are not in the
      resource pool, this workflow will call pre-requisite workflow builder
      functions to further populate the pipeline with workflows which will
      calculate/generate these necessary pre-requisites.

    Expected Resources in Resource Pool
      - func_reorient: The deobliqued, reoriented functional timeseries.

    New Resources Added to Resource Pool
      - functional_brain_mask: The binary brain mask of the functional time
                               series.

    Workflow Steps
      1. AFNI's 3dAutomask to generate the mask.

    :type workflow: Nipype workflow object
    :param workflow: A Nipype workflow object which can already contain other
                     connected nodes; this function will insert the following
                     workflow into this one provided.
    :type resource_pool: dict
    :param resource_pool: A dictionary defining input files and pointers to
                          Nipype node outputs / workflow connections; the keys
                          are the resource names.
    :type config: dict
    :param config: A dictionary defining the configuration settings for the
                   workflow, such as directory paths or toggled options.
    :type name: str
    :param name: (default: "_") A string to append to the end of each node
                 name.
    :rtype: Nipype workflow object
    :return: The Nipype workflow originally provided, but with this function's
              sub-workflow connected into it.
    :rtype: dict
    :return: The resource pool originally provided, but updated (if
             applicable) with the newest outputs and connections.
    """

    import copy
    import nipype.pipeline.engine as pe
    from nipype.interfaces.afni import preprocess

    if "func_reorient" not in resource_pool.keys():

        from functional_preproc import func_preproc_workflow
        old_rp = copy.copy(resource_pool)
        workflow, resource_pool = \
            func_preproc_workflow(workflow, resource_pool, config, name)
        if resource_pool == old_rp:
            return workflow, resource_pool
  
    func_get_brain_mask = pe.Node(interface=preprocess.Automask(),
                                  name='func_get_brain_mask%s' % name)
    func_get_brain_mask.inputs.outputtype = 'NIFTI_GZ'

    if len(resource_pool["func_reorient"]) == 2:
        node, out_file = resource_pool["func_reorient"]
        workflow.connect(node, out_file, func_get_brain_mask, 'in_file')
    else:
        func_get_brain_mask.inputs.in_file = \
            resource_pool["func_reorient"]

    resource_pool["functional_brain_mask"] = (func_get_brain_mask, 'out_file')

    return workflow, resource_pool