Beispiel #1
0
def pet_register_rois(name='pet_register_rois', pet_prefix='fdg'):
    inputnode = pe.Node(utility.IdentityInterface(
        fields=['pet_image', 't1_image', 'rois_image']),
                        name='inputspec')
    outputnode = pe.Node(utility.IdentityInterface(
        fields=['pet2t1', 'pet2t1_xfm', 'warped_rois', 'stats']),
                         name='outputspec')

    n_flirt_pet2t1 = pe.Node(fsl.FLIRT(dof=6,
                                       cost='mutualinfo',
                                       out_file=Undefined,
                                       out_matrix_file='%spet2t1.mat' %
                                       pet_prefix),
                             name='flirt_%spet2t1' % pet_prefix)

    n_fsl2xfm = pe.Node(freesurfer.preprocess.Tkregister(no_edit=True,
                                                         xfm_out='%s.xfm',
                                                         reg_file='%s.dat'),
                        name='fsl2xfm')

    n_warp_rois = pe.Node(freesurfer.ApplyVolTransform(
        inverse=True, interp='nearest', transformed_file='warped_rois.nii.gz'),
                          name='warp_rois')

    w = pe.Workflow(name=name)

    n_extract_signal = pe.Node(
        afni.ROIStats(args='-nzvoxels -nzsigma -nzmedian -nobriklab'),
        name='extract_signal')

    w.connect([(inputnode, n_flirt_pet2t1, [('pet_image', 'in_file'),
                                            ('t1_image', 'reference')]),
               (n_flirt_pet2t1, n_fsl2xfm, [('out_matrix_file', 'fsl_reg')]),
               (inputnode, n_fsl2xfm, [
                   ('pet_image', 'mov'),
                   ('t1_image', 'target'),
               ]), (n_fsl2xfm, n_warp_rois, [('xfm_out', 'xfm_reg_file')]),
               (inputnode, n_warp_rois, [('pet_image', 'source_file'),
                                         ('rois_image', 'target_file')]),
               (n_warp_rois, n_extract_signal, [('transformed_file', 'mask')]),
               (inputnode, n_extract_signal, [('pet_image', 'in_file')]),
               (n_warp_rois, outputnode, [('transformed_file', 'warped_rois')
                                          ]),
               (n_flirt_pet2t1, outputnode, [('out_matrix_file', 'pet2t1')]),
               (n_fsl2xfm, outputnode, [('xfm_out', 'pet2t1_xfm')]),
               (n_extract_signal, outputnode, [('stats', 'stats')])])
    return w
Beispiel #2
0
def test_roistats():
    input_map = dict(
        args=dict(argstr='%s', ),
        environ=dict(usedefault=True, ),
        ignore_exception=dict(usedefault=True, ),
        in_file=dict(
            argstr='%s',
            mandatory=True,
        ),
        mask=dict(argstr='-mask %s', ),
        mask_f2short=dict(argstr='-mask_f2short', ),
        outputtype=dict(),
        quiet=dict(argstr='-quiet', ),
    )
    instance = afni.ROIStats()
    for key, metadata in input_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(instance.inputs.traits()[key],
                                        metakey), value
Beispiel #3
0
def get_roi_timeseries(wf_name='roi_timeseries'):
    """
    Workflow to extract timeseries for each node in the ROI mask.
    For each node, mean across all the timepoint is calculated and stored 
    in csv and npz format.
    
    Parameters
    ----------
    wf_name : string
        name of the workflow
    
    Returns 
    -------
    wflow : workflow object
        workflow object
    
    Notes
    -----
    `Source <https://github.com/FCP-INDI/C-PAC/blob/master/CPAC/timeseries/timeseries_analysis.py>`_
    
    Workflow Inputs::
        
        inputspec.rest : string  (nifti file)
            path to input functional data
        inputspec.output_type : string (list of boolean)
            list of boolean for csv and npz file formats
        input_roi.roi : string (nifti file)
            path to ROI mask
        
    Workflow Outputs::

        outputspec.roi_ts : numpy array 
            Voxel time series stored in numpy array, which is used to create ndmg graphs. 
    
        outputspec.roi_outputs : string (list of files)
            Voxel time series stored in 1D (column wise timeseries for each node), 
            csv and/or npz files. By default it outputs timeseries in a 1D file.
            The 1D file is compatible with afni interfaces.
            
    Example
    -------
    >>> import CPAC.timeseries.timeseries_analysis as t
    >>> wf = t.get_roi_timeseries()
    >>> wf.inputs.inputspec.rest = '/home/data/rest.nii.gz'
    >>> wf.inputs.input_roi.roi = '/usr/local/fsl/data/atlases/HarvardOxford/HarvardOxford-cort-maxprob-thr0-2mm.nii.gz'
    >>> wf.inputs.inputspec.output_type = [True,True]
    >>> wf.base_dir = './'
    >>> wf.run()
    
    """

    wflow = pe.Workflow(name=wf_name)

    inputNode = pe.Node(util.IdentityInterface(fields=['rest', 'output_type']),
                        name='inputspec')

    inputnode_roi = pe.Node(util.IdentityInterface(fields=['roi']),
                            name='input_roi')

    outputNode = pe.Node(
        util.IdentityInterface(fields=['roi_ts', 'roi_outputs']),
        name='outputspec')

    timeseries_roi = pe.Node(interface=afni.ROIStats(), name='3dROIstats')
    timeseries_roi.inputs.quiet = False
    timeseries_roi.inputs.args = "-1Dformat"
    # TODO: add -mask_f2short for float parcellation mask
    # if parcellation mask has float values
    #     timeseries_roi.inputs.mask_f2short = True

    wflow.connect(inputNode, 'rest', timeseries_roi, 'in_file')

    wflow.connect(inputnode_roi, 'roi', timeseries_roi, 'mask')

    clean_csv_imports = ['import os']
    clean_csv = pe.Node(util.Function(
        input_names=['roi_csv'],
        output_names=['roi_array', 'edited_roi_csv'],
        function=clean_roi_csv,
        imports=clean_csv_imports),
                        name='clean_roi_csv')

    wflow.connect(timeseries_roi, 'stats', clean_csv, 'roi_csv')

    write_npz_imports = [
        'import os', 'import numpy as np', 'from numpy import genfromtxt'
    ]
    write_npz = pe.Node(util.Function(input_names=['roi_csv', 'out_type'],
                                      output_names=['roi_output_npz'],
                                      function=write_roi_npz,
                                      imports=write_npz_imports),
                        name='write_roi_npz')
    wflow.connect(clean_csv, 'edited_roi_csv', write_npz, 'roi_csv')
    wflow.connect(inputNode, 'output_type', write_npz, 'out_type')
    wflow.connect(clean_csv, 'roi_array', outputNode, 'roi_ts')
    wflow.connect(write_npz, 'roi_output_npz', outputNode, 'roi_outputs')

    return wflow
Beispiel #4
0
def get_roi_timeseries(wf_name='roi_timeseries'):
    """
    Workflow to extract timeseries for each node in the ROI mask.
    For each node, mean across all the timepoint is calculated and stored 
    in csv and npz format.
    
    Parameters
    ----------
    wf_name : string
        name of the workflow
    
    Returns 
    -------
    wflow : workflow object
        workflow object
    
    Notes
    -----
    `Source <https://github.com/FCP-INDI/C-PAC/blob/master/CPAC/timeseries/timeseries_analysis.py>`_
    
    Workflow Inputs::
        
        inputspec.rest : string  (nifti file)
            path to input functional data
        inputspec.output_type : string (list of boolean)
            list of boolean for csv and npz file formats
        input_roi.roi : string (nifti file)
            path to ROI mask
        
    Workflow Outputs::
    
        outputspec.roi_outputs : string (list of files)
            Voxel time series stored in 1D (column wise timeseries for each node), 
            csv and/or npz files. By default it outputs timeseries in a 1D file.
            The 1D file is compatible with afni interfaces.
            
    Example
    -------
    >>> import CPAC.timeseries.timeseries_analysis as t
    >>> wf = t.get_roi_timeseries()
    >>> wf.inputs.inputspec.rest = '/home/data/rest.nii.gz'
    >>> wf.inputs.input_roi.roi = '/usr/local/fsl/data/atlases/HarvardOxford/HarvardOxford-cort-maxprob-thr0-2mm.nii.gz'
    >>> wf.inputs.inputspec.output_type = [True,True]
    >>> wf.base_dir = './'
    >>> wf.run()
    
    """

    wflow = pe.Workflow(name=wf_name)

    inputNode = pe.Node(util.IdentityInterface(fields=['rest', 'output_type']),
                        name='inputspec')

    inputnode_roi = pe.Node(util.IdentityInterface(fields=['roi']),
                            name='input_roi')

    outputNode = pe.Node(util.IdentityInterface(fields=['roi_outputs']),
                         name='outputspec')

    timeseries_roi = pe.Node(interface=afni.ROIStats(), name='3dROIstats')
    timeseries_roi.inputs.quiet = False
    timeseries_roi.inputs.args = "-1Dformat"

    wflow.connect(inputNode, 'rest', timeseries_roi, 'in_file')
    #wflow.connect(inputNode, 'output_type',
    #              timeseries_roi, 'output_type')
    wflow.connect(inputnode_roi, 'roi', timeseries_roi, 'mask')

    wflow.connect(timeseries_roi, 'stats', outputNode, 'roi_outputs')

    return wflow
Beispiel #5
0
def ROIPARAMS():
    import nipype.pipeline.engine as pe
    import glob
    from nipype import Function
    import nipype.interfaces.utility as util
    import os
    import numpy as np
    from nipype.interfaces.utility import Merge
    from nipype.interfaces import afni as afni

    INITDIR = os.getcwd()

    BETAS = input('Please drag in the BRIK of beta weights\n')
    BETAS2 = BETAS.strip('\'"')
    mask2 = input('Please drag in the ROI mask\n')

    inputnode = pe.Node(
        interface=util.IdentityInterface(fields=['BETAS', 'MASKS']),
        name='inputspec')

    if type(mask2) == str:
        inputnode.inputs.MASKS = mask2
        NIFTIDIR = os.path.split(mask2)[0]
        os.chdir(mask2)
    elif type(mask2) == list:
        inputnode.iterables = ([('MASKS', mask2)])
        NIFTIDIR = os.path.split(mask2[0])[0]
        os.chdir(NIFTIDIR)

    inputnode.inputs.BETAS = BETAS2

    ROIINFO = pe.Node(interface=afni.ROIStats(), name='ROISTATS')

    def PLOTTENTSINROI(in_file, maskname):
        import matplotlib.pyplot as plt
        import numpy as np
        import os
        my_data2 = np.loadtxt(fname=in_file,
                              delimiter='\t',
                              comments='!',
                              usecols=(2, ),
                              skiprows=3)
        my_datalabels = np.genfromtxt(fname=in_file,
                                      delimiter='\t',
                                      comments='!',
                                      usecols=(1, ),
                                      skip_header=3,
                                      dtype=None)
        mystr = []
        for instr in range(0, len(my_datalabels)):
            start = my_datalabels[instr].index('[') + 1
            end = my_datalabels[instr].index('.')
            mystr.append(my_datalabels[instr][start:end])
        used = set()
        unique = [x for x in mystr if x not in used and (used.add(x) or True)]
        fig, ax = plt.subplots(figsize=(10, 10))
        st = np.linspace(0,
                         len(my_data2) - (len(my_data2) / len(unique)),
                         len(unique))
        from matplotlib.pyplot import cm
        import numpy as np
        plt.style.use('ggplot')
        plt.tight_layout()
        title = os.path.split(maskname)[1]
        fig.suptitle(title)
        ax1 = plt.subplot2grid((2, len(unique)), (0, 0), colspan=len(unique))
        color = cm.rainbow(np.linspace(0, 1, len(unique)))
        for lines in range(0, len(unique)):
            xax = np.linspace(1, (len(my_data2) / len(unique)),
                              (len(my_data2) / len(unique)))
            print(lines)
            ax = plt.subplot2grid((2, len(unique)), (1, lines))
            ax1.plot(xax,
                     my_data2[st[lines]:st[lines] +
                              (len(my_data2) / len(unique))],
                     c=color[lines])
            ax1.plot(xax,
                     my_data2[st[lines]:st[lines] +
                              (len(my_data2) / len(unique))],
                     '*',
                     c=color[lines])
            x = my_data2[st[lines]:st[lines] + (len(my_data2) / len(unique))]
            ax.set_ylim([min(my_data2), max(my_data2)])
            ax.set_xlim([min(xax), max(xax)])
            ax.set_title(unique[lines])
            ax.set_ylabel('Beta weight')
            ax.set_xlabel('Time from onset')
            ax.plot(xax, x, '--', linewidth=3, c=color[lines])
            ax.plot(xax, x, '*', linewidth=4, c=color[lines])
        plt.show()

    plotter = pe.Node(Function(input_names=['in_file', 'maskname'],
                               output_names=['fig'],
                               function=PLOTTENTSINROI),
                      name='PLOTROI')

    workflow = pe.Workflow(name='ROISTATS')
    workflow.base_dir = os.getcwd()

    workflow.connect(inputnode, 'BETAS', ROIINFO, 'in_file')
    workflow.connect(inputnode, 'MASKS', ROIINFO, 'mask')
    workflow.connect(inputnode, 'MASKS', plotter, 'maskname')
    workflow.connect(ROIINFO, 'stats', plotter, 'in_file')

    workflow.write_graph(graph2use='exec')

    result = workflow.run()

    print "Node completed. Returning to intital directory\n"

    os.chdir(INITDIR)