예제 #1
0
def dilate_out_low_intensity_voxels(settings, hemisphere, mesh_settings):
    '''
    looks for voxels of low intensity and marks dilates to try to correct for them
    Hopefully this is an unnessary step with volume to surface mapping is done well
    '''
    intput_func_gii = func_gii_file(settings.subject.id, settings.fmri_label,
                                    hemisphere, mesh_settings)
    lowvoxels_gii = func_gii_file(settings.subject.id, 'lowvoxels', hemisphere,
                                  mesh_settings)
    middle_TR = int(settings.num_TR) // 2
    low_intensity_thres = get_stdout([
        'wb_command', '-metric-stats', input_func_gii, '-percentile',
        str(settings.dilate_percent_below), '-column',
        str(middle_TR), '-roi',
        medial_wall_roi_file(settings.subject.id, hemisphere, mesh_settings)
    ])
    run([
        'wb_command', '-metric-math', '"(x < {})"'.format(low_intensity_thres),
        lowvoxels_gii, '-var', 'x', input_func_gii, '-column',
        str(middle_TR)
    ])
    run([
        'wb_command', '-metric-dilate', input_func_gii,
        medial_wall_roi_file(settings.subject.id, hemisphere, mesh_settings),
        str(settings.dilate_factor), input_func_gii, '-bad-vertex-roi',
        lowvoxels_gii, '-nearest'
    ])
예제 #2
0
def get_smoothed_dtseries_file(user_settings, temp_dir):
    '''
    create smoothed file if it does not exist,
    returns path to smoothed file
    '''
    pre_dtseries_sm = os.path.join(
        user_settings.work_dir, user_settings.subject, 'MNINonLinear',
        'Results', user_settings.fmri_name,
        '{}_Atlas_s{}.dtseries.nii'.format(user_settings.fmri_name,
                                           user_settings.fwhm))
    if os.path.exists(pre_dtseries_sm):
        return pre_dtseries_sm

    else:
        dtseries_sm = os.path.join(
            temp_dir,
            '{}_Atlas_s{}.dtseries.nii'.format(user_settings.fmri_name,
                                               user_settings.fwhm))
        Sigma = ciftify.utils.FWHM2Sigma(user_settings.fwhm)
        surfs_dir = os.path.join(user_settings.work_dir, user_settings.subject,
                                 'MNINonLinear', 'fsaverage_LR32k')
        run([
            'wb_command', '-cifti-smoothing', user_settings.dtseries_s0,
            str(Sigma),
            str(Sigma), 'COLUMN', dtseries_sm, '-left-surface',
            os.path.join(
                surfs_dir, '{}.L.midthickness{}.surf.gii'.format(
                    user_settings.subject, user_settings.surf_mesh)),
            '-right-surface',
            os.path.join(
                surfs_dir,
                '{}.R.midthickness{}.surf.gii'.format(user_settings.subject,
                                                      user_settings.surf_mesh))
        ])
        return dtseries_sm
예제 #3
0
def subcortical_atlas(input_fMRI, AtlasSpaceFolder, ResultsFolder,
                      GrayordinatesResolution, tmpdir):

    ROIFolder = os.path.join(AtlasSpaceFolder, "ROIs")
    ROIvols = os.path.join(ROIFolder,
                           'ROIs.{}.nii.gz'.format(GrayordinatesResolution))
    #generate subject-roi space fMRI cifti for subcortical
    func_vx_size = ciftify.io.voxel_spacing(input_fMRI)
    expected_resolution = (float(GrayordinatesResolution),
                           float(GrayordinatesResolution),
                           float(GrayordinatesResolution))
    if func_vx_size == expected_resolution:
        logger.info(
            "Creating subject-roi subcortical cifti at same resolution as output"
        )
        vol_rois = ROIvols
    else:
        logger.info(
            "Creating subject-roi subcortical cifti at differing fMRI resolution"
        )
        tmp_ROIs = os.path.join(tmpdir, 'ROIs.nii.gz')
        run([
            'wb_command', '-volume-affine-resample', ROIvols,
            os.path.join(ciftify.config.find_fsl(), 'etc',
                         'flirtsch/ident.mat'), input_fMRI, 'ENCLOSING_VOXEL',
            tmp_ROIs
        ])
        vol_rois = tmp_ROIs
    return (vol_rois)
예제 #4
0
def map_volume_to_surface(vol_input,
                          map_name,
                          subject,
                          hemisphere,
                          mesh_settings,
                          dilate_factor=None,
                          volume_roi=None):
    """
    Does wb_command -volume-to-surface mapping ribbon constrained
    than does optional dilate step
    """
    output_func = func_gii_file(subject, map_name, hemisphere, mesh_settings)
    cmd = [
        'wb_command', '-volume-to-surface-mapping', vol_input,
        surf_file(subject, 'midthickness', hemisphere, mesh_settings),
        output_func, '-ribbon-constrained',
        surf_file(subject, 'white', hemisphere, mesh_settings),
        surf_file(subject, 'pial', hemisphere, mesh_settings)
    ]
    if volume_roi:
        cmd.extend(['-volume-roi', volume_roi])
    run(cmd)

    if dilate_factor:
        ## dilate to get rid of wholes caused by the goodvoxels_vol mask
        run([
            'wb_command', '-metric-dilate', output_func,
            surf_file(subject, 'midthickness', hemisphere, mesh_settings),
            "{}".format(dilate_factor), output_func, '-nearest'
        ])
예제 #5
0
    def test_dry_run_prevents_command_from_running(self, mock_popen):
        mock_popen.return_value.communicate.return_value = (b'', b'')
        mock_popen.return_value.returncode = 0

        utils.run('touch ./test_file.txt', dryrun=True)

        assert mock_popen.call_count == 0
예제 #6
0
def test_clean_sm_plus_PINT(output_dir, clean_sm8_dtseries):

    ## run PINT on smoothed file without smoothing
    run([
        'ciftify_PINT_vertices', '--pcorr', clean_sm8_dtseries, left_surface,
        right_surface,
        os.path.join(ciftify.config.find_ciftify_global(), 'PINT',
                     'Yeo7_2011_80verts.csv'),
        os.path.join(output_dir, 'testsub_clean_sm8')
    ])

    assert os.path.exists(
        os.path.join(output_dir, 'testsub_clean_sm8_tvertex_meants.csv'))
    fixture_meants_t = read_meants_csv(
        os.path.join(get_test_data_path(), 'PINT',
                     'pint_clean_sm8_tvertex_meants.csv'))
    new_meants_t = read_meants_csv(
        os.path.join(output_dir, 'testsub_clean_sm8_tvertex_meants.csv'))
    assert (fixture_meants_t == new_meants_t).all().all()

    assert os.path.isfile(
        os.path.join(output_dir, 'testsub_clean_sm8_summary.csv'))
    fixture_summary = pd.read_csv(pint_summary)
    new_summary = pd.read_csv(
        os.path.join(output_dir, 'testsub_clean_sm8_summary.csv'))
    assert (fixture_summary == new_summary).all().all()

    assert os.path.isfile(
        os.path.join(output_dir, 'testsub_clean_sm8_pvertex_meants.csv'))
    fixture_meants_p = read_meants_csv(
        os.path.join(get_test_data_path(), 'PINT',
                     'pint_clean_sm8_pvertex_meants.csv'))
    new_meants_p = read_meants_csv(
        os.path.join(output_dir, 'testsub_clean_sm8_pvertex_meants.csv'))
    assert (fixture_meants_p == new_meants_p).all().all()
예제 #7
0
def fake_ciftify_work_dir():
    '''link in files to mode a ciftify work dir so that qc pages can be generated'''
    with ciftify.utils.TempDir() as ciftify_wd:
        # create a temp outputdir
        subject = "sub-50005"
        surfs_dir = os.path.join(ciftify_wd, subject, 'MNINonLinear',
                                 'fsaverage_LR32k')
        run(['mkdir', '-p', surfs_dir])
        os.symlink(
            left_surface,
            os.path.join(surfs_dir,
                         'sub-50005.L.midthickness.32k_fs_LR.surf.gii'))
        os.symlink(
            right_surface,
            os.path.join(surfs_dir,
                         'sub-50005.R.midthickness.32k_fs_LR.surf.gii'))
        for hemi in ['L', 'R']:
            old_path = os.path.join(
                ciftify.config.find_ciftify_global(), 'HCP_S1200_GroupAvg_v1',
                'S1200.{}.very_inflated_MSMAll.32k_fs_LR.surf.gii'.format(
                    hemi))
            new_path = os.path.join(
                surfs_dir,
                'sub-50005.{}.very_inflated.32k_fs_LR.surf.gii'.format(hemi))
            os.symlink(old_path, new_path)
        yield ciftify_wd
예제 #8
0
def run_fmriprep_func(bold_input, settings):
    '''runs fmriprep with combo of user args and required args for ciftify'''
    # if feildmaps are available use default settings
    fieldmap_list = settings.bids_layout.get_fieldmap(bold_input.path, return_list = True)
    if len(fieldmap_list) > 0 :
        if settings.no_sdc:
            fieldmap_arg = "--ignore fieldmaps"
        elif settings.ignore_fieldmaps:
            fieldmap_arg = "--ignore fieldmaps --use-syn-sdc"
        else:
            fieldmap_arg = ''
    else:
        fieldmap_arg = '--use-syn-sdc'
        if settings.no_sdc:
            fieldmap_arg = ""
    # if not, run with syn-dc
    fcmd = ['fmriprep', settings.bids_dir, os.path.dirname(settings.func_derivs_dir),
        'participant', '--participant_label', bold_input.subject,
        '-t', bold_input.task,
        '--output-space T1w template',
        fieldmap_arg,
        '--nthreads', str(settings.n_cpus),
        '--omp-nthreads', str(settings.n_cpus)]
    if settings.fmriprep_work:
        fcmd.extend(['--work-dir',settings.fmriprep_work])
    if settings.fs_license:
        fcmd.extend(['--fs-license-file', settings.fs_license])
    if settings.fmriprep_vargs:
        fcmd.append(settings.fmriprep_vargs)
    run(fcmd, dryrun = DRYRUN)
def resample_mask(rest_image, mask, output_path):
    vol_dims = ciftify.io.voxel_spacing(rest_image)
    mask_dims = ciftify.io.voxel_spacing(mask)

    if mask_dims == vol_dims:
        return mask

    new_mask = os.path.join(output_path, 'resampled_' + os.path.basename(mask))
    if os.path.exists(new_mask):
        prev_resample_dims = get_nifti_dimensions(new_mask)
        if prev_resample_dims == vol_dims:
            return new_mask
        # Remove old resampled mask if it doesnt match the dims of current image
        os.remove(new_mask)

    resample = "flirt -in {} -ref {} -out {} -applyxfm".format(
        mask, rest_image, new_mask)
    run(resample)

    binarize = "fslmaths {} -thr 0.5 -bin {}".format(new_mask, new_mask)
    run(binarize)

    if not os.path.exists(new_mask):
        sys.exit("Failed to resample {} to size {}".format(mask, vol_dims))
    return new_mask
예제 #10
0
def test_ciftify_meants_cifti_func_custom_dlabel_some_missing(
        output_dir, custom_dlabel_timeseries, left_hemisphere_dir,
        subcort_images_dir):
    ''' set to make sure that the correct number of ROIs are extracted if the data is missing'''
    ## build a cifti file with only one hemisphere of data
    one_hemi_func = os.path.join(output_dir, 'func_L_hemi.dtseries.nii')
    run([
        'wb_command', '-cifti-create-dense-timeseries', one_hemi_func,
        '-left-metric',
        os.path.join(left_hemisphere_dir, 'func.L.func.gii'), '-volume',
        os.path.join(subcort_images_dir, 'func.nii.gz'),
        os.path.join(ciftify.config.find_ciftify_global(),
                     'standard_mesh_atlases', 'Atlas_ROIs.2.nii.gz')
    ])
    meants_out = os.path.join(output_dir, 'meants.csv')
    labels_out = os.path.join(output_dir, 'labels.csv')
    run([
        'ciftify_meants', '--outputcsv', meants_out, '--outputlabels',
        labels_out, one_hemi_func, custom_dlabel
    ])
    assert os.path.isfile(meants_out)
    assert os.path.isfile(labels_out)
    meants_pd_out = read_meants_and_transpose(meants_out)
    meants_labels = pd.read_csv(labels_out)
    assert meants_pd_out.shape[1] == meants_labels.shape[0]
    print(meants_pd_out)
    print(meants_labels)
    assert np.allclose(meants_pd_out.loc[:, 0].values,
                       custom_dlabel_timeseries.loc[:, 0].values,
                       atol=0.001)
    assert np.allclose(meants_pd_out.loc[:, 1:2].values,
                       np.zeros((meants_pd_out.shape[0], 2)),
                       atol=0.001)
예제 #11
0
 def __show_scene(self, output, scene_file, logging, width, height):
     run([
         'wb_command', '-logging', logging, '-show-scene', scene_file,
         str(self.index), output,
         str(width),
         str(height)
     ])
예제 #12
0
    def test_ciftify_surface_rois_gaussian(self):

        vertices1_csv = os.path.join(self.path, 'vertices1.csv')

        with open(vertices1_csv, "w") as text_file:
            text_file.write('''hemi,vertex
        L,11801
        L,26245
        L,26235
        L,26257
        L,13356
        L,289
        L,13336
        L,13337
        L,26269
        L,13323
        L,26204
        ''')

        output_dscalar = os.path.join(self.path, 'gaussian.dscalar.nii')
        run(['ciftify_surface_rois', vertices1_csv, '10', '--gaussian',
             left_surface,
             right_surface,
             output_dscalar])
        assert os.path.isfile(output_dscalar)
예제 #13
0
def create_dense_timeseries(map_name, smoothing_fwhm, settings,
            subcortical_data, subcortical_labels, mesh_settings):
    '''
    put the surface mapped data and subcortical data together into the final dtseries file
    '''
    if mesh_settings['meshname'] == "32k_fs_LR":
        cifti_output = os.path.join(settings.results_dir,
            '{}_Atlas_s{}.dtseries.nii'.format(settings.fmri_label,
                    smoothing_fwhm))
    else:
        cifti_output = os.path.join(settings.results_dir,
            '{}_Atlas_s{}.{}.dtseries.nii'.format(settings.fmri_label,
                smoothing_fwhm, mesh_settings['meshname']))

    if smoothing_fwhm != '0':
        map_name = "{}_s{}".format(settings.fmri_label, smoothing_fwhm)
    else:
        map_name = settings.fmri_label

    run(['wb_command', '-cifti-create-dense-timeseries', cifti_output,
        '-volume', subcortical_data, subcortical_labels,
        '-left-metric', func_gii_file(settings.subject.id, map_name,'L', mesh_settings),
        '-roi-left', medial_wall_roi_file(settings.subject.id, 'L', mesh_settings),
        '-right-metric',func_gii_file(settings.subject.id, map_name,'R', mesh_settings),
        '-roi-right', medial_wall_roi_file(settings.subject.id, 'R', mesh_settings),
        '-timestep', settings.TR_in_ms])
예제 #14
0
def calc_sform_differences(native_func_3D, settings, tmpdir):
    """
    adjust for any differences between the func sform and the T1w image
    using nilearn resample to find and intermidiate
    """
    logger.info('---Adjusting for differences between underlying sform---')
    resampled_ref = os.path.join(tmpdir, 'vol_ref_rT1w.nii.gz')
    logger.info("Using nilearn to create resampled image {}".format(resampled_ref))
    resampled_ref_vol = nilearn.image.resample_to_img(
        source_img = native_func_3D,
        target_img = os.path.join(
                        settings.vol_reg['src_dir'],
                        settings.vol_reg['T1wImage']))
    resampled_ref_vol.to_filename(resampled_ref)

    logger.info("Calculating linear transform between resampled reference and reference vols")
    func2T1w_mat = os.path.join(settings.results_dir, 'native','mat_EPI_to_T1.mat')
    run(['mkdir','-p',os.path.join(settings.results_dir,'native')])
    run(['flirt',
        '-in', native_func_3D,
        '-ref', resampled_ref,
        '-omat', func2T1w_mat,
        '-2D',
        '-cost', "corratio", '-searchcost', "corratio"])
    return func2T1w_mat
예제 #15
0
def define_func_3D(settings, tmpdir):
    """
    create the func_3D file as per subject instrutions
    """
    logger.info(section_header("Getting fMRI reference volume"))

    if settings.func_ref.mode == "first_vol":
        '''take the fist image (default)'''
        native_func_3D = os.path.join(tmpdir, "native_func_first.nii.gz")
        run(['wb_command', '-volume-math "(x)"', native_func_3D,
                        '-var','x', settings.func_4D, '-subvolume', '1'])

    elif settings.func_ref.mode == "median":
        '''take the median over time, if indicated'''
        native_func_3D = os.path.join(tmpdir, "native_func_median.nii.gz")
        run(['wb_command', '-volume-reduce',
            settings.func_4D, 'MEDIAN', native_func_3D])

    elif settings.func_ref.mode == "path":
        '''use the file indicated by the user..after checking the dimension'''
        ciftify.meants.verify_nifti_dimensions_match(settings.func_ref.path,
                                                    settings.func_4D)
        native_func_3D = settings.func_ref.path
    else:
        sys.exit('Failed to define the ref volume')

    return native_func_3D
예제 #16
0
def find_or_build_fs_dir(settings, participant_label):
    '''either finds a freesurfer output folder in the outputs
    if the freesurfer output are not run..it runs the fmriprep anat pipeline'''
    fs_sub_dir = os.path.join(settings.fs_dir,
                              'sub-{}'.format(participant_label))
    ## check for a wmparc file to insure that freesurfer probably finished
    if os.path.isfile(os.path.join(fs_sub_dir, 'mri', 'wmparc.mgz')):
        logger.info(
            "Found freesurfer outputs for sub-{}".format(participant_label))
        return
    else:
        cmd = [
            'fmriprep', settings.bids_dir,
            os.path.dirname(settings.fmriprep_dir), 'participant',
            '--participant_label', participant_label, '--anat-only',
            '--output-space T1w template', '--nthreads',
            str(settings.n_cpus), '--omp-nthreads',
            str(settings.n_cpus)
        ]
        if settings.fmriprep_work:
            cmd.extend(['--work-dir', settings.fmriprep_work])
        if settings.fs_license:
            cmd.extend(['--fs-license-file', settings.fs_license])
        if settings.fmriprep_vargs:
            cmd.append(settings.fmriprep_vargs)
        run(cmd, dryrun=DRYRUN)
예제 #17
0
def run_group_workflow(settings):
    ''' run the QC tools index mode '''
    run('cifti_vis_recon_all index --ciftify-work-dir {ciftify_work_dir}'.
        format(ciftify_work_dir=settings.ciftify_work_dir),
        dryrun=DRYRUN)
    run('cifti_vis_fmri index --ciftify-work-dir {ciftify_work_dir}'.format(
        ciftify_work_dir=settings.ciftify_work_dir),
        dryrun=DRYRUN)
예제 #18
0
def test_ciftify_dlabel_to_vol_rsn_map2(output_dir):

    output_nii = os.path.join(output_dir, 'yeo17_atlas.nii.gz')
    run([
        'ciftify_dlabel_to_vol', '--map-number', '2', '--input-dlabel',
        rsn_dlabel, '--left-mid-surface', hcp_Lmid, '--volume-template',
        test_nifti, '--output-nifti', output_nii
    ])
    assert os.path.isfile(output_nii)
예제 #19
0
def run_cifti_vis_recon_all(subid, ciftify_work_dir):
    '''runs both subject and index stages of the cifti_vis_recon_all'''
    run([
        'cifti_vis_recon_all', 'subject', '--ciftify-work-dir',
        ciftify_work_dir, subid
    ])
    run([
        'cifti_vis_recon_all', 'index', '--ciftify-work-dir', ciftify_work_dir
    ])
예제 #20
0
 def __get_bids_layout(self):
     '''run the BIDS validator and produce the bids_layout'''
     run("bids-validator {}".format(self.bids_dir),  dryrun = DRYRUN)
     try:
         layout = BIDSLayout(self.bids_dir, exclude=['derivatives'])
     except:
         logger.critical('Could not parse <bids_dir> {}'.format(self.bids_dir))
         sys.exit(1)
     return layout
예제 #21
0
def test_ciftify_dlabel_to_vol_custom_map(output_dir):

    output_nii = os.path.join(output_dir, 'custom_atlas.nii.gz')
    run([
        'ciftify_dlabel_to_vol', '--input-dlabel', custom_dlabel,
        '--left-mid-surface', hcp_Lmid, '--volume-template', test_nifti,
        '--output-nifti', output_nii
    ])
    assert os.path.isfile(output_nii)
예제 #22
0
    def test_handles_list_commands(self, mock_popen):
        mock_popen.return_value.communicate.return_value = (b'', b'')
        mock_popen.return_value.returncode = 0
        cmd = ['touch', './test_file.txt']

        utils.run(cmd)

        assert mock_popen.call_count == 1
        assert mock_popen.call_args_list[0][0][0] == " ".join(cmd)
예제 #23
0
def main():
    ''''''
    arguments = docopt(__doc__)
    funcfile = arguments['<func.nii.gz>']
    outputname = arguments['<output.nii.gz>']
    min_low_freq = arguments['--min-low-freq']
    max_low_freq = arguments['--max-low-freq']
    min_total_freq = arguments['--min-total-freq']
    max_total_freq = arguments['--max-total-freq']
    maskfile = arguments['--mask-file']
    calc_alff = arguments['--calc-alff']

    logger.setLevel(logging.WARNING)

    if arguments['--debug']:
        logger.setLevel(logging.DEBUG)
        logging.getLogger('ciftify').setLevel(logging.DEBUG)

    logger.info(arguments)

    with ciftify.utils.TempDir() as tmpdir:

        # IF INPUT IS A NIFTI FILE
        # Sets input funcfile equal to inputfile
        func = NibInput(funcfile)


        # IF INPUT IS CIFTI FILE
        # Convert cifti input file to nifti input file
        if func.type == "cifti":
            inputfile = convert_cifti_to_nifti(func.path, tmpdir)
            if maskfile:
                maskinput = convert_cifti_to_nifti(maskfile, tmpdir)
            else:
                maskinput = None
        elif func.type == "nifti":
            inputfile = func.path
            if maskfile:
                maskinput = maskfile
            else:
                maskinput = None
        else:
            logger.critical("Could not read <func.nii.gz> as nifti or cifti file")
            sys.exit(1)


        falff_nifti_output = calc_nifti(inputfile, maskinput, min_low_freq, max_low_freq, min_total_freq, max_total_freq, tmpdir, calc_alff)

        # Convert nifti output file to cifti output file
        if func.type == "cifti":
            convert_nifti_to_cifti(falff_nifti_output, funcfile, outputname)

        # IF INPUT IS NIFTI FILE
        # If funcfile was not cifti file, save as nifti file to outputname
        if func.type == "nifti":
            run("mv {} {}".format(falff_nifti_output, outputname))
예제 #24
0
    def calc_vertex_areas_from_surface(self, tmpdir):
        ''' use wb_command to calculate the vertex areas from the given surface'''
        self.vertex_areas = os.path.join(
            tmpdir, 'surf{}_va.shape.gii'.format(self.hemi))

        run([
            'wb_command', '-surface-vertex-areas', self.surface,
            self.vertex_areas
        ])
        return (self)
예제 #25
0
def get_the_5_rois_meants_outputs(input_file, tmpdir, seed_dscalar):
    meants_csv = os.path.join(tmpdir, 'mts.csv')
    meants_labels = os.path.join(tmpdir, 'labels.csv')
    run([
        'ciftify_meants', '--outputcsv', meants_csv, '--outputlabels',
        meants_labels, input_file, seed_dscalar
    ])
    meants_pd = pd.read_csv(meants_csv, header=None)
    labels_pd = pd.read_csv(meants_labels)
    return meants_pd, labels_pd
예제 #26
0
def test_ciftify_dlabel_to_vol_rsn_nearest(output_dir):

    output_nii = os.path.join(output_dir, 'yeo7_atlas.nii.gz')
    run([
        'ciftify_dlabel_to_vol', '--use-nearest-vertex', '1.2',
        '--input-dlabel', rsn_dlabel, '--left-mid-surface',
        sub_left_mid_surface, '--volume-template', test_nifti,
        '--output-nifti', output_nii
    ])
    assert os.path.isfile(output_nii)
예제 #27
0
 def __make_fake_nifti(self, func_path, tmp_dir):
     nifti_path = os.path.join(tmp_dir, 'func.nii.gz')
     command_list = ['wb_command', '-cifti-convert', '-to-nifti', func_path,
                     nifti_path]
     run(command_list)
     if not os.path.exists(nifti_path):
         logger.critical("Failed to generate file critical file: {} failed "
                 "command: {}".format(nifti_path, " ".join(command_list)))
         sys.exit(1)
     return nifti_path
예제 #28
0
 def __generate_roi(self, vert_type, network_csv, seed_radius, l_surface,
         r_surface, output):
     ## make the overlaying ROIs
     run(['ciftify_surface_rois', '--vertex-col', vert_type, network_csv,
             str(seed_radius), l_surface, r_surface, output])
     if not os.path.exists(output):
         logger.error("Could not generate needed ROIs output file: "
                 "{}".format(output))
         sys.exit(1)
     return
예제 #29
0
def define_surface_settings(arguments, tmpdir):
    ''' parse arguments to define surfaces '''

    surf_settings = {
        'L': {
            'surface': arguments['--left-surface'],
            'vertex_areas': arguments['--left-surf-area'],
            'wb_structure': 'CORTEX_LEFT',
            'hemi': 'L'
        },
        'R': {
            'surface': arguments['--right-surface'],
            'vertex_areas': arguments['--right-surf-area'],
            'wb_structure': 'CORTEX_RIGHT',
            'hemi': 'R'
        },
    }

    if any((surf_settings['L']['surface'] == None,
            surf_settings['R']['surface'] == None)):
        if all((surf_settings['L']['surface'] == None,
                surf_settings['R']['surface'] == None)):
            for hemi in ['L', 'R']:
                surf_settings[hemi]['surface'] = os.path.join(
                    ciftify.config.find_HCP_S1200_GroupAvg(),
                    'S1200.{}.midthickness_MSMAll.32k_fs_LR.surf.gii'
                    ''.format(hemi))
                surf_settings[hemi]['vertex_areas'] = os.path.join(
                    ciftify.config.find_HCP_S1200_GroupAvg(),
                    'S1200.{}.midthickness_MSMAll_va.32k_fs_LR.shape.gii'
                    ''.format(hemi))
        else:
            logger.error(
                "Need both left and right surfaces - only one surface given")
            sys.exit(1)

    if any((surf_settings['L']['vertex_areas'] == None,
            surf_settings['R']['vertex_areas'] == None)):
        if all((surf_settings['L']['vertex_areas'] == None,
                surf_settings['R']['vertex_areas'] == None)):
            for hemi in ['L', 'R']:
                surf_settings[hemi]['vertex_areas'] = os.path.join(
                    tmpdir, 'surf{}_va.shape.gii'.format(hemi))
                run([
                    'wb_command', '-surface-vertex-areas',
                    surf_settings[hemi]['surface'],
                    surf_settings[hemi]['vertex_areas']
                ])
        else:
            logger.error(
                "Need both left and right surface area arguments - only one given"
            )
            sys.exit(1)

    return (surf_settings)
예제 #30
0
    def test_handles_string_commands(self, mock_popen):
        mock_popen.return_value.communicate.return_value = (b'', b'')
        mock_popen.return_value.returncode = 0
        cmd = 'touch ./test_file.txt'

        utils.run(cmd)

        assert mock_popen.call_count == 1
        # First item in list, first argument in tuple format,
        # first item of this tuple
        assert mock_popen.call_args_list[0][0][0] == cmd