Example #1
0
def create_activation_pics(sbref_brain, thresh_zstat1, thresh_zstat2,
                           thresh_zfstat1):
    import nipype.interfaces.fsl as fsl

    Overlay_t1_Contrast = fsl.Overlay()
    Overlay_t1_Contrast.inputs.background_image = sbref_brain
    Overlay_t1_Contrast.inputs.stat_image = thresh_zstat1
    Overlay_t1_Contrast.inputs.auto_thresh_bg = True
    Overlay_t1_Contrast.inputs.stat_thresh = (2.300302, 12)
    Overlay_t1_Contrast.inputs.transparency = True
    Overlay_t1_Contrast.inputs.out_file = 'rendered_thresh_zstat1.nii.gz'

    Overlay_t1_Contrast.run()

    Slicer_t1_Contrast = fsl.Slicer()
    Slicer_t1_Contrast.inputs.in_file = 'rendered_thresh_zstat1.nii.gz'
    Slicer_t1_Contrast.inputs.all_axial = True
    Slicer_t1_Contrast.inputs.image_width = 750
    Slicer_t1_Contrast.inputs.out_file = 'rendered_thresh_zstat1.png'

    Slicer_t1_Contrast.run()
    #===============================================================================

    Overlay_t2_Contrast = fsl.Overlay()
    Overlay_t2_Contrast.inputs.background_image = sbref_brain
    Overlay_t2_Contrast.inputs.stat_image = thresh_zstat1
    Overlay_t2_Contrast.inputs.auto_thresh_bg = True
    Overlay_t2_Contrast.inputs.stat_thresh = (2.300302, 12)
    Overlay_t2_Contrast.inputs.transparency = True
    Overlay_t2_Contrast.inputs.out_file = 'rendered_thresh_zstat2.nii.gz'

    Overlay_t2_Contrast.run()

    Slicer_t2_Contrast = fsl.Slicer()
    Slicer_t2_Contrast.inputs.in_file = 'rendered_thresh_zstat2.nii.gz'
    Slicer_t2_Contrast.inputs.all_axial = True
    Slicer_t2_Contrast.inputs.image_width = 750
    Slicer_t2_Contrast.inputs.out_file = 'rendered_thresh_zstat2.png'

    Slicer_t2_Contrast.run()
    #===============================================================================

    Overlay_f_Contrast = fsl.Overlay()
    Overlay_f_Contrast.inputs.background_image = sbref_brain
    Overlay_f_Contrast.inputs.stat_image = thresh_zstat1
    Overlay_f_Contrast.inputs.auto_thresh_bg = True
    Overlay_f_Contrast.inputs.stat_thresh = (2.300302, 12)
    Overlay_f_Contrast.inputs.transparency = True
    Overlay_f_Contrast.inputs.out_file = 'rendered_thresh_zfstat1.nii.gz'

    Overlay_f_Contrast.run()

    Slicer_f_Contrast = fsl.Slicer()
    Slicer_f_Contrast.inputs.in_file = 'rendered_thresh_zfstat1.nii.gz'
    Slicer_f_Contrast.inputs.all_axial = True
    Slicer_f_Contrast.inputs.image_width = 750
    Slicer_f_Contrast.inputs.out_file = 'rendered_thresh_zfstat1.png'

    Slicer_f_Contrast.run()
def create_overlay_workflow(name='overlay'):
    """Setup overlay workflow
    """

    overlay = pe.Workflow(name='overlay')
    overlaystats = pe.MapNode(interface=fsl.Overlay(), name="overlaystats",
                              iterfield=['stat_image'])
    overlaystats.inputs.show_negative_stats = True
    overlaystats.inputs.auto_thresh_bg = True

    slicestats = pe.MapNode(interface=fsl.Slicer(),
                            name="slicestats",
                            iterfield=['in_file'])
    slicestats.inputs.all_axial = True
    slicestats.inputs.image_width = 512

    overlay.connect(overlaystats, 'out_file', slicestats, 'in_file')
    return overlay
Example #3
0
level1estimate.inputs.estimation_method = {'Classical': 1}
"""Use :class:`nipype.interfaces.spm.EstimateContrast` to estimate the
first level contrasts specified in a few steps above.
"""

contrastestimate = pe.Node(spm.EstimateContrast(), name="contrastestimate")
"""Use :class: `nipype.interfaces.utility.Select` to select each contrast for
reporting.
"""

selectcontrast = pe.Node(niu.Select(), name="selectcontrast")
"""Use :class:`nipype.interfaces.fsl.Overlay` to combine the statistical output of
the contrast estimate and a background image into one volume.
"""

overlaystats = pe.Node(fsl.Overlay(), name="overlaystats")
overlaystats.inputs.stat_thresh = (3, 10)
overlaystats.inputs.show_negative_stats = True
overlaystats.inputs.auto_thresh_bg = True
"""Use :class:`nipype.interfaces.fsl.Slicer` to create images of the overlaid
statistical volumes for a report of the first-level results.
"""

slicestats = pe.Node(fsl.Slicer(), name="slicestats")
slicestats.inputs.all_axial = True
slicestats.inputs.image_width = 750

l1analysis.connect([
    (modelspec, level1design, [('session_info', 'session_info')]),
    (level1design, level1estimate, [('spm_mat_file', 'spm_mat_file')]),
    (level1estimate, contrastestimate, [('spm_mat_file', 'spm_mat_file'),
Example #4
0
"""Use :class:`nipype.interfaces.spm.EstimateContrast` to estimate the
first level contrasts specified in a few steps above.
"""

contrastestimate = pe.Node(interface=spm.EstimateContrast(),
                           name="contrastestimate")
"""Use :class: `nipype.interfaces.utility.Select` to select each contrast for
reporting.
"""

selectcontrast = pe.Node(interface=util.Select(), name="selectcontrast")
"""Use :class:`nipype.interfaces.fsl.Overlay` to combine the statistical output of
the contrast estimate and a background image into one volume.
"""

overlaystats = pe.Node(interface=fsl.Overlay(), name="overlaystats")
overlaystats.inputs.stat_thresh = (3, 10)
overlaystats.inputs.show_negative_stats = True
overlaystats.inputs.auto_thresh_bg = True
"""Use :class:`nipype.interfaces.fsl.Slicer` to create images of the overlaid
statistical volumes for a report of the first-level results.
"""

slicestats = pe.Node(interface=fsl.Slicer(), name="slicestats")
slicestats.inputs.all_axial = True
slicestats.inputs.image_width = 750

l1analysis.connect([
    (modelspec, level1design, [('session_info', 'session_info')]),
    (level1design, level1estimate, [('spm_mat_file', 'spm_mat_file')]),
    (level1estimate, contrastestimate, [('spm_mat_file', 'spm_mat_file'),
# Clustering_t.inputs.out_localmax_txt_file = 'localmax'



#-----------------------------------------------------------------------------------------------------
# In[15]:
#Clusterin on the statistical output of f-contrast
Clustering_f = Node(fsl.Cluster(), name = 'Clustering_f_Contrast')
Clustering_f.inputs.threshold = 2.3
Clustering_f.inputs.pthreshold = 0.05
Clustering_f.inputs.out_threshold_file = 'thresh_zfstat1.nii.gz'

#-----------------------------------------------------------------------------------------------------
# In[15]:
#Overlay t contrast
Overlay_t_Contrast = Node(fsl.Overlay(), name = 'Overlay_t_Contrast')
Overlay_t_Contrast.inputs.auto_thresh_bg = True
Overlay_t_Contrast.inputs.stat_thresh = (2.300302,4.877862)
Overlay_t_Contrast.inputs.transparency = True


#-----------------------------------------------------------------------------------------------------
# In[15]:
#Overlay f contrast
Overlay_f_Contrast = Node(fsl.Overlay(), name = 'Overlay_f_Contrast')
Overlay_f_Contrast.inputs.auto_thresh_bg = True
Overlay_f_Contrast.inputs.stat_thresh = (2.300302,4.877862)
Overlay_f_Contrast.inputs.transparency = True


#-----------------------------------------------------------------------------------------------------
Example #6
0
def easy_thresh(wf_name):
    """
    Workflow for carrying out cluster-based thresholding 
    and colour activation overlaying
    
    Parameters
    ----------
    wf_name : string 
        Workflow name
        
    Returns
    -------
    easy_thresh : object 
        Easy thresh workflow object
    
    Notes
    -----
    
    `Source <https://github.com/FCP-INDI/C-PAC/blob/master/CPAC/easy_thresh/easy_thresh.py>`_
        
    Workflow Inputs::
    
        inputspec.z_stats : string (nifti file)
            z_score stats output for t or f contrast from flameo
        
        inputspec.merge_mask : string (nifti file)
            mask generated from 4D Merged derivative file
        
        inputspec.z_threshold : float
            Z Statistic threshold value for cluster thresholding. It is used to 
            determine what level of activation would be statistically significant. 
            Increasing this will result in higher estimates of required effect.
        
        inputspec.p_threshold : float
            Probability threshold for cluster thresholding.
        
        inputspec.paramerters : string (tuple)
            tuple containing which MNI and FSLDIR path information
            
    Workflow Outputs::
    
        outputspec.cluster_threshold : string (nifti files)
           the thresholded Z statistic image for each t contrast
        
        outputspec.cluster_index : string (nifti files)
            image of clusters for each t contrast; the values 
            in the clusters are the index numbers as used 
            in the cluster list.
        
        outputspec.overlay_threshold : string (nifti files)
            3D color rendered stats overlay image for t contrast
            After reloading this image, use the Statistics Color 
            Rendering GUI to reload the color look-up-table
        
        outputspec.overlay_rendered_image : string (nifti files)
           2D color rendered stats overlay picture for each t contrast
        
        outputspec.cluster_localmax_txt : string (text files)
            local maxima text file, defines the coordinates of maximum value
            in the cluster
    
    
    Order of commands:
    
    - Estimate smoothness of the image::
        
        smoothest --mask= merge_mask.nii.gz --zstat=.../flameo/stats/zstat1.nii.gz
        
        arguments
        --mask  :  brain mask volume
        --zstat :  filename of zstat/zfstat image
    
    - Create mask. For details see `fslmaths <http://www.fmrib.ox.ac.uk/fslcourse/lectures/practicals/intro/index.htm#fslutils>`_::
        
        fslmaths ../flameo/stats/zstat1.nii.gz 
                 -mas merge_mask.nii.gz 
                 zstat1_mask.nii.gz
        
        arguments
        -mas   : use (following image>0) to mask current image

    - Copy Geometry image dimensions, voxel dimensions, voxel dimensions units string, image orientation/origin or qform/sform info) from one image to another::
    
        fslcpgeom MNI152_T1_2mm_brain.nii.gz zstat1_mask.nii.gz
    
    - Cluster based thresholding. For details see `FEAT <http://www.fmrib.ox.ac.uk/fsl/feat5/detail.html#poststats>`_::
        
        cluster --dlh = 0.0023683100 
                --in = zstat1_mask.nii.gz 
                --oindex = zstat1_cluster_index.nii.gz 
                --olmax = zstat1_cluster_localmax.txt
                --othresh = zstat1_cluster_threshold.nii.gz 
                --pthresh = 0.0500000000 
                --thresh = 2.3000000000 
                --volume = 197071
                
        arguments 
        --in    :    filename of input volume
        --dlh   :    smoothness estimate = sqrt(det(Lambda))
        --oindex  :  filename for output of cluster index
        --othresh :  filename for output of thresholded image
        --olmax   :  filename for output of local maxima text file
        --volume  :  number of voxels in the mask
        --pthresh :  p-threshold for clusters
        --thresh  :  threshold for input volume
        
     Z statistic image is thresholded to show which voxels or clusters of voxels are activated at a particular significance level.
     A Z statistic threshold is used to define contiguous clusters. Then each cluster's estimated significance level (from GRF-theory) 
     is compared with the cluster probability threshold. Significant clusters are then used to mask the original Z statistic image.
    
    - Get the maximum intensity value of the output thresholded image. This used is while rendering the Z statistic image:: 
        
        fslstats zstat1_cluster_threshold.nii.gz -R
        
        arguments
        -R  : output <min intensity> <max intensity>

    - Rendering. For details see `FEAT <http://www.fmrib.ox.ac.uk/fsl/feat5/detail.html#poststats>`_::
         
        overlay 1 0 MNI152_T1_2mm_brain.nii.gz 
               -a zstat1_cluster_threshold.nii.gz 
               2.30 15.67 
               zstat1_cluster_threshold_overlay.nii.gz
               
        slicer zstat1_cluster_threshold_overlay.nii.gz 
               -L  -A 750 
               zstat1_cluster_threshold_overlay.png
    
      The Z statistic range selected for rendering is automatically calculated by default, 
      to run from red (minimum Z statistic after thresholding) to yellow (maximum Z statistic, here 
      maximum intensity).
      
    High Level Workflow Graph:
    
    .. image:: ../images/easy_thresh.dot.png
       :width: 800
    
    
    Detailed Workflow Graph:
    
    .. image:: ../images/easy_thresh_detailed.dot.png
       :width: 800
               
    Examples
    --------
    
    >>> import easy_thresh
    >>> preproc = easy_thresh.easy_thresh("new_workflow")
    >>> preproc.inputs.inputspec.z_stats= 'flameo/stats/zstat1.nii.gz'
    >>> preproc.inputs.inputspec.merge_mask = 'merge_mask/alff_Z_fn2standard_merged_mask.nii.gz'
    >>> preproc.inputs.inputspec.z_threshold = 2.3
    >>> preproc.inputs.inputspec.p_threshold = 0.05
    >>> preproc.inputs.inputspec.parameters = ('/usr/local/fsl/', 'MNI152')
    >>> preporc.run()  -- SKIP doctest
    
    """

    easy_thresh = pe.Workflow(name=wf_name)

    inputnode = pe.Node(util.IdentityInterface(fields=[
        'z_stats', 'merge_mask', 'z_threshold', 'p_threshold', 'parameters'
    ]),
                        name='inputspec')

    outputnode = pe.Node(util.IdentityInterface(fields=[
        'cluster_threshold', 'cluster_index', 'cluster_localmax_txt',
        'overlay_threshold', 'rendered_image'
    ]),
                         name='outputspec')

    ### fsl easythresh
    # estimate image smoothness
    smooth_estimate = pe.MapNode(interface=fsl.SmoothEstimate(),
                                 name='smooth_estimate',
                                 iterfield=['zstat_file'])

    # run clustering after fixing stats header for talspace
    zstat_mask = pe.MapNode(interface=fsl.MultiImageMaths(),
                            name='zstat_mask',
                            iterfield=['in_file'])
    #operations to perform
    #-mas use (following image>0) to mask current image
    zstat_mask.inputs.op_string = '-mas %s'

    #fslcpgeom
    #copy certain parts of the header information (image dimensions,
    #voxel dimensions, voxel dimensions units string, image orientation/origin
    #or qform/sform info) from one image to another
    copy_geometry = pe.MapNode(util.Function(
        input_names=['infile_a', 'infile_b'],
        output_names=['out_file'],
        function=copy_geom),
                               name='copy_geometry',
                               iterfield=['infile_a', 'infile_b'])

    ##cluster-based thresholding
    #After carrying out the initial statistical test, the resulting
    #Z statistic image is then normally thresholded to show which voxels or
    #clusters of voxels are activated at a particular significance level.
    #A Z statistic threshold is used to define contiguous clusters.
    #Then each cluster's estimated significance level (from GRF-theory) is
    #compared with the cluster probability threshold. Significant clusters
    #are then used to mask the original Z statistic image for later production
    #of colour blobs.This method of thresholding is an alternative to
    #Voxel-based correction, and is normally more sensitive to activation.
    #    cluster = pe.MapNode(interface=fsl.Cluster(),
    #                            name='cluster',
    #                            iterfield=['in_file', 'volume', 'dlh'])
    #    #output of cluster index (in size order)
    #    cluster.inputs.out_index_file = True
    #    #thresholded image
    #    cluster.inputs.out_threshold_file = True
    #    #local maxima text file
    #    #defines the cluster cordinates
    #    cluster.inputs.out_localmax_txt_file = True

    cluster = pe.MapNode(util.Function(
        input_names=[
            'in_file', 'volume', 'dlh', 'threshold', 'pthreshold', 'parameters'
        ],
        output_names=['index_file', 'threshold_file', 'localmax_txt_file'],
        function=call_cluster),
                         name='cluster',
                         iterfield=['in_file', 'volume', 'dlh'])

    #max and minimum intensity values
    image_stats = pe.MapNode(interface=fsl.ImageStats(),
                             name='image_stats',
                             iterfield=['in_file'])
    image_stats.inputs.op_string = '-R'

    #create tuple of z_threshold and max intensity value of threshold file
    create_tuple = pe.MapNode(util.Function(
        input_names=['infile_a', 'infile_b'],
        output_names=['out_file'],
        function=get_tuple),
                              name='create_tuple',
                              iterfield=['infile_b'])

    #colour activation overlaying
    overlay = pe.MapNode(interface=fsl.Overlay(),
                         name='overlay',
                         iterfield=['stat_image', 'stat_thresh'])
    overlay.inputs.transparency = True
    overlay.inputs.auto_thresh_bg = True
    overlay.inputs.out_type = 'float'

    #colour rendering
    slicer = pe.MapNode(interface=fsl.Slicer(),
                        name='slicer',
                        iterfield=['in_file'])
    #set max picture width
    slicer.inputs.image_width = 750
    # set output all axial slices into one picture
    slicer.inputs.all_axial = True

    #function mapnode to get the standard fsl brain image
    #based on parameters as FSLDIR,MNI and voxel size
    get_backgroundimage = pe.MapNode(util.Function(
        input_names=['in_file', 'file_parameters'],
        output_names=['out_file'],
        function=get_standard_background_img),
                                     name='get_bckgrndimg1',
                                     iterfield=['in_file'])

    #function node to get the standard fsl brain image
    #outputs single file
    get_backgroundimage2 = pe.Node(util.Function(
        input_names=['in_file', 'file_parameters'],
        output_names=['out_file'],
        function=get_standard_background_img),
                                   name='get_backgrndimg2')

    #connections
    easy_thresh.connect(inputnode, 'z_stats', smooth_estimate, 'zstat_file')
    easy_thresh.connect(inputnode, 'merge_mask', smooth_estimate, 'mask_file')

    easy_thresh.connect(inputnode, 'z_stats', zstat_mask, 'in_file')
    easy_thresh.connect(inputnode, 'merge_mask', zstat_mask, 'operand_files')

    easy_thresh.connect(zstat_mask, 'out_file', get_backgroundimage, 'in_file')
    easy_thresh.connect(inputnode, 'parameters', get_backgroundimage,
                        'file_parameters')

    easy_thresh.connect(get_backgroundimage, 'out_file', copy_geometry,
                        'infile_a')
    easy_thresh.connect(zstat_mask, 'out_file', copy_geometry, 'infile_b')

    easy_thresh.connect(copy_geometry, 'out_file', cluster, 'in_file')
    easy_thresh.connect(inputnode, 'z_threshold', cluster, 'threshold')
    easy_thresh.connect(inputnode, 'p_threshold', cluster, 'pthreshold')
    easy_thresh.connect(smooth_estimate, 'volume', cluster, 'volume')
    easy_thresh.connect(smooth_estimate, 'dlh', cluster, 'dlh')
    easy_thresh.connect(inputnode, 'parameters', cluster, 'parameters')

    easy_thresh.connect(cluster, 'threshold_file', image_stats, 'in_file')

    easy_thresh.connect(image_stats, 'out_stat', create_tuple, 'infile_b')
    easy_thresh.connect(inputnode, 'z_threshold', create_tuple, 'infile_a')

    easy_thresh.connect(cluster, 'threshold_file', overlay, 'stat_image')
    easy_thresh.connect(create_tuple, 'out_file', overlay, 'stat_thresh')

    easy_thresh.connect(inputnode, 'merge_mask', get_backgroundimage2,
                        'in_file')
    easy_thresh.connect(inputnode, 'parameters', get_backgroundimage2,
                        'file_parameters')

    easy_thresh.connect(get_backgroundimage2, 'out_file', overlay,
                        'background_image')

    easy_thresh.connect(overlay, 'out_file', slicer, 'in_file')

    easy_thresh.connect(cluster, 'threshold_file', outputnode,
                        'cluster_threshold')
    easy_thresh.connect(cluster, 'index_file', outputnode, 'cluster_index')
    easy_thresh.connect(cluster, 'localmax_txt_file', outputnode,
                        'cluster_localmax_txt')
    easy_thresh.connect(overlay, 'out_file', outputnode, 'overlay_threshold')
    easy_thresh.connect(slicer, 'out_file', outputnode, 'rendered_image')

    return easy_thresh
Example #7
0
#cluster copes1
cluster_copes1 = Node(fsl.model.Cluster(), name='cluster_copes1')

cluster_copes1.inputs.threshold = 2.3
cluster_copes1.inputs.pthreshold = 0.05
cluster_copes1.inputs.connectivity = 26

cluster_copes1.inputs.out_threshold_file = 'thresh_zstat1.nii.gz'
cluster_copes1.inputs.out_index_file = 'cluster_mask_zstat1'
cluster_copes1.inputs.out_localmax_txt_file = 'lmax_zstat1_std.txt'
cluster_copes1.inputs.use_mm = True

#==========================================================================================================================================================
#overlay thresh_zstat1

overlay_cope1 = Node(fsl.Overlay(), name='overlay_cope1')
overlay_cope1.inputs.auto_thresh_bg = True
overlay_cope1.inputs.stat_thresh = (2.300302, 14)
overlay_cope1.inputs.transparency = True
overlay_cope1.inputs.out_file = 'rendered_thresh_zstat1.nii.gz'
overlay_cope1.inputs.show_negative_stats = True

#==========================================================================================================================================================
#generate pics thresh_zstat1

slicer_cope1 = Node(fsl.Slicer(), name='slicer_cope1')
slicer_cope1.inputs.sample_axial = 2
slicer_cope1.inputs.image_width = 2000
slicer_cope1.inputs.out_file = 'rendered_thresh_zstat1.png'

#===========================================================================================================================================================
Example #8
0
cluster_zstats = Node(name='cluster_zstats',
                      interface=Function(
                          input_names=['zstat', 'volume', 'dlh'],
                          output_names=['threshold_file'],
                          function=cluster_zstats))

#=========================================================================================================================================================
#threshold the maps to 3.1 to make it ready for submission
apply_thresh = Node(fsl.Threshold(), name='apply_threshold_3_1')
apply_thresh.inputs.thresh = 3.1
apply_thresh.inputs.out_file = 'threshold_file.nii.gz'

#==========================================================================================================================================================
#overlay thresh_zstat1

overlay_zstat = Node(fsl.Overlay(), name='overlay')
overlay_zstat.inputs.auto_thresh_bg = True
overlay_zstat.inputs.stat_thresh = (3.1, 10)
overlay_zstat.inputs.transparency = True
overlay_zstat.inputs.out_file = 'rendered_thresh_zstat.nii.gz'
overlay_zstat.inputs.show_negative_stats = True
overlay_zstat.inputs.background_image = template_brain

#==========================================================================================================================================================
#generate pics thresh_zstat1

slicer_zstat = Node(fsl.Slicer(), name='slicer')
slicer_zstat.inputs.sample_axial = 2
slicer_zstat.inputs.image_width = 2000
slicer_zstat.inputs.out_file = 'rendered_thresh_zstat.png'
Example #9
0
mask_zstat = Node(fsl.ApplyMask(), name='mask_zstat')
mask_zstat.inputs.out_file = 'thresh_zstat.nii.gz'

# ============================================================================================================================
clustering_t = Node(fsl.Cluster(), name='clustering_t_contrast')
clustering_t.inputs.threshold = 2.3
clustering_t.inputs.pthreshold = 0.05
clustering_t.inputs.out_threshold_file = 'thresh_zstat.nii.gz'
clustering_t.inputs.out_index_file = 'cluster_mask_zstat'
clustering_t.inputs.out_localmax_txt_file = 'lmax_zstat.txt'
clustering_t.inputs.connectivity = 26

# ============================================================================================================================
# In[15]:
# overlay t contrast
overlay_t_contrast = Node(fsl.Overlay(), name='overlay_t_contrast')
overlay_t_contrast.inputs.auto_thresh_bg = True
overlay_t_contrast.inputs.stat_thresh = (2.300302, 5)
overlay_t_contrast.inputs.transparency = True

# ============================================================================================================================
# In[15]:
# slicer
slicer_t_contrast = Node(fsl.Slicer(), name='generate_t_contrast_image')
slicer_t_contrast.inputs.all_axial = True
slicer_t_contrast.inputs.image_width = 500

# ============================================================================================================================
# ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
# ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
# ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Example #10
0
def create_confound_removal_workflow(workflow_name="confound_removal"):

    inputnode = pe.Node(util.IdentityInterface(
        fields=["subject_id", "timeseries", "reg_file", "motion_parameters"]),
                        name="inputs")

    # Get the Freesurfer aseg volume from the Subjects Directory
    getaseg = pe.Node(io.FreeSurferSource(subjects_dir=fs.Info.subjectsdir()),
                      name="getaseg")

    # Binarize the Aseg to use as a whole brain mask
    asegmask = pe.Node(fs.Binarize(min=0.5, dilate=2), name="asegmask")

    # Extract and erode a mask of the deep cerebral white matter
    extractwm = pe.Node(fs.Binarize(match=[2, 41], erode=3), name="extractwm")

    # Extract and erode a mask of the ventricles and CSF
    extractcsf = pe.Node(fs.Binarize(match=[4, 5, 14, 15, 24, 31, 43, 44, 63],
                                     erode=1),
                         name="extractcsf")

    # Mean the timeseries across the fourth dimension
    meanfunc = pe.MapNode(fsl.MeanImage(),
                          iterfield=["in_file"],
                          name="meanfunc")

    # Invert the anatomical coregistration and resample the masks
    regwm = pe.MapNode(fs.ApplyVolTransform(inverse=True, interp="nearest"),
                       iterfield=["source_file", "reg_file"],
                       name="regwm")

    regcsf = pe.MapNode(fs.ApplyVolTransform(inverse=True, interp="nearest"),
                        iterfield=["source_file", "reg_file"],
                        name="regcsf")

    regbrain = pe.MapNode(fs.ApplyVolTransform(inverse=True, interp="nearest"),
                          iterfield=["source_file", "reg_file"],
                          name="regbrain")

    # Convert to Nifti for FSL tools
    convertwm = pe.MapNode(fs.MRIConvert(out_type="niigz"),
                           iterfield=["in_file"],
                           name="convertwm")

    convertcsf = pe.MapNode(fs.MRIConvert(out_type="niigz"),
                            iterfield=["in_file"],
                            name="convertcsf")

    convertbrain = pe.MapNode(fs.MRIConvert(out_type="niigz"),
                              iterfield=["in_file"],
                              name="convertbrain")

    # Add the mask images together for a report image
    addconfmasks = pe.MapNode(fsl.ImageMaths(suffix="conf",
                                             op_string="-mul 2 -add",
                                             out_data_type="char"),
                              iterfield=["in_file", "in_file2"],
                              name="addconfmasks")

    # Overlay and slice the confound mask overlaied on mean func for reporting
    confoverlay = pe.MapNode(fsl.Overlay(auto_thresh_bg=True,
                                         stat_thresh=(.7, 2)),
                             iterfield=["background_image", "stat_image"],
                             name="confoverlay")

    confslice = pe.MapNode(fsl.Slicer(image_width=800, label_slices=False),
                           iterfield=["in_file"],
                           name="confslice")
    confslice.inputs.sample_axial = 2

    # Extract the mean signal from white matter and CSF masks
    wmtcourse = pe.MapNode(fs.SegStats(exclude_id=0, avgwf_txt_file=True),
                           iterfield=["segmentation_file", "in_file"],
                           name="wmtcourse")

    csftcourse = pe.MapNode(fs.SegStats(exclude_id=0, avgwf_txt_file=True),
                            iterfield=["segmentation_file", "in_file"],
                            name="csftcourse")

    # Extract the mean signal from over the whole brain
    globaltcourse = pe.MapNode(fs.SegStats(exclude_id=0, avgwf_txt_file=True),
                               iterfield=["segmentation_file", "in_file"],
                               name="globaltcourse")

    # Build the confound design matrix
    conf_inputs = [
        "motion_params", "global_waveform", "wm_waveform", "csf_waveform"
    ]
    confmatrix = pe.MapNode(util.Function(input_names=conf_inputs,
                                          output_names=["confound_matrix"],
                                          function=make_confound_matrix),
                            iterfield=conf_inputs,
                            name="confmatrix")

    # Regress the confounds out of the timeseries
    confregress = pe.MapNode(fsl.FilterRegressor(filter_all=True),
                             iterfield=["in_file", "design_file", "mask"],
                             name="confregress")

    # Rename the confound mask png
    renamepng = pe.MapNode(util.Rename(format_string="confound_sources.png"),
                           iterfield=["in_file"],
                           name="renamepng")

    # Define the outputs
    outputnode = pe.Node(
        util.IdentityInterface(fields=["timeseries", "confound_sources"]),
        name="outputs")

    # Define and connect the confound workflow
    confound = pe.Workflow(name=workflow_name)

    confound.connect([
        (inputnode, meanfunc, [("timeseries", "in_file")]),
        (inputnode, getaseg, [("subject_id", "subject_id")]),
        (getaseg, extractwm, [("aseg", "in_file")]),
        (getaseg, extractcsf, [("aseg", "in_file")]),
        (getaseg, asegmask, [("aseg", "in_file")]),
        (extractwm, regwm, [("binary_file", "target_file")]),
        (extractcsf, regcsf, [("binary_file", "target_file")]),
        (asegmask, regbrain, [("binary_file", "target_file")]),
        (meanfunc, regwm, [("out_file", "source_file")]),
        (meanfunc, regcsf, [("out_file", "source_file")]),
        (meanfunc, regbrain, [("out_file", "source_file")]),
        (inputnode, regwm, [("reg_file", "reg_file")]),
        (inputnode, regcsf, [("reg_file", "reg_file")]),
        (inputnode, regbrain, [("reg_file", "reg_file")]),
        (regwm, convertwm, [("transformed_file", "in_file")]),
        (regcsf, convertcsf, [("transformed_file", "in_file")]),
        (regbrain, convertbrain, [("transformed_file", "in_file")]),
        (convertwm, addconfmasks, [("out_file", "in_file")]),
        (convertcsf, addconfmasks, [("out_file", "in_file2")]),
        (addconfmasks, confoverlay, [("out_file", "stat_image")]),
        (meanfunc, confoverlay, [("out_file", "background_image")]),
        (confoverlay, confslice, [("out_file", "in_file")]),
        (confslice, renamepng, [("out_file", "in_file")]),
        (regwm, wmtcourse, [("transformed_file", "segmentation_file")]),
        (inputnode, wmtcourse, [("timeseries", "in_file")]),
        (regcsf, csftcourse, [("transformed_file", "segmentation_file")]),
        (inputnode, csftcourse, [("timeseries", "in_file")]),
        (regbrain, globaltcourse, [("transformed_file", "segmentation_file")]),
        (inputnode, globaltcourse, [("timeseries", "in_file")]),
        (inputnode, confmatrix, [("motion_parameters", "motion_params")]),
        (wmtcourse, confmatrix, [("avgwf_txt_file", "wm_waveform")]),
        (csftcourse, confmatrix, [("avgwf_txt_file", "csf_waveform")]),
        (globaltcourse, confmatrix, [("avgwf_txt_file", "global_waveform")]),
        (confmatrix, confregress, [("confound_matrix", "design_file")]),
        (inputnode, confregress, [("timeseries", "in_file")]),
        (convertbrain, confregress, [("out_file", "mask")]),
        (confregress, outputnode, [("out_file", "timeseries")]),
        (renamepng, outputnode, [("out_file", "confound_sources")]),
    ])

    return confound
Example #11
0
extractb0 = pe.Node(fsl.ExtractROI(t_size=1, t_min=1),
                       name = "extractb0")
bet = pe.Node(fsl.BET(frac=0.1, mask=True),
                 name="bet_func")
bet2 = pe.Node(fsl.BET(frac=0.1),
                 name="bet_struc")
segment = pe.Node(fsl.FAST(out_basename='fast_'),
                     name="fastSeg")
flirting = pe.Node(fsl.FLIRT(cost_func='normmi', dof=7, searchr_x=[-180, 180],
                             searchr_y=[-180, 180], searchr_z=[-180,180]),
                   name="struc_2_func")
applyxfm = pe.MapNode(fsl.ApplyXfm(apply_xfm = True),
                      name="MaskEPI", iterfield=['in_file'])
erosion = pe.MapNode(fsl.ErodeImage(),
                     name="erode_masks", iterfield=['in_file'])
regcheckoverlay = pe.Node(fsl.Overlay(auto_thresh_bg=True, stat_thresh=(100,500)),
                         name='OverlayCoreg')
regcheck = pe.Node(fsl.Slicer(),
                  name='CheckCoreg')
#filterfeeder = pe.MapNode(fsl.ImageMeants(eig=True, ))

datasink = pe.Node(nio.DataSink(),
                   name='datasink')
datasink.inputs.base_directory = "/Users/Katie/Dropbox/Data/habenula/derivatives/hb_test"

# Connect alllllll the nodes!!
hb_test_wf.connect(subj_iterable, 'subject_id', DataGrabber, 'subject_id')
hb_test_wf.connect(DataGrabber, 'bold', moco, 'in_file')
hb_test_wf.connect(moco, 'out_file', extractb0, 'in_file')
hb_test_wf.connect(extractb0, 'roi_file', bet, 'in_file')
hb_test_wf.connect(bet, 'out_file', datasink, '@epi_brain')
cluster_copes = Node(fsl.model.Cluster(), name='cluster')

#cluster_copes.inputs.threshold = 3.1
cluster_copes.iterables = ('threshold', [2.3, 3.1])
cluster_copes.inputs.pthreshold = 0.001
cluster_copes.inputs.connectivity = 26

cluster_copes.inputs.out_threshold_file = 'thresh_zstat.nii.gz'
cluster_copes.inputs.out_index_file = 'cluster_mask_zstat'
cluster_copes.inputs.out_localmax_txt_file = 'lmax_zstat_std.txt'
cluster_copes.inputs.use_mm = True

#==========================================================================================================================================================
#overlay thresh_zstat1

overlay_cope = Node(fsl.Overlay(), name='overlay')
overlay_cope.inputs.auto_thresh_bg = True
overlay_cope.inputs.stat_thresh = (3.1, 10)
overlay_cope.inputs.transparency = True
overlay_cope.inputs.out_file = 'rendered_thresh_zstat.nii.gz'
overlay_cope.inputs.show_negative_stats = True
overlay_cope.inputs.background_image = standard_brain

#==========================================================================================================================================================
#generate pics thresh_zstat1

slicer_cope = Node(fsl.Slicer(), name='slicer')
slicer_cope.inputs.sample_axial = 2
slicer_cope.inputs.image_width = 2000
slicer_cope.inputs.out_file = 'rendered_thresh_zstat.png'
Example #13
0
def overlay(wf_name='overlay', samethres=True):
    """

    samethres: use False in case of voxel-based thresholding, where ptoz must be a mapnode (also in case of TFCE corr)

    - Get the maximum intensity value of the output thresholded image. This used is while rendering the Z statistic image::

        fslstats zstat1_cluster_threshold.nii.gz -R

        arguments
        -R  : output <min intensity> <max intensity>

    - Rendering. For details see `FEAT <http://www.fmrib.ox.ac.uk/fsl/feat5/detail.html#poststats>`_::

        overlay 1 0 MNI152_T1_2mm_brain.nii.gz
               -a zstat1_cluster_threshold.nii.gz
               2.30 15.67
               zstat1_cluster_threshold_overlay.nii.gz

        slicer zstat1_cluster_threshold_overlay.nii.gz
               -L  -A 750
               zstat1_cluster_threshold_overlay.png

      The Z statistic range selected for rendering is automatically calculated by default,
      to run from red (minimum Z statistic after thresholding) to yellow (maximum Z statistic, here
      maximum intensity).
    """
    overl = pe.Workflow(name=wf_name)

    inputnode = pe.Node(
        util.IdentityInterface(fields=['stat_image', 'threshold', 'bg_image']),
        name='inputspec')

    outputnode = pe.Node(
        util.IdentityInterface(fields=['overlay_threshold', 'rendered_image']),
        name='outputspec')

    #max and minimum intensity values
    image_stats = pe.MapNode(interface=fsl.ImageStats(),
                             name='image_stats',
                             iterfield=['in_file'])
    image_stats.inputs.op_string = '-p 100'

    #create tuple of z_threshold and max intensity value of threshold file
    if (samethres):
        create_tuple = pe.MapNode(util.Function(
            input_names=['infile_a', 'infile_b'],
            output_names=['out_file'],
            function=get_tuple),
                                  name='create_tuple',
                                  iterfield=['infile_b'],
                                  nested=True)
    else:
        create_tuple = pe.MapNode(util.Function(
            input_names=['infile_a', 'infile_b'],
            output_names=['out_file'],
            function=get_tuple),
                                  name='create_tuple',
                                  iterfield=['infile_a', 'infile_b'],
                                  nested=True)

    #colour activation overlaying
    overlay = pe.MapNode(
        interface=fsl.Overlay(),
        name='overlay',
        iterfield=['stat_image', 'stat_thresh', 'background_image'])
    overlay.inputs.transparency = True
    overlay.inputs.auto_thresh_bg = True
    overlay.inputs.out_type = 'float'

    #colour rendering
    slicer = pe.MapNode(interface=fsl.Slicer(),
                        name='slicer',
                        iterfield=['in_file'])
    #set max picture width
    slicer.inputs.image_width = 1750
    # set output all axial slices into one picture
    slicer.inputs.all_axial = True

    overl.connect(inputnode, 'stat_image', image_stats, 'in_file')

    overl.connect(image_stats, 'out_stat', create_tuple, 'infile_b')
    overl.connect(inputnode, 'threshold', create_tuple, 'infile_a')

    overl.connect(inputnode, 'stat_image', overlay, 'stat_image')
    overl.connect(create_tuple, 'out_file', overlay, 'stat_thresh')

    overl.connect(inputnode, 'bg_image', overlay, 'background_image')

    overl.connect(overlay, 'out_file', slicer, 'in_file')

    overl.connect(overlay, 'out_file', outputnode, 'overlay_threshold')
    overl.connect(slicer, 'out_file', outputnode, 'rendered_image')

    return overl
Example #14
0
    (modelgen, conestimate, [('con_file', 'tcon_file')]),
    (modelestimate, conestimate, [('results_dir', 'stats_dir')]),
    (conestimate, ztopval, [(('zstats', lambda x: x[0]), 'in_file')]),
    (modelestimate, mergedestimate, [(('param_estimates', lambda x: x[0]),
                                      'in3')]),
    (conestimate, mergedestimate, [(('copes', lambda x: x[0]), 'in1'),
                                   (('varcopes', lambda x: x[0]), 'in2')]),
])
"""
Setup overlay workflow
----------------------

"""

overlay = pe.Workflow(name='overlay')
overlaystats = pe.MapNode(interface=fsl.Overlay(),
                          name="overlaystats",
                          iterfield=['stat_image'])
overlaystats.inputs.show_negative_stats = True
overlaystats.inputs.auto_thresh_bg = True
"""Use :class:`nipype.interfaces.fsl.Slicer` to create images of the overlaid
statistical volumes for a report of the first-level results.
"""

slicestats = pe.MapNode(interface=fsl.Slicer(),
                        name="slicestats",
                        iterfield=['in_file'])
slicestats.inputs.all_axial = True
slicestats.inputs.image_width = 512

overlay.connect(overlaystats, 'out_file', slicestats, 'in_file')