示例#1
0
def test_segment():
    if spm.Info.name() == "SPM12":
        assert spm.Segment()._jobtype == "tools"
        assert spm.Segment()._jobname == "oldseg"
    else:
        assert spm.Segment()._jobtype == "spatial"
        assert spm.Segment()._jobname == "preproc"
示例#2
0
def test_segment():
    if spm.Info.version()['name'] == "SPM12":
        yield assert_equal, spm.Segment()._jobtype, 'tools'
        yield assert_equal, spm.Segment()._jobname, 'oldseg'
    else:
        yield assert_equal, spm.Segment()._jobtype, 'spatial'
        yield assert_equal, spm.Segment()._jobname, 'preproc'
示例#3
0
def test_segment():
    if spm.Info.version()['name'] == "SPM12":
        assert spm.Segment()._jobtype == 'tools'
        assert spm.Segment()._jobname == 'oldseg'
    else:
        assert spm.Segment()._jobtype == 'spatial'
        assert spm.Segment()._jobname == 'preproc'
示例#4
0
 def __init__(self, data=['path'], **options):
     import nipype.interfaces.spm as spm
     seg = spm.Segment()
     seg.inputs.data = data
     for ef in options:
         setattr(seg.inputs, ef, options[ef])
     self.res = seg.run()
    def __init__(self, name, base_dir=None):

        super(BrainExtractionWorkflow, self).__init__(name, base_dir)

        # Segmentation
        # ============
        seg_node = npe.MapNode(name="Segmentation",
                               iterfield="data",
                               interface=spm.Segment())
        seg_node.inputs.gm_output_type = [False, False, True]
        seg_node.inputs.wm_output_type = [False, False, True]
        seg_node.inputs.csf_output_type = [False, False, True]
        add1_node = npe.MapNode(name="AddGMWM",
                                iterfield=["in_file", "operand_file"],
                                interface=fsl.BinaryMaths())
        add1_node.inputs.operation = 'add'
        add2_node = npe.MapNode(name="AddGMWMCSF",
                                iterfield=["in_file", "operand_file"],
                                interface=fsl.BinaryMaths())
        add2_node.inputs.operation = 'add'
        dil_node = npe.MapNode(name="Dilate",
                               iterfield="in_file",
                               interface=fsl.DilateImage())
        dil_node.inputs.operation = 'mean'
        ero_node = npe.MapNode(name="Erode",
                               iterfield="in_file",
                               interface=fsl.ErodeImage())
        thre_node = npe.MapNode(name="Threshold",
                                iterfield="in_file",
                                interface=fsl.Threshold())
        thre_node.inputs.thresh = 0.5
        fill_node = npe.MapNode(name="Fill",
                                iterfield="in_file",
                                interface=fsl.UnaryMaths())
        fill_node.inputs.operation = 'fillh'
        mask_node = npe.MapNode(name="ApplyMask",
                                iterfield=["in_file", "mask_file"],
                                interface=fsl.ApplyMask())

        mask_node.inputs.output_type = str("NIFTI")

        self.connect([
            (seg_node, add1_node, [('native_gm_image', 'in_file')]),
            (seg_node, add1_node, [('native_wm_image', 'operand_file')]),
            (seg_node, add2_node, [('native_csf_image', 'in_file')]),
            (add1_node, add2_node, [('out_file', 'operand_file')]),
            (add2_node, dil_node, [('out_file', 'in_file')]),
            (dil_node, ero_node, [('out_file', 'in_file')]),
            (ero_node, thre_node, [('out_file', 'in_file')]),
            (thre_node, fill_node, [('out_file', 'in_file')]),
            (fill_node, mask_node, [('out_file', 'mask_file')]),
        ])
示例#6
0
    def __init__(self, experiment_dir, output_dir, working_dir, func_source,
                 struct_source, datasink):
        self.experiment_dir = experiment_dir
        self.output_dir = output_dir
        self.working_dir = working_dir

        # specify input and output nodes
        self.func_source = func_source
        self.struct_source = struct_source
        self.datasink = datasink

        # specify workflow instance
        self.workflow = pe.Workflow(name='workflow')

        # specify nodes
        self.realign = pe.Node(interface=spm.Realign(), name='realign')

        self.coregister = pe.Node(interface=spm.Coregister(),
                                  name="coregister")
        self.coregister.inputs.jobtype = 'estimate'

        self.segment = pe.Node(interface=spm.Segment(), name="segment")

        self.normalize_func = pe.Node(interface=spm.Normalize(),
                                      name="normalize_func")
        self.normalize_func.inputs.jobtype = "write"

        self.normalize_struc = pe.Node(interface=spm.Normalize(),
                                       name="normalize_struc")
        self.normalize_struc.inputs.jobtype = "write"

        self.smooth = pe.Node(interface=spm.Smooth(), name="smooth")

        # connect the nodes to complete the workflow
        self.workflow.connect([
            (self.func_source, self.realign, [('outfiles', 'in_files')]),
            (self.struct_source, self.coregister, [('outfiles', 'source')]),
            (self.realign, self.coregister, [('mean_image', 'target')]),
            (self.coregister, self.segment, [('coregistered_source', 'data')]),
            (self.segment, self.normalize_func, [('transformation_mat',
                                                  'parameter_file')]),
            (self.realign, self.normalize_func, [('realigned_files',
                                                  'apply_to_files')]),
            (self.normalize_func, self.smooth, [('normalized_files',
                                                 'in_files')]),
            #(self.realign, self.datasink, [('realigned_files', 'realign')]),
            #(self.realign, self.datasink, [('mean_image', 'mean')]),
            (self.normalize_func, self.datasink, [('normalized_files', 'norm')]
             ),
            (self.smooth, self.datasink, [('smoothed_files', 'smooth')])
        ])
示例#7
0
def simple_segment(mri):
    """uses spm to segment an mri in native space"""
    startdir = os.getcwd()
    pth, _ = os.path.split(mri)
    os.chdir(pth)
    seg = spm.Segment(matlab_cmd='matlab-spm8')
    seg.inputs.data = mri
    seg.inputs.gm_output_type = [False, False, True]
    seg.inputs.wm_output_type = [False, False, True]
    seg.inputs.csf_output_type = [False, False, True]
    seg.inputs.ignore_exception = True
    segout = seg.run()
    os.chdir(startdir)
    return segout
示例#8
0
def test_segment():
    yield assert_equal, spm.Segment._jobtype, 'spatial'
    yield assert_equal, spm.Segment._jobname, 'preproc'
    input_map = dict(data=dict(field='data', copyfile=False, mandatory=True),
                     gm_output_type=dict(field='output.GM'),
                     wm_output_type=dict(field='output.WM'),
                     csf_output_type=dict(field='output.CSF'),
                     save_bias_corrected=dict(field='output.biascor'),
                     clean_masks=dict(field='output.cleanup'),
                     tissue_prob_maps=dict(field='opts.tpm'),
                     gaussians_per_class=dict(field='opts.ngaus'),
                     affine_regularization=dict(field='opts.regtype'),
                     warping_regularization=dict(field='opts.warpreg'),
                     warp_frequency_cutoff=dict(field='opts.warpco'),
                     bias_regularization=dict(field='opts.biasreg'),
                     bias_fwhm=dict(field='opts.biasfwhm'),
                     sampling_distance=dict(field='opts.samp'),
                     mask_image=dict(field='opts.msk'))
    seg = spm.Segment()
    for key, metadata in input_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(seg.inputs.traits()[key],
                                        metakey), value
示例#9
0
convert = pe.Node(interface=fs.MRIConvert(out_type='nii'), name='convert2nii')
convert2 = pe.MapNode(interface=fs.MRIConvert(out_type='nii'),
                      iterfield=['in_file'],
                      name='convertimg2nii')
"""
Use :class:`nipype.interfaces.spm.Segment` to segment the structural image and
generate the transformation file to MNI space.

.. note::

   Segment takes longer than usual because the nose is wrapped behind
   the head in the structural image.
"""

segment = pe.Node(interface=spm.Segment(), name='segment')
"""
Use :class:`nipype.interfaces.freesurfer.ApplyVolTransform` to convert contrast
images into freesurfer space.
"""

normwreg = pe.MapNode(interface=fs.ApplyVolTransform(),
                      iterfield=['source_file'],
                      name='applyreg2con')
"""
Use :class:`nipype.interfaces.spm.Normalize` to normalize the contrast images
to MNI space
"""

normalize = pe.Node(interface=spm.Normalize(jobtype='write'), name='norm2mni')
"""
示例#10
0
def create_spm_preproc_func_pipeline(data_dir=None,
                                     subject_id=None,
                                     task_list=None):

    ###############################
    ## Set up Nodes
    ###############################

    ds = Node(nio.DataGrabber(infields=['subject_id', 'task_id'],
                              outfields=['func', 'struc']),
              name='datasource')
    ds.inputs.base_directory = os.path.abspath(data_dir + '/' + subject_id)
    ds.inputs.template = '*'
    ds.inputs.sort_filelist = True
    ds.inputs.template_args = {'func': [['task_id']], 'struc': []}
    ds.inputs.field_template = {
        'func': 'Functional/Raw/%s/func.nii',
        'struc': 'Structural/SPGR/spgr.nii'
    }
    ds.inputs.subject_id = subject_id
    ds.inputs.task_id = task_list
    ds.iterables = ('task_id', task_list)
    # ds.run().outputs #show datafiles

    # #Setup Data Sinker for writing output files
    # datasink = Node(nio.DataSink(), name='sinker')
    # datasink.inputs.base_directory = '/path/to/output'
    # workflow.connect(realigner, 'realignment_parameters', datasink, 'motion.@par')
    # datasink.inputs.substitutions = [('_variable', 'variable'),('file_subject_', '')]

    #Get Timing Acquisition for slice timing
    tr = 2
    ta = Node(interface=util.Function(input_names=['tr', 'n_slices'],
                                      output_names=['ta'],
                                      function=get_ta),
              name="ta")
    ta.inputs.tr = tr

    #Slice Timing: sequential ascending
    slice_timing = Node(interface=spm.SliceTiming(), name="slice_timing")
    slice_timing.inputs.time_repetition = tr
    slice_timing.inputs.ref_slice = 1

    #Realignment - 6 parameters - realign to first image of very first series.
    realign = Node(interface=spm.Realign(), name="realign")
    realign.inputs.register_to_mean = True

    #Plot Realignment
    plot_realign = Node(interface=PlotRealignmentParameters(),
                        name="plot_realign")

    #Artifact Detection
    art = Node(interface=ra.ArtifactDetect(), name="art")
    art.inputs.use_differences = [True, False]
    art.inputs.use_norm = True
    art.inputs.norm_threshold = 1
    art.inputs.zintensity_threshold = 3
    art.inputs.mask_type = 'file'
    art.inputs.parameter_source = 'SPM'

    #Coregister - 12 parameters, cost function = 'nmi', fwhm 7, interpolate, don't mask
    #anatomical to functional mean across all available data.
    coregister = Node(interface=spm.Coregister(), name="coregister")
    coregister.inputs.jobtype = 'estimate'

    # Segment structural, gray/white/csf,mni,
    segment = Node(interface=spm.Segment(), name="segment")
    segment.inputs.save_bias_corrected = True

    #Normalize - structural to MNI - then apply this to the coregistered functionals
    normalize = Node(interface=spm.Normalize(), name="normalize")
    normalize.inputs.template = os.path.abspath(t1_template_file)

    #Plot normalization Check
    plot_normalization_check = Node(interface=Plot_Coregistration_Montage(),
                                    name="plot_normalization_check")
    plot_normalization_check.inputs.canonical_img = canonical_file

    #Create Mask
    compute_mask = Node(interface=ComputeMask(), name="compute_mask")
    #remove lower 5% of histogram of mean image
    compute_mask.inputs.m = .05

    #Smooth
    #implicit masking (.im) = 0, dtype = 0
    smooth = Node(interface=spm.Smooth(), name="smooth")
    fwhmlist = [0, 5, 8]
    smooth.iterables = ('fwhm', fwhmlist)

    #Create Covariate matrix
    make_covariates = Node(interface=Create_Covariates(),
                           name="make_covariates")

    ###############################
    ## Create Pipeline
    ###############################

    Preprocessed = Workflow(name="Preprocessed")
    Preprocessed.base_dir = os.path.abspath(data_dir + '/' + subject_id +
                                            '/Functional')

    Preprocessed.connect([
        (ds, ta, [(('func', get_n_slices), "n_slices")]),
        (ta, slice_timing, [("ta", "time_acquisition")]),
        (ds, slice_timing, [
            ('func', 'in_files'),
            (('func', get_n_slices), "num_slices"),
            (('func', get_slice_order), "slice_order"),
        ]),
        (slice_timing, realign, [('timecorrected_files', 'in_files')]),
        (realign, compute_mask, [('mean_image', 'mean_volume')]),
        (realign, coregister, [('mean_image', 'target')]),
        (ds, coregister, [('struc', 'source')]),
        (coregister, segment, [('coregistered_source', 'data')]),
        (segment, normalize, [
            ('transformation_mat', 'parameter_file'),
            ('bias_corrected_image', 'source'),
        ]),
        (realign, normalize, [('realigned_files', 'apply_to_files'),
                              (('realigned_files', get_vox_dims),
                               'write_voxel_sizes')]),
        (normalize, smooth, [('normalized_files', 'in_files')]),
        (compute_mask, art, [('brain_mask', 'mask_file')]),
        (realign, art, [('realignment_parameters', 'realignment_parameters')]),
        (realign, art, [('realigned_files', 'realigned_files')]),
        (realign, plot_realign, [('realignment_parameters',
                                  'realignment_parameters')]),
        (normalize, plot_normalization_check, [('normalized_files', 'wra_img')
                                               ]),
        (realign, make_covariates, [('realignment_parameters',
                                     'realignment_parameters')]),
        (art, make_covariates, [('outlier_files', 'spike_id')]),
    ])
    return Preprocessed
示例#11
0
def create_reg_workflow(name='registration'):
    """Create a FEAT preprocessing workflow together with freesurfer

    Parameters
    ----------

    ::

        name : name of workflow (default: 'registration')

    Inputs::

        inputspec.source_files : files (filename or list of filenames to register)
        inputspec.mean_image : reference image to use
        inputspec.anatomical_image : anatomical image to coregister to
        inputspec.target_image : registration target

    Outputs::

        outputspec.func2anat_transform : FLIRT transform
        outputspec.anat2target_transform : FLIRT+FNIRT transform
        outputspec.transformed_files : transformed files in target space
        outputspec.transformed_mean : mean image in target space

    Example
    -------

    """

    register = pe.Workflow(name=name)

    inputnode = pe.Node(interface=util.IdentityInterface(fields=['source_files',
                                                                 'mean_image',
                                                                 'anatomical_image',
                                                                 'target_image']),
                        name='inputspec')
    outputnode = pe.Node(interface=util.IdentityInterface(fields=['func2anat_transform',
                                                              'anat2target_transform',
                                                              'transformed_files',
                                                              'transformed_mean',
                                                              ]),
                     name='outputspec')

    """
    Estimate the tissue classes from the anatomical image. But use spm's segment
    as FSL appears to be breaking.
    """

    #fast = pe.Node(fsl.FAST(), name='fast')
    #fast.config = {'execution': {'keep_unncessary_outputs': True}}
    #register.connect(inputnode, 'anatomical_image', fast, 'in_files')

    convert = pe.Node(fs.MRIConvert(out_type='nii'), name='convert')
    register.connect(inputnode, 'anatomical_image', convert, 'in_file')

    segment = pe.Node(spm.Segment(), name='segment')
    segment.inputs.wm_output_type = [False, False, True]
    segment.config = {'execution': {'keep_unnecessary_outputs': 'true'}}
    register.connect(convert, 'out_file', segment, 'data')

    """
    Binarize the segmentation
    """

    binarize = pe.Node(fsl.ImageMaths(op_string='-nan -thr 0.5 -bin'),
                       name='binarize')
    #pickindex = lambda x, i: x[i]
    #register.connect(fast, ('partial_volume_files', pickindex, 1),
    #                 binarize, 'in_file')
    register.connect(segment, 'native_wm_image', binarize, 'in_file')

    """
    Calculate rigid transform from mean image to anatomical image
    """

    mean2anat = pe.Node(fsl.FLIRT(), name='mean2anat')
    mean2anat.inputs.dof = 6
    register.connect(inputnode, 'mean_image', mean2anat, 'in_file')
    register.connect(inputnode, 'anatomical_image', mean2anat, 'reference')

    """
    Now use bbr cost function to improve the transform
    """

    mean2anatbbr = pe.Node(fsl.FLIRT(), name='mean2anatbbr')
    mean2anatbbr.inputs.dof = 6
    mean2anatbbr.inputs.cost = 'bbr'
    os.environ['FSLDIR']
    mean2anatbbr.inputs.schedule = os.path.join(os.environ['FSLDIR'],'etc/flirtsch/bbr.sch')
    register.connect(inputnode, 'mean_image', mean2anatbbr, 'in_file')
    register.connect(binarize, 'out_file', mean2anatbbr, 'wm_seg')
    register.connect(inputnode, 'anatomical_image', mean2anatbbr, 'reference')
    register.connect(mean2anat, 'out_matrix_file', mean2anatbbr, 'in_matrix_file')

    """
    Calculate affine transform from anatomical to target
    """

    anat2target_affine = pe.Node(fsl.FLIRT(), name='anat2target_linear')
    register.connect(inputnode, 'anatomical_image', anat2target_affine, 'in_file')
    register.connect(inputnode, 'target_image', anat2target_affine, 'reference')

    """
    Calculate nonlinear transform from anatomical to target
    """

    anat2target_nonlinear = pe.Node(fsl.FNIRT(), name='anat2target_nonlinear')
    register.connect(anat2target_affine, 'out_matrix_file',
                     anat2target_nonlinear, 'affine_file')
    #anat2target_nonlinear.inputs.in_fwhm = [8, 4, 2, 2]
    #anat2target_nonlinear.inputs.subsampling_scheme = [4, 2, 1, 1]
    anat2target_nonlinear.inputs.warp_resolution = (8, 8, 8)
    register.connect(inputnode, 'anatomical_image', anat2target_nonlinear, 'in_file')
    register.connect(inputnode, 'target_image',
                     anat2target_nonlinear, 'ref_file')

    """
    Transform the mean image. First to anatomical and then to target
    """

    warp2anat = pe.Node(fsl.ApplyWarp(interp='spline'), name='warp2anat')
    register.connect(inputnode, 'mean_image', warp2anat, 'in_file')
    register.connect(inputnode, 'anatomical_image', warp2anat, 'ref_file')
    register.connect(mean2anatbbr, 'out_matrix_file', warp2anat, 'premat')

    warpmean = pe.Node(fsl.ApplyWarp(interp='spline'), name='warpmean')
    register.connect(warp2anat, 'out_file', warpmean, 'in_file')
    register.connect(inputnode, 'target_image', warpmean, 'ref_file')
    register.connect(anat2target_affine, 'out_matrix_file', warpmean, 'premat')
    register.connect(anat2target_nonlinear, 'field_file',
                     warpmean, 'field_file')

    """
    Transform the remaining images. First to anatomical and then to target
    """

    warpall2anat = pe.MapNode(fsl.ApplyWarp(interp='spline'),
                              iterfield=['in_file'],
                              name='warpall2anat')
    register.connect(inputnode, 'source_files', warpall2anat, 'in_file')
    register.connect(inputnode, 'anatomical_image', warpall2anat, 'ref_file')
    register.connect(mean2anatbbr, 'out_matrix_file', warpall2anat, 'premat')

    warpall = pe.MapNode(fsl.ApplyWarp(interp='spline'), name='warpall',
                         iterfield=['in_file'])
    register.connect(warpall2anat, 'out_file', warpall, 'in_file')
    register.connect(inputnode, 'target_image', warpall, 'ref_file')
    register.connect(anat2target_affine, 'out_matrix_file', warpall, 'premat')
    register.connect(anat2target_nonlinear, 'field_file',
                     warpall, 'field_file')

    """
    Assign all the output files
    """

    register.connect(warpmean, 'out_file', outputnode, 'transformed_mean')
    register.connect(warpall, 'out_file', outputnode, 'transformed_files')
    register.connect(mean2anatbbr, 'out_matrix_file',
                     outputnode, 'func2anat_transform')
    register.connect(anat2target_nonlinear, 'field_file',
                     outputnode, 'anat2target_transform')

    return register
def create_spm_preproc(c, name='preproc'):
    """
"""

    from nipype.workflows.smri.freesurfer.utils import create_getmask_flow
    import nipype.algorithms.rapidart as ra
    import nipype.interfaces.spm as spm
    import nipype.interfaces.utility as niu
    import nipype.pipeline.engine as pe
    import nipype.interfaces.io as nio
    import nipype.interfaces.freesurfer as fs

    workflow = pe.Workflow(name=name)

    inputnode = pe.Node(niu.IdentityInterface(fields=[
        'functionals', 'subject_id', 'subjects_dir', 'fwhm', 'norm_threshold',
        'zintensity_threshold', 'tr', 'do_slicetime', 'sliceorder',
        'parameters', 'node', 'csf_prob', 'wm_prob', 'gm_prob'
    ]),
                        name='inputspec')

    poplist = lambda x: x.pop()

    sym_func = pe.Node(niu.Function(input_names=['in_file'],
                                    output_names=['out_link'],
                                    function=do_symlink),
                       name='func_symlink')

    # REALIGN

    realign = pe.Node(niu.Function(
        input_names=[
            'node', 'in_file', 'tr', 'do_slicetime', 'sliceorder', 'parameters'
        ],
        output_names=['out_file', 'par_file', 'parameter_source'],
        function=mod_realign),
                      name="mod_realign")
    workflow.connect(inputnode, 'parameters', realign, 'parameters')
    workflow.connect(inputnode, 'functionals', realign, 'in_file')
    workflow.connect(inputnode, 'tr', realign, 'tr')
    workflow.connect(inputnode, 'do_slicetime', realign, 'do_slicetime')
    workflow.connect(inputnode, 'sliceorder', realign, 'sliceorder')
    workflow.connect(inputnode, 'node', realign, 'node')

    # TAKE MEAN IMAGE

    mean = art_mean_workflow()
    workflow.connect(realign, 'out_file', mean, 'inputspec.realigned_files')
    workflow.connect(realign, 'par_file', mean,
                     'inputspec.realignment_parameters')
    workflow.connect(realign, 'parameter_source', mean,
                     'inputspec.parameter_source')

    # CREATE BRAIN MASK

    maskflow = create_getmask_flow()
    workflow.connect([(inputnode, maskflow,
                       [('subject_id', 'inputspec.subject_id'),
                        ('subjects_dir', 'inputspec.subjects_dir')])])
    maskflow.inputs.inputspec.contrast_type = 't2'
    workflow.connect(mean, 'outputspec.mean_image', maskflow,
                     'inputspec.source_file')

    # SEGMENT

    segment = pe.Node(spm.Segment(csf_output_type=[True, True, False],
                                  gm_output_type=[True, True, False],
                                  wm_output_type=[True, True, False]),
                      name='segment')
    mergefunc = lambda in1, in2, in3: [in1, in2, in3]

    merge = pe.Node(niu.Function(input_names=['in1', 'in2', 'in3'],
                                 output_names=['out'],
                                 function=mergefunc),
                    name='merge')
    workflow.connect(inputnode, 'csf_prob', merge, 'in3')
    workflow.connect(inputnode, 'wm_prob', merge, 'in2')
    workflow.connect(inputnode, 'gm_prob', merge, 'in1')

    sym_prob = sym_func
    workflow.connect(merge, 'out', sym_prob, 'in_file')
    workflow.connect(sym_prob, 'out_link', segment, 'tissue_prob_maps')

    xform_mask = pe.Node(fs.ApplyVolTransform(fs_target=True),
                         name='transform_mask')
    workflow.connect(maskflow, ('outputspec.reg_file', pickfirst), xform_mask,
                     'reg_file')
    workflow.connect(maskflow, ('outputspec.mask_file', pickfirst), xform_mask,
                     'source_file')
    workflow.connect(xform_mask, "transformed_file", segment, 'mask_image')

    fssource = maskflow.get_node('fssource')
    convert2nii = pe.Node(fs.MRIConvert(in_type='mgz', out_type='nii'),
                          name='convert2nii')
    workflow.connect(fssource, 'brain', convert2nii, 'in_file')
    workflow.connect(convert2nii, 'out_file', segment, 'data')

    # NORMALIZE

    normalize = pe.MapNode(spm.Normalize(jobtype='write'),
                           name='normalize',
                           iterfield=['apply_to_files'])
    normalize_struct = normalize.clone('normalize_struct')
    normalize_mask = normalize.clone('normalize_mask')

    workflow.connect(segment, 'transformation_mat', normalize,
                     'parameter_file')
    workflow.connect(segment, 'transformation_mat', normalize_mask,
                     'parameter_file')
    workflow.connect(segment, 'transformation_mat', normalize_struct,
                     'parameter_file')
    workflow.connect(convert2nii, 'out_file', normalize_struct,
                     'apply_to_files')
    workflow.connect(xform_mask, "transformed_file", normalize_mask,
                     'apply_to_files')

    xform_image = pe.MapNode(fs.ApplyVolTransform(fs_target=True),
                             name='xform_image',
                             iterfield=['source_file'])
    workflow.connect(maskflow, ('outputspec.reg_file', pickfirst), xform_image,
                     'reg_file')
    workflow.connect(realign, 'out_file', xform_image, "source_file")
    workflow.connect(xform_image, "transformed_file", normalize,
                     "apply_to_files")

    #SMOOTH

    smooth = pe.Node(spm.Smooth(), name='smooth')

    workflow.connect(inputnode, 'fwhm', smooth, 'fwhm')
    workflow.connect(normalize, 'normalized_files', smooth, 'in_files')

    # ART

    artdetect = pe.Node(ra.ArtifactDetect(mask_type='file',
                                          use_differences=[True, False],
                                          use_norm=True,
                                          save_plot=True),
                        name='artdetect')
    workflow.connect(realign, 'parameter_source', artdetect,
                     'parameter_source')
    workflow.connect([(inputnode, artdetect,
                       [('norm_threshold', 'norm_threshold'),
                        ('zintensity_threshold', 'zintensity_threshold')])])
    workflow.connect([(realign, artdetect, [('out_file', 'realigned_files'),
                                            ('par_file',
                                             'realignment_parameters')])])
    workflow.connect(maskflow, ('outputspec.mask_file', poplist), artdetect,
                     'mask_file')

    # OUTPUTS

    outputnode = pe.Node(niu.IdentityInterface(fields=[
        "realignment_parameters", "smoothed_files", "mask_file", "mean_image",
        "reg_file", "reg_cost", 'outlier_files', 'outlier_stats',
        'outlier_plots', 'norm_components', 'mod_csf', 'unmod_csf', 'mod_wm',
        'unmod_wm', 'mod_gm', 'unmod_gm', 'mean', 'normalized_struct',
        'normalization_parameters', 'reverse_normalize_parameters'
    ]),
                         name="outputspec")
    workflow.connect([
        (maskflow, outputnode, [("outputspec.reg_file", "reg_file")]),
        (maskflow, outputnode, [("outputspec.reg_cost", "reg_cost")]),
        (realign, outputnode, [('par_file', 'realignment_parameters')]),
        (smooth, outputnode, [('smoothed_files', 'smoothed_files')]),
        (artdetect, outputnode, [('outlier_files', 'outlier_files'),
                                 ('statistic_files', 'outlier_stats'),
                                 ('plot_files', 'outlier_plots'),
                                 ('norm_files', 'norm_components')])
    ])
    workflow.connect(normalize_mask, "normalized_files", outputnode,
                     "mask_file")
    workflow.connect(segment, 'modulated_csf_image', outputnode, 'mod_csf')
    workflow.connect(segment, 'modulated_wm_image', outputnode, 'mod_wm')
    workflow.connect(segment, 'modulated_gm_image', outputnode, 'mod_gm')
    workflow.connect(segment, 'normalized_csf_image', outputnode, 'unmod_csf')
    workflow.connect(segment, 'normalized_wm_image', outputnode, 'unmod_wm')
    workflow.connect(segment, 'normalized_gm_image', outputnode, 'unmod_gm')
    workflow.connect(mean, 'outputspec.mean_image', outputnode, 'mean')
    workflow.connect(normalize_struct, 'normalized_files', outputnode,
                     'normalized_struct')
    workflow.connect(segment, 'transformation_mat', outputnode,
                     'normalization_parameters')
    workflow.connect(segment, 'inverse_transformation_mat', outputnode,
                     'reverse_normalize_parameters')

    # CONNECT TO CONFIG

    workflow.inputs.inputspec.fwhm = c.fwhm
    workflow.inputs.inputspec.subjects_dir = c.surf_dir
    workflow.inputs.inputspec.norm_threshold = c.norm_thresh
    workflow.inputs.inputspec.zintensity_threshold = c.z_thresh
    workflow.inputs.inputspec.node = c.motion_correct_node
    workflow.inputs.inputspec.tr = c.TR
    workflow.inputs.inputspec.do_slicetime = c.do_slicetiming
    workflow.inputs.inputspec.sliceorder = c.SliceOrder
    workflow.inputs.inputspec.csf_prob = c.csf_prob
    workflow.inputs.inputspec.gm_prob = c.grey_prob
    workflow.inputs.inputspec.wm_prob = c.white_prob
    workflow.inputs.inputspec.parameters = {"order": c.order}
    workflow.base_dir = c.working_dir
    workflow.config = {'execution': {'crashdump_dir': c.crash_dir}}

    datagrabber = get_dataflow(c)

    workflow.connect(datagrabber, 'func', inputnode, 'functionals')

    infosource = pe.Node(niu.IdentityInterface(fields=['subject_id']),
                         name='subject_names')
    if not c.test_mode:
        infosource.iterables = ('subject_id', c.subjects)
    else:
        infosource.iterables = ('subject_id', c.subjects[:1])

    workflow.connect(infosource, 'subject_id', inputnode, 'subject_id')
    workflow.connect(infosource, 'subject_id', datagrabber, 'subject_id')
    sub = lambda x: [('_subject_id_%s' % x, '')]

    sinker = pe.Node(nio.DataSink(), name='sinker')
    workflow.connect(infosource, 'subject_id', sinker, 'container')
    workflow.connect(infosource, ('subject_id', sub), sinker, 'substitutions')
    sinker.inputs.base_directory = c.sink_dir
    outputspec = workflow.get_node('outputspec')
    workflow.connect(outputspec, 'realignment_parameters', sinker,
                     'spm_preproc.realignment_parameters')
    workflow.connect(outputspec, 'smoothed_files', sinker,
                     'spm_preproc.smoothed_outputs')
    workflow.connect(outputspec, 'outlier_files', sinker,
                     'spm_preproc.art.@outlier_files')
    workflow.connect(outputspec, 'outlier_stats', sinker,
                     'spm_preproc.art.@outlier_stats')
    workflow.connect(outputspec, 'outlier_plots', sinker,
                     'spm_preproc.art.@outlier_plots')
    workflow.connect(outputspec, 'norm_components', sinker,
                     'spm_preproc.art.@norm')
    workflow.connect(outputspec, 'reg_file', sinker,
                     'spm_preproc.bbreg.@reg_file')
    workflow.connect(outputspec, 'reg_cost', sinker,
                     'spm_preproc.bbreg.@reg_cost')
    workflow.connect(outputspec, 'mask_file', sinker,
                     'spm_preproc.mask.@mask_file')
    workflow.connect(outputspec, 'mod_csf', sinker,
                     'spm_preproc.segment.mod.@csf')
    workflow.connect(outputspec, 'mod_wm', sinker,
                     'spm_preproc.segment.mod.@wm')
    workflow.connect(outputspec, 'mod_gm', sinker,
                     'spm_preproc.segment.mod.@gm')
    workflow.connect(outputspec, 'unmod_csf', sinker,
                     'spm_preproc.segment.unmod.@csf')
    workflow.connect(outputspec, 'unmod_wm', sinker,
                     'spm_preproc.segment.unmod.@wm')
    workflow.connect(outputspec, 'unmod_gm', sinker,
                     'spm_preproc.segment.unmod.@gm')
    workflow.connect(outputspec, 'mean', sinker, 'spm_preproc.mean')
    workflow.connect(outputspec, 'normalized_struct', sinker,
                     'spm_preproc.normalized_struct')
    workflow.connect(outputspec, 'normalization_parameters', sinker,
                     'spm_preproc.normalization_parameters.@forward')
    workflow.connect(outputspec, 'reverse_normalize_parameters', sinker,
                     'spm_preproc.normalization_parameters.@reverse')

    return workflow
示例#13
0
def create_spm_preproc(c, name='preproc'):
    """Create an spm preprocessing workflow with freesurfer registration and
artifact detection.

The workflow realigns and smooths and registers the functional images with
the subject's freesurfer space.

Example
-------

>>> preproc = create_spm_preproc()
>>> preproc.base_dir = '.'
>>> preproc.inputs.inputspec.fwhm = 6
>>> preproc.inputs.inputspec.subject_id = 's1'
>>> preproc.inputs.inputspec.subjects_dir = '.'
>>> preproc.inputs.inputspec.functionals = ['f3.nii', 'f5.nii']
>>> preproc.inputs.inputspec.norm_threshold = 1
>>> preproc.inputs.inputspec.zintensity_threshold = 3

Inputs::

inputspec.functionals : functional runs use 4d nifti
inputspec.subject_id : freesurfer subject id
inputspec.subjects_dir : freesurfer subjects dir
inputspec.fwhm : smoothing fwhm
inputspec.norm_threshold : norm threshold for outliers
inputspec.zintensity_threshold : intensity threshold in z-score

Outputs::

outputspec.realignment_parameters : realignment parameter files
outputspec.smoothed_files : smoothed functional files
outputspec.outlier_files : list of outliers
outputspec.outlier_stats : statistics of outliers
outputspec.outlier_plots : images of outliers
outputspec.mask_file : binary mask file in reference image space
outputspec.reg_file : registration file that maps reference image to
freesurfer space
outputspec.reg_cost : cost of registration (useful for detecting misalignment)
"""
    from nipype.workflows.smri.freesurfer.utils import create_getmask_flow
    import nipype.algorithms.rapidart as ra
    import nipype.interfaces.spm as spm
    import nipype.interfaces.utility as niu
    import nipype.pipeline.engine as pe
    import nipype.interfaces.io as nio
    """
Initialize the workflow
"""

    workflow = pe.Workflow(name=name)
    """
Define the inputs to this workflow
"""

    inputnode = pe.Node(niu.IdentityInterface(fields=[
        'functionals', 'subject_id', 'subjects_dir', 'fwhm', 'norm_threshold',
        'zintensity_threshold', 'tr', 'do_slicetime', 'sliceorder', 'node',
        'csf_prob', 'wm_prob', 'gm_prob'
    ]),
                        name='inputspec')
    """
Setup the processing nodes and create the mask generation and coregistration
workflow
"""

    poplist = lambda x: x.pop()
    #realign = pe.Node(spm.Realign(), name='realign')

    sym_func = pe.Node(niu.Function(input_names=['in_file'],
                                    output_names=['out_link'],
                                    function=do_symlink),
                       name='func_symlink')

    realign = pe.Node(niu.Function(
        input_names=['node', 'in_file', 'tr', 'do_slicetime', 'sliceorder'],
        output_names=['out_file', 'par_file'],
        function=mod_realign),
                      name="mod_realign")

    mean = art_mean_workflow()
    workflow.connect(realign, 'out_file', mean, 'inputspec.realigned_files')
    workflow.connect(realign, 'par_file', mean,
                     'inputspec.realignment_parameters')
    mean.inputs.inputspec.parameter_source = 'FSL'  # Modular realign puts it in FSL format for consistency

    #workflow.connect(inputnode, 'functionals', realign, 'in_file')
    workflow.connect(inputnode, 'functionals', sym_func, 'in_file')
    workflow.connect(sym_func, 'out_link', realign, 'in_file')

    workflow.connect(inputnode, 'tr', realign, 'tr')
    workflow.connect(inputnode, 'do_slicetime', realign, 'do_slicetime')
    workflow.connect(inputnode, 'sliceorder', realign, 'sliceorder')
    workflow.connect(inputnode, 'node', realign, 'node')

    maskflow = create_getmask_flow()
    workflow.connect([(inputnode, maskflow,
                       [('subject_id', 'inputspec.subject_id'),
                        ('subjects_dir', 'inputspec.subjects_dir')])])
    maskflow.inputs.inputspec.contrast_type = 't2'
    workflow.connect(mean, 'outputspec.mean_image', maskflow,
                     'inputspec.source_file')
    smooth = pe.Node(spm.Smooth(), name='smooth')

    normalize = pe.Node(spm.Normalize(jobtype='write'), name='normalize')
    normalize_struct = normalize.clone('normalize_struct')
    segment = pe.Node(spm.Segment(csf_output_type=[True, True, False],
                                  gm_output_type=[True, True, False],
                                  wm_output_type=[True, True, False]),
                      name='segment')

    mergefunc = lambda in1, in2, in3: [in1, in2, in3]

    # merge = pe.Node(niu.Merge(),name='merge')
    merge = pe.Node(niu.Function(input_names=['in1', 'in2', 'in3'],
                                 output_names=['out'],
                                 function=mergefunc),
                    name='merge')
    workflow.connect(inputnode, 'csf_prob', merge, 'in3')
    workflow.connect(inputnode, 'wm_prob', merge, 'in2')
    workflow.connect(inputnode, 'gm_prob', merge, 'in1')

    #workflow.connect(merge,'out', segment,'tissue_prob_maps')

    sym_prob = sym_func.clone('sym_prob')
    workflow.connect(merge, 'out', sym_prob, 'in_file')
    workflow.connect(sym_prob, 'out_link', segment, 'tissue_prob_maps')

    workflow.connect(maskflow, ('outputspec.mask_file', pickfirst), segment,
                     'mask_image')
    workflow.connect(inputnode, 'fwhm', smooth, 'fwhm')

    #sym_brain = sym_func.clone('sym_brain')
    #workflow.connect(realign, 'mean_image', normalize, 'source')
    #workflow.connect(maskflow,'fssource.brain',segment,'data')
    fssource = maskflow.get_node('fssource')
    import nipype.interfaces.freesurfer as fs
    convert_brain = pe.Node(interface=fs.ApplyVolTransform(inverse=True),
                            name='convert')
    workflow.connect(fssource, 'brain', convert_brain, 'target_file')
    workflow.connect(maskflow, ('outputspec.reg_file', pickfirst),
                     convert_brain, 'reg_file')
    workflow.connect(mean, 'outputspec.mean_image', convert_brain,
                     'source_file')
    convert2nii = pe.Node(fs.MRIConvert(in_type='mgz', out_type='nii'),
                          name='convert2nii')
    workflow.connect(convert_brain, 'transformed_file', convert2nii, 'in_file')
    workflow.connect(convert2nii, 'out_file', segment, 'data')

    workflow.connect(segment, 'transformation_mat', normalize,
                     'parameter_file')
    workflow.connect(segment, 'transformation_mat', normalize_struct,
                     'parameter_file')
    workflow.connect(convert2nii, 'out_file', normalize_struct,
                     'apply_to_files')
    workflow.connect(realign, 'out_file', normalize, 'apply_to_files')
    #normalize.inputs.template='/software/spm8/templates/EPI.nii'
    workflow.connect(normalize, 'normalized_files', smooth, 'in_files')
    #workflow.connect(realign, 'realigned_files', smooth, 'in_files')

    artdetect = pe.Node(ra.ArtifactDetect(mask_type='file',
                                          parameter_source='FSL',
                                          use_differences=[True, False],
                                          use_norm=True,
                                          save_plot=True),
                        name='artdetect')
    workflow.connect([(inputnode, artdetect,
                       [('norm_threshold', 'norm_threshold'),
                        ('zintensity_threshold', 'zintensity_threshold')])])
    workflow.connect([(realign, artdetect, [('out_file', 'realigned_files'),
                                            ('par_file',
                                             'realignment_parameters')])])
    workflow.connect(maskflow, ('outputspec.mask_file', poplist), artdetect,
                     'mask_file')
    """
Define the outputs of the workflow and connect the nodes to the outputnode
"""

    outputnode = pe.Node(niu.IdentityInterface(fields=[
        "realignment_parameters", "smoothed_files", "mask_file", "mean_image",
        "reg_file", "reg_cost", 'outlier_files', 'outlier_stats',
        'outlier_plots', 'norm_components', 'mod_csf', 'unmod_csf', 'mod_wm',
        'unmod_wm', 'mod_gm', 'unmod_gm', 'mean', 'normalized_struct',
        'struct_in_functional_space', 'normalization_parameters',
        'reverse_normalize_parameters'
    ]),
                         name="outputspec")
    workflow.connect([
        (maskflow, outputnode, [("outputspec.reg_file", "reg_file")]),
        (maskflow, outputnode, [("outputspec.reg_cost", "reg_cost")]),
        (maskflow, outputnode, [(("outputspec.mask_file", poplist),
                                 "mask_file")]),
        (realign, outputnode, [('par_file', 'realignment_parameters')]),
        (smooth, outputnode, [('smoothed_files', 'smoothed_files')]),
        (artdetect, outputnode, [('outlier_files', 'outlier_files'),
                                 ('statistic_files', 'outlier_stats'),
                                 ('plot_files', 'outlier_plots'),
                                 ('norm_files', 'norm_components')])
    ])
    workflow.connect(segment, 'modulated_csf_image', outputnode, 'mod_csf')
    workflow.connect(segment, 'modulated_wm_image', outputnode, 'mod_wm')
    workflow.connect(segment, 'modulated_gm_image', outputnode, 'mod_gm')
    workflow.connect(segment, 'normalized_csf_image', outputnode, 'unmod_csf')
    workflow.connect(segment, 'normalized_wm_image', outputnode, 'unmod_wm')
    workflow.connect(segment, 'normalized_gm_image', outputnode, 'unmod_gm')
    workflow.connect(mean, 'outputspec.mean_image', outputnode, 'mean')
    workflow.connect(normalize_struct, 'normalized_files', outputnode,
                     'normalized_struct')
    workflow.connect(segment, 'transformation_mat', outputnode,
                     'normalization_parameters')
    workflow.connect(segment, 'inverse_transformation_mat', outputnode,
                     'reverse_normalize_parameters')
    workflow.connect(convert2nii, 'out_file', outputnode,
                     'struct_in_functional_space')

    workflow.inputs.inputspec.fwhm = c.fwhm
    workflow.inputs.inputspec.subjects_dir = c.surf_dir
    workflow.inputs.inputspec.norm_threshold = c.norm_thresh
    workflow.inputs.inputspec.zintensity_threshold = c.z_thresh
    workflow.inputs.inputspec.node = c.motion_correct_node
    workflow.inputs.inputspec.tr = c.TR
    workflow.inputs.inputspec.do_slicetime = c.do_slicetiming
    workflow.inputs.inputspec.sliceorder = c.SliceOrder
    workflow.inputs.inputspec.csf_prob = c.csf_prob
    workflow.inputs.inputspec.gm_prob = c.grey_prob
    workflow.inputs.inputspec.wm_prob = c.white_prob
    workflow.base_dir = c.working_dir
    workflow.config = {'execution': {'crashdump_dir': c.crash_dir}}

    datagrabber = get_dataflow(c)

    workflow.connect(datagrabber, 'func', inputnode, 'functionals')

    infosource = pe.Node(niu.IdentityInterface(fields=['subject_id']),
                         name='subject_names')
    if not c.test_mode:
        infosource.iterables = ('subject_id', c.subjects)
    else:
        infosource.iterables = ('subject_id', c.subjects[:1])

    workflow.connect(infosource, 'subject_id', inputnode, 'subject_id')
    workflow.connect(infosource, 'subject_id', datagrabber, 'subject_id')
    sub = lambda x: [('_subject_id_%s' % x, '')]

    sinker = pe.Node(nio.DataSink(), name='sinker')
    workflow.connect(infosource, 'subject_id', sinker, 'container')
    workflow.connect(infosource, ('subject_id', sub), sinker, 'substitutions')
    sinker.inputs.base_directory = c.sink_dir
    outputspec = workflow.get_node('outputspec')
    workflow.connect(outputspec, 'realignment_parameters', sinker,
                     'spm_preproc.realignment_parameters')
    workflow.connect(outputspec, 'smoothed_files', sinker,
                     'spm_preproc.smoothed_outputs')
    workflow.connect(outputspec, 'outlier_files', sinker,
                     'spm_preproc.art.@outlier_files')
    workflow.connect(outputspec, 'outlier_stats', sinker,
                     'spm_preproc.art.@outlier_stats')
    workflow.connect(outputspec, 'outlier_plots', sinker,
                     'spm_preproc.art.@outlier_plots')
    workflow.connect(outputspec, 'norm_components', sinker,
                     'spm_preproc.art.@norm')
    workflow.connect(outputspec, 'reg_file', sinker,
                     'spm_preproc.bbreg.@reg_file')
    workflow.connect(outputspec, 'reg_cost', sinker,
                     'spm_preproc.bbreg.@reg_cost')
    workflow.connect(outputspec, 'mask_file', sinker,
                     'spm_preproc.mask.@mask_file')
    workflow.connect(outputspec, 'mod_csf', sinker,
                     'spm_preproc.segment.mod.@csf')
    workflow.connect(outputspec, 'mod_wm', sinker,
                     'spm_preproc.segment.mod.@wm')
    workflow.connect(outputspec, 'mod_gm', sinker,
                     'spm_preproc.segment.mod.@gm')
    workflow.connect(outputspec, 'unmod_csf', sinker,
                     'spm_preproc.segment.unmod.@csf')
    workflow.connect(outputspec, 'unmod_wm', sinker,
                     'spm_preproc.segment.unmod.@wm')
    workflow.connect(outputspec, 'unmod_gm', sinker,
                     'spm_preproc.segment.unmod.@gm')
    workflow.connect(outputspec, 'mean', sinker, 'spm_preproc.mean')
    workflow.connect(outputspec, 'normalized_struct', sinker,
                     'spm_preproc.normalized_struct')
    workflow.connect(outputspec, 'normalization_parameters', sinker,
                     'spm_preproc.normalization_parameters.@forward')
    workflow.connect(outputspec, 'reverse_normalize_parameters', sinker,
                     'spm_preproc.normalization_parameters.@reverse')
    workflow.connect(outputspec, 'struct_in_functional_space', sinker,
                     'spm_preproc.struct_in_func_space')

    return workflow
示例#14
0
def create_native_old_segment_pipe(params_template,
                                   params={},
                                   name="native_old_segment_pipe"):
    """
    Description: Extract brain using tissues masks output by SPM's old_segment
        function:

        - Segment the T1 using given priors;
        - Threshold GM, WM and CSF maps;
        - Compute union of those 3 tissues with indexes;

    Params:

    - segment (see `Segment <https://nipype.readthedocs.io/en/0.12.1/\
    interfaces/generated/nipype.interfaces.spm.preprocess.html#segment>`_)
    - threshold_gm, threshold_wm, threshold_csf (see `Threshold \
    <https://nipype.readthedocs.io/en/0.12.1/interfaces/generated/nipype.\
    interfaces.fsl.maths.html#threshold>`_ for arguments) - also available \
    as :ref:`indiv_params <indiv_params>`


    Inputs:

        inputnode:
            T1: T1 file name

        arguments:
            priors: list of file names

            params: dictionary of node sub-parameters (from a json file)

            name: pipeline name (default = "old_segment_pipe")

    Outputs:

        fill_holes.out_file:
            filled mask after erode

        fill_holes_dil.out_file
            filled mask after dilate

        threshold_gm, threshold_wm, threshold_csf.out_file:
            resp grey matter, white matter, and csf after thresholding

    """
    # creating pipeline
    seg_pipe = pe.Workflow(name=name)

    # Creating inputnode
    inputnode = pe.Node(niu.IdentityInterface(
        fields=['T1', 'indiv_params', "native_T1", "inv_transfo_file"]),
                        name='inputnode')

    assert set_spm(), \
        "Error, SPM was not found, cannot run SPM old segment pipeline"

    unzip = pe.Node(interface=niu.Function(input_names=['zipped_file'],
                                           output_names=["unzipped_file"],
                                           function=gunzip),
                    name="unzip")

    seg_pipe.connect(inputnode, 'T1', unzip, 'zipped_file')

    # Segment in to 6 tissues
    segment = NodeParams(spm.Segment(),
                         params=parse_key(params, "segment"),
                         name="old_segment")

    segment.inputs.tissue_prob_maps = [
        params_template["template_gm"], params_template["template_wm"],
        params_template["template_csf"]
    ]

    seg_pipe.connect(unzip, 'unzipped_file', segment, 'data')

    # gm
    register_gm_to_nat = pe.Node(fsl.ApplyXFM(), name="register_gm_to_nat")
    register_gm_to_nat.inputs.output_type = "NIFTI_GZ"  # for SPM segment

    seg_pipe.connect(segment, 'native_gm_image', register_gm_to_nat, 'in_file')

    seg_pipe.connect(inputnode, 'native_T1', register_gm_to_nat, 'reference')

    seg_pipe.connect(inputnode, 'inv_transfo_file', register_gm_to_nat,
                     "in_matrix_file")

    # wm
    register_wm_to_nat = pe.Node(fsl.ApplyXFM(), name="register_wm_to_nat")
    register_wm_to_nat.inputs.output_type = "NIFTI_GZ"  # for SPM segment

    seg_pipe.connect(segment, 'native_wm_image', register_wm_to_nat, 'in_file')

    seg_pipe.connect(inputnode, 'native_T1', register_wm_to_nat, 'reference')

    seg_pipe.connect(inputnode, 'inv_transfo_file', register_wm_to_nat,
                     "in_matrix_file")

    # csf
    register_csf_to_nat = pe.Node(fsl.ApplyXFM(), name="register_csf_to_nat")
    register_csf_to_nat.inputs.output_type = "NIFTI_GZ"  # for SPM segment

    seg_pipe.connect(segment, 'native_csf_image', register_csf_to_nat,
                     'in_file')

    seg_pipe.connect(inputnode, 'native_T1', register_csf_to_nat, 'reference')

    seg_pipe.connect(inputnode, 'inv_transfo_file', register_csf_to_nat,
                     "in_matrix_file")

    # threshold_gm
    threshold_gm = NodeParams(fsl.Threshold(),
                              params=parse_key(params, "threshold_gm"),
                              name="threshold_gm")

    seg_pipe.connect(register_gm_to_nat, 'out_file', threshold_gm, 'in_file')

    seg_pipe.connect(inputnode, ('indiv_params', parse_key, "threshold_gm"),
                     threshold_gm, "indiv_params")

    # threshold_wm
    threshold_wm = NodeParams(fsl.Threshold(),
                              params=parse_key(params, "threshold_wm"),
                              name="threshold_wm")

    seg_pipe.connect(register_wm_to_nat, 'out_file', threshold_wm, 'in_file')

    seg_pipe.connect(inputnode, ('indiv_params', parse_key, "threshold_wm"),
                     threshold_wm, "indiv_params")

    # threshold_csf
    threshold_csf = NodeParams(fsl.Threshold(),
                               params=parse_key(params, "threshold_csf"),
                               name="threshold_csf")

    seg_pipe.connect(register_csf_to_nat, 'out_file', threshold_csf, 'in_file')

    seg_pipe.connect(inputnode, ('indiv_params', parse_key, "threshold_csf"),
                     threshold_csf, "indiv_params")

    # outputnode
    outputnode = pe.Node(niu.IdentityInterface(
        fields=["threshold_gm", "threshold_wm", "threshold_csf"]),
                         name='outputnode')

    seg_pipe.connect(threshold_gm, 'out_file', outputnode, 'threshold_gm')
    seg_pipe.connect(threshold_wm, 'out_file', outputnode, 'threshold_wm')
    seg_pipe.connect(threshold_csf, 'out_file', outputnode, 'threshold_csf')

    return seg_pipe
示例#15
0
def create_old_segment_pipe(params_template,
                            params={},
                            name="old_segment_pipe"):
    """
    Description: Extract brain using tissues masks output by SPM's old_segment

    Function:

        - Segment the T1 using given priors;
        - Threshold GM, WM and CSF maps;
    Params:

    - segment (see `Segment <https://nipype.readthedocs.io/en/0.12.1/\
    interfaces/generated/nipype.interfaces.spm.preprocess.html#segment>`_)
    - threshold_gm, threshold_wm, threshold_csf (see `Threshold \
    <https://nipype.readthedocs.io/en/0.12.1/interfaces/generated/nipype.\
    interfaces.fsl.maths.html#threshold>`_ for arguments) - also available \
    as :ref:`indiv_params <indiv_params>`
    - dilate_mask (see `DilateMask <https://nipype.readthedocs.io/en/0.12.1/\
    interfaces/generated/nipype.interfaces.fsl.maths.html#dilateimage>`_)
    - erode_mask (see `ErodeMask <https://nipype.readthedocs.io/en/0.12.1/\
    interfaces/generated/nipype.interfaces.fsl.maths.html#erodeimage>`_)


    Inputs:

        inputnode:
            T1: T1 file name

        arguments:
            priors: list of file names

            params: dictionary of node sub-parameters (from a json file)

            name: pipeline name (default = "old_segment_pipe")

    Outputs:

        fill_holes.out_file:
            filled mask after erode

        fill_holes_dil.out_file
            filled mask after dilate

        threshold_gm, threshold_wm, threshold_csf.out_file:
            resp grey matter, white matter, and csf after thresholding

    """
    # creating pipeline
    seg_pipe = pe.Workflow(name=name)

    # Creating inputnode
    inputnode = pe.Node(niu.IdentityInterface(fields=['T1', 'indiv_params']),
                        name='inputnode')

    assert set_spm(), \
        "Error, SPM was not found, cannot run SPM old segment pipeline"

    unzip = pe.Node(interface=niu.Function(input_names=['zipped_file'],
                                           output_names=["unzipped_file"],
                                           function=gunzip),
                    name="unzip")

    seg_pipe.connect(inputnode, 'T1', unzip, 'zipped_file')

    # Segment in to 6 tissues
    segment = NodeParams(spm.Segment(),
                         params=parse_key(params, "segment"),
                         name="old_segment")

    segment.inputs.tissue_prob_maps = [
        params_template["template_gm"], params_template["template_wm"],
        params_template["template_csf"]
    ]

    seg_pipe.connect(unzip, 'unzipped_file', segment, 'data')

    # Threshold GM, WM and CSF
    thd_nodes = {}
    for tissue in ['gm', 'wm', 'csf']:

        tmp_node = NodeParams(fsl.Threshold(),
                              params=parse_key(params, "threshold_" + tissue),
                              name="threshold_" + tissue)

        seg_pipe.connect(segment, 'native_' + tissue + '_image', tmp_node,
                         'in_file')

        seg_pipe.connect(inputnode,
                         ('indiv_params', parse_key, "threshold_" + tissue),
                         tmp_node, "indiv_params")

        thd_nodes[tissue] = tmp_node

    # Creating output node
    outputnode = pe.Node(niu.IdentityInterface(
        fields=['threshold_gm', 'threshold_wm', 'threshold_csf']),
                         name='outputnode')

    seg_pipe.connect(thd_nodes['gm'], 'out_file', outputnode, 'threshold_gm')
    seg_pipe.connect(thd_nodes['wm'], 'out_file', outputnode, 'threshold_wm')
    seg_pipe.connect(thd_nodes['csf'], 'out_file', outputnode, 'threshold_csf')

    return seg_pipe
示例#16
0
epi_s2_stack.inputs.out_ext = '.nii'

st_corr = Node(spm.SliceTiming(), name='slicetiming_correction')

realign = Node(spm.Realign(), name='realign')
realign.inputs.register_to_mean = True

tsnr = MapNode(confounds.TSNR(), iterfield='in_file', name='tsnr')
tsnr.inputs.mean_file = 'mean.nii'
tsnr.inputs.stddev_file = 'stddev.nii'
tsnr.inputs.tsnr_file = 'tsnr.nii'

despike = MapNode(afni.Despike(), iterfield='in_file', name='despike')
despike.inputs.outputtype = 'NIFTI'

seg = Node(spm.Segment(), name='seg')
seg.inputs.csf_output_type = [False, False, True]  #Output native CSF seg
seg.inputs.gm_output_type = [False, False, True]  #Output native gm seg
seg.inputs.wm_output_type = [False, False, True]  #Output native wm seg

coreg2epi = MapNode(spm.Coregister(), iterfield='target', name='coreg2epi')

#Warps to MNI space using a 3mm template image
antsnorm = MapNode(ants.Registration(),
                   iterfield='moving_image',
                   name='antsnorm')
antsnorm.inputs.collapse_output_transforms = True
antsnorm.inputs.initial_moving_transform_com = True
antsnorm.inputs.num_threads = 1
antsnorm.inputs.output_inverse_warped_image = True
antsnorm.inputs.output_warped_image = True
示例#17
0
from nipype.pipeline.engine import Workflow, Node, MapNode
import nipype.interfaces.fsl as fsl
import nipype.interfaces.spm as spm

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

# Nodes

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

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

# Example connection to the main Workflow:
# main = Workflow(name='main', base_dir=w_dir)
# main.connect(infosource, 'subject_id', datasource, 'subject_id')
# main.connect(datasource, 'nii', segment, 'ro.in_file')
# main.connect(segment, 'seg.bias_corrected_image', sink, '@bias_corr')
# main.connect(segment, 'seg.native_csf_image', sink, '@csf')
# main.connect(segment, 'seg. native_gm_image', sink, '@gm')
# main.connect(segment, 'seg. native_wm_image', sink, '@wm')
示例#18
0
def create_old_segment_pipe(params_template, params={},
                            name="old_segment_pipe"):
    """
    Description: Extract brain using tissues masks output by SPM's old_segment
        function:

        - Segment the T1 using given priors;
        - Threshold GM, WM and CSF maps;
        - Compute union of those 3 tissues;
        - Apply morphological opening on the union mask
        - Fill holes

    Inputs:

        inputnode:
            T1: T1 file name

        arguments:
            priors: list of file names

            params: dictionary of node sub-parameters (from a json file)

            name: pipeline name (default = "old_segment_pipe")

    Outputs:

        fill_holes.out_file:
            filled mask after erode

        fill_holes_dil.out_file
            filled mask after dilate

        threshold_gm, threshold_wm, threshold_csf.out_file:
            resp grey matter, white matter, and csf after thresholding

    """
    # creating pipeline
    be_pipe = pe.Workflow(name=name)

    # Creating inputnode
    inputnode = pe.Node(
        niu.IdentityInterface(fields=['T1', 'indiv_params']),
        name='inputnode'
    )

    # Segment in to 6 tissues
    segment = NodeParams(spm.Segment(),
                         params=parse_key(params, "segment"),
                         name="old_segment")

    segment.inputs.tissue_prob_maps = [params_template["template_gm"],
                                       params_template["template_wm"],
                                       params_template["template_csf"]]

    be_pipe.connect(inputnode, 'T1', segment, 'data')

    # Threshold GM, WM and CSF
    thd_nodes = {}
    for tissue in ['gm', 'wm', 'csf']:

        tmp_node = NodeParams(fsl.Threshold(),
                              params=parse_key(params, "threshold_" + tissue),
                              name="threshold_" + tissue)

        be_pipe.connect(segment, 'native_' + tissue + '_image',
                        tmp_node, 'in_file')

        be_pipe.connect(
            inputnode, ('indiv_params', parse_key, "threshold_" + tissue),
            tmp_node, "indiv_params")

        thd_nodes[tissue] = tmp_node

    # Compute union of the 3 tissues
    # Done with 2 fslmaths as it seems to hard to do it
    wmgm_union = pe.Node(fsl.BinaryMaths(), name="wmgm_union")
    wmgm_union.inputs.operation = "add"
    be_pipe.connect(thd_nodes['gm'], 'out_file', wmgm_union, 'in_file')
    be_pipe.connect(thd_nodes['wm'], 'out_file', wmgm_union, 'operand_file')

    tissues_union = pe.Node(fsl.BinaryMaths(), name="tissues_union")
    tissues_union.inputs.operation = "add"
    be_pipe.connect(wmgm_union, 'out_file', tissues_union, 'in_file')
    be_pipe.connect(thd_nodes['csf'], 'out_file',
                    tissues_union, 'operand_file')

    # Opening
    dilate_mask = NodeParams(fsl.DilateImage(),
                             params=parse_key(params, "dilate_mask"),
                             name="dilate_mask")

    dilate_mask.inputs.operation = "mean"  # Arbitrary operation
    be_pipe.connect(tissues_union, 'out_file', dilate_mask, 'in_file')

    # Eroding mask
    erode_mask = NodeParams(fsl.ErodeImage(),
                            params=parse_key(params, "erode_mask"),
                            name="erode_mask")

    be_pipe.connect(tissues_union, 'out_file', erode_mask, 'in_file')

    # fill holes of erode_mask
    fill_holes = pe.Node(BinaryFillHoles(), name="fill_holes")
    be_pipe.connect(erode_mask, 'out_file', fill_holes, 'in_file')

    # fill holes of dilate_mask
    fill_holes_dil = pe.Node(BinaryFillHoles(), name="fill_holes_dil")
    be_pipe.connect(dilate_mask, 'out_file', fill_holes_dil, 'in_file')

    return be_pipe
示例#19
0
    def __init__(self, func_source, struct_source, datasink):
        # specify input and output nodes
        self.func_source = func_source
        self.struct_source = struct_source
        self.datasink = datasink

        # specify nodes
        # structual process
        self.bet_struct = pe.Node(interface=fsl.BET(),
                                  name='non_brain_removal_BET_struct')
        self.bet_struct.inputs.output_type = "NIFTI"

        # functional process
        self.slice_timer = pe.Node(interface=fsl.SliceTimer(),
                                   name='time_slice_correction')

        self.mcflirt = pe.Node(interface=fsl.MCFLIRT(),
                               name='motion_correction')
        self.mcflirt.inputs.output_type = "NIFTI"
        self.mcflirt.inputs.mean_vol = True

        self.fslsplit = pe.Node(interface=fsl.Split(), name='fslsplit')
        self.fslsplit.inputs.dimension = 't'
        self.fslsplit.inputs.output_type = "NIFTI"

        self.fslmerge = pe.Node(interface=fsl.Merge(), name='fslmerge')
        self.fslmerge.inputs.dimension = 't'
        self.fslmerge.inputs.output_type = "NIFTI"

        self.bet_mean = pe.Node(interface=fsl.BET(),
                                name='non_brain_removal_BET_mean')
        self.bet_mean.inputs.output_type = "NIFTI"

        # helper function(s)
        def bet_each(in_files):
            '''
            @param in_files: list of image files
            @return out_files: list of image files after applied fsl.BET on it
            '''
            from nipype.interfaces import fsl
            import nipype.pipeline.engine as pe

            out_files = list()
            step_no = 0
            for file_ in in_files:
                bet = pe.Node(interface=fsl.BET(),
                              name='BET_for_step_{}'.format(step_no))
                bet.inputs.in_file = file_
                bet.inputs.out_file = file_[:len(file_) - 4] + '_bet.nii'
                bet.inputs.output_type = "NIFTI"

                bet.run()
                out_files.append(bet.inputs.out_file)

                step_no += 1
            return out_files

        # bet_func return a list of NIFITI files
        self.bet_func = pe.Node(interface=Function(input_names=['in_files'],
                                                   output_names=['out_files'],
                                                   function=bet_each),
                                name='non_brain_removal_BET_func')

        self.coregister = pe.Node(interface=spm.Coregister(),
                                  name="coregister")
        self.coregister.inputs.jobtype = 'estimate'

        self.segment = pe.Node(interface=spm.Segment(), name="segment")
        self.segment.inputs.affine_regularization = 'mni'

        self.normalize_func = pe.Node(interface=spm.Normalize(),
                                      name="normalize_func")
        self.normalize_func.inputs.jobtype = "write"

        # self.fourier = pe.Node(interface=afni.Fourier(), name='temporal_filtering')
        # self.fourier.inputs.highpass = 0.01
        # self.fourier.inputs.lowpass = 0.1

        self.smooth = pe.Node(interface=spm.Smooth(), name="smooth")
        self.smooth.inputs.fwhm = [8, 8, 8]

        # specify workflow instance
        self.workflow = pe.Workflow(name='preprocessing_workflow')

        # connect nodes
        self.workflow.connect([
            (self.struct_source, self.bet_struct, [('outfiles', 'in_file')]),
            (self.func_source, self.slice_timer, [('outfiles', 'in_file')]),
            (self.slice_timer, self.mcflirt, [('slice_time_corrected_file',
                                               'in_file')]),
            (self.mcflirt, self.bet_mean, [('mean_img', 'in_file')]),
            (self.mcflirt, self.fslsplit, [('out_file', 'in_file')]),
            (self.fslsplit, self.bet_func, [('out_files', 'in_files')]),
            (self.bet_func, self.fslmerge, [('out_files', 'in_files')
                                            ]),  # intersect
            (self.bet_struct, self.coregister, [('out_file', 'source')]),
            (self.bet_mean, self.coregister, [('out_file', 'target')]),
            (self.coregister, self.segment, [('coregistered_source', 'data')]),
            (self.segment, self.normalize_func, [('transformation_mat',
                                                  'parameter_file')]),
            (self.fslmerge, self.normalize_func, [('merged_file',
                                                   'apply_to_files')]),
            (self.normalize_func, self.smooth, [('normalized_files',
                                                 'in_files')]),
            (self.coregister, self.datasink, [('coregistered_source',
                                               'registered_file')]),
            (self.normalize_func, self.datasink, [('normalized_files',
                                                   'before_smooth')]),
            (self.smooth, self.datasink, [('smoothed_files', 'final_out')])
        ])
示例#20
0
    def __init__(self,
                 subject,
                 func_source,
                 struct_source,
                 datasink,
                 TR,
                 num_slices,
                 dim=2):
        self.subject = subject
        # specify input and output nodes
        self.func_source = func_source
        self.struct_source = struct_source
        self.datasink = datasink

        self.TR = TR
        self.num_slices = num_slices

        # specify nodes
        # structual process
        self.bet_struct = pe.Node(interface=fsl.BET(),
                                  name='non_brain_removal_BET_struct')
        self.bet_struct.inputs.output_type = "NIFTI"
        self.bet_struct.inputs.frac = 0.3

        self.coregister_struct = pe.Node(interface=spm.Coregister(),
                                         name="coregister_struct_to_mni")
        self.coregister_struct.inputs.target = '/mnt/Program/python/dev/images/MNI152_T1_2mm_brain.nii'
        if dim == 1:
            self.coregister_struct.inputs.target = '/mnt/Program/python/dev/images/MNI152_T1_1mm_brain.nii'
        self.coregister_struct.inputs.write_interp = 7
        self.coregister_struct.inputs.separation = [1.0, 1.0]
        self.coregister_struct.inputs.jobtype = 'estwrite'

        self.segment_struct = pe.Node(interface=spm.Segment(),
                                      name="segment_struct")
        # self.segment_struct.inputs.affine_regularization = 'mni'
        self.segment_struct.inputs.csf_output_type = [True, True, True]
        self.segment_struct.inputs.gm_output_type = [True, True, True]
        self.segment_struct.inputs.wm_output_type = [True, True, True]

        self.normalize_struct = pe.Node(interface=spm.Normalize(),
                                        name='normalize_struct')
        self.normalize_struct.inputs.jobtype = 'write'
        self.normalize_struct.inputs.write_bounding_box = [[-90, -126, -72],
                                                           [90, 90, 108]
                                                           ]  # 91, 109, 91
        if dim == 1:
            self.normalize_struct.inputs.write_bounding_box = [[
                -91, -126, -72
            ], [90, 91, 109]]  # 182, 218, 182
            self.normalize_struct.inputs.write_voxel_sizes = [1, 1, 1]

        self.normalize_gm = pe.Node(interface=spm.Normalize(),
                                    name='normalize_gm')
        self.normalize_gm.inputs.jobtype = 'write'
        self.normalize_gm.inputs.write_bounding_box = [[-90, -126, -72],
                                                       [90, 90,
                                                        108]]  # 91, 109, 91
        if dim == 1:
            self.normalize_gm.inputs.write_bounding_box = [[-91, -126, -72],
                                                           [90, 91, 109]
                                                           ]  # 182, 218, 182
            self.normalize_gm.inputs.write_voxel_sizes = [1, 1, 1]

        self.normalize_wm = pe.Node(interface=spm.Normalize(),
                                    name='normalize_wm')
        self.normalize_wm.inputs.jobtype = 'write'
        self.normalize_wm.inputs.write_bounding_box = [[-90, -126, -72],
                                                       [90, 90,
                                                        108]]  # 91, 109, 91
        if dim == 1:
            self.normalize_wm.inputs.write_bounding_box = [[-91, -126, -72],
                                                           [90, 91, 109]
                                                           ]  # 182, 218, 182
            self.normalize_wm.inputs.write_voxel_sizes = [1, 1, 1]

        self.normalize_csf = pe.Node(interface=spm.Normalize(),
                                     name='normalize_csf')
        self.normalize_csf.inputs.jobtype = 'write'
        self.normalize_csf.inputs.write_bounding_box = [[-90, -126, -72],
                                                        [90, 90,
                                                         108]]  # 91, 109, 91
        if dim == 1:
            self.normalize_csf.inputs.write_bounding_box = [[-91, -126, -72],
                                                            [90, 91, 109]
                                                            ]  # 182, 218, 182
            self.normalize_csf.inputs.write_voxel_sizes = [1, 1, 1]

        ###################################################################################################

        # functional process
        self.fslsplit = pe.Node(interface=fsl.Split(), name='fslsplit')
        self.fslsplit.inputs.dimension = 't'
        self.fslsplit.inputs.output_type = "NIFTI"

        self.fslmerge = pe.Node(interface=fsl.Merge(), name='fslmerge')
        self.fslmerge.inputs.dimension = 't'
        self.fslmerge.inputs.output_type = "NIFTI"

        # helper function(s)
        def bet_each(in_files, subject_name):
            '''
            @param in_files: list of image files
            @return out_files: list of image files after applied fsl.BET on it
            '''
            from nipype.interfaces import fsl
            import nipype.pipeline.engine as pe

            out_files = list()
            step_no = 0
            for file_ in in_files:
                bet = pe.Node(interface=fsl.BET(),
                              name='BET_for_step_{}_{}'.format(
                                  step_no, subject_name))
                bet.inputs.in_file = file_
                bet.inputs.out_file = file_[:len(file_) - 4] + '_bet.nii'
                bet.inputs.output_type = "NIFTI"
                bet.inputs.frac = 0.5

                bet.run()
                out_files.append(bet.inputs.out_file)

                step_no += 1
            return out_files

        # bet_func return a list of NIFITI files
        self.bet_func = pe.Node(interface=Function(
            input_names=['in_files', 'subject_name'],
            output_names=['out_files'],
            function=bet_each),
                                name='non_brain_removal_BET_func')
        self.bet_func.inputs.subject_name = self.subject

        self.realign = pe.Node(interface=spm.Realign(),
                               name='realign_motion_correction')
        self.realign.inputs.register_to_mean = True

        self.coregister_func = pe.Node(interface=spm.Coregister(),
                                       name="coregister_func_to_mni")
        self.coregister_func.inputs.target = '/mnt/Program/python/dev/images/MNI152_T1_2mm_brain.nii'
        self.coregister_func.inputs.write_interp = 7
        self.coregister_func.inputs.separation = [1.0, 1.0]
        self.coregister_func.inputs.jobtype = 'estwrite'

        self.segment = pe.Node(interface=spm.Segment(), name="segment")

        self.normalize_func = pe.Node(interface=spm.Normalize(),
                                      name="normalize_func")
        self.normalize_func.inputs.jobtype = 'write'
        self.normalize_func.inputs.write_bounding_box = [[-90, -126, -72],
                                                         [90, 90,
                                                          108]]  # 91, 109, 91

        self.smooth = pe.Node(interface=spm.Smooth(), name="smooth")
        self.smooth.inputs.fwhm = [8, 8, 8]

        # backup node(s)
        self.slice_timing = pe.Node(interface=spm.SliceTiming(),
                                    name='time_slice_correction')
        self.slice_timing.inputs.time_repetition = self.TR
        self.slice_timing.inputs.num_slices = self.num_slices
        self.slice_timing.inputs.time_acquisition = self.TR - (self.TR /
                                                               self.num_slices)
        self.slice_timing.inputs.slice_order = list(
            range(self.num_slices, 0, -1))
        self.slice_timing.inputs.ref_slice = 1

        self.direct_normalize = pe.Node(interface=spm.Normalize12(),
                                        name='direct_normalize')
        self.direct_normalize.inputs.image_to_align = 'images/MNI152_T1_2mm_brain.nii'
        self.direct_normalize.inputs.affine_regularization_type = 'size'

        # specify workflow instance
        self.workflow = pe.Workflow(name='preprocess_workflow')

        # connect nodes
        self.workflow.connect([
            (self.struct_source, self.bet_struct, [('outfiles', 'in_file')]),
            (self.bet_struct, self.coregister_struct, [('out_file', 'source')
                                                       ]),
            (self.coregister_struct, self.segment_struct,
             [('coregistered_source', 'data')]),
            (self.segment_struct, self.normalize_struct,
             [('transformation_mat', 'parameter_file')]),
            (self.coregister_struct, self.normalize_struct,
             [('coregistered_source', 'apply_to_files')]),
            (self.segment_struct, self.normalize_gm, [('transformation_mat',
                                                       'parameter_file')]),
            (self.segment_struct, self.normalize_gm, [('native_gm_image',
                                                       'apply_to_files')]),
            (self.segment_struct, self.normalize_wm, [('transformation_mat',
                                                       'parameter_file')]),
            (self.segment_struct, self.normalize_wm, [('native_wm_image',
                                                       'apply_to_files')]),
            (self.segment_struct, self.normalize_csf, [('transformation_mat',
                                                        'parameter_file')]),
            (self.segment_struct, self.normalize_csf, [('native_csf_image',
                                                        'apply_to_files')]),
            (self.func_source, self.fslsplit, [('outfiles', 'in_file')]),
            (self.fslsplit, self.bet_func, [('out_files', 'in_files')]),
            (self.bet_func, self.fslmerge, [('out_files', 'in_files')]),
            (self.fslmerge, self.realign, [('merged_file', 'in_files')]),
            (self.realign, self.datasink, [('realignment_parameters',
                                            'realignment_parameters')]),
            (self.realign, self.coregister_func, [('mean_image', 'source')]),
            (self.realign, self.coregister_func, [('realigned_files',
                                                   'apply_to_files')]),
            (self.coregister_func, self.segment, [('coregistered_source',
                                                   'data')]),
            (self.segment, self.normalize_func, [('transformation_mat',
                                                  'parameter_file')]),
            (self.coregister_func, self.normalize_func, [('coregistered_files',
                                                          'apply_to_files')]),
            (self.normalize_func, self.smooth, [('normalized_files',
                                                 'in_files')]),  # end
            (self.normalize_func, self.datasink, [('normalized_files',
                                                   'before_smooth')]),
            (self.smooth, self.datasink, [('smoothed_files', 'final_out')]),
            (self.normalize_struct, self.datasink,
             [('normalized_files', 'standardized_struct_file')]),
            # (self.segment_struct, self.datasink, [('native_csf_image', 'csf'), ('native_gm_image', 'grey_matter'), ('native_wm_image', 'white_matter')])
            (self.normalize_gm, self.datasink, [('normalized_files',
                                                 'grey_matter')]),
            (self.normalize_wm, self.datasink, [('normalized_files',
                                                 'white_matter')]),
            (self.normalize_csf, self.datasink, [('normalized_files', 'csf')]),
        ])

        # backup workflow(s)
        self.workflow_only_fmri = pe.Workflow(name='preprocess_workflow')

        # connect nodes
        self.workflow_only_fmri.connect([
            (self.func_source, self.fslsplit, [('outfiles', 'in_file')]),
            (self.fslsplit, self.bet_func, [('out_files', 'in_files')]),
            (self.bet_func, self.fslmerge, [('out_files', 'in_files')]),
            (self.fslmerge, self.realign, [('merged_file', 'in_files')]),
            (self.realign, self.direct_normalize, [('realigned_files',
                                                    'apply_to_files')]),
            (self.direct_normalize, self.smooth, [('normalized_files',
                                                   'in_files')]),  # end
            (self.direct_normalize, self.datasink, [('normalized_files',
                                                     'before_smooth')]),
            (self.smooth, self.datasink, [('smoothed_files', 'final_out')])
        ])
示例#21
0
preproc = pe.Workflow(name='preproc')
"""Use :class:`nipype.interfaces.spm.Realign` for motion correction
and register all images to the mean image.
"""

realign = pe.Node(interface=spm.Realign(), name="realign")

slice_timing = pe.Node(interface=spm.SliceTiming(), name="slice_timing")
"""Use :class:`nipype.interfaces.spm.Coregister` to perform a rigid
body registration of the functional data to the structural data.
"""

coregister = pe.Node(interface=spm.Coregister(), name="coregister")
coregister.inputs.jobtype = 'estimate'

segment = pe.Node(interface=spm.Segment(), name="segment")
segment.inputs.save_bias_corrected = True
"""Uncomment the following line for faster execution
"""

# segment.inputs.gaussians_per_class = [1, 1, 1, 4]
"""Warp functional and structural data to SPM's T1 template using
:class:`nipype.interfaces.spm.Normalize`.  The tutorial data set
includes the template image, T1.nii.
"""

normalize_func = pe.Node(interface=spm.Normalize(), name="normalize_func")
normalize_func.inputs.jobtype = "write"

normalize_struc = pe.Node(interface=spm.Normalize(), name="normalize_struc")
normalize_struc.inputs.jobtype = "write"
def create_prepare_seeds_from_fmri_pipeline(name="prepare_seeds_from_fmri"):

    inputnode = pe.Node(interface=util.IdentityInterface(fields=[
        'epi', "stat", "dwi", "mask", "phsamples", "thsamples", "fsamples",
        "T1", "stat_labels"
    ]),
                        name="inputnode")

    first_dwi = pe.Node(interface=fsl.ExtractROI(t_min=0, t_size=1),
                        name="first_dwi")
    first_epi = first_dwi.clone(name="first_epi")

    coregister = pe.Node(interface=fsl.FLIRT(), name="coregister_epi2dwi")

    reslice_stat = pe.MapNode(interface=fsl.FLIRT(),
                              name="reslice_stat",
                              iterfield=["in_file"])
    reslice_stat.inputs.apply_xfm = True
    reslice_mask = pe.Node(interface=fsl.FLIRT(), name="reslice_mask")
    reslice_mask.inputs.interp = "nearestneighbour"

    smm = pe.MapNode(interface=fsl.SMM(),
                     name="smm",
                     iterfield=['spatial_data_file'])

    threshold = pe.MapNode(interface=fsl.Threshold(),
                           name="threshold",
                           iterfield=['in_file'])
    threshold.inputs.thresh = 0.95

    probtractx = pe.Node(interface=fsl.ProbTrackX(),
                         name="probtractx")  #, iterfield=['waypoints'])
    probtractx.inputs.opd = True
    probtractx.inputs.loop_check = True
    probtractx.inputs.c_thresh = 0.2
    probtractx.inputs.n_steps = 2000
    probtractx.inputs.step_length = 0.5
    probtractx.inputs.n_samples = 100
    probtractx.inputs.correct_path_distribution = True
    probtractx.inputs.verbose = 2

    segment = pe.Node(interface=spm.Segment(), name="segment")
    segment.inputs.gm_output_type = [False, False, True]
    segment.inputs.wm_output_type = [False, False, True]
    segment.inputs.csf_output_type = [False, False, False]

    th_wm = pe.Node(interface=fsl.Threshold(), name="th_wm")
    th_wm.inputs.direction = "below"
    th_wm.inputs.thresh = 0.2
    th_gm = th_wm.clone("th_gm")

    wm_gm_interface = pe.Node(fsl.ApplyMask(), name="wm_gm_interface")

    bet_t1 = pe.Node(fsl.BET(), name="bet_t1")

    coregister_t1_to_dwi = pe.Node(interface=fsl.FLIRT(),
                                   name="coregister_t1_to_dwi")

    invert_dwi_to_t1_xfm = pe.Node(interface=fsl.ConvertXFM(),
                                   name="invert_dwi_to_t1_xfm")
    invert_dwi_to_t1_xfm.inputs.invert_xfm = True

    reslice_gm = pe.Node(interface=fsl.FLIRT(), name="reslice_gm")
    reslice_gm.inputs.apply_xfm = True

    reslice_wm = reslice_gm.clone("reslice_wm")

    particles2trackvis = pe.Node(interface=neuroutils.Particle2Trackvis(),
                                 name='particles2trackvis')

    annotate_trackvis = pe.Node(interface=neuroutils.AnnotateTracts(),
                                name='annotate_trackvis')

    smooth_tracks = pe.Node(interface=dt.SplineFilter(), name="smooth_tracks")
    smooth_tracks.inputs.step_length = 0.5

    pipeline = pe.Workflow(name=name)
    pipeline.connect([
        (inputnode, first_dwi, [("dwi", "in_file")]),
        (inputnode, first_epi, [("epi", "in_file")]),
        (first_epi, coregister, [("roi_file", "in_file")]),
        (first_dwi, coregister, [("roi_file", "reference")]),
        (inputnode, reslice_stat, [("stat", "in_file"), ("dwi", "reference")]),
        (inputnode, reslice_mask, [("mask", "in_file"), ("dwi", "reference")]),
        (coregister, reslice_stat, [("out_matrix_file", "in_matrix_file")]),
        (coregister, reslice_mask, [("out_matrix_file", "in_matrix_file")]),
        (reslice_stat, smm, [("out_file", "spatial_data_file")]),
        (reslice_mask, smm, [("out_file", "mask")]),
        (smm, threshold, [('activation_p_map', 'in_file')]),
        (inputnode, probtractx, [("phsamples", "phsamples"),
                                 ("thsamples", "thsamples"),
                                 ("fsamples", "fsamples")]),
        (reslice_mask, probtractx, [("out_file", "mask")]),
        #(threshold, probtractx, [("out_file", "waypoints")]),
        (inputnode, segment, [("T1", "data")]),
        (inputnode, bet_t1, [("T1", "in_file")]),
        (bet_t1, coregister_t1_to_dwi, [("out_file", "reference")]),
        (first_dwi, coregister_t1_to_dwi, [("roi_file", "in_file")]),
        (coregister_t1_to_dwi, invert_dwi_to_t1_xfm, [("out_matrix_file",
                                                       "in_file")]),
        (invert_dwi_to_t1_xfm, reslice_gm, [("out_file", "in_matrix_file")]),
        (segment, reslice_gm, [("native_gm_image", "in_file")]),
        (first_dwi, reslice_gm, [("roi_file", "reference")]),
        (reslice_gm, th_gm, [("out_file", "in_file")]),
        (th_gm, wm_gm_interface, [("out_file", "in_file")]),
        (invert_dwi_to_t1_xfm, reslice_wm, [("out_file", "in_matrix_file")]),
        (segment, reslice_wm, [("native_wm_image", "in_file")]),
        (first_dwi, reslice_wm, [("roi_file", "reference")]),
        (reslice_wm, th_wm, [("out_file", "in_file")]),
        (th_wm, wm_gm_interface, [("out_file", "mask_file")]),
        (wm_gm_interface, probtractx, [("out_file", "seed")]),
        (probtractx, particles2trackvis, [('particle_files', 'particle_files')
                                          ]),
        (reslice_mask, particles2trackvis, [("out_file", "reference_file")]),
        (particles2trackvis, annotate_trackvis, [('trackvis_file',
                                                  'trackvis_file')]),
        (smm, annotate_trackvis, [('activation_p_map', 'stat_files')]),
        (inputnode, annotate_trackvis, [('stat_labels', 'stat_labels')]),
        (annotate_trackvis, smooth_tracks, [('annotated_trackvis_file',
                                             'track_file')])
    ])
    return pipeline