def register_skull_to_skull(skull_filename1,
                            skull_filename2,
                            prefix,
                            num_threads=1,
                            debug=False):
    cmd = RegistrationSynQuick(fixed_image=skull_filename2,
                               moving_image=skull_filename1,
                               output_prefix=prefix,
                               num_threads=num_threads)
    print(cmd.cmdline)
    cmd.run()
    if not debug:
        for fn in glob.glob(
                os.path.abspath(os.path.join(".", prefix + "*Warped.nii.gz"))):
            print("Removing:", fn)
            os.remove(fn)
Esempio n. 2
0
def register_images(moving: np.ndarray,
                    fixed: np.ndarray,
                    transform_type: str = 'a',
                    n_threads: int = 1) -> np.ndarray:
    """
    Apply RegistrationSynQuick to the input images.

    Parameters
    ----------
    moving: np.ndarray
    fixed: np.ndarray
    transform_type: str, optional
         |  t:  translation
         |  r:  rigid
         |  a:  rigid + affine (default)
         |  s:  rigid + affine + deformable syn
         |  sr: rigid + deformable syn
         |  b:  rigid + affine + deformable b-spline syn
         |  br: rigid + deformable b-spline syn
    n_threads: int, optional
        the number of threads used to apply the registration
    """
    with tempfile.TemporaryDirectory() as tempdir:
        template_path = jp(tempdir, 'template.nii.gz')
        moving_path = jp(tempdir, 'moving.nii.gz')
        nib.save(nib.Nifti1Image(fixed, np.eye(4)), template_path)
        nib.save(nib.Nifti1Image(moving, np.eye(4)), moving_path)

        reg = RegistrationSynQuick()
        reg.inputs.fixed_image = template_path
        reg.inputs.moving_image = moving_path
        reg.inputs.num_threads = n_threads
        reg.inputs.transform_type = transform_type
        reg.inputs.output_prefix = jp(tempdir, 'transform')
        reg.run()

        return nib.load(jp(tempdir, 'transformWarped.nii.gz')).get_data()
Esempio n. 3
0
def create_registration_node(config, moving_image):
    log.info('Creating Registration node...')

    reg = Node(RegistrationSynQuick(), name='registration_node')

    for key, val in reg.inputs.items():

        if key in config:
            config_val = config[key]
            reg.set_input(key, config_val)

    warped_output = 'warped_output.nii'
    reg.inputs.moving_image = moving_image

    log.debug(reg.inputs)
    log.info('...Complete!')

    return (reg)
Esempio n. 4
0
def quick(dir_fix_image='/home/silasi/ants_data/nrrd/0.tif',
          dir_moving_img='/home/silasi/ants_data/tissue/0.tif',
          dir_output='/home/silasi/ants_data/output_',
          ANTs_script="/home/silasi/ANTs/Scripts/"):
    """
    Ants registration function
    :param dir_fix_image:
    :param dir_moving_img:
    :param dir_output:
    :return:
    """
    reg = RegistrationSynQuick()
    reg.inputs.dimension = 2
    reg.inputs.fixed_image = dir_fix_image
    reg.inputs.moving_image = dir_moving_img
    reg.inputs.output_prefix = dir_output
    reg.inputs.transform_type = 's'
    reg.inputs.num_threads = 16
    command = os.path.join(ANTs_script, reg.cmdline)
    args = shlex.split(command)
    p = subprocess.Popen(args)
    p.wait()
Esempio n. 5
0
def register_dti_maps_on_atlas(working_directory=None,
                               name="register_dti_maps_on_atlas"):
    """
    Register FA-map on a subject towards a FA atlas and apply the estimated
    deformation to MD, AD & RD.

    This pipelines performs the analysis of tracts using a white matter atlas
    and computes mean value of the scalar on each tracts of this atlas. The
    pipelines registers the FA-map of a subject onto the FA-map of the atlas
    thanks to antsRegistrationSyNQuick. Then, the estimated deformation is
    applied to the MD-map, AD-map and RD-map. Finally, the labelled atlas
    is used to compute the statistics of each scalar on each tract of the white
    matter atlas.

    Args:
        working_directory (Optional[str]): Directory where the temporary
            results are stored. If not specified, it is
            automatically generated (generally in /tmp/).
        name (Optional[str]): Name of the pipelines.

    Inputnode:
        in_fa (str): FA-map of the subject in native space.
        in_md (str): MD-map of the subject in native space.
        in_ad (str): AD-map of the subject in native space.
        in_rd (str): RD-map of the subject in native space.

    Outputnode:
        out_affine_transform (str): Affine transformation matrix obtained by
            antsRegistrationSyNQuick after registration towards <atlas_name>.
        out_b_spline_transform (str): BSpline transformation obtained by
            antsRegistrationSyNQuick after registration towards <atlas_name>.
        out_norm_fa (str): FA-map registered on <atlas_name>.
        out_norm_md (str): MD-map registered on <atlas_name>.
        out_norm_ad (str): AD-map registered on <atlas_name>.
        out_norm_rd (str): RD-map registered on <atlas_name>.
    """
    import tempfile
    import nipype.interfaces.fsl as fsl
    import nipype.interfaces.utility as niu
    import nipype.pipeline.engine as pe
    from nipype.interfaces.ants import RegistrationSynQuick
    from clinica.utils.atlas import AtlasAbstract
    from clinica.utils.mri_registration import apply_ants_registration_syn_quick_transformation

    from clinica.utils.atlas import JHUDTI811mm
    atlas = JHUDTI811mm()

    if not isinstance(atlas, AtlasAbstract):
        raise Exception("Atlas element must be an AtlasAbstract type")

    if working_directory is None:
        working_directory = tempfile.mkdtemp()

    inputnode = pe.Node(niu.IdentityInterface(
        fields=['in_fa', 'in_md', 'in_ad', 'in_rd', 'in_atlas_scalar_image']),
                        name='inputnode')
    inputnode.inputs.in_atlas_scalar_image = atlas.get_atlas_map()

    register_fa = pe.Node(interface=RegistrationSynQuick(), name='register_fa')

    apply_ants_registration_for_md = pe.Node(
        interface=niu.Function(
            input_names=[
                'in_image', 'in_reference_image', 'in_affine_transformation',
                'in_bspline_transformation', 'name_output_image'
            ],
            output_names=['out_deformed_image'],
            function=apply_ants_registration_syn_quick_transformation),
        name='apply_ants_registration_for_md')
    apply_ants_registration_for_md.inputs.name_output_image = \
        'space-' + atlas.get_name_atlas() + '_res-' + atlas.get_spatial_resolution() + '_MD.nii.gz'
    apply_ants_registration_for_ad = pe.Node(
        interface=niu.Function(
            input_names=[
                'in_image', 'in_reference_image', 'in_affine_transformation',
                'in_bspline_transformation', 'name_output_image'
            ],
            output_names=['out_deformed_image'],
            function=apply_ants_registration_syn_quick_transformation),
        name='apply_ants_registration_for_ad')
    apply_ants_registration_for_ad.inputs.name_output_image = \
        'space-' + atlas.get_name_atlas() + '_res-' + atlas.get_spatial_resolution() + '_AD.nii.gz'
    apply_ants_registration_for_rd = pe.Node(
        interface=niu.Function(
            input_names=[
                'in_image', 'in_reference_image', 'in_affine_transformation',
                'in_bspline_transformation', 'name_output_image'
            ],
            output_names=['out_deformed_image'],
            function=apply_ants_registration_syn_quick_transformation),
        name='apply_ants_registration_for_rd')
    apply_ants_registration_for_rd.inputs.name_output_image = \
        'space-' + atlas.get_name_atlas() + '_res-' + atlas.get_spatial_resolution() + '_RD.nii.gz'

    thres_map = pe.Node(fsl.Threshold(thresh=0.0),
                        iterfield=['in_file'],
                        name='RemoveNegative')
    thres_fa = thres_map.clone('RemoveNegative_FA')
    thres_md = thres_map.clone('RemoveNegative_MD')
    thres_ad = thres_map.clone('RemoveNegative_AD')
    thres_rd = thres_map.clone('RemoveNegative_RD')

    outputnode = pe.Node(niu.IdentityInterface(fields=[
        'out_norm_fa', 'out_norm_md', 'out_norm_ad', 'out_norm_rd',
        'out_affine_matrix', 'out_b_spline_transform'
    ]),
                         name='outputnode')

    wf = pe.Workflow(name=name, base_dir=working_directory)
    wf.connect([
        # Registration of FA-map onto the atlas:
        (
            inputnode,
            register_fa,
            [
                ('in_fa', 'moving_image'),  # noqa
                ('in_atlas_scalar_image', 'fixed_image')
            ]),  # noqa
        # Apply deformation field on MD, AD & RD:
        (inputnode, apply_ants_registration_for_md, [('in_md', 'in_image')]
         ),  # noqa
        (inputnode, apply_ants_registration_for_md,
         [('in_atlas_scalar_image', 'in_reference_image')]),  # noqa
        (register_fa, apply_ants_registration_for_md,
         [('out_matrix', 'in_affine_transformation')]),  # noqa
        (register_fa, apply_ants_registration_for_md,
         [('forward_warp_field', 'in_bspline_transformation')]),  # noqa
        (inputnode, apply_ants_registration_for_ad, [('in_ad', 'in_image')
                                                     ]),  # noqa
        (inputnode, apply_ants_registration_for_ad,
         [('in_atlas_scalar_image', 'in_reference_image')]),  # noqa
        (register_fa, apply_ants_registration_for_ad,
         [('out_matrix', 'in_affine_transformation')]),  # noqa
        (register_fa, apply_ants_registration_for_ad,
         [('forward_warp_field', 'in_bspline_transformation')]),  # noqa
        (inputnode, apply_ants_registration_for_rd, [('in_rd', 'in_image')
                                                     ]),  # noqa
        (inputnode, apply_ants_registration_for_rd,
         [('in_atlas_scalar_image', 'in_reference_image')]),  # noqa
        (register_fa, apply_ants_registration_for_rd,
         [('out_matrix', 'in_affine_transformation')]),  # noqa
        (register_fa, apply_ants_registration_for_rd,
         [('forward_warp_field', 'in_bspline_transformation')]),  # noqa
        # Remove negative values from the DTI maps:
        (register_fa, thres_fa, [('warped_image', 'in_file')]),  # noqa
        (apply_ants_registration_for_md, thres_md, [('out_deformed_image',
                                                     'in_file')]),  # noqa
        (apply_ants_registration_for_rd, thres_rd, [('out_deformed_image',
                                                     'in_file')]),  # noqa
        (apply_ants_registration_for_ad, thres_ad, [('out_deformed_image',
                                                     'in_file')]),  # noqa
        # Outputnode:
        (thres_fa, outputnode, [('out_file', 'out_norm_fa')]),  # noqa
        (
            register_fa,
            outputnode,
            [
                ('out_matrix', 'out_affine_matrix'),  # noqa
                ('forward_warp_field', 'out_b_spline_transform'),  # noqa
                ('inverse_warp_field', 'out_inverse_warp')
            ]),  # noqa
        (thres_md, outputnode, [('out_file', 'out_norm_md')]),  # noqa
        (thres_ad, outputnode, [('out_file', 'out_norm_ad')]),  # noqa
        (thres_rd, outputnode, [('out_file', 'out_norm_rd')])  # noqa
    ])

    return wf
Esempio n. 6
0
    def build_core_nodes(self):
        """Build and connect the core nodes of the pipeline."""
        import os

        import nipype.interfaces.fsl as fsl
        import nipype.interfaces.mrtrix as mrtrix
        import nipype.interfaces.utility as nutil
        import nipype.pipeline.engine as npe
        from nipype.interfaces.ants import ApplyTransforms, RegistrationSynQuick
        from nipype.interfaces.mrtrix.preprocess import DWI2Tensor

        from clinica.lib.nipype.interfaces.mrtrix3.utils import TensorMetrics
        from clinica.utils.check_dependency import check_environment_variable

        from .dwi_dti_utils import (
            extract_bids_identifier_from_caps_filename,
            get_ants_transforms,
            get_caps_filenames,
            print_begin_pipeline,
            print_end_pipeline,
            statistics_on_atlases,
        )

        # Nodes creation
        # ==============
        get_bids_identifier = npe.Node(
            interface=nutil.Function(
                input_names=["caps_dwi_filename"],
                output_names=["bids_identifier"],
                function=extract_bids_identifier_from_caps_filename,
            ),
            name="0-Get_BIDS_Identifier",
        )

        get_caps_filenames = npe.Node(
            interface=nutil.Function(
                input_names=["caps_dwi_filename"],
                output_names=[
                    "bids_source",
                    "out_dti",
                    "out_fa",
                    "out_md",
                    "out_ad",
                    "out_rd",
                    "out_evec",
                ],
                function=get_caps_filenames,
            ),
            name="0-CAPS_Filenames",
        )

        convert_gradients = npe.Node(interface=mrtrix.FSL2MRTrix(),
                                     name="0-Convert_FSL_Gradient")

        dwi_to_dti = npe.Node(interface=DWI2Tensor(), name="1-Compute_DTI")

        dti_to_metrics = npe.Node(interface=TensorMetrics(),
                                  name="2-DTI-based_Metrics")

        register_fa = npe.Node(interface=RegistrationSynQuick(),
                               name="3a-Register_FA")
        fsl_dir = check_environment_variable("FSLDIR", "FSL")
        fa_map = os.path.join(fsl_dir, "data", "atlases", "JHU",
                              "JHU-ICBM-FA-1mm.nii.gz")
        register_fa.inputs.fixed_image = fa_map

        ants_transforms = npe.Node(
            interface=nutil.Function(
                input_names=[
                    "in_affine_transformation", "in_bspline_transformation"
                ],
                output_names=["transforms"],
                function=get_ants_transforms,
            ),
            name="combine_ants_transforms",
        )

        apply_ants_registration = npe.Node(interface=ApplyTransforms(),
                                           name="apply_ants_registration")
        apply_ants_registration.inputs.dimension = 3
        apply_ants_registration.inputs.input_image_type = 0
        apply_ants_registration.inputs.interpolation = "Linear"
        apply_ants_registration.inputs.reference_image = fa_map

        apply_ants_registration_for_md = apply_ants_registration.clone(
            "3b-Apply_ANTs_Registration_MD")
        apply_ants_registration_for_ad = apply_ants_registration.clone(
            "3b-Apply_ANTs_Registration_AD")
        apply_ants_registration_for_rd = apply_ants_registration.clone(
            "3b-Apply_ANTs_Registration_RD")

        thres_map = npe.Node(fsl.Threshold(thresh=0.0),
                             iterfield=["in_file"],
                             name="RemoveNegative")
        thres_norm_fa = thres_map.clone("3c-RemoveNegative_FA")
        thres_norm_md = thres_map.clone("3c-RemoveNegative_MD")
        thres_norm_ad = thres_map.clone("3c-RemoveNegative_AD")
        thres_norm_rd = thres_map.clone("3c-RemoveNegative_RD")

        scalar_analysis = npe.Node(
            interface=nutil.Function(
                input_names=["in_registered_map", "name_map", "prefix_file"],
                output_names=["atlas_statistics_list"],
                function=statistics_on_atlases,
            ),
            name="4-Scalar_Analysis",
        )
        scalar_analysis_fa = scalar_analysis.clone("4-Scalar_Analysis_FA")
        scalar_analysis_fa.inputs.name_map = "FA"
        scalar_analysis_md = scalar_analysis.clone("4-Scalar_Analysis_MD")
        scalar_analysis_md.inputs.name_map = "MD"
        scalar_analysis_ad = scalar_analysis.clone("4-Scalar_Analysis_AD")
        scalar_analysis_ad.inputs.name_map = "AD"
        scalar_analysis_rd = scalar_analysis.clone("4-Scalar_Analysis_RD")
        scalar_analysis_rd.inputs.name_map = "RD"

        thres_map = npe.Node(fsl.Threshold(thresh=0.0),
                             iterfield=["in_file"],
                             name="5-Remove_Negative")
        thres_fa = thres_map.clone("5-Remove_Negative_FA")
        thres_md = thres_map.clone("5-Remove_Negative_MD")
        thres_ad = thres_map.clone("5-Remove_Negative_AD")
        thres_rd = thres_map.clone("5-Remove_Negative_RD")
        thres_decfa = thres_map.clone("5-Remove_Negative_DECFA")

        print_begin_message = npe.Node(
            interface=nutil.Function(input_names=["in_bids_or_caps_file"],
                                     function=print_begin_pipeline),
            name="Write-Begin_Message",
        )

        print_end_message = npe.Node(
            interface=nutil.Function(
                input_names=[
                    "in_bids_or_caps_file", "final_file_1", "final_file_2"
                ],
                function=print_end_pipeline,
            ),
            name="Write-End_Message",
        )

        # Connection
        # ==========
        # fmt: off
        self.connect([
            (self.input_node, get_caps_filenames, [("preproc_dwi",
                                                    "caps_dwi_filename")]),
            # Print begin message
            (self.input_node, print_begin_message, [("preproc_dwi",
                                                     "in_bids_or_caps_file")]),
            # Get BIDS/CAPS identifier from filename
            (self.input_node, get_bids_identifier, [("preproc_dwi",
                                                     "caps_dwi_filename")]),
            # Convert FSL gradient files (bval/bvec) to MRtrix format
            (self.input_node, convert_gradients,
             [("preproc_bval", "bval_file"), ("preproc_bvec", "bvec_file")]),
            # Computation of the DTI model
            (self.input_node, dwi_to_dti, [("b0_mask", "mask"),
                                           ("preproc_dwi", "in_file")]),
            (convert_gradients, dwi_to_dti, [("encoding_file", "encoding_file")
                                             ]),
            (get_caps_filenames, dwi_to_dti, [("out_dti", "out_filename")]),
            # Computation of the different metrics from the DTI
            (get_caps_filenames, dti_to_metrics, [("out_fa", "out_fa")]),
            (get_caps_filenames, dti_to_metrics, [("out_md", "out_adc")]),
            (get_caps_filenames, dti_to_metrics, [("out_ad", "out_ad")]),
            (get_caps_filenames, dti_to_metrics, [("out_rd", "out_rd")]),
            (get_caps_filenames, dti_to_metrics, [("out_evec", "out_evec")]),
            (self.input_node, dti_to_metrics, [("b0_mask", "in_mask")]),
            (dwi_to_dti, dti_to_metrics, [("tensor", "in_file")]),
            # Registration of FA-map onto the atlas:
            (dti_to_metrics, register_fa, [("out_fa", "moving_image")]),
            # Apply deformation field on MD, AD & RD:
            (register_fa, ants_transforms, [("out_matrix",
                                             "in_affine_transformation")]),
            (register_fa, ants_transforms, [("forward_warp_field",
                                             "in_bspline_transformation")]),
            (dti_to_metrics, apply_ants_registration_for_md,
             [("out_adc", "input_image")]),
            (ants_transforms, apply_ants_registration_for_md,
             [("transforms", "transforms")]),
            (dti_to_metrics, apply_ants_registration_for_ad,
             [("out_ad", "input_image")]),
            (ants_transforms, apply_ants_registration_for_ad,
             [("transforms", "transforms")]),
            (dti_to_metrics, apply_ants_registration_for_rd,
             [("out_rd", "input_image")]),
            (ants_transforms, apply_ants_registration_for_rd,
             [("transforms", "transforms")]),
            # Remove negative values from the DTI maps:
            (register_fa, thres_norm_fa, [("warped_image", "in_file")]),
            (apply_ants_registration_for_md, thres_norm_md, [("output_image",
                                                              "in_file")]),
            (apply_ants_registration_for_rd, thres_norm_rd, [("output_image",
                                                              "in_file")]),
            (apply_ants_registration_for_ad, thres_norm_ad, [("output_image",
                                                              "in_file")]),
            # Generate regional TSV files
            (get_bids_identifier, scalar_analysis_fa, [("bids_identifier",
                                                        "prefix_file")]),
            (thres_norm_fa, scalar_analysis_fa, [("out_file",
                                                  "in_registered_map")]),
            (get_bids_identifier, scalar_analysis_md, [("bids_identifier",
                                                        "prefix_file")]),
            (thres_norm_md, scalar_analysis_md, [("out_file",
                                                  "in_registered_map")]),
            (get_bids_identifier, scalar_analysis_ad, [("bids_identifier",
                                                        "prefix_file")]),
            (thres_norm_ad, scalar_analysis_ad, [("out_file",
                                                  "in_registered_map")]),
            (get_bids_identifier, scalar_analysis_rd, [("bids_identifier",
                                                        "prefix_file")]),
            (thres_norm_rd, scalar_analysis_rd, [("out_file",
                                                  "in_registered_map")]),
            # Remove negative values from the DTI maps:
            (get_caps_filenames, thres_fa, [("out_fa", "out_file")]),
            (dti_to_metrics, thres_fa, [("out_fa", "in_file")]),
            (get_caps_filenames, thres_md, [("out_md", "out_file")]),
            (dti_to_metrics, thres_md, [("out_adc", "in_file")]),
            (get_caps_filenames, thres_ad, [("out_ad", "out_file")]),
            (dti_to_metrics, thres_ad, [("out_ad", "in_file")]),
            (get_caps_filenames, thres_rd, [("out_rd", "out_file")]),
            (dti_to_metrics, thres_rd, [("out_rd", "in_file")]),
            (get_caps_filenames, thres_decfa, [("out_evec", "out_file")]),
            (dti_to_metrics, thres_decfa, [("out_evec", "in_file")]),
            # Outputnode
            (dwi_to_dti, self.output_node, [("tensor", "dti")]),
            (thres_fa, self.output_node, [("out_file", "fa")]),
            (thres_md, self.output_node, [("out_file", "md")]),
            (thres_ad, self.output_node, [("out_file", "ad")]),
            (thres_rd, self.output_node, [("out_file", "rd")]),
            (thres_decfa, self.output_node, [("out_file", "decfa")]),
            (register_fa, self.output_node, [("out_matrix", "affine_matrix")]),
            (register_fa, self.output_node, [("forward_warp_field",
                                              "b_spline_transform")]),
            (thres_norm_fa, self.output_node, [("out_file", "registered_fa")]),
            (thres_norm_md, self.output_node, [("out_file", "registered_md")]),
            (thres_norm_ad, self.output_node, [("out_file", "registered_ad")]),
            (thres_norm_rd, self.output_node, [("out_file", "registered_rd")]),
            (scalar_analysis_fa, self.output_node, [("atlas_statistics_list",
                                                     "statistics_fa")]),
            (scalar_analysis_md, self.output_node, [("atlas_statistics_list",
                                                     "statistics_md")]),
            (scalar_analysis_ad, self.output_node, [("atlas_statistics_list",
                                                     "statistics_ad")]),
            (scalar_analysis_rd, self.output_node, [("atlas_statistics_list",
                                                     "statistics_rd")]),
            # Print end message
            (self.input_node, print_end_message, [("preproc_dwi",
                                                   "in_bids_or_caps_file")]),
            (thres_rd, print_end_message, [("out_file", "final_file_1")]),
            (scalar_analysis_rd, print_end_message, [("atlas_statistics_list",
                                                      "final_file_2")]),
        ])
from nipype import Workflow, Node
from nipype.interfaces.utility import IdentityInterface
from nipype.interfaces.ants import (RegistrationSynQuick)
experiment_dir = '/home/luiscp/Documents/Data/ADRC_90Plus/output'
output_dir = 'seg_analysis'

subject_list = [
    '233', '234', '235', '236', '237', '238', '239', '240', '242', '243',
    '244', '245', '246', '248', '249', '250', '251', '253', '254', '256',
    '257', '259'
]
#subject_list = ['259']
###############################
#specify nodes
###############################
reg = Node(RegistrationSynQuick(dimension=3, transform_type=u's'), name="reg")

###############################
#specify input output
###############################
# Infosource - a function free node to iterate over the list of subject names
infosource = Node(IdentityInterface(fields=['subject_id']), name="infosource")
infosource.iterables = [('subject_id', subject_list)]

dwi_file = opj('dwi_analysis', 'preproc', 'sub_{subject_id}',
               'data_brain.nii.gz')
t1_file = opj('seg_analysis', 'preproc', 'sub_{subject_id}', 'brain.nii.gz')

templates = {'dwi': dwi_file, 't1': t1_file}

selectfiles = Node(SelectFiles(
Esempio n. 8
0
"""Test a quicker registration of option from the ANTs interface.
"""
from nipype.interfaces.ants import RegistrationSynQuick

#Get template path per your system
from nipype.interfaces.fsl import Info
template_path = Info.standard_image('MNI152_T1_1mm_brain.nii.gz')

reg = RegistrationSynQuick()
reg.inputs.fixed_image = template_path
reg.inputs.moving_image = 'test-data/haxby2001/subj2/anat.nii.gz'
reg.inputs.num_threads = 2
reg.cmdline

%timeit reg.run()  
                                             '-endfor ' +
                                             '-merge', 
                                     out_files = 'UMC_SEG_resliced_labels.nii.gz'),
                            name='UMC_reslice_labels_SEG_n', iterfield=['in_file', 'ref_in_file']) 

# Image used to reslice
wf.connect([(UMC_reslice_TSE_n, UMC_reslice_labels_SEG_n, [('out_files','in_file')])])
# Image to be resliced, NOTE ref_in_file needs to be added in the c3 interface!
wf.connect([(selectfiles, UMC_reslice_labels_SEG_n, [('umc_seg_native','ref_in_file')])])


############    
## Step 4 ##
############
# ANTS is used to register the umc_MPRAGE to the umc_TSE_native
UMC_register_MPRAGE_to_UMC_TSE_native_n = MapNode(RegistrationSynQuick(transform_type = 'a'),
                     	name='UMC_register_MPRAGE_to_UMC_TSE_native_n', iterfield=['fixed_image', 'moving_image'])

wf.connect([(selectfiles, UMC_register_MPRAGE_to_UMC_TSE_native_n, [('umc_tse_native', 'fixed_image'),
                                                                    ('umc_mprage_chunk', 'moving_image')])])


############
## Step 5 ##
############
# Reslice UMC_MPRAGE after registration
UMC_reslice_MPRAGE_n =  MapNode(C3d(interp = "Sinc", pix_type = 'float', args = '-reslice-identity', out_files = 'UMC_MPRAGE_resliced.nii.gz'),
                             name='UMC_reslice_MPRAGE_n', iterfield =['in_file', 'opt_in_file'])

# Reslicing image
wf.connect([(UMC_reslice_TSE_n, UMC_reslice_MPRAGE_n, [('out_files','in_file')])])
Esempio n. 10
0
#FULL_SUBJECT_LIST = ['107220', '109123', '111716', '113821', '116120', '120212', '123117', '124826', '562446', '567961', '613235', '733548', '745555', 'addlInfo', '113417', '111312', '112819', '113619', '128127', '129028', '145531', '159845', '203721', '486759', '567052', '571548', '953764', '108828', '111514', '114924', '115320', '120111', '126931', '128329', '129432', '131621', '143527', '165234', '169141', '221218', '552544', '782157', '186949', '822244', '107321', '108121', '114419', '126325', '126628', '127630', '128632', '168038', '317332', '611231', '662551', '171128', '623137', '122620', '142424', '201717', '121315', '190132', '521331', '355542', '109325', '734247', '129533', '123420', '113215', '118528', '116524', '120515', '127933', '355845', 'addlInfoV2', '117728', '239136', '108323', '119833', '580751', '106319', '485757', '570243', '197449', '650746', '121618', '689470', '584355', '124220', '171734', '579665', '107422', '150423', '108525', '565452', '111413', '492754', '568963', '579867', '122317', '121820', '207628', '113922', '559053', '209531', '121719', '106521', '110411']
"""
Setup for Registration  Pipeline InfoSource i.e. subjects
"""
subj_infosource = pe.Node(
    interface=util.IdentityInterface(fields=['subject_id']),
    name="subj_infosource")
#infosource.iterables = ('subject_id', SampleSubjList)
subj_infosource.iterables = ('subject_id', FULL_SUBJECT_LIST[:10])
### Above just converts the list of subjects into an iterable list I can connect to the next part of the pipeline

#roi = "/data/HCP_Data/EHECHT_ROIS/Human_Hypothalamus_Left.nii.gz"
roiList = glob.glob(mountPoint + "/EHECHT_ROIS/Human_*nii.gz")

#### RIGID BODY REGISTRATION OF DTI -- >  Struct Brain    using RegSynQuick
regDtiToStruct = pe.Node(RegistrationSynQuick(num_threads=4,
                                              output_prefix="dtiToStruct"),
                         name='regDtiToStruct')

regStructToMni = pe.Node(RegistrationSynQuick(num_threads=5,
                                              fixed_image=MNI_template,
                                              output_prefix="structToMni"),
                         name='regStructToMNI')

warpROIsMniToDti = pe.Node(nipype.interfaces.ants.ApplyTransforms(
    invert_transform_flags=[True, False, True, False],
    interpolation='NearestNeighbor',
),
                           iterfield=['input_image'],
                           name="warpROIsMniToDti")
warpROIsMniToDti.iterables = ('input_image', roiList)
Esempio n. 11
0
coreg_fsl = Node(FLIRT(cost_func='bbr',
                        output_type='NIFTI', 
                        uses_qform=True), 
                    name="coreg_fsl") # iterfield=['in_file']) # Example of turning a variable into an iterfield.

FLIRT_anat2func = Node(FLIRT(cost_func='bbr',
                            output_type='NIFTI', 
                            uses_qform=True), 
                        name="FLIRT_anat2func")

FLIRT_func2anat = Node(FLIRT(cost_func='bbr', 
                            output_type='NIFTI', 
                            uses_qform=True), 
                        name="FLIRT_func2anat")

coreg_ANTs_SyNQuick = Node(RegistrationSynQuick(num_threads=2, 
                                                transform_type='a'), 
                            name="coreg_ANTs_SyNQuick") # Spelling error in documentation.

# Gunzip Files
gunzip = MapNode(Gunzip(), 
                name="gzip", 
                iterfield=['in_file'])

# ComputeRMSE
rmse = Node(interface=Function(input_names=['in_mat','out_mat'], 
                                output_names=['out_file'],
                                function=compute_rmse), 
              name="rmse")

# ComputeVals
vals = Node(interface=Function(input_names=['in_mat','out_mat'], 
Esempio n. 12
0
def fit_population_map(vb_image,
                       nb_image,
                       nb_name,
                       output_prefix,
                       name='ants',
                       j=4,
                       transform_type='s',
                       verbose=True):
    """
    Fits a diffeomorphism ψ from `vb` (the domain of ψ) to `nb` (the
    image of ψ) using the images `vb_image` and `nb_image` as references
    in `vb` and `nb` respectively.

    Parameters
    ----------
    vb_image : Image
        Template in the domain (the »Vorbereich«)
    nb_image : Image
        Template in the image (the »Nachbereich«)
    output_prefix : str
        String that will be used as a prefix for temporary files created
        by ANTS.
    j : int
        Number of threads to use.
    name : str
        Give a name to the diffeomorphism.
    """

    dfile = os.path.dirname(output_prefix)
    if dfile and not isdir(dfile):
        os.makedirs(dfile)

    vb_file = output_prefix + 'vb.nii.gz'
    nb_file = output_prefix + 'nb.nii.gz'

    ni.save(image2nii(vb_image), vb_file)
    ni.save(image2nii(nb_image), nb_file)

    reg = RegistrationSynQuick()
    reg.inputs.fixed_image = vb_file
    reg.inputs.moving_image = nb_file
    reg.inputs.num_threads = j
    reg.inputs.output_prefix = output_prefix

    reg.inputs.transform_type = transform_type

    if verbose:
        print()
        print(reg.cmdline)

    reg.run()

    vb_coord = output_prefix + 'vb-coordinates.csv'
    nb_coord = output_prefix + 'nb-coordinates.csv'

    vb_grid = vb_image.coordinates()
    vb_grid[..., :2] = -vb_grid[..., :2]
    vb_grid = vb_grid.reshape(-1, 3)

    np.savetxt(vb_coord,
               X=vb_grid,
               delimiter=',',
               fmt='%.2f',
               header='x,y,z',
               comments='')

    transM = output_prefix + '0GenericAffine.mat'
    transW = output_prefix + '1Warp.nii.gz'
    transWI = output_prefix + '1InverseWarp.nii.gz'

    at = ApplyTransformsToPoints()
    at.inputs.dimension = 3
    at.inputs.input_file = vb_coord
    at.inputs.transforms = [transW, transM]
    at.inputs.invert_transform_flags = [False, False]
    at.inputs.output_file = nb_coord

    if verbose:
        print()
        print(at.cmdline)

    at.run()

    coordinates = np.loadtxt(nb_coord, delimiter=',', skiprows=1)
    coordinates = coordinates.reshape(vb_image.shape + (3, ))
    coordinates[..., :2] = -coordinates[..., :2]

    diffeomorphism = Warp(reference=vb_image.reference,
                          warp=coordinates,
                          vb=vb_image.name,
                          nb=nb_name,
                          name=name,
                          metadata={
                              'vb_file': vb_file,
                              'nb_file': nb_file,
                              'transW': transW,
                              'transM': transM,
                              'RegistrationSyNQuick': reg.cmdline,
                              'ApplyTransformsToPoints': at.cmdline
                          })

    try:
        vb_estimate_file = output_prefix + 'Warped.nii.gz'
        vb_estimate = nii2image(ni.load(vb_estimate_file),
                                name='vb_estimate_ants')
    except Exception as e:
        print('Unable to read: {}, {}'.format(vb_estimate_file, e))

    try:
        nb_estimate_file = output_prefix + 'InverseWarped.nii.gz'
        nb_estimate = nii2image(ni.load(nb_estimate_file),
                                name='nb_estimate_ants')
    except Exception as e:
        print('Unable to read: {}, {}'.format(nb_estimate_file, e))

    return PopulationMap(diffeomorphism,
                         vb=vb_image,
                         nb=nb_image,
                         vb_estimate=vb_estimate,
                         nb_estimate=nb_estimate)
                         name='MAG_register_MPRAGE_to_MAG_native_n', iterfield=['moving_image','fixed_image'])

wf.connect([(selectfiles, MAG_register_MPRAGE_to_MAG_native_n, [('mag_mprage_chunk','moving_image')])])
wf.connect([(selectfiles, MAG_register_MPRAGE_to_MAG_native_n, [('mag_tse_native','fixed_image')])])
'''

############
## Step 2 ##
############
# Register MAG_TSE_whole ---> UMC_TSE_whole
# NOTE! THIS IS THE ONLY PLACE WHERE WE ARE OUTPUTTING A WHOLE IMAGE!
# We register the TSEs of the magdeberg dataset to the template of the UMC dataset rigidly.
# The template is in the github repo cause we had to make it first

MAG_register_TSE_whole_to_UMC_TSE_whole_n = MapNode(
    RegistrationSynQuick(transform_type='r', use_histogram_matching=True),
    name='MAG_register_TSE_whole_to_UMC_TSE_whole_n',
    iterfield=['moving_image'])
wf.connect([(selecttemplates, MAG_register_TSE_whole_to_UMC_TSE_whole_n,
             [('umc_tse_whole_template', 'fixed_image')])])
wf.connect([(selectfiles, MAG_register_TSE_whole_to_UMC_TSE_whole_n,
             [('mag_tse_whole', 'moving_image')])])

#############
## Step 3a ##
#############
# The mag data needs to have the same treatment as the umc data now.
# First, take the transformation that we just computed and apply it to the mag_tse_native_chunk

MAG_apply_transform_TSE_n = MapNode(
    ApplyTransforms(dimension=3,