Пример #1
0
def test_normalize12_list_outputs(create_files_in_directory):
    filelist, outdir, cwd = create_files_in_directory
    norm12 = spm.Normalize12(image_to_align=filelist[0])
    assert norm12._list_outputs()['normalized_image'][0].startswith('w')
    norm12 = spm.Normalize12(image_to_align=filelist[0],
                             apply_to_files=filelist[1])
    assert norm12._list_outputs()['normalized_files'][0].startswith('w')
Пример #2
0
def spm_warp_to_mni(wf_name="spm_warp_to_mni"):
    """ Run Gunzip and SPM Normalize12 to the list of files input and outputs the list of warped files.

    It does:
    - Warp each individual input image to the standard SPM template

    Parameters
    ----------
    wf_name: str
        Name of the workflow.

    Nipype Inputs
    -------------
    warp_input.in_files: list of traits.File
        The raw NIFTI_GZ image files

    Nipype outputs
    --------------
    warp_output.warped_files: list of existing file
        The warped files.

    Returns
    -------
    wf: nipype Workflow
    """
    # input
    # check if spm_pet_preproc.do_petpvc is True
    in_fields = ["in_files"]
    out_fields = ["warped_files"]

    input = setup_node(
        IdentityInterface(fields=in_fields, mandatory_inputs=True),
        name="warp_input",
    )

    gunzip = pe.MapNode(Gunzip(), name="gunzip", iterfield=['in_file'])

    warp = setup_node(spm.Normalize12(jobtype='estwrite',
                                      affine_regularization_type='mni'),
                      name="normalize12",
                      type="map",
                      iterfield=['image_to_align'])

    # output
    output = setup_node(IdentityInterface(fields=out_fields),
                        name="warp_output")

    # Create the workflow object
    wf = pe.Workflow(name=wf_name)

    wf.connect([
        # inputs
        (input, gunzip, [("in_files", "in_file")]),
        (gunzip, warp, [("out_file", "image_to_align")]),

        # output
        (warp, output, [("normalized_image", "warped_files")]),
    ])

    return wf
Пример #3
0
 def __init__(self, **template_dict):
     self.node = pe.Node(interface=spm.Normalize12(), name='normalize')
     self.node.inputs.tpm = template_dict['tpm_path']
     self.node.inputs.affine_regularization_type = template_dict[
         'normalize_affine_regularization_type']
     self.node.inputs.write_bounding_box = template_dict[
         'normalize_write_bounding_box']
     self.node.inputs.write_interp = template_dict['normalize_write_interp']
     self.node.inputs.write_voxel_sizes = template_dict[
         'normalize_write_voxel_sizes']
Пример #4
0
def spm_apply_deformations(in_file=traits.Undefined,
                           trans_field=traits.Undefined,
                           bbox=traits.Undefined,
                           voxel_sizes=None):
    """Return a Normalize12 interface object.
    SPM12's new Normalise routine for warping an image to a template.
    For more info:
    http://www.mit.edu/~satra/nipype-nightly/interfaces/generated/nipype.interfaces.spm.preprocess.html#normalize12

    Parameters
    ----------
    in_file: file

    trans_field: file
        file y_*.nii containing 3 deformation fields for the deformation in
        x, y and z dimension

    bbox: (a list of from 2 to 2 items which are a list of
           from 3 to 3 items which are a float)
        write_bounding_box option.
        3x2-element list of lists representing the bounding box (in mm) to
        be written
        See the preproc.get_bounding_box function.
        This is important to set when applying deformation fields
        to cropped images.

    voxel_sizes: list of 3 ints or floats
        Default: [1, 1, 1]

    Nipype Ouputs
    -------------
    deformation_field: (a list of items which are an existing file name)
        NIfTI file containing 3 deformation fields for the deformation in x,
        y and z dimension

    normalized_files: (a list of items which are an existing file name)
        Normalized other files

    normalized_image: (a list of items which are an existing file name)
        Normalized file that needed to be aligned

    """
    if voxel_sizes is None:
        voxel_sizes = [1, 1, 1]

    norm12 = spm.Normalize12(jobtype='write')

    norm12.inputs.deformation_file = trans_field
    norm12.inputs.image_to_align = in_file
    norm12.inputs.write_voxel_sizes = voxel_sizes
    norm12.inputs.write_bounding_box = bbox

    #norm12.run()
    return norm12
Пример #5
0
def process_subject(func_fname, anat_fname):
    # Drop dummy volumes
    img = nib.load(func_fname)
    dropped_img = nib.Nifti1Image(img.get_data()[..., n_dummies:], img.affine,
                                  img.header)
    fixed_fname = prefix_path('f', degz(func_fname))
    nib.save(dropped_img, fixed_fname)

    # Ungz anatomical
    if anat_fname.endswith('.gz'):
        anat_img = nib.load(anat_fname)
        anat_fname = degz(anat_fname)
        nib.save(anat_img, anat_fname)

    # Slice time correction
    num_slices = img.shape[2]
    time_for_one_slice = TR / num_slices
    TA = TR - time_for_one_slice
    st = spm.SliceTiming()
    st.inputs.in_files = fixed_fname
    st.inputs.num_slices = num_slices
    st.inputs.time_repetition = TR
    st.inputs.time_acquisition = TA
    st.inputs.slice_order = order_func(num_slices)
    st.inputs.ref_slice = ref_slice
    st.run()
    fixed_stimed = prefix_path('a', fixed_fname)

    # Realign
    realign = spm.Realign()
    realign.inputs.in_files = fixed_stimed
    # Do not write resliced files, do write mean image
    realign.inputs.write_which = write_which
    realign.run()

    # Coregistration
    coreg = spm.Coregister()
    # Coregister structural to mean image from realignment
    coreg.inputs.target = prefix_path('mean', fixed_stimed)
    coreg.inputs.source = anat_fname
    coreg.run()

    # Normalization / resampling with normalization + realign params
    seg_norm = spm.Normalize12()
    seg_norm.inputs.image_to_align = anat_fname
    seg_norm.inputs.apply_to_files = fixed_stimed
    seg_norm.inputs.write_bounding_box = bounding_box
    seg_norm.inputs.write_voxel_sizes = voxel_sizes
    seg_norm.run()
Пример #6
0
def spm_normalize(in_file=traits.Undefined, template=None, **kwargs):
    """Return a Normalize12 interface object.
    SPM12's new Normalise routine for warping an image to a template.

    Parameters
    ----------
    in_file: file

    template: file
        Template in form of tissue probablitiy maps to normalize to
        mutually_exclusive: deformation_file.
        Default: the SPM TPM file.

    Nipype Ouputs
    -------------
    deformation_field: (a list of items which are an existing file name)
        NIfTI file containing 3 deformation fields for the deformation in x,
        y and z dimension

    normalized_files: (a list of items which are an existing file name)
        Normalized other files

    normalized_image: (a list of items which are an existing file name)
        Normalized file that needed to be aligned

    Raises
    ------
    FileNotFoundError
        If `template` is `None` and can't find the TPM.nii file from SPM.

    Notes
    -----
    For more info:
    http://www.mit.edu/~satra/nipype-nightly/interfaces/generated/nipype.interfaces.spm.preprocess.html#normalize12
    """
    if template is None:
        template = spm_tpm_priors_path()

    norm12 = spm.Normalize12(jobtype='estwrite', tpm=template, **kwargs)

    if isdefined(in_file):
        norm12.inputs.image_to_align = in_file

    #norm12.run()
    return norm12
Пример #7
0
    def analysis_steps(self):
        self.analysis = type('', (), {})()
        # Get files
        subj_list = [
            subj.split('_')[:-1] for subj in next(os.walk(self.proj_dir))[1]
        ]
        # TODO limit the subj_list to those without sw processed files.

        # for parallelization by subject, use idnetityInterface
        self.analysis.infosource = Node(
            IdentityInterface(fields=['subj_id', 'task']), name="infosource")
        self.analysis.infosource.iterables = [('subject_id', subj_list),
                                              ('task', self.task_names)]

        templates = {
            'anat': '{subj_id}/t1/{subj_id}_t1*.nii',
            'func': '{subj_id}/{task}*/{subj_id}_{task}*.nii'
        }
        self.analysis.sf = Node(SelectFiles(templates), name='selectfiles')
        self.analysis.sf.inputs.base_directory = self.proj_dir

        # Realign
        self.analysis.realign = Node(spm.Realign(register_to_mean=True,
                                                 fwhm=self.opts.fwhm),
                                     name='realign')

        # Coregister
        self.analysis.coreg = Node(spm.Coregister(), name='coregistration')
        # Normalize
        self.analysis.norm12 = Node(spm.Normalize12(
            bias_regularization=1e-05, affine_regularization_type='mni'),
                                    name='normalize')

        #Smooth
        self.analysis.smooth = Node(spm.Smooth(), name='smooth')
        #smooth.inputs.in_files = 'functional.nii'
        self.analysis.smooth.inputs.fwhm = self.opts.smooth_fwhm
Пример #8
0
def test_normalize12():
    assert spm.Normalize12._jobtype == 'spatial'
    assert spm.Normalize12._jobname == 'normalise'
    assert spm.Normalize12().inputs.jobtype == 'estwrite'
Пример #9
0
    art = Node(interface=ra.ArtifactDetect(), name='art')
    art.inputs.norm_threshold = 1
    art.inputs.zintensity_threshold = 5
    art.inputs.mask_type = 'spm_global'
    art.inputs.parameter_source = 'SPM'
    art.inputs.use_differences = [
        True, False
    ]  # Reflects use difference for motion, not intensity
    art.inputs.use_norm = True

    # SPM Coregister (Estimate Only)
    coreg = Node(interface=spm.Coregister(), name="coregister")
    coreg.inputs.jobtype = 'estimate'

    # SPM Normalise (Estimate & Reslice)
    norm12 = Node(interface=spm.Normalize12(), name="normalize")
    #spm.Normalize12().input_spec.gm_output_type = [True, False, False] # Should be modulated normalised

    # Smooth
    smooth = Node(interface=spm.Smooth(), name="smooth")
    fwhmlist = [8]
    smooth.iterables = (
        'fwhm', fwhmlist
    )  # Iterables seem to follow the convention of variable.input[key] = value of the iterable.

    # ## Set up the file management through ds to be able to wipe out unnecessary files?
    #  - There are all sorts of files labelled under the type of processing that produced them in each subject's folder, so I am unclear why this is a useful management step. It simply adds a "ds" folder next to the processing folders.

    # Collect key output files in a useful place
    ds = Node(interface=DataSink(), name="ds")
    ds.inputs.base_directory = op.abspath(output_dir)
Пример #10
0
    def build_core_nodes(self):
        """Build and connect the core nodes of the pipelines.
        """

        import fmri_preprocessing_workflows as utils
        import nipype.interfaces.utility as nutil
        import nipype.interfaces.spm as spm
        import nipype.pipeline.engine as npe
        from clinica.utils.filemanip import zip_nii, unzip_nii

        # Zipping
        # =======
        unzip_node = npe.MapNode(name='Unzipping',
                                 iterfield=['in_file'],
                                 interface=nutil.Function(
                                     input_names=['in_file'],
                                     output_names=['out_file'],
                                     function=unzip_nii))

        unzip_T1w = unzip_node.clone('UnzippingT1w')
        unzip_phasediff = unzip_node.clone('UnzippingPhasediff')
        unzip_bold = unzip_node.clone('UnzippingBold')
        unzip_magnitude1 = unzip_node.clone('UnzippingMagnitude1')

        # FieldMap calculation
        # ====================
        if self.parameters['unwarping']:
            fm_node = npe.MapNode(name="FieldMapCalculation",
                                  iterfield=[
                                      'phase', 'magnitude', 'epi', 'et',
                                      'blipdir', 'tert'
                                  ],
                                  interface=spm.FieldMap())

        # Slice timing correction
        # =======================
        st_node = npe.MapNode(name="SliceTimingCorrection",
                              iterfield=[
                                  'in_files', 'time_repetition', 'slice_order',
                                  'num_slices', 'ref_slice', 'time_acquisition'
                              ],
                              interface=spm.SliceTiming())

        # Motion correction and unwarping
        # ===============================

        if self.parameters['unwarping']:
            mc_node = npe.MapNode(name="MotionCorrectionUnwarping",
                                  iterfield=["scans", "pmscan"],
                                  interface=spm.RealignUnwarp())
            mc_node.inputs.register_to_mean = True
            mc_node.inputs.reslice_mask = False
        else:
            mc_node = npe.MapNode(name="MotionCorrection",
                                  iterfield=["in_files"],
                                  interface=spm.Realign())
            mc_node.inputs.register_to_mean = True

        # Brain extraction
        # ================
        import os.path as path
        from nipype.interfaces.freesurfer import MRIConvert
        if self.parameters['freesurfer_brain_mask']:
            brain_masks = [
                path.join(self.caps_directory, 'subjects', self.subjects[i],
                          self.sessions[i], 't1/freesurfer_cross_sectional',
                          self.subjects[i] + '_' + self.sessions[i],
                          'mri/brain.mgz') for i in range(len(self.subjects))
            ]
            conv_brain_masks = [
                str(self.subjects[i] + '_' + self.sessions[i] + '.nii')
                for i in range(len(self.subjects))
            ]
            bet_node = npe.MapNode(interface=MRIConvert(),
                                   iterfield=["in_file", "out_file"],
                                   name="BrainConversion")
            bet_node.inputs.in_file = brain_masks
            bet_node.inputs.out_file = conv_brain_masks
            bet_node.inputs.out_type = 'nii'
        else:
            bet_node = utils.BrainExtractionWorkflow(name="BrainExtraction")

        # Registration
        # ============
        reg_node = npe.MapNode(
            interface=spm.Coregister(),
            iterfield=["apply_to_files", "source", "target"],
            name="Registration")

        # Normalization
        # =============
        norm_node = npe.MapNode(interface=spm.Normalize12(),
                                iterfield=['image_to_align', 'apply_to_files'],
                                name='Normalization')

        # Smoothing
        # =========
        smooth_node = npe.MapNode(interface=spm.Smooth(),
                                  iterfield=['in_files'],
                                  name='Smoothing')
        smooth_node.inputs.fwhm = self.parameters['full_width_at_half_maximum']

        # Zipping
        # =======
        zip_node = npe.MapNode(name='Zipping',
                               iterfield=['in_file'],
                               interface=nutil.Function(
                                   input_names=['in_file'],
                                   output_names=['out_file'],
                                   function=zip_nii))

        zip_bet_node = zip_node.clone('ZippingBET')
        zip_mc_node = zip_node.clone('ZippingMC')
        zip_reg_node = zip_node.clone('ZippingRegistration')
        zip_norm_node = zip_node.clone('ZippingNormalization')
        zip_smooth_node = zip_node.clone('ZippingSmoothing')

        # Connections
        # ===========

        if self.parameters['freesurfer_brain_mask']:
            self.connect([
                # Brain extraction
                (bet_node, reg_node, [('out_file', 'target')]),
                (bet_node, zip_bet_node, [('out_file', 'in_file')]),
            ])
        else:
            self.connect([
                # Brain extraction
                (unzip_T1w, bet_node, [('out_file', 'Segmentation.data')]),
                (unzip_T1w, bet_node, [('out_file', 'ApplyMask.in_file')]),
                (bet_node, reg_node, [('ApplyMask.out_file', 'target')]),
                (bet_node, zip_bet_node, [('Fill.out_file', 'in_file')]),
            ])

        if self.parameters['unwarping']:
            self.connect([
                # FieldMap calculation
                (self.input_node, fm_node, [('et', 'et')]),
                (self.input_node, fm_node, [('blipdir', 'blipdir')]),
                (self.input_node, fm_node, [('tert', 'tert')]),
                (self.input_node, unzip_phasediff, [('phasediff', 'in_file')]),
                (self.input_node, unzip_magnitude1, [('magnitude1', 'in_file')
                                                     ]),
                (unzip_magnitude1, fm_node, [('out_file', 'magnitude')]),
                (unzip_phasediff, fm_node, [('out_file', 'phase')]),
                (unzip_bold, fm_node, [('out_file', 'epi')]),
                # Motion correction and unwarping
                (st_node, mc_node, [('timecorrected_files', 'scans')]),
                (fm_node, mc_node, [('vdm', 'pmscan')]),
                (mc_node, reg_node, [('realigned_unwarped_files',
                                      'apply_to_files')]),
                (mc_node, zip_mc_node, [('realigned_unwarped_files', 'in_file')
                                        ]),
            ])
        else:
            self.connect([
                # Motion correction and unwarping
                (st_node, mc_node, [('timecorrected_files', 'in_files')]),
                (mc_node, reg_node, [('realigned_files', 'apply_to_files')]),
                (mc_node, zip_mc_node, [('realigned_files', 'in_file')]),
            ])
        self.connect([
            # Unzipping
            (self.input_node, unzip_T1w, [('T1w', 'in_file')]),
            (self.input_node, unzip_bold, [('bold', 'in_file')]),
            # Slice timing correction
            (unzip_bold, st_node, [('out_file', 'in_files')]),
            (self.input_node, st_node, [('time_repetition', 'time_repetition')
                                        ]),
            (self.input_node, st_node, [('num_slices', 'num_slices')]),
            (self.input_node, st_node, [('slice_order', 'slice_order')]),
            (self.input_node, st_node, [('ref_slice', 'ref_slice')]),
            (self.input_node, st_node, [('time_acquisition',
                                         'time_acquisition')]),
            # Registration
            (mc_node, reg_node, [('mean_image', 'source')]),
            # Normalization
            (unzip_T1w, norm_node, [('out_file', 'image_to_align')]),
            (reg_node, norm_node, [('coregistered_files', 'apply_to_files')]),
            # Smoothing
            (norm_node, smooth_node, [('normalized_files', 'in_files')]),
            # Zipping
            (reg_node, zip_reg_node, [('coregistered_files', 'in_file')]),
            (norm_node, zip_norm_node, [('normalized_files', 'in_file')]),
            (smooth_node, zip_smooth_node, [('smoothed_files', 'in_file')]),
            # Returning output
            (zip_bet_node, self.output_node, [('out_file', 't1_brain_mask')]),
            (mc_node, self.output_node, [('realignment_parameters',
                                          'mc_params')]),
            (zip_mc_node, self.output_node, [('out_file', 'native_fmri')]),
            (zip_reg_node, self.output_node, [('out_file', 't1_fmri')]),
            (zip_norm_node, self.output_node, [('out_file', 'mni_fmri')]),
            (zip_smooth_node, self.output_node, [('out_file',
                                                  'mni_smoothed_fmri')]),
        ])
Пример #11
0
# Start at the slice-time corrected image
base_fname = 'afds114_sub009_t2r1.nii'
structural_fname = 'ds114_sub009_highres.nii'

# Realign
realign = spm.Realign()
realign.inputs.in_files = base_fname
# Do not write resliced files, do write mean image
realign.inputs.write_which = [0, 1]
realign.run()

# Coregistration
coreg = spm.Coregister()
# Coregister structural to mean image from realignment
coreg.inputs.target = 'mean' + base_fname
coreg.inputs.source = structural_fname
coreg.run()

# Normalization / resampling with normalization + realign params
seg_norm = spm.Normalize12()
seg_norm.inputs.image_to_align = structural_fname
seg_norm.inputs.apply_to_files = base_fname
seg_norm.run()

# Smoothing
smooth = spm.Smooth()
smooth.inputs.in_files = 'w' + base_fname
smooth.inputs.fwhm = [8, 8, 8]
smooth.run()
# if the directory doesn't exist, create it
if not os.path.exists(outDir):
    os.makedirs(outDir)

#
#    T1 Normalization nodes
#
# gunzip node
gunzip_T1w = Node(Gunzip(in_file=imageT1), name="gunzip_T1w")

# Segmentation, native space
segNative = Node(spm.NewSegment(), name='segNative')

# Normalize - normalizes structural images to the MNI template
normalizeT1 = Node(spm.Normalize12(jobtype='estwrite',
                                   tpm=fTPM,
                                   write_bounding_box=[[-90, -120, -70],
                                                       [90, 90, 105]]),
                   name="normalizeT1")

# Segmentation, template space
segMNI = Node(spm.NewSegment(), name='segMNI')

#
#   fMRI pre-processing
#
# skip dummy scans
extract = Node(
    fsl.ExtractROI(
        in_file=imagefMRI,  # input image
        t_min=4,  # first 4 volumes are deleted
        t_size=-1,
Пример #13
0
def test_normalize12():
    yield assert_equal, spm.Normalize12._jobtype, 'spatial'
    yield assert_equal, spm.Normalize12._jobname, 'normalise'
    yield assert_equal, spm.Normalize12().inputs.jobtype, 'estwrite'
Пример #14
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')])
        ])
Пример #15
0
def test_normalize12():
    assert spm.Normalize12._jobtype == "spatial"
    assert spm.Normalize12._jobname == "normalise"
    assert spm.Normalize12().inputs.jobtype == "estwrite"