예제 #1
0
def mask2subjspace_real(mnimask, anat, pe, mni2anat_hd5, affine_matrix, workdir):
    """
    Simulate data based on transformation matrices already obtained
    from analysis of real data.
    (This is the same as mask2pe_ants in extract_pe.py for extracting parameter estimates).
    """

    """
    paths for temporary files and output file
    """

    # temporary nifti file
    mni2anat_out_name = join(workdir, 'mnimask2anat.nii.gz')
    # inverse affine transform
    affine_matrix_inverse = join(workdir, 'anat2pe.txt')
    # path to output file
    outfile = join(workdir, 'mask2pe.nii.gz')

    """
    Invert affine and apply both transforms
    """

    # invert affine transmatrix (output from glm analysis)
    inverse = ConvertXFM(
        in_file=affine_matrix,
        out_file=affine_matrix_inverse,
        invert_xfm=True)
    inverse.run()

    # apply inverse transform from mni to anat space
    # (output from glm analysis)
    mni2anat = ants.ApplyTransforms(
        input_image=mnimask,
        reference_image=anat,
        output_image=mni2anat_out_name,
        transforms=[mni2anat_hd5],
        dimension=3, interpolation='NearestNeighbor',
        terminal_output='file')
    mni2anat.run()

    # apply inverse affine transform from anat to pe estimate space
    mni2pe = fsl.FLIRT(
        interp='nearestneighbour',
        apply_xfm=True,
        in_matrix_file=affine_matrix_inverse,
        out_matrix_file=join(workdir, 'anat2pe_flirt.mat'),
        # the above output matrix is redundant. But if we don't specify,
        # it just gets stored next to the script (and overwritten when
        # iterating over subjects!). We want it tidy.
        in_file=mni2anat_out_name,
        reference=pe,
        out_file=outfile)
    mni2pe.run()

    # return path to projected mask
    return outfile
예제 #2
0
def mask2pe(
        pe,
        anat,
        mnimask,
        workdir,
        standard='/usr/share/fsl/5.0/data/standard/MNI152_T1_2mm_brain.nii.gz'
):
    """
    Compute new 2-step projection for a masn from mni to 3D parameter space (and apply it).
    """

    # create transformation matrix from mni to anatomical
    mni2anat = fsl.FLIRT(dof=12,
                         interp='trilinear',
                         in_file=standard,
                         reference=anat,
                         out_file=join(workdir, 'mni2anat.nii.gz'),
                         out_matrix_file=join(workdir, 'mni2anat.txt'))
    mni2anat.run()

    # anat to parameter estimate map (3D statistical volume)
    anat2pe = fsl.FLIRT(dof=6,
                        interp='trilinear',
                        in_file=anat,
                        reference=pe,
                        out_file=join(workdir, 'anat2pe.nii.gz'),
                        out_matrix_file=join(workdir, 'anat2pe.txt'))
    anat2pe.run()

    # concatinate matrices
    concat = ConvertXFM(concat_xfm=True,
                        in_file2=join(workdir, 'mni2anat.txt'),
                        in_file=join(workdir, 'anat2pe.txt'),
                        out_file=join(workdir, 'mni2pe.txt'))
    concat.run()

    # set path to output file
    outfile = join(workdir, 'mask2pe.nii.gz')

    # apply transformation to mask image
    mni2pe = fsl.FLIRT(interp='nearestneighbour',
                       apply_xfm=True,
                       in_matrix_file=join(workdir, 'mni2pe.txt'),
                       out_matrix_file=join(workdir, 'mask2pe.txt'),
                       in_file=mnimask,
                       reference=pe,
                       out_file=outfile)
    mni2pe.run()

    # return path to transformed result
    return outfile
예제 #3
0
파일: shambrain.py 프로젝트: shamit/shamit
def mni2bold(bold, anat, standard, mask, workdir):
    """
    Use fsl.FLIRT to transform a mask from MNI to subject space
    """

    os.makedirs(workdir)

    # bold to anat
    bold2anat = fsl.FLIRT(dof=6,
                          no_clamp=True,
                          in_file=bold,
                          reference=anat,
                          out_matrix_file=join(workdir, 'bold2anat.txt'),
                          out_file=join(workdir, 'bold2anat.nii.gz'))
    bold2anat.run()

    # anat to mni
    anat2mni = fsl.FLIRT(dof=12,
                         in_file=anat,
                         reference=standard,
                         out_matrix_file=join(workdir, 'anat2mni.txt'),
                         out_file=join(workdir, sub, run,
                                       '%s_%s_anat2mni.nii.gz' % (sub, run)))
    anat2mni.run()

    # concatinate matrices
    concat = ConvertXFM(concat_xfm=True,
                        in_file2=join(workdir, sub, run,
                                      '%s_%s_bold2anat.txt' % (sub, run)),
                        in_file=join(workdir, sub, run,
                                     '%s_%s_anat2mni.txt' % (sub, run)),
                        out_file=join(workdir, sub, run,
                                      '%s_%s_bold2mni.txt' % (sub, run)))
    concat.run()

    # inverse transmatrix
    inverse = ConvertXFM(in_file=join(workdir, sub, run,
                                      '%s_%s_bold2mni.txt' % (sub, run)),
                         out_file=join(workdir, sub, run,
                                       '%s_%s_mni2bold.txt' % (sub, run)),
                         invert_xfm=True)
    inverse.run()

    # apply to mask
    mni2bold = fsl.FLIRT(
        interp='nearestneighbour',
        apply_xfm=True,
        in_matrix_file=join(workdir, sub, run,
                            '%s_%s_mni2bold.txt' % (sub, run)),
        in_file=join(mask),
        reference=join(data_basedir, sub, 'BOLD', run, 'bold.nii.gz'),
        out_file=join(workdir, sub, run, '%s_%s_roimask.nii.gz' % (sub, run)))
    mni2bold.run()

    mask_subjspace = join(workdir, sub, run,
                          '%s_%s_roimask.nii.gz' % (sub, run))

    # return path of created mask
    return mask_subjspace
예제 #4
0
def mask2subjspace(sub, run, data_basedir, workdir, mask):
    """
    Use fsl.FLIRT to transform roi mask from MNI to subject space
    (without brain extraction).
    """
    from nipype.interfaces import fsl
    from nipype.interfaces.fsl.utils import ConvertXFM
    from os.path import join
    import os

    os.makedirs(join(workdir, sub, run))

    # bold to anat
    bold2anat = fsl.FLIRT(
        dof=6, no_clamp=True,
        in_file=join(data_basedir, sub, 'BOLD', run, 'bold.nii.gz'),
        reference=join(data_basedir, sub, 'anatomy', 'highres001.nii.gz'),
        out_matrix_file=join(workdir, sub, run, '%s_%s_bold2anat.txt' % (sub, run)),
        out_file=join(workdir, sub, run, '%s_%s_bold2anat.nii.gz' % (sub, run)))
    bold2anat.run()

    # anat to mni
    anat2mni = fsl.FLIRT(
        dof=12, interp='nearestneighbour',
        in_file=join(data_basedir, sub, 'anatomy', 'highres001.nii.gz'),
        reference='/usr/share/fsl/5.0//data/standard/MNI152_T1_2mm_brain.nii.gz',
        out_matrix_file=join(workdir, sub, run, '%s_%s_anat2mni.txt' % (sub, run)),
        out_file=join(workdir, sub, run, '%s_%s_anat2mni.nii.gz' % (sub, run)))
    anat2mni.run()

    # concatinate matrices
    concat = ConvertXFM(
        concat_xfm=True,
        in_file2=join(workdir, sub, run, '%s_%s_bold2anat.txt' % (sub, run)),
        in_file=join(workdir, sub, run, '%s_%s_anat2mni.txt' % (sub, run)),
        out_file=join(workdir, sub, run, '%s_%s_bold2mni.txt' % (sub, run)))
    concat.run()

    # inverse transmatrix
    inverse = ConvertXFM(
        in_file=join(workdir, sub, run, '%s_%s_bold2mni.txt' % (sub, run)),
        out_file=join(workdir, sub, run, '%s_%s_mni2bold.txt' % (sub, run)),
        invert_xfm=True)
    inverse.run()

    # apply to mask
    mni2bold = fsl.FLIRT(
        interp='nearestneighbour',
        apply_xfm=True,
        in_matrix_file=join(workdir, sub, run, '%s_%s_mni2bold.txt' % (sub, run)),
        in_file=join(mask),
        reference=join(data_basedir, sub, 'BOLD', run, 'bold.nii.gz'),
        out_file=join(workdir, sub, run, '%s_%s_roimask.nii.gz' % (sub, run)))
    mni2bold.run()

    mask_subjspace = join(workdir, sub, run, '%s_%s_roimask.nii.gz' % (sub, run))

    # return path of created mask
    return mask_subjspace
예제 #5
0
def test_ConvertXFM_outputs():
    output_map = dict(out_file=dict(), )
    outputs = ConvertXFM.output_spec()

    for key, metadata in output_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(outputs.traits()[key], metakey), value
예제 #6
0
def test_ConvertXFM_outputs():
    output_map = dict(out_file=dict(),
    )
    outputs = ConvertXFM.output_spec()

    for key, metadata in output_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(outputs.traits()[key], metakey), value
예제 #7
0
def test_ConvertXFM_inputs():
    input_map = dict(
        args=dict(argstr='%s', ),
        concat_xfm=dict(
            argstr='-concat',
            position=-3,
            requires=['in_file2'],
            xor=['invert_xfm', 'concat_xfm', 'fix_scale_skew'],
        ),
        environ=dict(
            nohash=True,
            usedefault=True,
        ),
        fix_scale_skew=dict(
            argstr='-fixscaleskew',
            position=-3,
            requires=['in_file2'],
            xor=['invert_xfm', 'concat_xfm', 'fix_scale_skew'],
        ),
        ignore_exception=dict(
            nohash=True,
            usedefault=True,
        ),
        in_file=dict(
            argstr='%s',
            mandatory=True,
            position=-1,
        ),
        in_file2=dict(
            argstr='%s',
            position=-2,
        ),
        invert_xfm=dict(
            argstr='-inverse',
            position=-3,
            xor=['invert_xfm', 'concat_xfm', 'fix_scale_skew'],
        ),
        out_file=dict(
            argstr='-omat %s',
            genfile=True,
            hash_files=False,
            position=1,
        ),
        output_type=dict(),
        terminal_output=dict(
            mandatory=True,
            nohash=True,
        ),
    )
    inputs = ConvertXFM.input_spec()

    for key, metadata in input_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(inputs.traits()[key], metakey), value
예제 #8
0
def test_ConvertXFM_inputs():
    input_map = dict(args=dict(argstr='%s',
    ),
    concat_xfm=dict(argstr='-concat',
    position=-3,
    requires=['in_file2'],
    xor=['invert_xfm', 'concat_xfm', 'fix_scale_skew'],
    ),
    environ=dict(nohash=True,
    usedefault=True,
    ),
    fix_scale_skew=dict(argstr='-fixscaleskew',
    position=-3,
    requires=['in_file2'],
    xor=['invert_xfm', 'concat_xfm', 'fix_scale_skew'],
    ),
    ignore_exception=dict(nohash=True,
    usedefault=True,
    ),
    in_file=dict(argstr='%s',
    mandatory=True,
    position=-1,
    ),
    in_file2=dict(argstr='%s',
    position=-2,
    ),
    invert_xfm=dict(argstr='-inverse',
    position=-3,
    xor=['invert_xfm', 'concat_xfm', 'fix_scale_skew'],
    ),
    out_file=dict(argstr='-omat %s',
    genfile=True,
    hash_files=False,
    position=1,
    ),
    output_type=dict(),
    terminal_output=dict(mandatory=True,
    nohash=True,
    ),
    )
    inputs = ConvertXFM.input_spec()

    for key, metadata in input_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(inputs.traits()[key], metakey), value
예제 #9
0
def mask2bold(
        bold,
        anat,
        roi_mask,
        workdir,
        standard='/usr/share/fsl/5.0/data/standard/MNI152_T1_2mm_brain.nii.gz'
):
    """
    Project a mask image to individual subject space. anatomical image must
    be defined for registration. workdir is needed to dump temporary files
    created by fsl. output is a nifti image.
    """

    from os.path import join
    import os

    # create workdir
    if not os.path.exists(workdir):
        print('working directory did not exist and is created now.')
        os.makedirs(workdir)

    # produce matrix for bold2anat
    bold2anat = fsl.FLIRT(dof=6,
                          interp='trilinear',
                          in_file=bold,
                          reference=anat,
                          out_file=join(workdir, 'bold2anat.nii.gz'),
                          out_matrix_file=join(workdir, 'bold2anat.txt'))
    bold2anat.run()

    # anat to mni
    anat2mni = fsl.FLIRT(dof=12,
                         interp='trilinear',
                         in_file=anat,
                         reference=standard,
                         out_file=join(workdir, 'anat2mni.nii.gz'),
                         out_matrix_file=join(workdir, 'anat2mni.txt'))
    anat2mni.run()

    # concatinate matrices
    concat = ConvertXFM(concat_xfm=True,
                        in_file2=join(workdir, 'bold2anat.txt'),
                        in_file=join(workdir, 'anat2mni.txt'),
                        out_file=join(workdir, 'bold2mni.txt'))
    concat.run()

    # inverse transmatrix
    inverse = ConvertXFM(in_file=join(workdir, 'bold2mni.txt'),
                         out_file=join(workdir, 'mni2bold.txt'),
                         invert_xfm=True)
    inverse.run()

    # apply to mask
    mni2bold = fsl.FLIRT(interp='nearestneighbour',
                         apply_xfm=True,
                         in_matrix_file=join(workdir, 'mni2bold.txt'),
                         out_matrix_file=join(workdir, 'roimask.txt'),
                         in_file=roi_mask,
                         reference=bold,
                         out_file=join(workdir, 'roimask.nii.gz'))
    mni2bold.run()

    mask_subspace_path = join(workdir, 'roimask.nii.gz')

    # TODO: registration fails pretty much ...

    return mask_subspace_path
예제 #10
0
    def fix_preparation_pipeline(self, **kwargs):

        pipeline = self.create_pipeline(
            name='prepare_fix',
            inputs=[
                DatasetSpec('melodic_ica', directory_format),
                DatasetSpec('filtered_data', nifti_gz_format),
                DatasetSpec('coreg_to_atlas_mat', text_matrix_format),
                DatasetSpec('coreg_matrix', text_matrix_format),
                DatasetSpec('preproc', nifti_gz_format),
                DatasetSpec('brain', nifti_gz_format),
                DatasetSpec('coreg_ref_brain', nifti_gz_format),
                DatasetSpec('mc_par', par_format),
                DatasetSpec('brain_mask', nifti_gz_format)
            ],
            outputs=[
                DatasetSpec('fix_dir', directory_format),
                DatasetSpec('hand_label_noise', text_format)
            ],
            desc=("Pipeline to create the right folder structure before "
                  "running FIX"),
            version=1,
            citations=[fsl_cite],
            **kwargs)

        struct_ants2fsl = pipeline.create_node(ANTs2FSLMatrixConversion(),
                                               name='struct_ants2fsl',
                                               requirements=[c3d_req])
        struct_ants2fsl.inputs.ras2fsl = True
        struct_ants2fsl.inputs.reference_file = self.parameter('MNI_template')
        pipeline.connect_input('coreg_to_atlas_mat', struct_ants2fsl,
                               'itk_file')
        pipeline.connect_input('coreg_ref_brain', struct_ants2fsl,
                               'source_file')
        epi_ants2fsl = pipeline.create_node(ANTs2FSLMatrixConversion(),
                                            name='epi_ants2fsl',
                                            requirements=[c3d_req])
        epi_ants2fsl.inputs.ras2fsl = True
        pipeline.connect_input('brain', epi_ants2fsl, 'source_file')
        pipeline.connect_input('coreg_matrix', epi_ants2fsl, 'itk_file')
        pipeline.connect_input('coreg_ref_brain', epi_ants2fsl,
                               'reference_file')

        MNI2t1 = pipeline.create_node(ConvertXFM(),
                                      name='MNI2t1',
                                      wall_time=5,
                                      requirements=[fsl509_req])
        MNI2t1.inputs.invert_xfm = True
        pipeline.connect(struct_ants2fsl, 'fsl_matrix', MNI2t1, 'in_file')

        struct2epi = pipeline.create_node(ConvertXFM(),
                                          name='struct2epi',
                                          wall_time=5,
                                          requirements=[fsl509_req])
        struct2epi.inputs.invert_xfm = True
        pipeline.connect(epi_ants2fsl, 'fsl_matrix', struct2epi, 'in_file')

        meanfunc = pipeline.create_node(ImageMaths(op_string='-Tmean',
                                                   suffix='_mean'),
                                        name='meanfunc',
                                        wall_time=5,
                                        requirements=[fsl509_req])
        pipeline.connect_input('preproc', meanfunc, 'in_file')

        prep_fix = pipeline.create_node(PrepareFIX(), name='prep_fix')
        pipeline.connect_input('melodic_ica', prep_fix, 'melodic_dir')
        pipeline.connect_input('coreg_ref_brain', prep_fix, 't1_brain')
        pipeline.connect_input('mc_par', prep_fix, 'mc_par')
        pipeline.connect_input('brain_mask', prep_fix, 'epi_brain_mask')
        pipeline.connect_input('preproc', prep_fix, 'epi_preproc')
        pipeline.connect_input('filtered_data', prep_fix, 'filtered_epi')
        pipeline.connect(epi_ants2fsl, 'fsl_matrix', prep_fix, 'epi2t1_mat')
        pipeline.connect(struct_ants2fsl, 'fsl_matrix', prep_fix, 't12MNI_mat')
        pipeline.connect(MNI2t1, 'out_file', prep_fix, 'MNI2t1_mat')
        pipeline.connect(struct2epi, 'out_file', prep_fix, 't12epi_mat')
        pipeline.connect(meanfunc, 'out_file', prep_fix, 'epi_mean')

        pipeline.connect_output('fix_dir', prep_fix, 'fix_dir')
        pipeline.connect_output('hand_label_noise', prep_fix,
                                'hand_label_file')

        return pipeline
예제 #11
0
    def fix_preparation_pipeline(self, **name_maps):

        pipeline = self.new_pipeline(
            name='prepare_fix',
            desc=("Pipeline to create the right folder structure before "
                  "running FIX"),
            citations=[fsl_cite],
            name_maps=name_maps)

        if self.branch('coreg_to_tmpl_method', 'ants'):

            struct_ants2fsl = pipeline.add(
                'struct_ants2fsl',
                ANTs2FSLMatrixConversion(ras2fsl=True),
                inputs={
                    'reference_file': ('template_brain', nifti_gz_format),
                    'itk_file': ('coreg_to_tmpl_ants_mat', text_matrix_format),
                    'source_file': ('coreg_ref_brain', nifti_gz_format)
                },
                requirements=[c3d_req.v('1.0.0')])

            struct_matrix = (struct_ants2fsl, 'fsl_matrix')
        else:
            struct_matrix = ('coreg_to_tmpl_fsl_mat', text_matrix_format)


#         if self.branch('coreg_method', 'ants'):
#         epi_ants2fsl = pipeline.add(
#             'epi_ants2fsl',
#             ANTs2FSLMatrixConversion(
#                 ras2fsl=True),
#             inputs={
#                 'source_file': ('brain', nifti_gz_format),
#                 'itk_file': ('coreg_ants_mat', text_matrix_format),
#                 'reference_file': ('coreg_ref_brain', nifti_gz_format)},
#             requirements=[c3d_req.v('1.0.0')])

        MNI2t1 = pipeline.add('MNI2t1',
                              ConvertXFM(invert_xfm=True),
                              inputs={'in_file': struct_matrix},
                              wall_time=5,
                              requirements=[fsl_req.v('5.0.9')])

        struct2epi = pipeline.add(
            'struct2epi',
            ConvertXFM(invert_xfm=True),
            inputs={'in_file': ('coreg_fsl_mat', text_matrix_format)},
            wall_time=5,
            requirements=[fsl_req.v('5.0.9')])

        meanfunc = pipeline.add(
            'meanfunc',
            ImageMaths(op_string='-Tmean',
                       suffix='_mean',
                       output_type='NIFTI_GZ'),
            inputs={'in_file': ('series_preproc', nifti_gz_format)},
            wall_time=5,
            requirements=[fsl_req.v('5.0.9')])

        pipeline.add('prep_fix',
                     PrepareFIX(),
                     inputs={
                         'melodic_dir': ('melodic_ica', directory_format),
                         't1_brain': ('coreg_ref_brain', nifti_gz_format),
                         'mc_par': ('mc_par', par_format),
                         'epi_brain_mask': ('brain_mask', nifti_gz_format),
                         'epi_preproc': ('series_preproc', nifti_gz_format),
                         'filtered_epi': ('filtered_data', nifti_gz_format),
                         'epi2t1_mat': ('coreg_fsl_mat', text_matrix_format),
                         't12MNI_mat': (struct_ants2fsl, 'fsl_matrix'),
                         'MNI2t1_mat': (MNI2t1, 'out_file'),
                         't12epi_mat': (struct2epi, 'out_file'),
                         'epi_mean': (meanfunc, 'out_file')
                     },
                     outputs={
                         'fix_dir': ('fix_dir', directory_format),
                         'hand_label_noise': ('hand_label_file', text_format)
                     })

        return pipeline
예제 #12
0
def hybrid_rois_registration(base_dir,
                             subject_id,
                             visit_id,
                             output_dir,
                             csf_roi,
                             wm_roi,
                             template="MNI152_T1_2mm.nii.gz",
                             dof=6,
                             output_type="NIFTI"):
    """Function to register csf and wm roi from template to diffusion space and output the MEDIAN signal within the roi. Needed for hybrid Beltrami FW fitting
        Parameters
        ----------
        base_dir : absolute path pointing at the root directory of the bids repository
        subject_id: string, the tag subject (i.e. sub-sublabel) of the subject to treat
        visit_id: the VALUE of the session tag to be treated (i.e. for ses-02, only "02" need to be entered)
        output_dir: absolute path of the directories were the indexes will be written
        csf_roi: absolute path of the roi representative of the csf. It should be in the same space as "template" and binary
        wm_roi: absolute path of the roi representative of the wm. It should be in in the same space as "template" and binary
        template: name of the file with extension of the template to be used for inverse registation of the rois. 
        output_type: ["NIFTI", "NIFTI_GZ"], the type of nifti output desired,
        ... : other parameters related to the dipy functions used
        Returns
        ----------
        csf_mean, wm_mean: floats. The median csf and wm values from the registered ROIs
        
        """

    diff_dir = "{}/{}/ses-{}/dwi".format(base_dir, subject_id, visit_id)
    anat_dir = "{}/{}/ses-{}/anat".format(base_dir, subject_id, visit_id)
    if output_type == "NIFTI":
        ext = ".nii"
    elif output_type == "NIFTI_GZ":
        ext = ".nii.gz"
    else:
        raise ValueError(
            "Output file type {} not recognized".format(output_type))
    t1_file = glob("{}/*T1w.nii*".format(anat_dir))[0]
    t1_base_name = get_base_name_all_type(t1_file)
    diff_file = glob("{}/*dwi.nii*".format(diff_dir))[0]
    diff_base_name = get_base_name_all_type(diff_file)
    fsldir_system = subprocess.check_output("echo $FSLDIR", shell=True)
    if type(fsldir_system) == bytes:
        fsl_dir = fsldir_system.decode("utf-8").rstrip()
    else:
        fsl_dir = fsldir_system.rstrip()
    template_base_name = get_base_name_all_type(template)
    template_no_underscore = "x".join(template_base_name.split("_"))
    template_abs = "{}/data/standard/{}".format(fsl_dir, template)
    flirt = FLIRT()
    #T1 to template
    print("Registering T1 onto template")
    flirt.inputs.in_file = t1_file
    flirt.inputs.reference = template_abs
    flirt.inputs.out_file = "{}/{}_ref-{}_dof-12_reg-flirt{}".format(
        output_dir, t1_base_name, template_no_underscore, ext)
    flirt.inputs.out_matrix_file = "{}/{}_ref-{}_dof-12_reg-flirt.mat".format(
        output_dir, t1_base_name, template_no_underscore)
    flirt.inputs.output_type = output_type
    flirt.run()
    #diff to t1
    print("Registering diffusion onto T1")
    flirt.inputs.in_file = diff_file
    flirt.inputs.reference = t1_file
    flirt.inputs.dof = dof
    flirt.inputs.out_file = "{}/{}_ref-t1_dof-{}_reg-flirt{}".format(
        output_dir, diff_base_name, str(dof), ext)
    flirt.inputs.out_matrix_file = "{}/{}_ref-t1_dof-{}_reg-flirt.mat".format(
        output_dir, diff_base_name, str(dof))
    flirt.inputs.output_type = output_type
    flirt.run()
    #concat and inverse matrices
    print("Concat and inverse matrix, send rois to diff")
    mat_transform = ConvertXFM()
    #concat diff to t1 and t1 to template
    mat_transform.inputs.in_file = "{}/{}_ref-{}_dof-12_reg-flirt.mat".format(
        output_dir, t1_base_name, template_no_underscore)
    mat_transform.inputs.in_file2 = "{}/{}_ref-t1_dof-{}_reg-flirt.mat".format(
        output_dir, diff_base_name, str(dof))
    mat_transform.inputs.concat_xfm = True
    mat_transform.inputs.out_file = "{}/diff_to_{}.mat".format(
        output_dir, template_no_underscore)
    mat_transform.run()
    #inverse
    mat_transform = ConvertXFM()
    mat_transform.inputs.in_file = "{}/diff_to_{}.mat".format(
        output_dir, template_no_underscore)
    mat_transform.inputs.invert_xfm = True
    mat_transform.inputs.out_file = "{}/{}_to_diff.mat".format(
        output_dir, template_no_underscore)
    mat_transform.run()
    #send csf and wm roi to diff
    csf_roi_base_name = get_base_name_all_type(csf_roi)
    wm_roi_base_name = get_base_name_all_type(wm_roi)
    #csf
    flirt.inputs.in_file = csf_roi
    flirt.inputs.reference = diff_file
    flirt.inputs.apply_xfm = True
    flirt.inputs.in_matrix_file = "{}/{}_to_diff.mat".format(
        output_dir, template_no_underscore)
    flirt.inputs.interp = "nearestneighbour"
    flirt.inputs.output_type = output_type
    flirt.inputs.out_file = "{}/{}_in_diff{}".format(output_dir,
                                                     csf_roi_base_name, ext)
    flirt.run()
    #wm
    flirt.inputs.in_file = wm_roi
    flirt.inputs.reference = diff_file
    flirt.inputs.apply_xfm = True
    flirt.inputs.in_matrix_file = "{}/{}_to_diff.mat".format(
        output_dir, template_no_underscore)
    flirt.inputs.interp = "nearestneighbour"
    flirt.inputs.output_type = output_type
    flirt.inputs.out_file = "{}/{}_in_diff{}".format(output_dir,
                                                     wm_roi_base_name, ext)
    flirt.run()

    #extract values from roi
    csf_image = nb.load("{}/{}_in_diff{}".format(output_dir, csf_roi_base_name,
                                                 ext))
    csf_array = csf_image.get_fdata()
    csf_array_mask = np.where(csf_array == 1)
    wm_image = nb.load("{}/{}_in_diff{}".format(output_dir, wm_roi_base_name,
                                                ext))
    wm_array = wm_image.get_fdata()
    wm_array_mask = np.where(wm_array == 1)
    diff_image = nb.load(diff_file)
    b0_array = diff_image.get_fdata()[:, :, :, 0]
    csf_mean = np.median(b0_array[csf_array_mask])
    wm_mean = np.median(b0_array[wm_array_mask])
    return (csf_mean, wm_mean)
예제 #13
0
    def registration_pipeline(self, **kwargs):  # @UnusedVariable @IgnorePep8
        """
        Register T1 and T2 to the

        Parameters
        ----------
        """
        pipeline = self.create_pipeline(
            name='registration_pipeline',
            inputs=[
                DatasetSpec('ute_echo1', dicom_format),
                DatasetSpec('ute_echo2', dicom_format)
            ],
            outputs=[
                DatasetSpec('ute1_registered', nifti_format),
                DatasetSpec('ute2_registered', nifti_gz_format),
                DatasetSpec('template_to_ute_mat', text_matrix_format),
                DatasetSpec('ute_to_template_mat', text_matrix_format)
            ],
            desc="Register ute images to the template",
            version=1,
            citations=(fsl_cite),
            **kwargs)

        echo1_conv = pipeline.create_node(MRConvert(), name='echo1_conv')
        echo1_conv.inputs.out_ext = '.nii.gz'

        pipeline.connect_input('ute_echo1', echo1_conv, 'in_file')

        echo2_conv = pipeline.create_node(MRConvert(), name='echo2_conv')
        echo2_conv.inputs.out_ext = '.nii.gz'

        pipeline.connect_input('ute_echo2', echo2_conv, 'in_file')

        # Create registration node
        registration = pipeline.create_node(FLIRT(),
                                            name='ute1_registration',
                                            requirements=[fsl5_req],
                                            wall_time=180)

        pipeline.connect(echo1_conv, 'out_file', registration, 'in_file')

        registration.inputs.reference = self.template_path
        registration.inputs.output_type = 'NIFTI_GZ'
        registration.inputs.searchr_x = [-180, 180]
        registration.inputs.searchr_y = [-180, 180]
        registration.inputs.searchr_z = [-180, 180]
        registration.inputs.bins = 256
        registration.inputs.cost_func = 'corratio'

        # Inverse matrix conversion
        convert_mat = pipeline.create_node(ConvertXFM(),
                                           name='inverse_matrix_conversion',
                                           requirements=[fsl5_req],
                                           wall_time=10)
        pipeline.connect(registration, 'out_matrix_file', convert_mat,
                         'in_file')
        convert_mat.inputs.invert_xfm = True

        # UTE_echo_2 transformation
        transform_ute2 = pipeline.create_node(ApplyXFM(),
                                              name='transform_t2',
                                              requirements=[fsl5_req],
                                              wall_time=10)
        pipeline.connect(registration, 'out_matrix_file', transform_ute2,
                         'in_matrix_file')
        pipeline.connect(echo2_conv, 'out_file', transform_ute2, 'in_file')

        transform_ute2.inputs.output_type = 'NIFTI_GZ'
        transform_ute2.inputs.reference = self.template_path
        transform_ute2.inputs.apply_xfm = True

        # Connect outputs
        pipeline.connect_output('ute1_registered', registration, 'out_file')
        pipeline.connect_output('ute_to_template_mat', registration,
                                'out_matrix_file')
        pipeline.connect_output('ute2_registered', transform_ute2, 'out_file')
        pipeline.connect_output('template_to_ute_mat', convert_mat, 'out_file')
        pipeline.assert_connected()

        return pipeline