示例#1
0
def methods_02_stats(config, verbose=False):

    input_dir = config['dirs']['input']

    util.mkcd_dir([config['methods']['results']['dir']], True)

    command = [
        'fslmaths',
        os.path.join(config['dirs']['methods']['01-register'],
                     'nu_brain.nii.gz'), '-bin',
        os.path.join(config['dirs']['methods']['results'], 'brain_mask.nii.gz')
    ]

    util.iw_subprocess(command, verbose, verbose, False)

    for ii in ['swi', 'swi_magnitude', 'swi_phase']:

        command = [
            'fslmaths',
            os.path.join(config['dirs']['methods']['01-register'],
                         'swi_Affine_nu__' + ii + '.nii.gz'), '-mas',
            'brain_mask.nii.gz', ii + '.nii.gz'
        ]

        util.iw_subprocess(command, verbose, verbose, False)

    util.force_hard_link(
        os.path.join(config['methods']['input']['dir'], 'nu.nii.gz'),
        'nu.nii.gz')
    util.force_hard_link(
        os.path.join(config['methods']['input']['dir'], 'nu_brain.nii.gz'),
        'nu_brain.nii.gz')
示例#2
0
def transform_image(in_filename, out_filename, reference_filename,
                    in_transforms, interpolation_method, verbose_flag,
                    debug_flag):

    if type(in_filename) is list:
        filename = in_filename
    else:
        filename = [in_filename]

    if type(in_transforms) is list:
        transforms = in_transforms
    else:
        transforms = [in_transforms]

    input_files = filename + reference_filename + transforms

    if debug_flag:
        print('\n')
        print('!!! ctf.transform_image ')
        print(input_files)
        print('\n')

    util.verify_inputs(filename)

    cmd = [
        "antsApplyTransforms", "-d", "3", "-i", in_filename[0], "-o",
        out_filename[0], "-r", reference_filename[0], "-n",
        interpolation_method, "-t"
    ] + transforms

    util.iw_subprocess(cmd, debug_flag, debug_flag)
示例#3
0
def methods_02_lpa(input_dir, verbose):

    cenc_dirs = cenc.directories(input_dir)

    wm_lesions_dir = cenc_dirs['wmlesions']['dirs']['root']
    wm_lesions_lpa_dir = cenc_dirs['wmlesions']['dirs']['lpa']

    util.mkcd_dir([cenc_dirs['wmlesions']['dirs']['lpa']], True)

    util.copy_inputs([
        os.path.join(cenc_dirs['wmlesions']['dirs']['register'],
                     't2flair_Affine_nu__t2flair_Warped.nii.gz')
    ], cenc_dirs['wmlesions']['dirs']['lpa'])

    glob_files = glob.glob('*.gz')

    for ii in glob_files:
        os.system('gunzip ' + ii)
        os.chmod(str.replace(ii, '.gz', ''),
                 stat.S_IRUSR | stat.S_IRGRP | stat.S_IWUSR | stat.S_IWGRP)

    # Run Matlab

    command = ['cenc_wmlesions_run.sh', cenc_dirs['wmlesions']['dirs']['lpa']]
    util.iw_subprocess(command, verbose, verbose, False)

    os.chdir(cenc_dirs['wmlesions']['dirs']['lpa'])

    for ii in glob.glob('*.nii'):
        os.system('gzip ' + ii)
        os.chmod(str.replace(ii, '.nii', '.nii.gz'),
                 stat.S_IRUSR | stat.S_IRGRP | stat.S_IWUSR | stat.S_IWGRP)
示例#4
0
def methods( t1full, t2full, t2flair, options, verbose=False, debug=False, nohup=False):

     print('\nRunnning ants_lct.py\n')
          
     if  qa.qa_input_files( input_files, False):
          
          if not os.path.exists( out_directory ):
               os.makedirs( out_directory )

#  bash $0 -d 3 -e brainWithSkullTemplate.nii.gz -m brainPrior.nii.gz -p segmentationPriors%d.nii.gz -o output \${anatomicalImages[@]}
               
          callCommand = ['antsLongitudinalCorticalThickness.sh', '-d', '3', '-t', options['t_option'], '-w', '0.25',
                         '-e', options['e_option'], '-m', options['m_option'], '-f', options['f_option'], '-p', options['p_option'], 
                         '-o', options['o_option'], t1full 
                         ]
               


          callCommand = callCommand + [ '-a', t1full ] 
          
          if not t2full == None:
               callCommand = callCommand + [ '-a', t2full ] 
               
          if not inArgs.t2flair == None:
               callCommand = callCommand + [ '-a', t2flair ] 
               
          util.iw_subprocess( callCommand, verbose, debug,  nohup )
                    
     else:
          print('\nUnable to run iwAntsCT.py. Failed input QA.')
          qa.qa_exist( input_files, True )
          print('\n')
示例#5
0
def results(ants_ct_info, verbose=False):

    # Create results directory and populate

    util.mkcd_dir([ants_ct_info['base']['results']], True)

    files_to_link = [
        (ants_ct_info['segment']['p_wm'], ants_ct_info['results']['p_wm']),
        (ants_ct_info['segment']['segment'],
         ants_ct_info['results']['segment']),
        (ants_ct_info['register']['ct'], ants_ct_info['results']['ct']),
        (ants_ct_info['register']['subject_to_template_affine'],
         ants_ct_info['results']['subject_to_template_affine']),
        (ants_ct_info['register']['subject_to_template_warp'],
         ants_ct_info['results']['subject_to_template_warp']),
        (ants_ct_info['register']['subject_to_template_jacobian'],
         ants_ct_info['results']['subject_to_template_jacobian']),
        (ants_ct_info['register']['template_to_subject_affine'],
         ants_ct_info['results']['template_to_subject_affine']),
        (ants_ct_info['register']['template_to_subject_warp'],
         ants_ct_info['results']['template_to_subject_warp'])
    ]

    for ii in files_to_link:
        util.force_hard_link(ii[0], ii[1])

    fsl_command = [
        'fslmaths', ants_ct_info['segment']['p_gm_cortical'], '-add',
        ants_ct_info['segment']['p_gm_subcortical'],
        ants_ct_info['results']['p_gm']
    ]

    util.iw_subprocess(fsl_command)

    methods_write_json_redcap_ants_ct_instrument(ants_ct_info, verbose)
示例#6
0
def ants_apply_transform(input_file):

    # This simple command appears to work.
    command = [
        'antsApplyTransforms', '-d', '3', '-i', input_file + '.nii.gz', '-r',
        'nu.nii.gz', '-o', 'swi_Affine_nu__' + input_file + '.nii.gz', '-t',
        'swi_Affine_nu__swi_magnitude_0GenericAffine.mat'
    ]

    util.iw_subprocess(command, True, True, False)
示例#7
0
def ants_register(input_file):

    # This simple command appears to work.
    command = [
        'antsRegistrationSyNQuick.sh', '-d', '3', '-m', input_file + '.nii.gz',
        '-r', 'nu.nii.gz', '-f', 'nu.nii.gz', '-t', 'a', '-o',
        'swi_Affine_nu__' + input_file + '_'
    ]

    util.iw_subprocess(command, True, True, False)
示例#8
0
def recon_all(input_dir):

    cenc_dirs = cenc.directories(input_dir)

    freesurfer_command = [
        'recon-all', '-sd', cenc_dirs['cenc']['freesurfer_subjects_dir'],
        '-subjid', cenc_dirs['cenc']['id'], '-all', '-i', 't1w.nii.gz',
        '-qcache', '-measure', 'thickness', '-measure', 'curv', '-measure',
        'sulc', '-measure', 'area', '-measure', 'jacobian_white'
    ]

    util.iw_subprocess(freesurfer_command, True, True, True)

    return
示例#9
0
def transform_points(in_filename, out_filename, in_transforms, scale,
                     verbose_flag, debug_flag):

    if type(in_filename) is list:
        filename = in_filename
    else:
        filename = [in_filename]

    if type(in_transforms) is list:
        transforms = in_transforms
    else:
        transforms = [in_transforms]

    input_files = filename + transforms

    if debug_flag:
        print('\n')
        print('!!! ctf.transform_points ')
        print(input_files)
        print('\n')

    util.verify_inputs(filename)

    in_points = print_points_from_file(in_filename, verbose_flag)

    cmd = [
        "antsApplyTransformsToPoints", "-d", "3", "-i", in_filename, "-o",
        out_filename, "-t"
    ] + transforms

    util.iw_subprocess(cmd, debug_flag, debug_flag)

    # Perform scaling

    out_points = pd.read_csv(out_filename, sep=',', header=0)
    out_points = scale_points(out_points, scale, debug_flag)

    # Fix Comment Column
    out_points['label'] = in_points['label']
    out_points['comment'] = in_points['comment']

    #
    write_points(out_filename, out_points, verbose_flag)
示例#10
0
def methods_01_register(input_dir, verbose=False):

    # Register MT images to nu.nii.gz
    cenc_dirs = cenc.directories(input_dir)
    mt_link_inputs(input_dir, cenc_dirs['mt']['dirs']['register'])

    ants_register('mt_m0')
    ants_register('mt_m1')

    # Calculate MTR image
    command = [
        'ImageMath', 3, 'mtr.nii.gz', 'MTR',
        'mt_Affine_nu__mt_m0_Warped.nii.gz',
        'mt_Affine_nu__mt_m1_Warped.nii.gz', 'nu_brain.nii.gz'
    ]

    util.iw_subprocess(command, verbose, verbose, False)

    return
示例#11
0
def apply_affine_transform(in_filename,
                           out_filename,
                           transform,
                           inverse_flag=False,
                           verbose_flag=False):

    if isinstance(transform, basestring):
        transform = [transform]

    in_points = pd.read_csv(in_filename,
                            names=['x', 'y', 'z', 't', 'label', 'comment'],
                            skiprows=[0])

    print_points(in_filename, in_points, verbose_flag)

    cmd1 = [
        'antsApplyTransformsToPoints', '-d', '3', '-i', in_filename, '-o',
        out_filename
    ]

    if inverse_flag:
        cmd2 = ["-t", "["] + transform + [",", "1", "]"]
    else:
        cmd2 = ["-t"] + transform

    util.iw_subprocess(cmd1 + cmd2, False, False)

    out_points = pd.read_csv(out_filename,
                             names=['x', 'y', 'z', 't', 'label', 'comment'],
                             skiprows=[0])
    out_points['label'] = in_points['label']
    out_points['comment'] = in_points['comment']

    write_points(out_filename, out_points, verbose_flag)

    return out_points
示例#12
0
def methods(t1full,
            t2full,
            t2flair,
            options,
            verbose=False,
            debug=False,
            nohup=False):

    print('\nRunnning ants_ct.py\n')

    if qa.qa_input_files(input_files, False):

        if not os.path.exists(out_directory):
            os.makedirs(out_directory)

        callCommand = [
            'antsCorticalThickness.sh', '-d', '3', '-t', options['t_option'],
            '-w', '0.25', '-e', options['e_option'], '-m', options['m_option'],
            '-f', options['f_option'], '-p', options['p_option'], '-o',
            options['o_option']
        ]

        callCommand = callCommand + ['-a', t1full]

        if not t2full == None:
            callCommand = callCommand + ['-a', t2full]

        if not inArgs.t2flair == None:
            callCommand = callCommand + ['-a', t2flair]

        util.iw_subprocess(callCommand, verbose, debug, nohup)

    else:
        print('\nUnable to run iwAntsCT.py. Failed input QA.')
        qa.qa_exist(input_files, True)
        print('\n')
示例#13
0
def ants_register(input_file):

    # antsRegistration call:
    #--------------------------------------------------------------------------------------
    if False:

        # I am having problems callling the interface.  Same problem of bad interface.

        command = [
            'antsRegistration', '--dimensionality', 3, '--float', 0,
            '--output', '[', 'mt_Affine_nu__' + input_file + '_,',
            'mt_Affine_nu__' + input_file + '_Warped.nii.gz,',
            'mt_Affine_nu__' + input_file + '_InverseWarped.nii.gz', ']',
            '--interpolation', 'Linear',
            '--use-histogram-matching', 0, '--winsorize-image-intensities',
            [0.005, 0.995], '--initial-moving-transform', '[', 'nu.nii.gz,' +
            input_file + '.nii.gz,', 1, ']', '--transform', 'Rigid[0.1]',
            '--metric', 'MI[nu.nii.gz,mt_m1.nii.gz,1,32,Regular,0.25]',
            '--convergence', '[1000x500x250x0,1e-6,10]', '--shrink-factors',
            '8x4x2x1', '--smoothing-sigmas', '3x2x1x0vox', '--transform',
            'Affine[0.1]', '--metric',
            'MI[nu.nii.gz,' + input_file + '.nii.gz,1,32,Regular,0.25]',
            '--convergence', '[1000x500x250x0,1e-6,10]', '--shrink-factors',
            '8x4x2x1', '--smoothing-sigmas', '3x2x1x0vox'
        ]
    #--------------------------------------------------------------------------------------

    # I am having problems callling the interface.  Same problem of bad interface.
    if False:
        reg = Registration()
        reg.inputs.fixed_image = 'nu.nii.gz'
        reg.inputs.moving_image = input_file + '.nii.gz'
        reg.inputs.output_transform_prefix = "t2flair_Affine_nu__" + input_file + "_"
        reg.inputs.transforms = ['Affine']
        reg.inputs.transform_parameters = [(2.0, ), (0.25, 3.0, 0.0)]
        reg.inputs.number_of_iterations = [[1000, 500, 200, 100]]
        reg.inputs.dimension = 3
        reg.inputs.write_composite_transform = False
        reg.inputs.collapse_output_transforms = False
        reg.inputs.initialize_transforms_per_stage = False
        reg.inputs.metric = ['MI']
        reg.inputs.metric_weight = [1]
        reg.inputs.radius_or_number_of_bins = [32]
        reg.inputs.sampling_strategy = ['Random']
        reg.inputs.sampling_percentage = [0.05]
        reg.inputs.convergence_threshold = [1.e-10]
        reg.inputs.convergence_window_size = [10]
        reg.inputs.smoothing_sigmas = [[3, 2, 1, 0]]
        reg.inputs.sigma_units = ['vox']
        reg.inputs.shrink_factors = [[8, 4, 2, 1]]
        reg.inputs.use_estimate_learning_rate_once = [True]
        reg.inputs.use_histogram_matching = [True]  # This is the default
        reg.inputs.output_warped_image = 't2flair_Affine_nu__' + input_file + '.nii.gz'
        reg.inputs.terminal_output = 'stream'
        print reg.cmdline
        # reg.run()

    # This simple command appears to work.
    command = [
        'antsRegistrationSyNQuick.sh', '-d', '3', '-m', input_file + '.nii.gz',
        '-r', 'nu.nii.gz', '-f', 'nu.nii.gz', '-t', 'a', '-o',
        't2flair_Affine_nu__' + input_file + '_'
    ]

    util.iw_subprocess(command, True, True, False)
示例#14
0
def methods_03_stats(input_dir, verbose=False, min_lesion_volume=10):

    cenc_dirs = cenc.directories(input_dir)

    wm_lesions_dir = cenc_dirs['wmlesions']['dirs']['root']
    wm_lesions_lpa_dir = cenc_dirs['wmlesions']['dirs']['lpa']

    util.mkcd_dir([cenc_dirs['wmlesions']['dirs']['stats']], True)

    wm_lesions_stats_filename = os.path.join(
        cenc_dirs['wmlesions']['dirs']['stats'], 'wmlesions_lpa_labels.csv')

    # Create labels file from LPA probability map
    iw_labels_label.create(
        os.path.join(cenc_dirs['wmlesions']['dirs']['lpa'],
                     'ples_lpa_mt2flair_Affine_nu__t2flair_Warped.nii.gz'),
        os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                     'wmlesions_lpa_labels.nii.gz'))

    # Measure statistics of labels
    iw_labels_stats.measure(
        os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                     'wmlesions_lpa_labels.nii.gz'),
        None,
        False, ['volume_mm3'],
        wm_lesions_stats_filename,
        limits_volume_voxels=[min_lesion_volume, numpy.inf],
        limits_bb_volume_voxels=[0, numpy.inf],
        limits_fill_factor=[0, 1],
        sort='volume_mm3',
        verbose=verbose,
        verbose_nlines=20)

    # Keep labels greater than 10 mm^3.  Limit is set above
    iw_labels_keep.keep(
        os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                     'wmlesions_lpa_labels.nii.gz'), [],
        wm_lesions_stats_filename,
        os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                     'wmlesions_lpa_labels.nii.gz'))
    #  1)
    #  2) Create a WM Lesions mask
    #  3)

    command = [[
        'fslmaths',
        os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                     'wmlesions_lpa_labels.nii.gz'), '-bin', '-mul',
        os.path.join(cenc_dirs['wmlesions']['dirs']['lpa'],
                     'ples_lpa_mt2flair_Affine_nu__t2flair_Warped.nii.gz'),
        '-mas',
        os.path.join(cenc_dirs['wmlesions']['dirs']['input'], 'mask.nii.gz'),
        os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                     'wmlesions_lpa_pmap.nii.gz')
    ],
               [
                   'fslmaths',
                   os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                                'wmlesions_lpa_labels.nii.gz'), '-bin',
                   os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                                'wmlesions_lpa_mask.nii.gz')
               ],
               [
                   'fslmaths',
                   os.path.join(cenc_dirs['wmlesions']['dirs']['lpa'],
                                'mt2flair_Affine_nu__t2flair_Warped.nii.gz'),
                   '-mas',
                   os.path.join(cenc_dirs['wmlesions']['dirs']['input'],
                                'mask.nii.gz'),
                   os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                                'wmlesions_lpa_t2flair.nii.gz')
               ]]

    for ii in command:
        util.iw_subprocess(ii, verbose, verbose, False)

    # Write out JSON file with RedCap Instrument
    methods_write_json_redcap_instrument(input_dir, wm_lesions_stats_filename,
                                         verbose)
示例#15
0
def create_pial_mask(subject_id,
                     subjects_dir,
                     output_filename,
                     output_directory,
                     reference=None,
                     mo_radius=7,
                     verbose=False,
                     save=False):

    mri_directory = os.path.abspath(
        os.path.join(subjects_dir, subject_id, 'mri'))

    if False:

        # I attempted to use nipype to call the mri_surf2vol.  This did not work so I had to use the subprocess method.
        surf2vol = Surface2VolTransform()
        #    surf2vol.inputs.reg_file = 'register.mat'

        surf2vol.inputs.template_file = os.path.abspath(
            os.path.join(mri_directory, 'brain.mgz'))
        surf2vol.inputs.subjects_dir = subjects_dir
        surf2vol.inputs.subject_id = subject_id
        surf2vol.mkmask = True
        surf2vol.projfrac = 0.05
        surf2vol.surf_name = 'pial'
        surf2vol.args = '--fillribbon --fill-projfrac -2 0 0.05'

        for ii in ['lh', 'rh']:
            surf2vol.inputs.hemi = 'lh'
            surf2vol.transformed_file = os.path.abspath(
                os.path.join(output_directory,
                             '_cpm_mask_surf2vol.pial_' + ii + '.nii.gz'))

            if verbose:
                surf2vol.cmdline

    else:

        for ii in ['lh', 'rh']:

            ii_output = os.path.abspath(
                os.path.join(output_directory,
                             '_cpm_mask_surf2vol.pial_' + ii + '.nii.gz'))

            command = [
                'mri_surf2vol', '--hemi', ii, '--surf', 'pial', '--o',
                ii_output, '--identity', subject_id, '--template',
                os.path.abspath(
                    os.path.join(subjects_dir, subject_id, 'mri',
                                 'brain.mgz')), '--mkmask', '--fillribbon',
                '--fill-projfrac', '-2', '0', '0.05'
            ]

            if not os.path.isfile(ii_output):
                util.iw_subprocess(command, verbose_flag=verbose)

            if not os.path.isfile(ii_output):
                print(ii_output + ' does not exist. Exiting!')
                exit()

    # Convert aseg.nii.gz

    aseg_nii_gz = os.path.abspath(
        os.path.join(output_directory, '_cpm_aseg.nii.gz'))

    if not os.path.isfile(aseg_nii_gz):
        mri_convert = MRIConvert(in_file=os.path.abspath(
            os.path.join(mri_directory, 'aseg.mgz')),
                                 out_file=aseg_nii_gz,
                                 out_type='niigz')
        mri_convert.run()

    # Remove GM Cortex from aseg.nii.gz

    mask_aseg_without_gm_cortex = os.path.join(
        output_directory, '_cpm_mask.aseg_without_gm_cortex.nii.gz')

    if not os.path.isfile(mask_aseg_without_gm_cortex):
        labels.remove(aseg_nii_gz, [3, 42], [],
                      mask_aseg_without_gm_cortex,
                      merge=1)

    # 1) Combine masks into a single mask
    # 2) Threshold and invert mask
    # 3) Grab largest component
    # 4) Threshold image to remove negative numbers
    # 5) ImageMath Opening operation with radius 3
    # 6) Threshold image to remove negative numbers
    # 7) ImageMath Closing operation with radius 3
    # 8) Threshold and invert mask.

    if not os.path.isfile(os.path.join(output_directory,
                                       '_cpm_01.mask.nii.gz')):
        os.chdir(output_directory)

        commands = [[
            'fslmaths',
            os.path.join(output_directory,
                         '_cpm_mask.aseg_without_gm_cortex.nii.gz'), '-add',
            os.path.abspath(
                os.path.join(output_directory,
                             '_cpm_mask_surf2vol.pial_lh.nii.gz')), '-add',
            os.path.abspath(
                os.path.join(output_directory,
                             '_cpm_mask_surf2vol.pial_rh.nii.gz')), '-bin',
            '-fillh26',
            os.path.abspath(
                os.path.join(output_directory, '_cpm_01.mask.nii.gz'))
        ],
                    [
                        'fslmaths',
                        os.path.join(output_directory, '_cpm_01.mask.nii.gz'),
                        '-thr', 0, '-binv',
                        os.path.join(output_directory, '_cpm_02.mask.nii.gz')
                    ],
                    [
                        'ImageMath', 3, '_cpm_03.mask.nii.gz',
                        'GetLargestComponent', '_cpm_02.mask.nii.gz'
                    ],
                    [
                        'ImageMath', 3, '_cpm_04.mask.nii.gz', 'MO',
                        '_cpm_03.mask.nii.gz', 7
                    ],
                    [
                        'fslmaths', '_cpm_04.mask.nii.gz', '-thr', 0, '-bin',
                        '_cpm_05.mask.nii.gz'
                    ],
                    [
                        'ImageMath', 3, '_cpm_06.mask.nii.gz', 'MC',
                        '_cpm_05.mask.nii.gz', 7
                    ],
                    [
                        'fslmaths', '_cpm_06.mask.nii.gz', '-thr', 0, '-binv',
                        '_cpm_07.mask.nii.gz'
                    ]]

        for ii in commands:
            util.iw_subprocess(ii, verbose_flag=verbose)

    if reference is not None:
        command = [
            'antsApplyTransforms', '-i',
            os.path.join(output_directory, '_cpm_07.mask.nii.gz'), '-r',
            reference, '-n', 'Multilabel', '-o',
            os.path.join(output_directory, output_filename), '-t', 'identity'
        ]

        util.iw_subprocess(command, verbose_flag=verbose)

    else:
        shutil.copy2(os.path.join(output_directory, '_cpm_07.mask.nii.gz'),
                     os.path.join(output_directory, out_filename))

    if not save:

        remove_files = [
            os.path.join(output_directory, '_cpm_01.mask.nii.gz'),
            os.path.join(output_directory, '_cpm_02.mask.nii.gz'),
            os.path.join(output_directory, '_cpm_03.mask.nii.gz'),
            os.path.join(output_directory, '_cpm_04.mask.nii.gz'),
            os.path.join(output_directory, '_cpm_05.mask.nii.gz'),
            os.path.join(output_directory, '_cpm_06.mask.nii.gz'),
            os.path.join(output_directory, '_cpm_07.mask.nii.gz'),
            os.path.join(output_directory, '_cpm_aseg.nii.gz'),
            os.path.join(output_directory,
                         '_cpm_mask.aseg_without_gm_cortex.nii.gz'),
            os.path.abspath(
                os.path.join(output_directory,
                             '_cpm_mask_surf2vol.pial_lh.nii.gz')),
            os.path.abspath(
                os.path.join(output_directory,
                             '_cpm_mask_surf2vol.pial_rh.nii.gz'))
        ]

        clean(remove_files)

    return
示例#16
0
def results(input_dir, verbose):

    cenc_dirs = cenc.directories(input_dir)
    cenc_freesurfer_dir = cenc_dirs['freesurfer']['mri']

    util.mkcd_dir([
        cenc_dirs['results']['dirs']['root'],
        cenc_dirs['results']['dirs']['images'],
        cenc_dirs['results']['dirs']['labels']
    ], True)

    files_to_convert = [
        os.path.join(cenc_freesurfer_dir, 'nu.mgz'),
        os.path.join(cenc_freesurfer_dir, 'aseg.mgz'),
        os.path.join(cenc_freesurfer_dir, 'brainmask.mgz'),
        os.path.join(cenc_freesurfer_dir, 'aparc.a2009s+aseg.mgz'),
        os.path.join(cenc_freesurfer_dir, 'wmparc.mgz')
    ]

    # Check if files exist

    if util.check_files(files_to_convert, True) == False:
        sys.exit()

    # Create link to directory

    if not os.path.exists(cenc_dirs['freesurfer']['results']):
        util.force_symbolic_link(cenc_dirs['freesurfer']['mri'],
                                 cenc_dirs['freesurfer']['results'])

    # TODO use input node to run this instead of a loop. The trick part is to have the files named correctly.

    for ii in files_to_convert:
        mc = fs.MRIConvert(in_file=ii,
                           out_file=os.path.join(
                               cenc_dirs['results']['dirs']['labels'],
                               str.replace(os.path.basename(ii), '.mgz',
                                           '.nii.gz')),
                           out_type='niigz')
        mc.run()

        reorient = fsl.Reorient2Std(in_file=mc.inputs.out_file,
                                    out_file=mc.inputs.out_file)
        reorient.run()

    # Link nu.nii.gz to results/native/images

    result_files = [[
        os.path.join(cenc_dirs['results']['dirs']['labels'], 'nu.nii.gz'),
        os.path.join(cenc_dirs['results']['dirs']['images'], 'nu.nii.gz')
    ]]

    for ii in result_files:
        util.force_hard_link(ii[0], ii[1])

    # Create final brain mask.

    cenc.create_mask(
        os.path.join(cenc_dirs['results']['dirs']['labels'],
                     'brainmask.nii.gz'),
        os.path.join(cenc_dirs['results']['dirs']['labels'],
                     'aparc.a2009s+aseg.nii.gz'),
        os.path.join(cenc_dirs['results']['dirs']['labels'], 'mask.nii.gz'))

    # Create macroscopic labels

    labels.extract(os.path.join(cenc_dirs['results']['dirs']['labels'],
                                'aseg.nii.gz'), [],
                   [10, 11, 12, 13, 17, 18, 49, 50, 51, 52, 53, 54],
                   os.path.join(cenc_dirs['results']['dirs']['labels'],
                                'gm.subcortical.nii.gz'),
                   merge=1)

    labels.extract(os.path.join(cenc_dirs['results']['dirs']['labels'],
                                'aseg.nii.gz'), [], [3, 42],
                   os.path.join(cenc_dirs['results']['dirs']['labels'],
                                'gm.cerebral_cortex.nii.gz'),
                   merge=1)

    labels.extract(os.path.join(cenc_dirs['results']['dirs']['labels'],
                                'aseg.nii.gz'), [], [8, 47],
                   os.path.join(cenc_dirs['results']['dirs']['labels'],
                                'gm.cerebellum.nii.gz'),
                   merge=1)

    labels.extract(os.path.join(cenc_dirs['results']['dirs']['labels'],
                                'aseg.nii.gz'), [], [2, 41],
                   os.path.join(cenc_dirs['results']['dirs']['labels'],
                                'wm.cerebral.nii.gz'),
                   merge=1)

    labels.extract(os.path.join(cenc_dirs['results']['dirs']['labels'],
                                'aseg.nii.gz'), [], [7, 46],
                   os.path.join(cenc_dirs['results']['dirs']['labels'],
                                'wm.cerebellum.nii.gz'),
                   merge=1)

    labels.extract(os.path.join(cenc_dirs['results']['dirs']['labels'],
                                'aseg.nii.gz'), [], [4, 43],
                   os.path.join(cenc_dirs['results']['dirs']['labels'],
                                'ventricles.nii.gz'),
                   merge=1)

    # Brain extraction nu.nii.gz
    util.iw_subprocess([
        'fslmaths',
        os.path.join(cenc_dirs['results']['dirs']['images'], 'nu.nii.gz'),
        '-mas',
        os.path.join(cenc_dirs['results']['dirs']['labels'], 'mask.nii.gz'),
        os.path.join(cenc_dirs['results']['dirs']['images'], 'nu_brain.nii.gz')
    ])
示例#17
0
def methods_03_stats(input_dir,
                     lower_threshold=0.5,
                     upper_threshold=numpy.inf,
                     min_lesion_volume_voxels=10,
                     verbose=False):

    cenc_dirs = cenc.directories(input_dir)

    wm_lesions_dir = cenc_dirs['wmlesions']['dirs']['root']
    wm_lesions_lpa_dir = cenc_dirs['wmlesions']['dirs']['lpa']

    util.mkcd_dir([cenc_dirs['wmlesions']['dirs']['stats']], True)

    wm_lesions_stats_filename = os.path.join(
        cenc_dirs['wmlesions']['dirs']['stats'], 'wmlesions_lpa_labels.csv')
    wm_lesions_pmap_stats_filename = os.path.join(
        cenc_dirs['wmlesions']['dirs']['stats'], 'wmlesions_lpa_pmap.csv')

    # Mask LPA Probability Mask and remove NaN

    command = [[
        'fslmaths',
        os.path.join(cenc_dirs['wmlesions']['dirs']['lpa'],
                     'ples_lpa_mt2flair_Affine_nu__t2flair_Warped.nii.gz'),
        '-mas',
        os.path.join(cenc_dirs['wmlesions']['dirs']['input'],
                     'mask.nii.gz'), '-nan',
        os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                     'wmlesions_lpa_pmap.nii.gz')
    ]]

    for ii in command:
        util.iw_subprocess(ii, verbose, verbose, False)

    # Create labels file from LPA probability map

    labels.label_connected_components(
        os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                     'wmlesions_lpa_pmap.nii.gz'),
        os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                     'wmlesions_lpa_labels.nii.gz'), lower_threshold,
        upper_threshold)

    # Measure properties of labels
    labels.properties(
        os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                     'wmlesions_lpa_labels.nii.gz'),
        None,
        False, ['volume_mm3'],
        wm_lesions_stats_filename,
        limits_volume_voxels=[min_lesion_volume_voxels, numpy.inf],
        limits_bb_volume_voxels=[0, numpy.inf],
        limits_fill_factor=[0, 1],
        sort='volume_mm3',
        verbose=verbose,
        verbose_nlines=20)

    # Keep labels greater than 10 mm^3.  Limit is set above
    labels.keep(
        os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                     'wmlesions_lpa_labels.nii.gz'), [],
        wm_lesions_stats_filename,
        os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                     'wmlesions_lpa_labels.nii.gz'))
    #  1) Create a WM Lesions mask
    #  2) Mask LPA Registered T2 FLAIR

    command = [[
        'fslmaths',
        os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                     'wmlesions_lpa_labels.nii.gz'), '-bin',
        os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                     'wmlesions_lpa_mask.nii.gz')
    ],
               [
                   'fslmaths',
                   os.path.join(cenc_dirs['wmlesions']['dirs']['lpa'],
                                'mt2flair_Affine_nu__t2flair_Warped.nii.gz'),
                   '-mas',
                   os.path.join(cenc_dirs['wmlesions']['dirs']['input'],
                                'mask.nii.gz'),
                   os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                                'wmlesions_lpa_t2flair.nii.gz')
               ]]

    for ii in command:
        util.iw_subprocess(ii, verbose, verbose, False)

    # Measure Pmaps stats labels
    df_pmap_measure = labels.measure(
        os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                     'wmlesions_lpa_labels.nii.gz'),
        os.path.join(cenc_dirs['wmlesions']['dirs']['stats'],
                     'wmlesions_lpa_pmap.nii.gz'))

    df_pmap_measure.to_csv(wm_lesions_pmap_stats_filename, index=False)

    # Write out JSON file with RedCap Instrument
    methods_write_json_redcap_instrument(input_dir, wm_lesions_stats_filename,
                                         wm_lesions_pmap_stats_filename,
                                         verbose)
示例#18
0
def create_mask(in_image, n4_flag=True, imopen_flag=True, thr=0, thrp=25, scale=1, imopen_iterations=0, imclose_iterations=0, 
                verbose=False, debug=False, noglc_flag=True):

    inMask = in_image

    # N4 Bias Correction
    
    if n4_flag:
        
        outMask = util.add_prefix_to_filename( in_image, 'n4')
        
        if not os.path.isfile( outMask ):
            util.iw_subprocess( ["N4BiasFieldCorrection","-d","3", "-i", inMask, "-r", "-s", "-o", outMask], verbose)
            
        inMask = outMask

    # Threshold 

    iiMask  = 1
    outMask = util.add_prefix_to_filename( in_image, str(iiMask) + ".create_mask.")
        
    util.iw_subprocess( ["fslmaths", inMask, "-mul", str(scale), "-thrp", 
                                str(thrp), "-thr", str(thr), "-bin",outMask ],           verbose, debug)

    # Fill Holes

    inMask  = outMask
    iiMask  = iiMask + 1
    outMask = util.add_prefix_to_filename( in_image, str(iiMask) + ".create_mask.")

    util.iw_subprocess( ["ImageMath","3", outMask, "FillHoles",   inMask ], verbose, debug)

    # Opening image operation

    inMask  = outMask

    if imopen_iterations > 0: 
        iiMask  = iiMask + 1
        outMask = util.add_prefix_to_filename( in_image, str(iiMask) + ".create_mask.") 
        util.iw_subprocess( ["fslmaths", inMask,  "-kernel", "2D"] + 
                                   ["-ero"]*imopen_iterations +["-dilM"]*imopen_iterations  + [outMask], verbose, debug)

    # Close image operation
    inMask  = outMask

    if imclose_iterations > 0: 
        iiMask  = iiMask + 1
        outMask = util.add_prefix_to_filename( in_image, str(iiMask) + ".create_mask.")
        util.iw_subprocess( ["fslmaths", inMask,  "-kernel", "2D"] + 
                                   ["-dilM"]*imclose_iterations +["-ero"]*imclose_iterations  + [outMask], verbose, debug)

    # Don't grab greatest larges component

    inMask = outMask
         
    if not noglc_flag:
        iiMask  = iiMask + 1
        outMask = util.add_prefix_to_filename( in_image, str(iiMask) + ".create_mask.")
        util.iw_subprocess(["ImageMath","3", outMask, "GetLargestComponent",  inMask],verbose, debug)

    # Active Contour

    inMask  = outMask
    out_mask_filename = util.add_prefix_to_filename( in_image, "mask.")

#    if inArgs.active_contour and False:  # Active contour no longer works. Talk to Craig 
#
#        util.iw_subprocess( ["matlab", "-nodisplay", "-noFigureWindows", "-nosplash", "-r", 
#                                    "iw_calculate_boundary('"+inMask+"',[ " +  str(inArgs.smoothing) + "," + 
#                                    str(inArgs.iterations) + " ],'ch."+outMask+"', 'ac." + outMask + "'); exit"], verbose)
#        shutil.copyfile("ac."+outMask, out_mask_filename)
#
#    else:
 
    shutil.copyfile(outMask, out_mask_filename)    
    util.iw_subprocess( ["fslcpgeom", in_image, out_mask_filename], verbose)


    return out_mask_filename