Exemple #1
0
def save_frmi_color_per_subject(out_file, threshold=2):
    # subjects_folders = utils.get_subfolders(SPM_ROOT)
    good_subjects = ['pp002', 'pp003', 'pp004', 'pp005', 'pp006']
    subjects_folders = [os.path.join(SPM_ROOT, sub) for sub in good_subjects]
    subjects_colors = utils.get_spaced_colors(len(subjects_folders))
    # subjects_colors = utils.arr_to_colors(range(len(subjects_folders)), colors_map='Set1')[:, :3]
    for hemi in ['rh', 'lh']:
        first = True
        all_colors = []
        for sub_id, (subject_fol, subject_color) in enumerate(
                zip(subjects_folders, subjects_colors)):
            subject = utils.namebase(subject_fol)
            print(hemi, subject)
            # if subject not in good_subjects:
            #     continue
            fs_hemi_map = os.path.join(
                subject_fol,
                FS_HEMI_MAP_TEMPLATE.format(subject=subject, hemi=hemi))
            old, brain = get_hemi_data(FS_SUBJECT, hemi, fs_hemi_map, 'pial')
            x = old.mlab_data
            brain.close()
            # x = nib.load(fs_hemi_map).get_data().squeeze()
            # plt.hist(x, bins=50)
            # plt.show()
            subject_colors = np.ones((len(x), 3))
            print(sum(x > threshold))
            # print(np.unique(x[np.where(x)]))
            subject_colors[x > threshold, :] = subject_color
            all_colors.append(subject_colors)
        all_colors = np.array(all_colors).mean(0)
        all_colors = np.hstack((np.ones(
            (all_colors.shape[0], 1)) * 10, all_colors))
        np.save(out_file.format(hemi=hemi), all_colors)
Exemple #2
0
def run_over_subjects(print_only=False, use_scaled_masks=False):
    for subject_fol in utils.get_subfolders(SPM_ROOT):
        subject = utils.namebase(subject_fol)
        spm_brain_file = SPM_BRAIN_TEMPLATE.format(subject=subject.upper())
        reg_file = '{}_register.lta'.format(subject)
        reg_spm_brain = '{}_reg.mgz'.format(subject)
        spm_map = os.path.basename(
            glob.glob(os.path.join(subject_fol, 'spmT_*.nii'))[0])
        spm_mask = SPM_MASK_TEMPLATE.format(subject=subject.upper())
        if use_scaled_masks:
            spm_mask_name, spm_mask_type = os.path.splitext(spm_mask)
            spm_mask = '{}_scaled{}'.format(spm_mask_name, spm_mask_type)
        spm_map_masked = '{}_masked.mgz'.format(os.path.splitext(spm_map)[0])
        fs_hemi_map = FS_HEMI_MAP_TEMPLATE.format(subject=subject,
                                                  hemi='{hemi}')
        run(subject_fol,
            spm_brain_file,
            FS_BRAIN_FILE,
            reg_file,
            reg_spm_brain,
            spm_map,
            spm_mask,
            spm_map_masked,
            fs_hemi_map,
            fs_subject=FS_SUBJECT,
            print_only=print_only)
Exemple #3
0
def run_over_subjects(print_only=False, use_scaled_masks=False):
    for subject_fol in utils.get_subfolders(SPM_ROOT):
        subject = utils.namebase(subject_fol)
        spm_brain_file = SPM_BRAIN_TEMPLATE.format(subject=subject.upper())
        reg_file = "{}_register.lta".format(subject)
        reg_spm_brain = "{}_reg.mgz".format(subject)
        spm_map = os.path.basename(glob.glob(os.path.join(subject_fol, "spmT_*.nii"))[0])
        spm_mask = SPM_MASK_TEMPLATE.format(subject=subject.upper())
        if use_scaled_masks:
            spm_mask_name, spm_mask_type = os.path.splitext(spm_mask)
            spm_mask = "{}_scaled{}".format(spm_mask_name, spm_mask_type)
        spm_map_masked = "{}_masked.mgz".format(os.path.splitext(spm_map)[0])
        fs_hemi_map = FS_HEMI_MAP_TEMPLATE.format(subject=subject, hemi="{hemi}")
        run(
            subject_fol,
            spm_brain_file,
            FS_BRAIN_FILE,
            reg_file,
            reg_spm_brain,
            spm_map,
            spm_mask,
            spm_map_masked,
            fs_hemi_map,
            fs_subject=FS_SUBJECT,
            print_only=print_only,
        )
Exemple #4
0
def save_frmi_color_per_subject(out_file, threshold=2):
    # subjects_folders = utils.get_subfolders(SPM_ROOT)
    good_subjects = ["pp002", "pp003", "pp004", "pp005", "pp006"]
    subjects_folders = [os.path.join(SPM_ROOT, sub) for sub in good_subjects]
    subjects_colors = utils.get_spaced_colors(len(subjects_folders))
    # subjects_colors = utils.arr_to_colors(range(len(subjects_folders)), colors_map='Set1')[:, :3]
    for hemi in ["rh", "lh"]:
        first = True
        all_colors = []
        for sub_id, (subject_fol, subject_color) in enumerate(zip(subjects_folders, subjects_colors)):
            subject = utils.namebase(subject_fol)
            print(hemi, subject)
            # if subject not in good_subjects:
            #     continue
            fs_hemi_map = os.path.join(subject_fol, FS_HEMI_MAP_TEMPLATE.format(subject=subject, hemi=hemi))
            old, brain = get_hemi_data(FS_SUBJECT, hemi, fs_hemi_map, "pial")
            x = old.mlab_data
            brain.close()
            # x = nib.load(fs_hemi_map).get_data().squeeze()
            # plt.hist(x, bins=50)
            # plt.show()
            subject_colors = np.ones((len(x), 3))
            print(sum(x > threshold))
            # print(np.unique(x[np.where(x)]))
            subject_colors[x > threshold, :] = subject_color
            all_colors.append(subject_colors)
        all_colors = np.array(all_colors).mean(0)
        all_colors = np.hstack((np.ones((all_colors.shape[0], 1)) * 10, all_colors))
        np.save(out_file.format(hemi=hemi), all_colors)
def get_subjects():
    if not op.isfile(op.join(LOCAL_ROOT_DIR, 'subjects.npy')):
        epos = glob.glob(op.join(REMOTE_ROOT_DIR, 'ave', '*_ecr_nTSSS_conflict-epo.fif'))
        subjects = [utils.namebase(s).split('_')[0] for s in epos]
        np.save(op.join(LOCAL_ROOT_DIR, 'subjects'), subjects)
        print(subjects)
    else:
        subjects = np.load(op.join(LOCAL_ROOT_DIR, 'subjects.npy'))
    return subjects
def scale_masks(scale = 10):
    for subject_fol in utils.get_subfolders(SPM_ROOT):
        subject = utils.namebase(subject_fol)
        spm_mask = SPM_MASK_TEMPLATE.format(subject=subject.upper())
        spm_scaled_mask = os.path.join(subject_fol, '{}_scaled{}'.format(os.path.splitext(spm_mask)[0],os.path.splitext(spm_mask)[1]))
        img = nib.load(os.path.join(subject_fol, spm_mask))
        data = img.get_data()
        affine = img.get_affine()
        scaled_data = data * scale
        new_img = nib.Nifti1Image(scaled_data, affine)
        nib.save(new_img, spm_scaled_mask)
Exemple #7
0
def check_colors():
    subjects_folders = utils.get_subfolders(SPM_ROOT)
    good_subjects = ['pp002', 'pp003', 'pp004', 'pp005', 'pp006']
    subjects_folders = [os.path.join(SPM_ROOT, sub) for sub in good_subjects]
    subjects_colors = utils.get_spaced_colors(len(subjects_folders))
    # subjects_colors = utils.arr_to_colors(range(len(subjects_folders)), colors_map='Set1')
    plt.figure()
    for subject_fol, color in zip(subjects_folders, subjects_colors):
        subject = utils.namebase(subject_fol)
        plt.scatter([0], [0], label='{} {}'.format(subject, color), c=color)
    plt.legend()
    plt.show()
Exemple #8
0
def check_colors():
    subjects_folders = utils.get_subfolders(SPM_ROOT)
    good_subjects = ["pp002", "pp003", "pp004", "pp005", "pp006"]
    subjects_folders = [os.path.join(SPM_ROOT, sub) for sub in good_subjects]
    subjects_colors = utils.get_spaced_colors(len(subjects_folders))
    # subjects_colors = utils.arr_to_colors(range(len(subjects_folders)), colors_map='Set1')
    plt.figure()
    for subject_fol, color in zip(subjects_folders, subjects_colors):
        subject = utils.namebase(subject_fol)
        plt.scatter([0], [0], label="{} {}".format(subject, color), c=color)
    plt.legend()
    plt.show()
def _morphed_epochs_files(params):
    subject, cond_name, stc_file_name, inverse_method, subjects_dir = params
    print('morphing {}'.format(stc_file_name))
    epoch_id = utils.namebase(stc_file_name).split('_')[2]
    morphed_stc_file_name = op.join(LOCAL_ROOT_DIR, 'stc_epochs_morphed',  '{}_{}_{}_{}'.format(subject, cond_name, epoch_id, inverse_method))
    if not op.isfile('{}-stc.h5'.format(morphed_stc_file_name)):
        stc = mne.read_source_estimate(stc_file_name)
        stc_morphed = mne.morph_data(subject, 'fsaverage', stc, grade=5, smooth=20,
            subjects_dir=subjects_dir)
        stc_morphed.save(morphed_stc_file_name, ftype='h5')
    else:
        print('{} {} {} already morphed'.format(subject, cond_name, epoch_id))
Exemple #10
0
def scale_masks(scale=10):
    for subject_fol in utils.get_subfolders(SPM_ROOT):
        subject = utils.namebase(subject_fol)
        spm_mask = SPM_MASK_TEMPLATE.format(subject=subject.upper())
        spm_scaled_mask = os.path.join(
            subject_fol, "{}_scaled{}".format(os.path.splitext(spm_mask)[0], os.path.splitext(spm_mask)[1])
        )
        img = nib.load(os.path.join(subject_fol, spm_mask))
        data = img.get_data()
        affine = img.get_affine()
        scaled_data = data * scale
        new_img = nib.Nifti1Image(scaled_data, affine)
        nib.save(new_img, spm_scaled_mask)
Exemple #11
0
def get_morphed_epochs_stcs(tmin, tmax, cond_name, subsects_to_choose_from=None, stcs_num=None, inverse_method='dSPM'):
    if subsects_to_choose_from is None:
        subsects_to_choose_from = get_subjects()
    epochs = glob.glob(op.join(LOCAL_ROOT_DIR, 'stc_epochs_morphed', '*_{}_*_{}-stc.h5'.format(cond_name, inverse_method)))
    epochs_subset = [ep for ep in epochs if utils.namebase(ep).split('_')[0] in subsects_to_choose_from]
    if len(epochs_subset) == 0 or stcs_num is not None and len(epochs_subset) < stcs_num:
        print('subset to choose from is smaller({}) than {}! {}'.format(len(epochs_subset), stcs_num, subsects_to_choose_from))
        return None
    if stcs_num is not None:
        epochs_subset = random.sample(epochs_subset, stcs_num)
    for ind, epoc_helthy_file_name in enumerate(epochs_subset):
        print('reading stc {}/{}'.format(ind, len(epochs_subset)))
        stc = mne.read_source_estimate(epoc_helthy_file_name)
        stc.crop(tmin, tmax)
        if ind==0:
            stcs = np.zeros(stc.data.shape + (len(epochs_subset), ))
        # data = stc.data.T # time x space
        stcs[:, :, ind] = stc.data
    return stcs
Exemple #12
0
def calc_average_hc_epochs_stc(events_id, inverse_method='dSPM'):
    epochs_num = len(glob.glob(op.join(LOCAL_ROOT_DIR, 'stc_epochs', '{}_{}_*_{}-stc.h5'.format(get_healthy_controls()[0], events_id.keys()[0], inverse_method))))
    epochs_num = 36
    for cond_name in events_id.keys():
        for epoch_id in range(epochs_num):
            averaged_stc_file_name = op.join(LOCAL_ROOT_DIR, 'stc_hc_average_epochs',  '{}_{}_{}'.format(cond_name, epoch_id, inverse_method))
            if op.isfile('{}.npy'.format(averaged_stc_file_name)):
                print('averaged hc stc was already calculated for {} {}'.format(cond_name, epoch_id))
            else:
                stc_files = glob.glob(op.join(LOCAL_ROOT_DIR, 'stc_epochs_morphed', '*_{}_{}_{}-stc.h5'.format(cond_name, epoch_id, inverse_method)))
                # Get only the healthy controls
                stc_files = [stc_file_name for stc_file_name in stc_files if utils.namebase(stc_file_name).split('_')[0] in get_healthy_controls()]
                stcs = []
                for ind, stc_file_name in enumerate(stc_files):
                    if op.isfile(stc_file_name):
                        stc = mne.read_source_estimate(stc_file_name)
                        stcs.append(stc.data)
                stcs = np.array(stcs)
                stc_avg = stcs.data.mean(0).reshape(stc.data.shape)
                np.save(averaged_stc_file_name, stc_avg)