예제 #1
0
def test_reslice():
    moving = example_data(infile='functional.nii')
    space_defining = example_data(infile='T1.nii')
    reslice = spmu.Reslice(matlab_cmd='mymatlab_version')
    assert_equal(reslice.inputs.matlab_cmd, 'mymatlab_version')
    reslice.inputs.in_file = moving
    reslice.inputs.space_defining = space_defining
    assert_equal(reslice.inputs.interp, 0)
    assert_raises(TraitError, reslice.inputs.trait_set, interp='nearest')
    assert_raises(TraitError, reslice.inputs.trait_set, interp=10)
    reslice.inputs.interp = 1
    script = reslice._make_matlab_command(None)
    outfile = fname_presuffix(moving, prefix='r')
    assert_equal(reslice.inputs.out_file, outfile)
    expected = '\nflags.mean=0;\nflags.which=1;\nflags.mask=0;'
    assert_equal(expected in script.replace(' ', ''), True)
    expected_interp = 'flags.interp = 1;\n'
    assert_equal(expected_interp in script, True)
    assert_equal('spm_reslice(invols, flags);' in script, True)
예제 #2
0
    def reslice_mask(self, segmentation, target=None):
        for k, v in mask_dict.items():
            if segmentation in v:
                print('Reslicing eroded {} mask'.format(v[0]))
                thresh_map = glob.glob(
                    os.path.join(
                        '/'.join(self.img.split('/')[:5]), 't1',
                        ('thresh_' + k + '*' +
                         self.img.split('/')[4].split('_')[0] + '*t1*')))

        # Do the reslicing
        coreg = spmu.Reslice()
        coreg.inputs.space_defining = self.fsl_file + '.nii.gz'  # target
        try:
            coreg.inputs.in_file = thresh_map[0]
        except IndexError:
            print('Threshrolded image not available.')
            return
        coreg.run()  # Throwing error, b/c mimicking bash?
예제 #3
0
def test_reslice():
    moving = example_data(infile="functional.nii")
    space_defining = example_data(infile="T1.nii")
    reslice = spmu.Reslice(matlab_cmd="mymatlab_version")
    assert reslice.inputs.matlab_cmd == "mymatlab_version"
    reslice.inputs.in_file = moving
    reslice.inputs.space_defining = space_defining
    assert reslice.inputs.interp == 0
    with pytest.raises(TraitError):
        reslice.inputs.trait_set(interp="nearest")
    with pytest.raises(TraitError):
        reslice.inputs.trait_set(interp=10)
    reslice.inputs.interp = 1
    script = reslice._make_matlab_command(None)
    outfile = fname_presuffix(moving, prefix="r")
    assert reslice.inputs.out_file == outfile
    expected = "\nflags.mean=0;\nflags.which=1;\nflags.mask=0;"
    assert expected in script.replace(" ", "")
    expected_interp = "flags.interp = 1;\n"
    assert expected_interp in script
    assert "spm_reslice(invols, flags);" in script
예제 #4
0
    def build_core_nodes(self):
        """Build and connect an output node to the pipeline."""
        import nipype.interfaces.spm as spm
        import nipype.interfaces.spm.utils as spmutils
        import nipype.interfaces.utility as nutil
        import nipype.pipeline.engine as npe
        from nipype.interfaces.petpvc import PETPVC

        from clinica.utils.filemanip import unzip_nii
        from clinica.utils.spm import spm_standalone_is_available, use_spm_standalone

        from .pet_volume_utils import (
            apply_binary_mask,
            atlas_statistics,
            create_binary_mask,
            create_pvc_mask,
            get_from_list,
            init_input_node,
            normalize_to_reference,
            pet_pvc_name,
        )

        if spm_standalone_is_available():
            use_spm_standalone()

        # Initialize pipeline
        # ===================
        init_node = npe.Node(
            interface=nutil.Function(
                input_names=["pet_nii"],
                output_names=["pet_nii"],
                function=init_input_node,
            ),
            name="init_pipeline",
        )

        # Unzipping
        # =========
        unzip_pet_image = npe.Node(
            nutil.Function(input_names=["in_file"],
                           output_names=["out_file"],
                           function=unzip_nii),
            name="unzip_pet_image",
        )

        unzip_t1_image_native = npe.Node(
            nutil.Function(input_names=["in_file"],
                           output_names=["out_file"],
                           function=unzip_nii),
            name="unzip_t1_image_native",
        )

        unzip_flow_fields = npe.Node(
            nutil.Function(input_names=["in_file"],
                           output_names=["out_file"],
                           function=unzip_nii),
            name="unzip_flow_fields",
        )

        unzip_dartel_template = npe.Node(
            nutil.Function(input_names=["in_file"],
                           output_names=["out_file"],
                           function=unzip_nii),
            name="unzip_dartel_template",
        )

        unzip_reference_mask = npe.Node(
            nutil.Function(input_names=["in_file"],
                           output_names=["out_file"],
                           function=unzip_nii),
            name="unzip_reference_mask",
        )

        unzip_mask_tissues = npe.MapNode(
            nutil.Function(input_names=["in_file"],
                           output_names=["out_file"],
                           function=unzip_nii),
            name="unzip_mask_tissues",
            iterfield=["in_file"],
        )

        # Coregister PET into T1 native space
        # ===================================
        coreg_pet_t1 = npe.Node(spm.Coregister(), name="coreg_pet_t1")

        # Spatially normalize PET into MNI
        # ================================
        dartel_mni_reg = npe.Node(spm.DARTELNorm2MNI(), name="dartel_mni_reg")
        dartel_mni_reg.inputs.modulate = False
        dartel_mni_reg.inputs.fwhm = 0

        # Reslice reference region mask into PET
        # ======================================
        reslice = npe.Node(spmutils.Reslice(), name="reslice")

        # Normalize PET values according to reference region
        # ==================================================
        norm_to_ref = npe.Node(
            nutil.Function(
                input_names=["pet_image", "region_mask"],
                output_names=["suvr_pet_path"],
                function=normalize_to_reference,
            ),
            name="norm_to_ref",
        )

        # Create binary mask from segmented tissues
        # =========================================
        binary_mask = npe.Node(
            nutil.Function(
                input_names=["tissues", "threshold"],
                output_names=["out_mask"],
                function=create_binary_mask,
            ),
            name="binary_mask",
        )
        binary_mask.inputs.threshold = self.parameters["mask_threshold"]

        # Mask PET image
        # ==============
        apply_mask = npe.Node(
            nutil.Function(
                input_names=["image", "binary_mask"],
                output_names=["masked_image_path"],
                function=apply_binary_mask,
            ),
            name="apply_mask",
        )

        # Smoothing
        # =========
        if self.parameters["smooth"] is not None and len(
                self.parameters["smooth"]) > 0:
            smoothing_node = npe.MapNode(spm.Smooth(),
                                         name="smoothing_node",
                                         iterfield=["fwhm", "out_prefix"])
            smoothing_node.inputs.fwhm = [[x, x, x]
                                          for x in self.parameters["smooth"]]
            smoothing_node.inputs.out_prefix = [
                "fwhm-" + str(x) + "mm_" for x in self.parameters["smooth"]
            ]
            # fmt: off
            self.connect([
                (apply_mask, smoothing_node, [("masked_image_path", "in_files")
                                              ]),
                (smoothing_node, self.output_node,
                 [("smoothed_files", "pet_suvr_masked_smoothed")]),
            ])
            # fmt: on
        else:
            self.output_node.inputs.pet_suvr_masked_smoothed = [[]]

        # Atlas Statistics
        # ================
        atlas_stats_node = npe.MapNode(
            nutil.Function(
                input_names=["in_image", "in_atlas_list"],
                output_names=["atlas_statistics"],
                function=atlas_statistics,
            ),
            name="atlas_stats_node",
            iterfield=["in_image"],
        )
        atlas_stats_node.inputs.in_atlas_list = self.parameters["atlases"]

        # Connection
        # ==========
        # fmt: off
        self.connect([
            (self.input_node, init_node, [("pet_image", "pet_nii")]),
            (init_node, unzip_pet_image, [("pet_nii", "in_file")]),
            (self.input_node, unzip_t1_image_native, [("t1_image_native",
                                                       "in_file")]),
            (self.input_node, unzip_flow_fields, [("flow_fields", "in_file")]),
            (self.input_node, unzip_dartel_template, [("dartel_template",
                                                       "in_file")]),
            (self.input_node, unzip_reference_mask, [("reference_mask",
                                                      "in_file")]),
            (self.input_node, unzip_mask_tissues, [("mask_tissues", "in_file")
                                                   ]),
            (unzip_pet_image, coreg_pet_t1, [("out_file", "source")]),
            (unzip_t1_image_native, coreg_pet_t1, [("out_file", "target")]),
            (unzip_flow_fields, dartel_mni_reg, [("out_file",
                                                  "flowfield_files")]),
            (unzip_dartel_template, dartel_mni_reg, [("out_file",
                                                      "template_file")]),
            (unzip_reference_mask, reslice, [("out_file", "in_file")]),
            (unzip_mask_tissues, binary_mask, [("out_file", "tissues")]),
            (coreg_pet_t1, dartel_mni_reg, [("coregistered_source",
                                             "apply_to_files")]),
            (dartel_mni_reg, reslice, [("normalized_files", "space_defining")
                                       ]),
            (dartel_mni_reg, norm_to_ref, [("normalized_files", "pet_image")]),
            (reslice, norm_to_ref, [("out_file", "region_mask")]),
            (norm_to_ref, apply_mask, [("suvr_pet_path", "image")]),
            (binary_mask, apply_mask, [("out_mask", "binary_mask")]),
            (norm_to_ref, atlas_stats_node, [("suvr_pet_path", "in_image")]),
            (coreg_pet_t1, self.output_node, [("coregistered_source",
                                               "pet_t1_native")]),
            (dartel_mni_reg, self.output_node, [("normalized_files", "pet_mni")
                                                ]),
            (norm_to_ref, self.output_node, [("suvr_pet_path", "pet_suvr")]),
            (binary_mask, self.output_node, [("out_mask", "binary_mask")]),
            (apply_mask, self.output_node, [("masked_image_path",
                                             "pet_suvr_masked")]),
            (atlas_stats_node, self.output_node, [("atlas_statistics",
                                                   "atlas_statistics")]),
        ])
        # fmt: on

        # PVC
        # ==========
        if self.parameters["apply_pvc"]:
            # Unzipping
            # =========
            unzip_pvc_mask_tissues = npe.MapNode(
                nutil.Function(
                    input_names=["in_file"],
                    output_names=["out_file"],
                    function=unzip_nii,
                ),
                name="unzip_pvc_mask_tissues",
                iterfield=["in_file"],
            )

            # Creating Mask to use in PVC
            # ===========================
            pvc_mask = npe.Node(
                nutil.Function(
                    input_names=["tissues"],
                    output_names=["out_mask"],
                    function=create_pvc_mask,
                ),
                name="pvc_mask",
            )
            # PET PVC
            # =======
            petpvc = npe.Node(PETPVC(), name="pvc")
            petpvc.inputs.pvc = "RBV"
            petpvc.inputs.out_file = "pvc.nii"

            # Spatially normalize PET into MNI
            # ================================
            dartel_mni_reg_pvc = npe.Node(spm.DARTELNorm2MNI(),
                                          name="dartel_mni_reg_pvc")
            dartel_mni_reg_pvc.inputs.modulate = False
            dartel_mni_reg_pvc.inputs.fwhm = 0

            # Reslice reference region mask into PET
            # ======================================
            reslice_pvc = npe.Node(spmutils.Reslice(), name="reslice_pvc")

            # Normalize PET values according to reference region
            # ==================================================
            norm_to_ref_pvc = npe.Node(
                nutil.Function(
                    input_names=["pet_image", "region_mask"],
                    output_names=["suvr_pet_path"],
                    function=normalize_to_reference,
                ),
                name="norm_to_ref_pvc",
            )

            # Mask PET image
            # ==============
            apply_mask_pvc = npe.Node(
                nutil.Function(
                    input_names=["image", "binary_mask"],
                    output_names=["masked_image_path"],
                    function=apply_binary_mask,
                ),
                name="apply_mask_pvc",
            )
            # Smoothing
            # =========
            if (self.parameters["smooth"] is not None
                    and len(self.parameters["smooth"]) > 0):
                smoothing_pvc = npe.MapNode(spm.Smooth(),
                                            name="smoothing_pvc",
                                            iterfield=["fwhm", "out_prefix"])
                smoothing_pvc.inputs.fwhm = [[x, x, x]
                                             for x in self.parameters["smooth"]
                                             ]
                smoothing_pvc.inputs.out_prefix = [
                    "fwhm-" + str(x) + "mm_" for x in self.parameters["smooth"]
                ]
                # fmt: off
                self.connect([
                    (apply_mask_pvc, smoothing_pvc, [("masked_image_path",
                                                      "in_files")]),
                    (smoothing_pvc, self.output_node,
                     [("smoothed_files", "pet_pvc_suvr_masked_smoothed")]),
                ])
                # fmt: on
            else:
                self.output_node.inputs.pet_pvc_suvr_masked_smoothed = [[]]
            # Atlas Statistics
            # ================
            atlas_stats_pvc = npe.MapNode(
                nutil.Function(
                    input_names=["in_image", "in_atlas_list"],
                    output_names=["atlas_statistics"],
                    function=atlas_statistics,
                ),
                name="atlas_stats_pvc",
                iterfield=["in_image"],
            )
            atlas_stats_pvc.inputs.in_atlas_list = self.parameters["atlases"]

            # Connection
            # ==========
            # fmt: off
            self.connect([
                (self.input_node, unzip_pvc_mask_tissues, [("pvc_mask_tissues",
                                                            "in_file")]),
                (unzip_pvc_mask_tissues, pvc_mask, [("out_file", "tissues")]),
                (unzip_flow_fields, dartel_mni_reg_pvc, [("out_file",
                                                          "flowfield_files")]),
                (unzip_dartel_template, dartel_mni_reg_pvc,
                 [("out_file", "template_file")]),
                (unzip_reference_mask, reslice_pvc, [("out_file", "in_file")]),
                (coreg_pet_t1, petpvc, [("coregistered_source", "in_file"),
                                        (("coregistered_source", pet_pvc_name,
                                          "RBV"), "out_file")]),
                (pvc_mask, petpvc, [("out_mask", "mask_file")]),
                (self.input_node, petpvc,
                 [(("psf", get_from_list, 0), "fwhm_x"),
                  (("psf", get_from_list, 1), "fwhm_y"),
                  (("psf", get_from_list, 2), "fwhm_z")]),
                (petpvc, dartel_mni_reg_pvc, [("out_file", "apply_to_files")]),
                (dartel_mni_reg_pvc, reslice_pvc, [("normalized_files",
                                                    "space_defining")]),
                (dartel_mni_reg_pvc, norm_to_ref_pvc, [("normalized_files",
                                                        "pet_image")]),
                (reslice_pvc, norm_to_ref_pvc, [("out_file", "region_mask")]),
                (norm_to_ref_pvc, apply_mask_pvc, [("suvr_pet_path", "image")
                                                   ]),
                (binary_mask, apply_mask_pvc, [("out_mask", "binary_mask")]),
                (norm_to_ref_pvc, atlas_stats_pvc, [("suvr_pet_path",
                                                     "in_image")]),
                (petpvc, self.output_node, [("out_file", "pet_pvc")]),
                (dartel_mni_reg_pvc, self.output_node, [("normalized_files",
                                                         "pet_pvc_mni")]),
                (norm_to_ref_pvc, self.output_node, [("suvr_pet_path",
                                                      "pet_pvc_suvr")]),
                (apply_mask_pvc, self.output_node, [("masked_image_path",
                                                     "pet_pvc_suvr_masked")]),
                (atlas_stats_pvc, self.output_node,
                 [("atlas_statistics", "pvc_atlas_statistics")]),
            ])
            # fmt: on
        else:
            self.output_node.inputs.pet_pvc = [[]]
            self.output_node.inputs.pet_pvc_mni = [[]]
            self.output_node.inputs.pet_pvc_suvr = [[]]
            self.output_node.inputs.pet_pvc_suvr_masked = [[]]
            self.output_node.inputs.pvc_atlas_statistics = [[]]
            self.output_node.inputs.pet_pvc_suvr_masked_smoothed = [[]]
예제 #5
0
def create_pipeline_nii_to_conmat(main_path,
                                  filter_gm_threshold=0.9,
                                  pipeline_name="nii_to_conmat",
                                  conf_interval_prob=0.05,
                                  background_val=-1.0,
                                  plot=True,
                                  reslice=False,
                                  resample=False,
                                  min_BOLD_intensity=50,
                                  percent_signal=0.5):
    """
    Description:

    Pipeline from nifti 4D (after preprocessing) to connectivity matrices

    Inputs (inputnode):

        * nii_4D_file
        * rp_file
        * ROI_mask_file
        * gm_anat_file
        * wm_anat_file
        * csf_anat_file
        * ROI_coords_file
        * ROI_MNI_coords_file
        * ROI_labels_file

    Comments:

    Typically used after nipype preprocessing pipeline and
    before conmat_to_graph pipeline

    """
    if reslice and resample:
        print("Only reslice OR resample can be true, setting reslice to False")
        reslice = False

    pipeline = pe.Workflow(name=pipeline_name)
    pipeline.base_dir = main_path

    inputnode = pe.Node(niu.IdentityInterface(fields=[
        'nii_4D_file', 'ROI_mask_file', 'rp_file', 'gm_anat_file',
        'wm_anat_file', 'csf_anat_file', 'ROI_coords_file',
        'ROI_MNI_coords_file', 'ROI_labels_file'
    ]),
                        name='inputnode')

    # reslice gm
    if reslice:

        reslice_gm = pe.Node(interface=spmu.Reslice(), name='reslice_gm')
        pipeline.connect(inputnode, 'ROI_mask_file', reslice_gm,
                         'space_defining')
        pipeline.connect(inputnode, 'gm_anat_file', reslice_gm, 'in_file')

    if resample:

        resample_gm = pe.Node(interface=RegResample(), name='resample_gm')
        pipeline.connect(inputnode, 'ROI_mask_file', resample_gm, 'ref_file')
        pipeline.connect(inputnode, 'gm_anat_file', resample_gm, 'flo_file')

    # reslice wm
    if reslice:

        reslice_wm = pe.Node(interface=spmu.Reslice(), name='reslice_wm')
        pipeline.connect(inputnode, 'ROI_mask_file', reslice_wm,
                         'space_defining')
        pipeline.connect(inputnode, 'wm_anat_file', reslice_wm, 'in_file')

    if resample:

        resample_wm = pe.Node(interface=RegResample(), name='resample_wm')
        pipeline.connect(inputnode, 'ROI_mask_file', resample_wm, 'ref_file')
        pipeline.connect(inputnode, 'wm_anat_file', resample_wm, 'flo_file')
    # reslice csf
    if reslice:

        reslice_csf = pe.Node(interface=spmu.Reslice(), name='reslice_csf')
        pipeline.connect(inputnode, 'ROI_mask_file', reslice_csf,
                         'space_defining')

        pipeline.connect(inputnode, 'csf_anat_file', reslice_csf, 'in_file')

    if resample:

        resample_csf = pe.Node(interface=RegResample(), name='resample_csf')
        pipeline.connect(inputnode, 'ROI_mask_file', resample_csf, 'ref_file')
        pipeline.connect(inputnode, 'csf_anat_file', resample_csf, 'flo_file')

    # Preprocess pipeline,
    filter_ROI_mask_with_GM = pe.Node(interface=IntersectMask(),
                                      name='filter_ROI_mask_with_GM')

    filter_ROI_mask_with_GM.inputs.filter_thr = filter_gm_threshold
    filter_ROI_mask_with_GM.inputs.background_val = background_val

    pipeline.connect(inputnode, 'ROI_mask_file', filter_ROI_mask_with_GM,
                     'indexed_rois_file')
    pipeline.connect(inputnode, 'ROI_coords_file', filter_ROI_mask_with_GM,
                     'coords_rois_file')
    pipeline.connect(inputnode, 'ROI_MNI_coords_file', filter_ROI_mask_with_GM,
                     'MNI_coords_rois_file')
    pipeline.connect(inputnode, 'ROI_labels_file', filter_ROI_mask_with_GM,
                     'labels_rois_file')

    if reslice:
        pipeline.connect(reslice_gm, 'out_file', filter_ROI_mask_with_GM,
                         'filter_mask_file')

    elif resample:
        pipeline.connect(resample_gm, 'out_file', filter_ROI_mask_with_GM,
                         'filter_mask_file')

    else:
        pipeline.connect(inputnode, 'gm_anat_file', filter_ROI_mask_with_GM,
                         'filter_mask_file')

    # Nodes version: use min_BOLD_intensity and
    # return coords where signal is strong enough
    extract_mean_ROI_ts = pe.Node(interface=ExtractTS(plot_fig=plot),
                                  name='extract_mean_ROI_ts')

    extract_mean_ROI_ts.inputs.percent_signal = percent_signal
    extract_mean_ROI_ts.inputs.min_BOLD_intensity = min_BOLD_intensity

    pipeline.connect(inputnode, 'nii_4D_file', extract_mean_ROI_ts, 'file_4D')
    pipeline.connect(filter_ROI_mask_with_GM, 'filtered_indexed_rois_file',
                     extract_mean_ROI_ts, 'indexed_rois_file')
    pipeline.connect(filter_ROI_mask_with_GM, 'filtered_MNI_coords_rois_file',
                     extract_mean_ROI_ts, 'MNI_coord_rois_file')
    pipeline.connect(filter_ROI_mask_with_GM, 'filtered_coords_rois_file',
                     extract_mean_ROI_ts, 'coord_rois_file')
    pipeline.connect(filter_ROI_mask_with_GM, 'filtered_labels_rois_file',
                     extract_mean_ROI_ts, 'label_rois_file')

    # extract white matter signal
    compute_wm_ts = pe.Node(interface=ExtractMeanTS(plot_fig=plot),
                            name='extract_wm_ts')
    compute_wm_ts.inputs.suffix = 'wm'

    pipeline.connect(inputnode, 'nii_4D_file', compute_wm_ts, 'file_4D')

    if reslice:
        pipeline.connect(reslice_wm, 'out_file', compute_wm_ts,
                         'filter_mask_file')

    elif resample:
        pipeline.connect(resample_wm, 'out_file', compute_wm_ts,
                         'filter_mask_file')

    else:
        pipeline.connect(inputnode, 'wm_anat_file', compute_wm_ts,
                         'filter_mask_file')

    # extract csf signal
    compute_csf_ts = pe.Node(interface=ExtractMeanTS(plot_fig=plot),
                             name='extract_csf_ts')
    compute_csf_ts.inputs.suffix = 'csf'

    pipeline.connect(inputnode, 'nii_4D_file', compute_csf_ts, 'file_4D')

    if reslice:
        pipeline.connect(reslice_csf, 'out_file', compute_csf_ts,
                         'filter_mask_file')

    elif resample:
        pipeline.connect(resample_csf, 'out_file', compute_csf_ts,
                         'filter_mask_file')

    else:
        pipeline.connect(inputnode, 'csf_anat_file', compute_csf_ts,
                         'filter_mask_file')

    # regress covariates
    regress_covar = pe.Node(interface=RegressCovar(plot_fig=plot),
                            iterfield=[
                                'masked_ts_file', 'rp_file', 'mean_wm_ts_file',
                                'mean_csf_ts_file'
                            ],
                            name='regress_covar')

    pipeline.connect(extract_mean_ROI_ts, 'mean_masked_ts_file', regress_covar,
                     'masked_ts_file')
    pipeline.connect(inputnode, 'rp_file', regress_covar, 'rp_file')

    pipeline.connect(compute_wm_ts, 'mean_masked_ts_file', regress_covar,
                     'mean_wm_ts_file')
    pipeline.connect(compute_csf_ts, 'mean_masked_ts_file', regress_covar,
                     'mean_csf_ts_file')

    # compute correlations
    compute_conf_cor_mat = pe.Node(interface=ComputeConfCorMat(plot_mat=plot),
                                   name='compute_conf_cor_mat')
    compute_conf_cor_mat.inputs.conf_interval_prob = conf_interval_prob

    pipeline.connect(regress_covar, 'resid_ts_file', compute_conf_cor_mat,
                     'ts_file')
    pipeline.connect(extract_mean_ROI_ts, 'subj_label_rois_file',
                     compute_conf_cor_mat, 'labels_file')

    return pipeline
예제 #6
0
def create_pipeline_nii_to_subj_ROI(main_path,
                                    filter_gm_threshold=0.9,
                                    pipeline_name="nii_to_subj_ROI",
                                    background_val=-1.0,
                                    plot=True,
                                    reslice=False,
                                    resample=False,
                                    min_BOLD_intensity=50,
                                    percent_signal=0.5):
    """
    Description:

    Pipeline from nifti 4D (after preprocessing) to connectivity matrices
    Use Grey matter for having a mask for each subject

    Inputs (inputnode):

        * nii_4D_file
        * gm_anat_file
        * ROI_mask_file
        * ROI_coords_file
        * ROI_MNI_coords_file
        * ROI_labels_file

    Comments:

    Typically used after nipype preprocessing pipeline and
    before conmat_to_graph pipeline

    """
    if reslice and resample:
        print("Only reslice OR resample can be true, setting reslice to False")
        reslice = False

    pipeline = pe.Workflow(name=pipeline_name)
    pipeline.base_dir = main_path

    inputnode = pe.Node(niu.IdentityInterface(fields=[
        'nii_4D_file', 'ROI_mask_file', 'gm_anat_file', 'ROI_coords_file',
        'ROI_MNI_coords_file', 'ROI_labels_file'
    ]),
                        name='inputnode')

    # reslice gm
    if reslice:

        reslice_gm = pe.Node(interface=spmu.Reslice(), name='reslice_gm')
        pipeline.connect(inputnode, 'ROI_mask_file', reslice_gm,
                         'space_defining')
        pipeline.connect(inputnode, 'gm_anat_file', reslice_gm, 'in_file')

    if resample:

        resample_gm = pe.Node(interface=RegResample(), name='resample_gm')
        pipeline.connect(inputnode, 'ROI_mask_file', resample_gm, 'ref_file')
        pipeline.connect(inputnode, 'gm_anat_file', resample_gm, 'flo_file')

    # Preprocess pipeline,
    filter_ROI_mask_with_GM = pe.Node(interface=IntersectMask(),
                                      name='filter_ROI_mask_with_GM')

    filter_ROI_mask_with_GM.inputs.filter_thr = filter_gm_threshold
    filter_ROI_mask_with_GM.inputs.background_val = background_val

    pipeline.connect(inputnode, 'ROI_mask_file', filter_ROI_mask_with_GM,
                     'indexed_rois_file')
    pipeline.connect(inputnode, 'ROI_coords_file', filter_ROI_mask_with_GM,
                     'coords_rois_file')
    pipeline.connect(inputnode, 'ROI_MNI_coords_file', filter_ROI_mask_with_GM,
                     'MNI_coords_rois_file')
    pipeline.connect(inputnode, 'ROI_labels_file', filter_ROI_mask_with_GM,
                     'labels_rois_file')

    if reslice:
        pipeline.connect(reslice_gm, 'out_file', filter_ROI_mask_with_GM,
                         'filter_mask_file')

    elif resample:
        pipeline.connect(resample_gm, 'out_file', filter_ROI_mask_with_GM,
                         'filter_mask_file')

    else:
        pipeline.connect(inputnode, 'gm_anat_file', filter_ROI_mask_with_GM,
                         'filter_mask_file')

    # Nodes version: use min_BOLD_intensity and
    # return coords where signal is strong enough
    extract_mean_ROI_ts = pe.Node(interface=ExtractTS(plot_fig=plot),
                                  name='extract_mean_ROI_ts')

    extract_mean_ROI_ts.inputs.percent_signal = percent_signal
    extract_mean_ROI_ts.inputs.min_BOLD_intensity = min_BOLD_intensity

    pipeline.connect(inputnode, 'nii_4D_file', extract_mean_ROI_ts, 'file_4D')
    pipeline.connect(filter_ROI_mask_with_GM, 'filtered_indexed_rois_file',
                     extract_mean_ROI_ts, 'indexed_rois_file')
    pipeline.connect(filter_ROI_mask_with_GM, 'filtered_MNI_coords_rois_file',
                     extract_mean_ROI_ts, 'MNI_coord_rois_file')
    pipeline.connect(filter_ROI_mask_with_GM, 'filtered_coords_rois_file',
                     extract_mean_ROI_ts, 'coord_rois_file')
    pipeline.connect(filter_ROI_mask_with_GM, 'filtered_labels_rois_file',
                     extract_mean_ROI_ts, 'label_rois_file')

    return pipeline
예제 #7
0
    def build_core_nodes(self):
        """Build and connect an output node to the pipeline."""
        import nipype.interfaces.spm as spm
        import nipype.interfaces.spm.utils as spmutils
        from nipype.interfaces.petpvc import PETPVC
        import nipype.interfaces.utility as nutil
        import nipype.pipeline.engine as npe

        from clinica.utils.filemanip import unzip_nii
        from clinica.utils.spm import spm_standalone_is_available, use_spm_standalone
        import clinica.pipelines.pet_volume.pet_volume_utils as utils

        if spm_standalone_is_available():
            use_spm_standalone()

        # Initialize pipeline
        # ===================
        init_node = npe.Node(interface=nutil.Function(
            input_names=['pet_nii'],
            output_names=['pet_nii'],
            function=utils.init_input_node),
                             name='init_pipeline')

        # Unzipping
        # =========
        unzip_pet_image = npe.Node(nutil.Function(input_names=['in_file'],
                                                  output_names=['out_file'],
                                                  function=unzip_nii),
                                   name='unzip_pet_image')

        unzip_t1_image_native = npe.Node(nutil.Function(
            input_names=['in_file'],
            output_names=['out_file'],
            function=unzip_nii),
                                         name='unzip_t1_image_native')

        unzip_flow_fields = npe.Node(nutil.Function(input_names=['in_file'],
                                                    output_names=['out_file'],
                                                    function=unzip_nii),
                                     name='unzip_flow_fields')

        unzip_dartel_template = npe.Node(nutil.Function(
            input_names=['in_file'],
            output_names=['out_file'],
            function=unzip_nii),
                                         name='unzip_dartel_template')

        unzip_reference_mask = npe.Node(nutil.Function(
            input_names=['in_file'],
            output_names=['out_file'],
            function=unzip_nii),
                                        name='unzip_reference_mask')

        unzip_mask_tissues = npe.MapNode(nutil.Function(
            input_names=['in_file'],
            output_names=['out_file'],
            function=unzip_nii),
                                         name='unzip_mask_tissues',
                                         iterfield=['in_file'])

        # Coregister PET into T1 native space
        # ===================================
        coreg_pet_t1 = npe.Node(spm.Coregister(), name='coreg_pet_t1')

        # Spatially normalize PET into MNI
        # ================================
        dartel_mni_reg = npe.Node(spm.DARTELNorm2MNI(), name='dartel_mni_reg')
        dartel_mni_reg.inputs.modulate = False
        dartel_mni_reg.inputs.fwhm = 0

        # Reslice reference region mask into PET
        # ======================================
        reslice = npe.Node(spmutils.Reslice(), name='reslice')

        # Normalize PET values according to reference region
        # ==================================================
        norm_to_ref = npe.Node(nutil.Function(
            input_names=['pet_image', 'region_mask'],
            output_names=['suvr_pet_path'],
            function=utils.normalize_to_reference),
                               name='norm_to_ref')

        # Create binary mask from segmented tissues
        # =========================================
        binary_mask = npe.Node(nutil.Function(
            input_names=['tissues', 'threshold'],
            output_names=['out_mask'],
            function=utils.create_binary_mask),
                               name='binary_mask')
        binary_mask.inputs.threshold = self.parameters['mask_threshold']

        # Mask PET image
        # ==============
        apply_mask = npe.Node(nutil.Function(
            input_names=['image', 'binary_mask'],
            output_names=['masked_image_path'],
            function=utils.apply_binary_mask),
                              name='apply_mask')

        # Smoothing
        # =========
        if self.parameters['smooth'] is not None and len(
                self.parameters['smooth']) > 0:
            smoothing_node = npe.MapNode(spm.Smooth(),
                                         name='smoothing_node',
                                         iterfield=['fwhm', 'out_prefix'])
            smoothing_node.inputs.fwhm = [[x, x, x]
                                          for x in self.parameters['smooth']]
            smoothing_node.inputs.out_prefix = [
                'fwhm-' + str(x) + 'mm_' for x in self.parameters['smooth']
            ]
            self.connect([(apply_mask, smoothing_node, [('masked_image_path',
                                                         'in_files')]),
                          (smoothing_node, self.output_node,
                           [('smoothed_files', 'pet_suvr_masked_smoothed')])])
        else:
            self.output_node.inputs.pet_suvr_masked_smoothed = [[]]

        # Atlas Statistics
        # ================
        atlas_stats_node = npe.MapNode(nutil.Function(
            input_names=['in_image', 'in_atlas_list'],
            output_names=['atlas_statistics'],
            function=utils.atlas_statistics),
                                       name='atlas_stats_node',
                                       iterfield=['in_image'])
        atlas_stats_node.inputs.in_atlas_list = self.parameters['atlases']

        # Connection
        # ==========
        self.connect([
            (self.input_node, init_node, [('pet_image', 'pet_nii')]),
            (init_node, unzip_pet_image, [('pet_nii', 'in_file')]),
            (self.input_node, unzip_t1_image_native, [('t1_image_native',
                                                       'in_file')]),
            (self.input_node, unzip_flow_fields, [('flow_fields', 'in_file')]),
            (self.input_node, unzip_dartel_template, [('dartel_template',
                                                       'in_file')]),
            (self.input_node, unzip_reference_mask, [('reference_mask',
                                                      'in_file')]),
            (self.input_node, unzip_mask_tissues, [('mask_tissues', 'in_file')
                                                   ]),
            (unzip_pet_image, coreg_pet_t1, [('out_file', 'source')]),
            (unzip_t1_image_native, coreg_pet_t1, [('out_file', 'target')]),
            (unzip_flow_fields, dartel_mni_reg, [('out_file',
                                                  'flowfield_files')]),
            (unzip_dartel_template, dartel_mni_reg, [('out_file',
                                                      'template_file')]),
            (unzip_reference_mask, reslice, [('out_file', 'in_file')]),
            (unzip_mask_tissues, binary_mask, [('out_file', 'tissues')]),
            (coreg_pet_t1, dartel_mni_reg, [('coregistered_source',
                                             'apply_to_files')]),
            (dartel_mni_reg, reslice, [('normalized_files', 'space_defining')
                                       ]),
            (dartel_mni_reg, norm_to_ref, [('normalized_files', 'pet_image')]),
            (reslice, norm_to_ref, [('out_file', 'region_mask')]),
            (norm_to_ref, apply_mask, [('suvr_pet_path', 'image')]),
            (binary_mask, apply_mask, [('out_mask', 'binary_mask')]),
            (norm_to_ref, atlas_stats_node, [('suvr_pet_path', 'in_image')]),
            (coreg_pet_t1, self.output_node, [('coregistered_source',
                                               'pet_t1_native')]),
            (dartel_mni_reg, self.output_node, [('normalized_files', 'pet_mni')
                                                ]),
            (norm_to_ref, self.output_node, [('suvr_pet_path', 'pet_suvr')]),
            (binary_mask, self.output_node, [('out_mask', 'binary_mask')]),
            (apply_mask, self.output_node, [('masked_image_path',
                                             'pet_suvr_masked')]),
            (atlas_stats_node, self.output_node, [('atlas_statistics',
                                                   'atlas_statistics')])
        ])

        # PVC
        # ==========
        if self.parameters['apply_pvc']:
            # Unzipping
            # =========
            unzip_pvc_mask_tissues = npe.MapNode(nutil.Function(
                input_names=['in_file'],
                output_names=['out_file'],
                function=unzip_nii),
                                                 name='unzip_pvc_mask_tissues',
                                                 iterfield=['in_file'])

            # Creating Mask to use in PVC
            # ===========================
            pvc_mask = npe.Node(nutil.Function(input_names=['tissues'],
                                               output_names=['out_mask'],
                                               function=utils.create_pvc_mask),
                                name='pvc_mask')
            # PET PVC
            # =======
            petpvc = npe.Node(PETPVC(), name='pvc')
            petpvc.inputs.pvc = 'RBV'
            petpvc.inputs.out_file = 'pvc.nii'

            # Spatially normalize PET into MNI
            # ================================
            dartel_mni_reg_pvc = npe.Node(spm.DARTELNorm2MNI(),
                                          name='dartel_mni_reg_pvc')
            dartel_mni_reg_pvc.inputs.modulate = False
            dartel_mni_reg_pvc.inputs.fwhm = 0

            # Reslice reference region mask into PET
            # ======================================
            reslice_pvc = npe.Node(spmutils.Reslice(), name='reslice_pvc')

            # Normalize PET values according to reference region
            # ==================================================
            norm_to_ref_pvc = npe.Node(nutil.Function(
                input_names=['pet_image', 'region_mask'],
                output_names=['suvr_pet_path'],
                function=utils.normalize_to_reference),
                                       name='norm_to_ref_pvc')

            # Mask PET image
            # ==============
            apply_mask_pvc = npe.Node(nutil.Function(
                input_names=['image', 'binary_mask'],
                output_names=['masked_image_path'],
                function=utils.apply_binary_mask),
                                      name='apply_mask_pvc')
            # Smoothing
            # =========
            if self.parameters['smooth'] is not None and len(
                    self.parameters['smooth']) > 0:
                smoothing_pvc = npe.MapNode(spm.Smooth(),
                                            name='smoothing_pvc',
                                            iterfield=['fwhm', 'out_prefix'])
                smoothing_pvc.inputs.fwhm = [[x, x, x]
                                             for x in self.parameters['smooth']
                                             ]
                smoothing_pvc.inputs.out_prefix = [
                    'fwhm-' + str(x) + 'mm_' for x in self.parameters['smooth']
                ]
                self.connect([(apply_mask_pvc, smoothing_pvc,
                               [('masked_image_path', 'in_files')]),
                              (smoothing_pvc, self.output_node,
                               [('smoothed_files',
                                 'pet_pvc_suvr_masked_smoothed')])])
            else:
                self.output_node.inputs.pet_pvc_suvr_masked_smoothed = [[]]
            # Atlas Statistics
            # ================
            atlas_stats_pvc = npe.MapNode(nutil.Function(
                input_names=['in_image', 'in_atlas_list'],
                output_names=['atlas_statistics'],
                function=utils.atlas_statistics),
                                          name='atlas_stats_pvc',
                                          iterfield=['in_image'])
            atlas_stats_pvc.inputs.in_atlas_list = self.parameters['atlases']

            # Connection
            # ==========
            self.connect([
                (self.input_node, unzip_pvc_mask_tissues, [('pvc_mask_tissues',
                                                            'in_file')]),
                (unzip_pvc_mask_tissues, pvc_mask, [('out_file', 'tissues')]),
                (unzip_flow_fields, dartel_mni_reg_pvc, [('out_file',
                                                          'flowfield_files')]),
                (unzip_dartel_template, dartel_mni_reg_pvc,
                 [('out_file', 'template_file')]),
                (unzip_reference_mask, reslice_pvc, [('out_file', 'in_file')]),
                (coreg_pet_t1, petpvc, [('coregistered_source', 'in_file'),
                                        (('coregistered_source',
                                          utils.pet_pvc_name, 'RBV'),
                                         'out_file')]),
                (pvc_mask, petpvc, [('out_mask', 'mask_file')]),
                (self.input_node, petpvc,
                 [(('psf', utils.get_from_list, 0), 'fwhm_x'),
                  (('psf', utils.get_from_list, 1), 'fwhm_y'),
                  (('psf', utils.get_from_list, 2), 'fwhm_z')]),
                (petpvc, dartel_mni_reg_pvc, [('out_file', 'apply_to_files')]),
                (dartel_mni_reg_pvc, reslice_pvc, [('normalized_files',
                                                    'space_defining')]),
                (dartel_mni_reg_pvc, norm_to_ref_pvc, [('normalized_files',
                                                        'pet_image')]),
                (reslice_pvc, norm_to_ref_pvc, [('out_file', 'region_mask')]),
                (norm_to_ref_pvc, apply_mask_pvc, [('suvr_pet_path', 'image')
                                                   ]),
                (binary_mask, apply_mask_pvc, [('out_mask', 'binary_mask')]),
                (norm_to_ref_pvc, atlas_stats_pvc, [('suvr_pet_path',
                                                     'in_image')]),
                (petpvc, self.output_node, [('out_file', 'pet_pvc')]),
                (dartel_mni_reg_pvc, self.output_node, [('normalized_files',
                                                         'pet_pvc_mni')]),
                (norm_to_ref_pvc, self.output_node, [('suvr_pet_path',
                                                      'pet_pvc_suvr')]),
                (apply_mask_pvc, self.output_node, [('masked_image_path',
                                                     'pet_pvc_suvr_masked')]),
                (atlas_stats_pvc, self.output_node, [('atlas_statistics',
                                                      'pvc_atlas_statistics')])
            ])
        else:
            self.output_node.inputs.pet_pvc = [[]]
            self.output_node.inputs.pet_pvc_mni = [[]]
            self.output_node.inputs.pet_pvc_suvr = [[]]
            self.output_node.inputs.pet_pvc_suvr_masked = [[]]
            self.output_node.inputs.pvc_atlas_statistics = [[]]
            self.output_node.inputs.pet_pvc_suvr_masked_smoothed = [[]]