Пример #1
0
def test_morph_labels():
    """Test morph_labels."""
    # Just process the first 5 labels for speed
    parc_fsaverage = read_labels_from_annot('fsaverage',
                                            'aparc',
                                            subjects_dir=subjects_dir)[:5]
    parc_sample = read_labels_from_annot('sample',
                                         'aparc',
                                         subjects_dir=subjects_dir)[:5]
    parc_fssamp = morph_labels(parc_fsaverage,
                               'sample',
                               subjects_dir=subjects_dir)
    for lf, ls, lfs in zip(parc_fsaverage, parc_sample, parc_fssamp):
        assert lf.hemi == ls.hemi == lfs.hemi
        assert lf.name == ls.name == lfs.name
        perc_1 = np.in1d(lfs.vertices, ls.vertices).mean() * 100
        perc_2 = np.in1d(ls.vertices, lfs.vertices).mean() * 100
        # Ideally this would be 100%, but we do not use the same algorithm
        # as FreeSurfer ...
        assert perc_1 > 92
        assert perc_2 > 88
    with pytest.raises(ValueError, match='wrong and fsaverage'):
        morph_labels(parc_fsaverage,
                     'sample',
                     subjects_dir=subjects_dir,
                     subject_from='wrong')
    with pytest.raises(RuntimeError, match='Number of surface vertices'):
        _load_vert_pos('sample', subjects_dir, 'white', 'lh', 1)
    for label in parc_fsaverage:
        label.subject = None
    with pytest.raises(ValueError, match='subject_from must be provided'):
        morph_labels(parc_fsaverage, 'sample', subjects_dir=subjects_dir)
Пример #2
0
def test_morph_labels():
    """Test morph_labels."""
    # Just process the first 5 labels for speed
    parc_fsaverage = read_labels_from_annot(
        'fsaverage', 'aparc', subjects_dir=subjects_dir)[:5]
    parc_sample = read_labels_from_annot(
        'sample', 'aparc', subjects_dir=subjects_dir)[:5]
    parc_fssamp = morph_labels(
        parc_fsaverage, 'sample', subjects_dir=subjects_dir)
    for lf, ls, lfs in zip(parc_fsaverage, parc_sample, parc_fssamp):
        assert lf.hemi == ls.hemi == lfs.hemi
        assert lf.name == ls.name == lfs.name
        perc_1 = np.in1d(lfs.vertices, ls.vertices).mean() * 100
        perc_2 = np.in1d(ls.vertices, lfs.vertices).mean() * 100
        # Ideally this would be 100%, but we do not use the same algorithm
        # as FreeSurfer ...
        assert perc_1 > 92
        assert perc_2 > 88
    with pytest.raises(ValueError, match='wrong and fsaverage'):
        morph_labels(parc_fsaverage, 'sample', subjects_dir=subjects_dir,
                     subject_from='wrong')
    with pytest.raises(RuntimeError, match='Number of surface vertices'):
        _load_vert_pos('sample', subjects_dir, 'white', 'lh', 1)
    for label in parc_fsaverage:
        label.subject = None
    with pytest.raises(ValueError, match='subject_from must be provided'):
        morph_labels(parc_fsaverage, 'sample', subjects_dir=subjects_dir)
Пример #3
0
def mvgc_main(cond, i, d, normalize):

    meg = subjects[i]
    sub_to = MRI_sub[i][1:15]

    # morph labels from fsaverage to each subject
    morphed_labels = mne.morph_labels(SN_ROI, subject_to=data_path+sub_to,
                                      subject_from='fsaverage',
                                      subjects_dir=data_path)
    # read epochs
    epo_name = data_path + meg + 'block_'+cond+'_words_epochs-epo.fif'

    epochs_cond = mne.read_epochs(epo_name, preload=True)

    # crop epochs
    epochs = epochs_cond['words'].copy(
    ).crop(-.200, .900).resample(f_down_sampling)
    inv_fname_epoch = data_path + meg + 'InvOp_'+cond+'_EMEG-inv.fif'

    output_roi = mvgc_roi(epochs, inv_fname_epoch, morphed_labels, sub_to)

    for roi_x in C.rois_labels:
        for roi_y in C.rois_labels:
            mvgc_parallel(epochs, output_roi, roi_x, roi_y, d, i, cond,
                         normalize)
Пример #4
0
def morph_labels_from_fsaverage(mri_sub):
    parcellations = ['aparc_sub', 'HCPMMP1_combined', 'HCPMMP1']
    if not isfile(join(mri_sub.subjects_dir, 'fsaverage/label',
                       'lh.' + parcellations[0] + '.annot')):
        mne.datasets.fetch_hcp_mmp_parcellation(subjects_dir=mri_sub.subjects_dir,
                                                verbose=True)

        mne.datasets.fetch_aparc_sub_parcellation(subjects_dir=mri_sub.subjects_dir,
                                                  verbose=True)
    else:
        print('You\'ve already downloaded the parcellations, splendid!')

    if not isfile(join(mri_sub.subjects_dir, mri_sub.name, 'label',
                       'lh.' + parcellations[0] + '.annot')):
        for pc in parcellations:
            labels = mne.read_labels_from_annot('fsaverage', pc, hemi='both')

            m_labels = mne.morph_labels(labels, mri_sub.name, 'fsaverage', mri_sub.subjects_dir,
                                        surf_name='pial')

            mne.write_labels_to_annot(m_labels, subject=mri_sub.name, parc=pc,
                                      subjects_dir=mri_sub.subjects_dir, overwrite=True)

    else:
        print(f'{parcellations} already exist')
Пример #5
0
def write_aparc_sub(subjid=None, subjects_dir=None):
    '''Check for fsaverage and aparc_sub and download
    Morph fsaverage aparc_sub labels to single subject data
    
    https://mne.tools/stable/auto_examples/visualization/plot_parcellation.html
    '''
    mne.datasets.fetch_fsaverage(verbose='ERROR')  #True requires TQDM
    mne.datasets.fetch_aparc_sub_parcellation(subjects_dir=subjects_dir,
                                              verbose='ERROR')

    sub_labels = mne.read_labels_from_annot('fsaverage',
                                            parc='aparc_sub',
                                            subjects_dir=subjects_dir)
    subject_labels = mne.morph_labels(sub_labels,
                                      subject_to=subjid,
                                      subjects_dir=subjects_dir)
    mne.write_labels_to_annot(subject_labels,
                              subject=subjid,
                              parc='aparc_sub',
                              subjects_dir=subjects_dir,
                              overwrite=True)
Пример #6
0
def tfr_roi(i, subjects, MRI_sub, roi, freq, n_cycles):
    X = np.zeros([2 * len(roi), len(freq), 600])
    meg = subjects[i]
    sub_to = MRI_sub[i][1:15]
    print('Participant : ', i)

    # morphing ROIs from fsaverage to each individual
    morphed_labels = mne.morph_labels(roi,
                                      subject_to=sub_to,
                                      subject_from='fsaverage',
                                      subjects_dir=data_path)
    # Reading epochs for SD(n=0)/LD(n=1)
    for n in np.array([0, 1]):
        epo_name = data_path + meg + epochs_names[n]
        epochs = mne.read_epochs(epo_name, preload=True)
        epochs = epochs['words'].resample(500)

        # Reading inverse operator
        inv_fname = data_path + meg + inv_op_name[n]
        inv_op = read_inverse_operator(inv_fname)

        # Computing the power and phase lock value for each ROI
        for j in np.arange(0, len(morphed_labels)):
            print('Participant: ', i, '/ condition: ', n, '/ ROI: ', j)
            power, itc = source_induced_power(epochs,
                                              inverse_operator=inv_op,
                                              freqs=freq,
                                              label=morphed_labels[j],
                                              lambda2=C.lambda2,
                                              method='MNE',
                                              baseline=(-.300, 0),
                                              baseline_mode='percent',
                                              n_jobs=-1,
                                              n_cycles=n_cycles,
                                              zero_mean=True)
            # Averaging across vertices
            # Power
            X[i, n * len(morphed_labels) + j, :, :] = power.copy().mean(0)
    return X
Пример #7
0
def method_linear_transformation_main(cond, roi_y, roi_x, i, normalize):
    print('***Running sn_transformation_main...')
    meg = subjects[i]
    sub_to = mri_sub[i][1:15]

    # file_name to save the output
    file_name = os.path.expanduser('~') + \
        '/my_semnet/json_files/transformation/trans_' + cond + '_x' + \
        str(roi_x) + '-y' + str(roi_y) + '_sub_' + str(i) + '_' + \
        str(t_down_sampling) + '_bl.json'

    # morph labels from fsaverage to each subject
    morphed_labels = mne.morph_labels(roi, subject_to=data_path + sub_to,
                                      subject_from='fsaverage',
                                      subjects_dir=data_path)

    # read,crop and resample epochs
    epoch_name = data_path + meg + 'block_' + cond + '_words_epochs-epo.fif'
    epoch_condition = mne.read_epochs(epoch_name, preload=True)
    epochs = epoch_condition['words'].copy().crop(-.200, .900) \
        .resample(f_down_sampling)

    # inverse operator
    inverse_fname_epoch = data_path + meg + 'InvOp_' + cond + '_EMEG-inv.fif'

    print('***Running SN_transformation_io...')
    # prepares the patterns of roi_x and roi_y over time
    output = method_linear_transformation_io(epochs, inverse_fname_epoch,
                                             morphed_labels, sub_to, roi_x,
                                             roi_y)
    print('***Running SN_transformation...')
    # computes the connectivity (explained_variance) of the patterns of roi_x
    # and roi_y over time: roi_x patterns= output[0], roi_y patterns= output[1]
    gof = method_linear_transformation(output[0], output[1], normalize)
    with open(file_name, "wb") as fp:  # Pickling
        pickle.dump(gof, fp)
    return gof
def _compute_rest_psd(subject, kind, freqs):

    ###########################################################################
    # Compute source space
    # -------------------
    src = mne.setup_source_space(subject,
                                 spacing='oct6',
                                 add_dist=False,
                                 subjects_dir=cfg.mne_camcan_freesurfer_path)
    trans = trans_map[subject]
    bem = cfg.mne_camcan_freesurfer_path + \
        "/%s/bem/%s-meg-bem.fif" % (subject, subject)

    ###########################################################################
    # Compute handle MEG data
    # -----------------------

    fname = op.join(cfg.camcan_meg_raw_path, subject, kind,
                    '%s_raw.fif' % kind)

    raw = mne.io.read_raw_fif(fname)
    mne.channels.fix_mag_coil_types(raw.info)
    if DEBUG:
        # raw.crop(0, 180)
        raw.crop(0, 120)
    else:
        raw.crop(0, 300)

    raw = _run_maxfilter(raw, subject, kind)
    _compute_add_ssp_exg(raw)

    # get empty room
    fname_er = op.join(cfg.camcan_meg_path, "emptyroom", subject,
                       "emptyroom_%s.fif" % subject)

    raw_er = mne.io.read_raw_fif(fname_er)
    mne.channels.fix_mag_coil_types(raw.info)

    raw_er = _run_maxfilter(raw_er, subject, kind, coord_frame="meg")
    raw_er.info["projs"] += raw.info["projs"]

    cov = mne.compute_raw_covariance(raw_er, method='oas')
    # compute before band-pass of interest

    event_length = 5.
    event_overlap = 0.
    raw_length = raw.times[-1]
    events = mne.make_fixed_length_events(raw,
                                          duration=event_length,
                                          start=0,
                                          stop=raw_length - event_length)

    #######################################################################
    # Compute the forward and inverse
    # -------------------------------

    info = mne.Epochs(raw,
                      events=events,
                      tmin=0,
                      tmax=event_length,
                      baseline=None,
                      reject=None,
                      preload=False,
                      decim=10).info
    fwd = mne.make_forward_solution(info, trans, src, bem)
    inv = make_inverse_operator(info, fwd, cov)
    del fwd

    #######################################################################
    # Compute label time series and do envelope correlation
    # -----------------------------------------------------
    mne_subjects_dir = "/storage/inria/agramfor/MNE-sample-data/subjects"
    labels = mne.read_labels_from_annot('fsaverage',
                                        'aparc_sub',
                                        subjects_dir=mne_subjects_dir)
    labels = mne.morph_labels(labels,
                              subject_from='fsaverage',
                              subject_to=subject,
                              subjects_dir=cfg.mne_camcan_freesurfer_path)
    labels = [ll for ll in labels if 'unknown' not in ll.name]

    for fmin, fmax, band in freqs:
        print(f"computing {subject}: {fmin} - {fmax} Hz")
        this_raw = raw.copy()
        this_raw.filter(fmin, fmax, n_jobs=1)
        reject = _get_global_reject_epochs(this_raw, decim=5)
        epochs = mne.Epochs(this_raw,
                            events=events,
                            tmin=0,
                            tmax=event_length,
                            baseline=None,
                            reject=reject,
                            preload=True,
                            decim=5)
        if DEBUG:
            epochs = epochs[:3]

        data_cov = mne.compute_covariance(epochs, method='oas')
        stc = _apply_inverse_cov(cov=data_cov,
                                 info=epochs.info,
                                 nave=1,
                                 inverse_operator=inv,
                                 lambda2=1. / 9.,
                                 pick_ori=None,
                                 method='MNE')
        assert np.all(stc.data < 0)

        label_power = mne.extract_label_time_course(
            stc, labels, inv['src'],
            mode="mean")  # XXX signal should be positive

        out_fname = op.join(
            cfg.derivative_path, f'{subject + ("-debug" if DEBUG else "")}_'
            f'cov_mne_{band}.h5')

        mne.externals.h5io.write_hdf5(out_fname, {
            'power': label_power,
            'subject': subject,
            'fmin': fmin,
            'fmax': fmax,
            "band": band,
            'label_names': [ll.name for ll in labels]
        },
                                      overwrite=True)
Пример #9
0
def SN_functional_connectivity_betweenROIs_runs_BL(i, method):
    s = time.time()
    meg = subjects[i]
    sub_to = MRI_sub[i][1:15]

    # stc_SD_file_name=os.path.expanduser('~') +'/my_semnet/json_files/connectivity/con_labels_'+method+'_bl_bands_SD_sub'+str(i)+'.json'
    # stc_LD_file_name=os.path.expanduser('~') +'/my_semnet/json_files/connectivity/con_labels_'+method+'_bl_bands_LD_sub'+str(i)+'.json'
    stc_F_file_name = os.path.expanduser(
        '~'
    ) + '/my_semnet/json_files/connectivity/con_labels_' + method + '_bl_bands_F_sub' + str(
        i) + '.json'
    stc_M_file_name = os.path.expanduser(
        '~'
    ) + '/my_semnet/json_files/connectivity/con_labels_' + method + '_bl_bands_M_sub' + str(
        i) + '.json'
    stc_O_file_name = os.path.expanduser(
        '~'
    ) + '/my_semnet/json_files/connectivity/con_labels_' + method + '_bl_bands_O_sub' + str(
        i) + '.json'

    morphed_labels = mne.morph_labels(SN_ROI,subject_to=data_path+sub_to,\
                  subject_from='fsaverage',subjects_dir=data_path)

    # Reading epochs
    epoch_fname_fruit = data_path + meg + 'block_fruit_epochs-epo.fif'
    epoch_fname_odour = data_path + meg + 'block_odour_epochs-epo.fif'
    epoch_fname_milk = data_path + meg + 'block_milk_epochs-epo.fif'
    epo_name_LD = data_path + meg + 'block_LD_words_epochs-epo.fif'

    epochs_fruit = mne.read_epochs(epoch_fname_fruit, preload=True)
    epochs_odour = mne.read_epochs(epoch_fname_odour, preload=True)
    epochs_milk = mne.read_epochs(epoch_fname_milk, preload=True)
    epochs_ld = mne.read_epochs(epo_name_LD, preload=True)

    epochs_f = mne.epochs.combine_event_ids(
        epochs_fruit, ['visual', 'hear', 'hand', 'neutral', 'emotional'],
        {'words': 15})
    epochs_o = mne.epochs.combine_event_ids(
        epochs_odour, ['visual', 'hear', 'hand', 'neutral', 'emotional'],
        {'words': 15})
    epochs_m = mne.epochs.combine_event_ids(
        epochs_milk, ['visual', 'hear', 'hand', 'neutral', 'emotional'],
        {'words': 15})

    epochs_f = epochs_f['words'].copy().crop(-.200, 0).resample(500)
    epochs_o = epochs_o['words'].copy().crop(-.200, 0).resample(500)
    epochs_m = epochs_m['words'].copy().crop(-.200, 0).resample(500)
    epochs_LD = epochs_ld['words'].copy().crop(-.200, 0).resample(500)

    # Reading inverse operator
    inv_fname_SD = data_path + meg + 'InvOp_SD_EMEG-inv.fif'
    inv_fname_LD = data_path + meg + 'InvOp_LD_EMEG-inv.fif'

    inv_op_SD = read_inverse_operator(inv_fname_SD)
    inv_op_LD = read_inverse_operator(inv_fname_LD)

    stc_F = apply_inverse_epochs(epochs_f,
                                 inv_op_SD,
                                 lambda2,
                                 method='MNE',
                                 pick_ori="normal",
                                 return_generator=False)
    stc_O = apply_inverse_epochs(epochs_o,
                                 inv_op_SD,
                                 lambda2,
                                 method='MNE',
                                 pick_ori="normal",
                                 return_generator=False)
    stc_M = apply_inverse_epochs(epochs_m,
                                 inv_op_SD,
                                 lambda2,
                                 method='MNE',
                                 pick_ori="normal",
                                 return_generator=False)

    stc_LD = apply_inverse_epochs(epochs_LD,
                                  inv_op_LD,
                                  lambda2,
                                  method='MNE',
                                  pick_ori="normal",
                                  return_generator=False)

    src_SD = inv_op_SD['src']
    src_LD = inv_op_LD['src']

    for k in np.arange(0, 6):
        # print('[i,win,k]: ',i,win,k)
        morphed_labels[k].name = C.rois_labels[k]

    for f in np.arange(0, len(C.con_freq_band) - 1):
        print('[i,k,f]: ', i, k, f)
        f_min = C.con_freq_band[f]
        f_max = C.con_freq_band[f + 1]
        print(f_min, f_max)

        labels_ts_f = mne.extract_label_time_course(stc_F, morphed_labels, \
               src_SD, mode='mean_flip',return_generator=False)
        labels_ts_o = mne.extract_label_time_course(stc_O, morphed_labels, \
           src_SD, mode='mean_flip',return_generator=False)
        labels_ts_m = mne.extract_label_time_course(stc_M, morphed_labels, \
                   src_SD, mode='mean_flip',return_generator=False)

        labels_ts_ld= mne.extract_label_time_course(stc_LD, morphed_labels, \
               src_LD, mode='mean_flip',return_generator=False)

        con_F, freqs, times, n_epochs, n_tapers = spectral_connectivity(
            labels_ts_f,
            method=method,
            mode='fourier',
            sfreq=500,
            fmin=f_min,
            fmax=f_max,
            faverage=True,
            n_jobs=10)
        con_O, freqs, times, n_epochs, n_tapers = spectral_connectivity(
            labels_ts_o,
            method=method,
            mode='fourier',
            sfreq=500,
            fmin=f_min,
            fmax=f_max,
            faverage=True,
            n_jobs=10)
        con_M, freqs, times, n_epochs, n_tapers = spectral_connectivity(
            labels_ts_m,
            method=method,
            mode='fourier',
            sfreq=500,
            fmin=f_min,
            fmax=f_max,
            faverage=True,
            n_jobs=10)

        # con_LD, freqs, times, n_epochs, n_tapers = spectral_connectivity(
        #      labels_ts_ld, method=method, mode='fourier',
        #     sfreq=500, fmin=f_min, fmax=f_max, faverage=True, n_jobs=10)
        # con_SD=(con_F+ con_O+ con_M)/3

        # con_labels_SD[f]= con_SD.reshape(6,6)
        # con_labels_LD[f]= con_LD.reshape(6,6)
        con_labels_F[f] = con_F.reshape(6, 6)
        con_labels_M[f] = con_M.reshape(6, 6)
        con_labels_O[f] = con_O.reshape(6, 6)

    # with open(stc_SD_file_name, "wb") as fp:   #Pickling
    #     pickle.dump(con_labels_SD, fp)

    # with open(stc_LD_file_name, "wb") as fp:   #Pickling
    #     pickle.dump(con_labels_LD, fp)

    with open(stc_F_file_name, "wb") as fp:  #Pickling
        pickle.dump(con_labels_F, fp)

    with open(stc_M_file_name, "wb") as fp:  #Pickling
        pickle.dump(con_labels_M, fp)

    with open(stc_O_file_name, "wb") as fp:  #Pickling
        pickle.dump(con_labels_O, fp)

    e = time.time()
    print(e - s)
Пример #10
0
def SN_functional_connectivity_bands(i, method):
    s = time.time()
    meg = subjects[i]
    sub_to = MRI_sub[i][1:15]
    stc_SD_file_name = os.path.expanduser(
        '~'
    ) + '/my_semnet/json_files/connectivity/stc_' + method + '200_equalized_bands_SD_sub' + str(
        i) + '.json'
    stc_LD_file_name = os.path.expanduser(
        '~'
    ) + '/my_semnet/json_files/connectivity/stc_' + method + '200_equalized_bands_LD_sub' + str(
        i) + '.json'
    # stc_SD_file_name=os.path.expanduser('~') +'/my_semnet/json_files/connectivity/stc_'+method+'bl_bands_SD_sub'+str(i)+'.json'
    # stc_LD_file_name=os.path.expanduser('~') +'/my_semnet/json_files/connectivity/stc_'+method+'bl_bands_LD_sub'+str(i)+'.json'

    morphed_labels = mne.morph_labels(SN_ROI,subject_to=data_path+sub_to,\
                  subject_from='fsaverage',subjects_dir=data_path)

    # Reading epochs
    epo_name_SD = data_path + meg + 'block_SD_words_epochs-epo.fif'
    epo_name_LD = data_path + meg + 'block_LD_words_epochs-epo.fif'

    epochs_sd = mne.read_epochs(epo_name_SD, preload=True)
    epochs_ld = mne.read_epochs(epo_name_LD, preload=True)

    epochs_SD = epochs_sd['words'].copy().resample(500)
    epochs_LD = epochs_ld['words'].copy().resample(500)

    equalize_epoch_counts([epochs_SD, epochs_LD])
    # Reading inverse operator
    inv_fname_SD = data_path + meg + 'InvOp_SD_EMEG-inv.fif'
    inv_fname_LD = data_path + meg + 'InvOp_LD_EMEG-inv.fif'

    inv_op_SD = read_inverse_operator(inv_fname_SD)
    inv_op_LD = read_inverse_operator(inv_fname_LD)

    stc_sd = apply_inverse_epochs(epochs_SD,
                                  inv_op_SD,
                                  lambda2,
                                  method='MNE',
                                  pick_ori="normal",
                                  return_generator=False)
    stc_ld = apply_inverse_epochs(epochs_LD,
                                  inv_op_LD,
                                  lambda2,
                                  method='MNE',
                                  pick_ori="normal",
                                  return_generator=False)
    src_SD = inv_op_SD['src']
    src_LD = inv_op_LD['src']
    # Construct indices to estimate connectivity between the label time course
    # and all source space time courses
    vertices_SD = [src_SD[j]['vertno'] for j in range(2)]
    n_signals_tot = 1 + len(vertices_SD[0]) + len(vertices_SD[1])
    indices = seed_target_indices([0], np.arange(1, n_signals_tot))

    morph_SD = mne.compute_source_morph(src=inv_op_SD['src'],\
                    subject_from=sub_to, subject_to=C.subject_to,\
                    spacing=C.spacing_morph, subjects_dir=C.data_path)

    morph_LD = mne.compute_source_morph(src= inv_op_LD['src'],\
                    subject_from=sub_to, subject_to=C.subject_to,\
                    spacing=C.spacing_morph, subjects_dir=C.data_path)

    for win in np.arange(0, len(C.con_time_window) - 1):
        print('[i,win]: ', i, win)

        t_min = C.con_time_window[win]
        t_max = C.con_time_window[win + 1]
        stc_SD = []
        stc_LD = []

        for n in np.arange(0, len(stc_sd)):
            stc_SD.append(stc_sd[n].copy().crop(t_min * 1e-3, t_max * 1e-3))

        for n in np.arange(0, len(stc_ld)):
            stc_LD.append(stc_ld[n].copy().crop(t_min * 1e-3, t_max * 1e-3))

        for k in np.arange(0, 6):
            print('[i,win,k]: ', i, win, k)
            morphed_labels[k].name = C.rois_labels[k]

            seed_ts_sd = mne.extract_label_time_course(stc_SD, morphed_labels[k], \
                        src_SD, mode='mean_flip',return_generator=False)
            seed_ts_ld = mne.extract_label_time_course(stc_LD, morphed_labels[k], \
                        src_LD, mode='mean_flip',return_generator=False)

            for f in np.arange(0, len(C.con_freq_band) - 1):
                print('[i,win,k,f]: ', i, win, k, f)
                f_min = C.con_freq_band[f]
                f_max = C.con_freq_band[f + 1]
                print(f_min, f_max)

                comb_ts_sd = zip(seed_ts_sd, stc_SD)
                comb_ts_ld = zip(seed_ts_ld, stc_LD)

                con_SD, freqs, times, n_epochs, n_tapers = spectral_connectivity(
                    comb_ts_sd,
                    method=method,
                    mode='fourier',
                    indices=indices,
                    sfreq=500,
                    fmin=f_min,
                    fmax=f_max,
                    faverage=True,
                    n_jobs=10)

                con_LD, freqs, times, n_epochs, n_tapers = spectral_connectivity(
                    comb_ts_ld,
                    method=method,
                    mode='fourier',
                    indices=indices,
                    sfreq=500,
                    fmin=f_min,
                    fmax=f_max,
                    faverage=True,
                    n_jobs=10)

                con_stc_SD = mne.SourceEstimate(con_SD, vertices=vertices_SD,\
                              tmin=t_min*1e-3, tstep=2e-3,subject=sub_to)

                con_stc_LD = mne.SourceEstimate(con_LD, vertices=vertices_SD,\
                              tmin=t_min*1e-3, tstep=2e-3,subject=sub_to)

                stc_total_SD[win][k][f] = morph_SD.apply(con_stc_SD)
                stc_total_LD[win][k][f] = morph_LD.apply(con_stc_LD)

    with open(stc_SD_file_name, "wb") as fp:  #Pickling
        pickle.dump(stc_total_SD, fp)

    with open(stc_LD_file_name, "wb") as fp:  #Pickling
        pickle.dump(stc_total_LD, fp)
    e = time.time()
    print(e - s)
Пример #11
0
    evoked_LD = epochs_LD.average().set_eeg_reference(ref_channels = \
                        'average',projection=True)

    # Applying inverse solution to get sourse signals    
    stc_sd = apply_inverse(evoked_SD, inv_op_SD,lambda2,method ='MNE', 
                           pick_ori=None)
    stc_ld = apply_inverse(evoked_LD, inv_op_LD,lambda2,method ='MNE',
                           pick_ori=None)

    # stc_sd_corrected = stc_baseline_correction(stc_sd) 
    # stc_ld_corrected = stc_baseline_correction(stc_ld) 
   
    src_SD = inv_op_SD['src']
    src_LD = inv_op_LD['src']
    
    morphed_labels = mne.morph_labels(SN_ROI,subject_to=sub_to,\
                  subject_from='fsaverage',subjects_dir=C.data_path)

    
    # label_ts_SD = mne.extract_label_time_course(stc_SD, morphed_labels,\
    #               src_SD, mode='mean_flip')       
    # label_ts_LD = mne.extract_label_time_course(stc_LD, morphed_labels,\
    #               src_LD,mode='mean_flip') 
    
    # X[i,0:6,:] = label_ts_SD[:,0:850] 
    # Y[i,0:6,:] = label_ts_LD[:,0:850] 
        
    for j in np.arange(0,6):
        morphed_labels[j].subject = sub_to   
        
        label_vertices =  stc_sd.in_label(morphed_labels[j])  
        stc_sd_corrected = stc_baseline_correction(label_vertices) 
Пример #12
0
        epochs = mne.Epochs(
            raw_use,
            events=events,
            tmin=0,
            tmax=tmax,
            baseline=None,
            reject=None,
            flat=None,
            preload=True,
            decim=decim,
        )
        epochs.apply_hilbert(envelope=False)

        # Compute ROI time series and do envelope correlation
        inv = mne.minimum_norm.read_inverse_operator(inv_fname)
        these_rois = mne.morph_labels(all_rois, subject, "fsaverage",
                                      defaults.subjects_dir)
        these_rois = [
            roi for roi in these_rois if not roi.name.startswith("unknown")
        ]
        stcs = apply_inverse_epochs(
            epochs,
            inv,
            lambda2=1.0 / 9.0,
            pick_ori="normal",
            return_generator=True,
        )
        label_ts = mne.extract_label_time_course(stcs,
                                                 these_rois,
                                                 inv["src"],
                                                 return_generator=True)
Пример #13
0
                           lambda2,
                           method='MNE',
                           pick_ori="normal")
    stc_ld = apply_inverse(evoked_LD,
                           inv_op_LD,
                           lambda2,
                           method='MNE',
                           pick_ori="normal")
    stc_SD = stc_baseline_correction(stc_sd, -300, 0)
    stc_LD = stc_baseline_correction(stc_ld, -300, 0)

    src_SD = inv_op_SD['src']
    src_LD = inv_op_LD['src']
    # Average the source estimates within each label using sign-flips to reduce
    # signal cancellations, also here we return a generator
    morphed_labels = mne.morph_labels(labels,subject_to=data_path+sub_to,\
                     subject_from='fsaverage',subjects_dir=data_path)

    label_ts_SD = mne.extract_label_time_course(stc_SD, morphed_labels, src_SD,\
                  mode='mean_flip')
    label_ts_LD = mne.extract_label_time_course(stc_LD, morphed_labels, src_LD,\
                  mode='mean_flip')

    X_SD[i, :, :] = label_ts_SD
    X_LD[i, :, :] = label_ts_LD

    # for i in np.arange(0,len(labels)-5):
my_colors = ['b', 'r', 'y', 'g', 'black', 'c']
labless = ['lATL', 'rATL', 'TG', 'IFG', 'AG', 'V']
t_value, p_value = stats.ttest_rel(X_SD, X_LD)
y = np.arange(0, 600)
fig, ax = plt.subplots(4, figsize=(10, 40))
def SN_effective_connectivity_bands(i, method):
    n_subjects = len(subjects)
    meg = subjects[i]
    sub_to = MRI_sub[i][1:15]

    print('Participant : ', i)
    stc_SD_file_name = os.path.expanduser(
        '~'
    ) + '/my_semnet/json_files/connectivity/stc_' + method + '200_bands_SD_sub' + str(
        i) + '.json'
    stc_LD_file_name = os.path.expanduser(
        '~'
    ) + '/my_semnet/json_files/connectivity/stc_' + method + '200_bands_LD_sub' + str(
        i) + '.json'
    morphed_labels = mne.morph_labels(SN_ROI,subject_to=data_path+sub_to,\
                  subject_from='fsaverage',subjects_dir=data_path)

    # Reading epochs
    epo_name_SD = data_path + meg + 'block_SD_words_epochs-epo.fif'
    epo_name_LD = data_path + meg + 'block_LD_words_epochs-epo.fif'

    epochs_sd = mne.read_epochs(epo_name_SD, preload=True)
    epochs_ld = mne.read_epochs(epo_name_LD, preload=True)

    epochs_SD = epochs_sd['words'].copy().resample(500)
    epochs_LD = epochs_ld['words'].copy().resample(500)

    # Equalize trial counts to eliminate bias (which would otherwise be
    # introduced by the abs() performed below)
    equalize_epoch_counts([epochs_SD, epochs_LD])

    # Reading inverse operator
    inv_fname_SD = data_path + meg + 'InvOp_SD_EMEG-inv.fif'
    inv_fname_LD = data_path + meg + 'InvOp_LD_EMEG-inv.fif'

    inv_op_SD = read_inverse_operator(inv_fname_SD)
    inv_op_LD = read_inverse_operator(inv_fname_LD)

    stc_sd = apply_inverse_epochs(epochs_SD,
                                  inv_op_SD,
                                  C.lambda2,
                                  method='MNE',
                                  pick_ori="normal",
                                  return_generator=False)
    stc_ld = apply_inverse_epochs(epochs_LD,
                                  inv_op_LD,
                                  C.lambda2,
                                  method='MNE',
                                  pick_ori="normal",
                                  return_generator=False)
    times = epochs_SD.times
    stc_SD_t = []
    stc_LD_t = []

    src_SD = inv_op_SD['src']
    src_LD = inv_op_LD['src']
    # Construct indices to estimate connectivity between the label time course
    # and all source space time courses
    vertices_SD = [src_SD[j]['vertno'] for j in range(2)]
    n_signals_tot = 1 + len(vertices_SD[0]) + len(vertices_SD[1])
    indices = seed_target_indices([0], np.arange(1, n_signals_tot))

    morph_SD = mne.compute_source_morph(src=inv_op_SD['src'],\
                    subject_from=sub_to, subject_to=C.subject_to,\
                    spacing=C.spacing_morph, subjects_dir=C.data_path)

    morph_LD = mne.compute_source_morph(src= inv_op_LD['src'],\
                    subject_from=sub_to, subject_to=C.subject_to,\
                    spacing=C.spacing_morph, subjects_dir=C.data_path)

    for n in np.arange(0, len(stc_sd)):
        stc_SD_t.append(stc_baseline_correction(stc_sd[n], times))
        stc_LD_t.append(stc_baseline_correction(stc_ld[n], times))

    for win in np.arange(0, len(C.con_time_window)):
        t_min = C.con_time_window[win]
        t_max = C.con_time_window[win] + C.con_time_window_len
        stc_SD = []
        stc_LD = []
        for n in np.arange(0, len(stc_sd)):
            stc_SD.append(stc_SD_t[n].copy().crop(t_min * 1e-3, t_max * 1e-3))
            stc_LD.append(stc_LD_t[n].copy().crop(t_min * 1e-3, t_max * 1e-3))

        for k in np.arange(0, 6):
            print('Participant : ', i, '/ ROI: ', k)
            morphed_labels[k].name = C.rois_labels[k]

            seed_ts_sd = mne.extract_label_time_course(stc_SD, morphed_labels[k], \
                       src_SD, mode='mean_flip',return_generator=False)
            seed_ts_ld = mne.extract_label_time_course(stc_LD, morphed_labels[k], \
                       src_LD, mode='mean_flip',return_generator=False)

            for f in np.arange(0, len(C.con_freq_band_psi) - 1):
                f_min = C.con_freq_band_psi[f]
                f_max = C.con_freq_band_psi[f + 1]
                print('Participant : ' , i, '/ ROI: ',k,' win:', win,\
                      ' freq: ',f)
                comb_ts_sd = zip(seed_ts_sd, stc_SD)
                comb_ts_ld = zip(seed_ts_ld, stc_LD)

                psi_SD, freqs, times, n_epochs, _ = phase_slope_index(
                    comb_ts_sd,
                    mode='fourier',
                    indices=indices,
                    sfreq=500,
                    fmin=f_min,
                    fmax=f_max,
                    n_jobs=15)

                psi_LD, freqs, times, n_epochs, _ = phase_slope_index(
                    comb_ts_ld,
                    mode='fourier',
                    indices=indices,
                    sfreq=500,
                    fmin=f_min,
                    fmax=f_max,
                    n_jobs=15)


                psi_stc_SD = mne.SourceEstimate(psi_SD, vertices=vertices_SD,\
                             tmin=t_min*1e-3, tstep=2e-3,subject=sub_to)

                psi_stc_LD = mne.SourceEstimate(psi_LD, vertices=vertices_SD,\
                             tmin=t_min*1e-3, tstep=2e-3,subject=sub_to)

                stc_total_SD[win][k][f] = morph_SD.apply(psi_stc_SD)
                stc_total_LD[win][k][f] = morph_LD.apply(psi_stc_LD)

    with open(stc_SD_file_name, "wb") as fp:  #Pickling
        pickle.dump(stc_total_SD, fp)

    with open(stc_LD_file_name, "wb") as fp:  #Pickling
        pickle.dump(stc_total_LD, fp)
    e = time.time()
    print(e - s)
Пример #15
0
def SN_functional_connectivity_betweenROIs(i, method):
    s = time.time()
    meg = subjects[i]
    sub_to = MRI_sub[i][1:15]
    con_SD_file_name = os.path.expanduser(
        '~'
    ) + '/my_semnet/json_files/connectivity/con_labels_' + method + '_bands_SD_sub' + str(
        i) + '.json'
    con_LD_file_name = os.path.expanduser(
        '~'
    ) + '/my_semnet/json_files/connectivity/con_labels_' + method + '_bands_LD_sub' + str(
        i) + '.json'

    morphed_labels = mne.morph_labels(SN_ROI,subject_to=data_path+sub_to,\
                  subject_from='fsaverage',subjects_dir=data_path)

    # Reading epochs
    epo_name_SD = data_path + meg + 'block_SD_words_epochs-epo.fif'
    epo_name_LD = data_path + meg + 'block_LD_words_epochs-epo.fif'

    epochs_sd = mne.read_epochs(epo_name_SD, preload=True)
    epochs_ld = mne.read_epochs(epo_name_LD, preload=True)

    epochs_SD = epochs_sd['words'].copy().resample(500)
    epochs_LD = epochs_ld['words'].copy().resample(500)

    # Equalize trial counts to eliminate bias
    equalize_epoch_counts([epochs_SD, epochs_LD])

    # Reading inverse operator
    inv_fname_SD = data_path + meg + 'InvOp_SD_EMEG-inv.fif'
    inv_fname_LD = data_path + meg + 'InvOp_LD_EMEG-inv.fif'

    inv_op_SD = read_inverse_operator(inv_fname_SD)
    inv_op_LD = read_inverse_operator(inv_fname_LD)

    stc_sd = apply_inverse_epochs(epochs_SD,
                                  inv_op_SD,
                                  lambda2,
                                  method='MNE',
                                  pick_ori="normal",
                                  return_generator=False)
    stc_ld = apply_inverse_epochs(epochs_LD,
                                  inv_op_LD,
                                  lambda2,
                                  method='MNE',
                                  pick_ori="normal",
                                  return_generator=False)
    times = epochs_SD.times
    stc_SD_t = []
    stc_LD_t = []

    src_SD = inv_op_SD['src']
    src_LD = inv_op_LD['src']

    for n in np.arange(0, len(stc_sd)):
        stc_SD_t.append(stc_baseline_correction(stc_sd[n], times))
        stc_LD_t.append(stc_baseline_correction(stc_ld[n], times))

    for win in np.arange(0, len(C.con_time_window) - 1):
        print('[i,win]: ', i, win)

        t_min = C.con_time_window[win]
        t_max = C.con_time_window[win + 1]
        stc_SD = []
        stc_LD = []
        for n in np.arange(0, len(stc_sd)):
            stc_SD.append(stc_SD_t[n].copy().crop(t_min * 1e-3, t_max * 1e-3))
            stc_LD.append(stc_LD_t[n].copy().crop(t_min * 1e-3, t_max * 1e-3))

        for k in np.arange(0, 6):
            # print('[i,win,k]: ',i,win,k)
            morphed_labels[k].name = C.rois_labels[k]

        labels_ts_sd = mne.extract_label_time_course(stc_SD, morphed_labels, \
                   src_SD, mode='mean_flip',return_generator=False)
        labels_ts_ld = mne.extract_label_time_course(stc_LD, morphed_labels, \
                   src_LD, mode='mean_flip',return_generator=False)

        for f in np.arange(0, len(C.con_freq_band) - 1):
            print('[i,win,k,f]: ', i, win, k, f)
            f_min = C.con_freq_band[f]
            f_max = C.con_freq_band[f + 1]
            print(f_min, f_max)

            con_SD, freqs, times, n_epochs, n_tapers = spectral_connectivity(
                labels_ts_sd,
                method=method,
                mode='fourier',
                sfreq=500,
                fmin=f_min,
                fmax=f_max,
                faverage=True,
                n_jobs=10)

            con_LD, freqs, times, n_epochs, n_tapers = spectral_connectivity(
                labels_ts_ld,
                method=method,
                mode='fourier',
                sfreq=500,
                fmin=f_min,
                fmax=f_max,
                faverage=True,
                n_jobs=10)

            con_labels_SD[win][f] = con_SD.reshape(6, 6)
            con_labels_LD[win][f] = con_LD.reshape(6, 6)

    with open(con_SD_file_name, "wb") as fp:  #Pickling
        pickle.dump(con_labels_SD, fp)

    with open(con_LD_file_name, "wb") as fp:  #Pickling
        pickle.dump(con_labels_LD, fp)
    e = time.time()
    print(e - s)
Пример #16
0
# ROI_x=1
# ROI_y=0
s = time.time()
fs = 1000
f_down_sampling = 100  # 100Hz, 20Hz
t_down_sampling = fs / f_down_sampling  # 10ms, 50ms
i = 0
ROI_x, ROI_y = 0, 2
cond = 'fruit'
normalize = True
meg = subjects[i]
sub_to = MRI_sub[i][1:15]

# morph labels from fsaverage to each subject
labels = mne.morph_labels(SN_ROI,
                          subject_to=data_path + sub_to,
                          subject_from='fsaverage',
                          subjects_dir=data_path)

# read epochs
epo_name = data_path + meg + 'block_' + cond + '_words_epochs-epo.fif'

epochs_cond = mne.read_epochs(epo_name, preload=True)

# crop epochs
epochs = epochs_cond['words'].copy().crop(-.200,
                                          .900).resample(f_down_sampling)

# equalize trial counts to eliminate bias
# equalize_epoch_counts([epochs_SD, epochs_LD])

inv_fname_epoch = data_path + meg + 'InvOp_' + cond + '_EMEG-inv.fif'
Пример #17
0
def SN_functional_connectivity_bands_runs(i, method, SN_ROI):
    s = time.time()
    meg = subjects[i]
    sub_to = MRI_sub[i][1:15]
    stc_F_file_name = os.path.expanduser(
        '~'
    ) + '/old_semnet/my_semnet/json_files/connectivity/stc_' + method + '200_F_bands_SD_sub' + str(
        i) + '.json'
    stc_O_file_name = os.path.expanduser(
        '~'
    ) + '/old_semnet/my_semnet/json_files/connectivity/stc_' + method + '200_O_bands_LD_sub' + str(
        i) + '.json'
    stc_M_file_name = os.path.expanduser(
        '~'
    ) + '/old_semnet/my_semnet/json_files/connectivity/stc_' + method + '200_M_bands_SD_sub' + str(
        i) + '.json'
    stc_SD_file_name = os.path.expanduser(
        '~'
    ) + '/old_semnet/my_semnet/json_files/connectivity/stc_' + method + '200_mean_bands_SD_sub' + str(
        i) + '.json'
    stc_LD_file_name = os.path.expanduser(
        '~'
    ) + '/old_semnet/my_semnet/json_files/connectivity/stc_' + method + '200_mean_bands_LD_sub' + str(
        i) + '.json'

    morphed_labels = mne.morph_labels(SN_ROI,
                                      subject_to=sub_to,
                                      subject_from='fsaverage',
                                      subjects_dir=data_path)

    # Reading epochs

    # Reading epochs
    epo_name_LD = data_path + meg + 'block_LD_words_epochs-epo.fif'

    epochs_ld = mne.read_epochs(epo_name_LD, preload=True)

    epochs_LD = epochs_ld['words'].copy().resample(500)

    epoch_fname_fruit = data_path + meg + 'block_fruit_epochs-epo.fif'
    epoch_fname_odour = data_path + meg + 'block_odour_epochs-epo.fif'
    epoch_fname_milk = data_path + meg + 'block_milk_epochs-epo.fif'

    epochs_fruit = mne.read_epochs(epoch_fname_fruit, preload=True)
    epochs_odour = mne.read_epochs(epoch_fname_odour, preload=True)
    epochs_milk = mne.read_epochs(epoch_fname_milk, preload=True)

    epochs_f = mne.epochs.combine_event_ids(
        epochs_fruit, ['visual', 'hear', 'hand', 'neutral', 'emotional'],
        {'words': 15})
    epochs_o = mne.epochs.combine_event_ids(
        epochs_odour, ['visual', 'hear', 'hand', 'neutral', 'emotional'],
        {'words': 15})
    epochs_m = mne.epochs.combine_event_ids(
        epochs_milk, ['visual', 'hear', 'hand', 'neutral', 'emotional'],
        {'words': 15})

    epochs_f = epochs_f['words'].copy().resample(500)
    epochs_o = epochs_o['words'].copy().resample(500)
    epochs_m = epochs_m['words'].copy().resample(500)

    # Reading inverse operator
    inv_fname_SD = data_path + meg + 'InvOp_SD_EMEG-inv.fif'
    inv_fname_LD = data_path + meg + 'InvOp_LD_EMEG-inv.fif'

    inv_op_SD = read_inverse_operator(inv_fname_SD)
    inv_op_LD = read_inverse_operator(inv_fname_LD)

    stc_f = apply_inverse_epochs(epochs_f,
                                 inv_op_SD,
                                 lambda2,
                                 method='MNE',
                                 pick_ori="normal",
                                 return_generator=False)
    stc_o = apply_inverse_epochs(epochs_o,
                                 inv_op_SD,
                                 lambda2,
                                 method='MNE',
                                 pick_ori="normal",
                                 return_generator=False)
    stc_m = apply_inverse_epochs(epochs_m,
                                 inv_op_SD,
                                 lambda2,
                                 method='MNE',
                                 pick_ori="normal",
                                 return_generator=False)
    stc_ld = apply_inverse_epochs(epochs_LD,
                                  inv_op_LD,
                                  lambda2,
                                  method='MNE',
                                  pick_ori="normal",
                                  return_generator=False)

    src_SD = inv_op_SD['src']
    src_LD = inv_op_LD['src']

    # Construct indices to estimate connectivity between the label time course
    # and all source space time courses
    vertices_SD = [src_SD[j]['vertno'] for j in range(2)]
    n_signals_tot = 1 + len(vertices_SD[0]) + len(vertices_SD[1])
    indices = seed_target_indices([0], np.arange(1, n_signals_tot))

    morph_SD = mne.compute_source_morph(src=inv_op_SD['src'],
                                        subject_from=sub_to,
                                        subject_to=C.subject_to,
                                        spacing=C.spacing_morph,
                                        subjects_dir=C.data_path)
    morph_LD = mne.compute_source_morph(src=inv_op_LD['src'],
                                        subject_from=sub_to,
                                        subject_to=C.subject_to,
                                        spacing=C.spacing_morph,
                                        subjects_dir=C.data_path)

    for win in np.arange(0, len(C.con_time_window) - 1):
        print('[i,win]: ', i, win)

        t_min = C.con_time_window[win]
        t_max = C.con_time_window[win + 1]
        stc_F = []
        stc_O = []
        stc_M = []
        stc_LD = []

        for n in np.arange(0, len(stc_f)):
            stc_F.append(stc_f[n].copy().crop(t_min * 1e-3, t_max * 1e-3))
        for n in np.arange(0, len(stc_o)):
            stc_O.append(stc_o[n].copy().crop(t_min * 1e-3, t_max * 1e-3))
        for n in np.arange(0, len(stc_m)):
            stc_M.append(stc_m[n].copy().crop(t_min * 1e-3, t_max * 1e-3))
        for n in np.arange(0, len(stc_ld)):
            stc_LD.append(stc_ld[n].copy().crop(t_min * 1e-3, t_max * 1e-3))

        for k in np.arange(0, 6):
            print('[i,win,k]: ', i, win, k)
            morphed_labels[k].name = C.rois_labels[k]

            seed_ts_f = mne.extract_label_time_course(stc_F,
                                                      morphed_labels[k],
                                                      src_SD,
                                                      mode='mean_flip',
                                                      return_generator=False)
            seed_ts_o = mne.extract_label_time_course(stc_O,
                                                      morphed_labels[k],
                                                      src_SD,
                                                      mode='mean_flip',
                                                      return_generator=False)
            seed_ts_m = mne.extract_label_time_course(stc_M,
                                                      morphed_labels[k],
                                                      src_SD,
                                                      mode='mean_flip',
                                                      return_generator=False)
            seed_ts_ld = mne.extract_label_time_course(stc_LD,
                                                       morphed_labels[k],
                                                       src_LD,
                                                       mode='mean_flip',
                                                       return_generator=False)

            for f in np.arange(0, len(C.con_freq_band) - 1):
                print('[i,win,k,f]: ', i, win, k, f)
                f_min = C.con_freq_band[f]
                f_max = C.con_freq_band[f + 1]
                print(f_min, f_max)

                comb_ts_f = zip(seed_ts_f, stc_F)
                comb_ts_o = zip(seed_ts_o, stc_O)
                comb_ts_m = zip(seed_ts_m, stc_M)
                comb_ts_ld = zip(seed_ts_ld, stc_LD)

                con_F, freqs, times, n_epochs, n_tapers = spectral_connectivity(
                    comb_ts_f,
                    method=method,
                    mode='fourier',
                    indices=indices,
                    sfreq=500,
                    fmin=f_min,
                    fmax=f_max,
                    faverage=True,
                    n_jobs=10)

                con_O, freqs, times, n_epochs, n_tapers = spectral_connectivity(
                    comb_ts_o,
                    method=method,
                    mode='fourier',
                    indices=indices,
                    sfreq=500,
                    fmin=f_min,
                    fmax=f_max,
                    faverage=True,
                    n_jobs=10)

                con_M, freqs, times, n_epochs, n_tapers = spectral_connectivity(
                    comb_ts_m,
                    method=method,
                    mode='fourier',
                    indices=indices,
                    sfreq=500,
                    fmin=f_min,
                    fmax=f_max,
                    faverage=True,
                    n_jobs=10)
                con_LD, freqs, times, n_epochs, n_tapers = spectral_connectivity(
                    comb_ts_ld,
                    method=method,
                    mode='fourier',
                    indices=indices,
                    sfreq=500,
                    fmin=f_min,
                    fmax=f_max,
                    faverage=True,
                    n_jobs=10)

                con_SD = (con_F + con_O + con_M) / 3

                con_stc_F = mne.SourceEstimate(con_F,
                                               vertices=vertices_SD,
                                               tmin=t_min * 1e-3,
                                               tstep=2e-3,
                                               subject=sub_to)
                con_stc_O = mne.SourceEstimate(con_O,
                                               vertices=vertices_SD,
                                               tmin=t_min * 1e-3,
                                               tstep=2e-3,
                                               subject=sub_to)
                con_stc_M = mne.SourceEstimate(con_M,
                                               vertices=vertices_SD,
                                               tmin=t_min * 1e-3,
                                               tstep=2e-3,
                                               subject=sub_to)
                con_stc_SD = mne.SourceEstimate(con_SD,
                                                vertices=vertices_SD,
                                                tmin=t_min * 1e-3,
                                                tstep=2e-3,
                                                subject=sub_to)

                con_stc_LD = mne.SourceEstimate(con_LD,
                                                vertices=vertices_SD,
                                                tmin=t_min * 1e-3,
                                                tstep=2e-3,
                                                subject=sub_to)

                stc_total_F[win][k][f] = morph_SD.apply(con_stc_F)
                stc_total_O[win][k][f] = morph_SD.apply(con_stc_O)
                stc_total_M[win][k][f] = morph_SD.apply(con_stc_M)
                stc_total_SD[win][k][f] = morph_SD.apply(con_stc_SD)
                stc_total_LD[win][k][f] = morph_LD.apply(con_stc_LD)

    # with open(stc_F_file_name, "wb") as fp:   #Pickling
    #     pickle.dump(stc_total_F, fp)
    # with open(stc_O_file_name, "wb") as fp:   #Pickling
    #     pickle.dump(stc_total_O, fp)
    # with open(stc_M_file_name, "wb") as fp:   #Pickling
    #     pickle.dump(stc_total_M, fp)
    # with open(stc_SD_file_name, "wb") as fp:   #Pickling
    #     pickle.dump(stc_total_SD, fp)
    with open(stc_LD_file_name, "wb") as fp:  # Pickling
        pickle.dump(stc_total_LD, fp)
    e = time.time()
    print(e - s)
Пример #18
0
cov = mne.read_cov("{}empty-cov.fif".format(proc_dir))
fs_labels = mne.read_labels_from_annot("fsaverage",
                                       "RegionGrowing_70",
                                       subjects_dir=subjects_dir)
for sub in subjs:
    fwd_name = "{dir}nc_{sub}_{sp}-fwd.fif".format(dir=proc_dir,
                                                   sub=sub,
                                                   sp=spacing)
    fwd = mne.read_forward_solution(fwd_name)
    src_name = "{dir}{sub}_{sp}-src.fif".format(dir=proc_dir,
                                                sub=sub,
                                                sp=spacing)
    src = mne.read_source_spaces(src_name)
    labels = mne.morph_labels(fs_labels,
                              sub_key[sub],
                              subject_from="fsaverage",
                              subjects_dir=subjects_dir)
    for run in runs:
        if run == "rest":
            epo_name = "{dir}nc_{sub}_{run}_hand-epo.fif".format(dir=proc_dir,
                                                                 sub=sub,
                                                                 run=run)
            epo = mne.read_epochs(epo_name)
        else:
            epos = []
            for wav_idx, wav_name in enumerate(wavs):
                epo_name = "{dir}nc_{sub}_{run}_{wav}_hand-epo.fif".format(
                    dir=proc_dir, sub=sub, run=run, wav=wav_name)
                temp_epo = mne.read_epochs(epo_name)
                temp_epo.interpolate_bads()
                epos.append(temp_epo)
Пример #19
0
def make_dataset_from_sample():
    # assign paths
    data_path = mne.datasets.sample.data_path()
    subjects_dir = os.path.join(data_path, 'subjects')
    mne.datasets.fetch_hcp_mmp_parcellation(subjects_dir=subjects_dir,
                                            verbose=True)

    # get parcels and remove corpus callosum
    parcels = read_labels_from_annot('fsaverage',
                                     'HCPMMP1_combined',
                                     'both',
                                     subjects_dir=subjects_dir)
    # corpus callosum labels
    aparc_file_lh = os.path.join(subjects_dir, 'fsaverage', "label",
                                 'lh.aparc.a2009s.annot')
    aparc_file_rh = os.path.join(subjects_dir, 'fsaverage', "label",
                                 'rh.aparc.a2009s.annot')

    labels_corpus_lh = read_labels_from_annot(subject='fsaverage',
                                              annot_fname=aparc_file_lh,
                                              hemi='lh',
                                              subjects_dir=subjects_dir)
    labels_corpus_rh = read_labels_from_annot(subject='fsaverage',
                                              annot_fname=aparc_file_rh,
                                              hemi='rh',
                                              subjects_dir=subjects_dir)

    assert labels_corpus_lh[-1].name[:7] == 'Unknown'  # corpus callosum
    assert labels_corpus_rh[-1].name[:7] == 'Unknown'  # corpus callosum
    corpus_callosum = [labels_corpus_lh[-1], labels_corpus_rh[-1]]

    # remove from parcels all the vertices from corpus callosum
    to_remove = []
    for idx, parcel in enumerate(parcels):
        if parcel.hemi == 'lh':
            cc_free = set(parcel.vertices) - set(corpus_callosum[0].vertices)
        elif parcel.hemi == 'rh':
            cc_free = set(parcel.vertices) - set(corpus_callosum[1].vertices)
        parcel.vertices = np.array(list(cc_free))
        if len(parcel.vertices) == 0:
            to_remove.append(idx)
    [parcels.pop(idc) for idc in to_remove[::-1]]
    # morph from fsaverage to sample
    parcels = mne.morph_labels(parcels, 'sample', subjects_dir=subjects_dir)

    raw_fname = os.path.join(data_path, 'MEG', 'sample',
                             'sample_audvis_raw.fif')
    fwd_fname = os.path.join(data_path, 'MEG', 'sample',
                             'sample_audvis-meg-eeg-oct-6-fwd.fif')
    assert os.path.exists(raw_fname)
    assert os.path.exists(fwd_fname)

    info = mne.io.read_info(raw_fname)
    sel = mne.pick_types(info, meg='grad', eeg=False, stim=True, exclude=[])
    sel_data = mne.pick_types(info,
                              meg='grad',
                              eeg=False,
                              stim=False,
                              exclude=[])
    info_data = mne.pick_info(info, sel_data)
    info = mne.pick_info(info, sel)
    tstep = 1. / info['sfreq']

    # read forward solution
    fwd = mne.read_forward_solution(fwd_fname)
    src = fwd['src']

    fwd = mne.convert_forward_solution(fwd, force_fixed=True)
    fwd = mne.pick_channels_forward(fwd,
                                    include=info_data['ch_names'],
                                    ordered=True)
    lead_field = fwd['sol']['data']

    rng = np.random.RandomState(42)

    n_samples = 3
    signal_len = 20
    n_events = 50
    n_events = 2
    add_noise = False
    source_time_series = np.sin(
        2. * np.pi * 18. * np.arange(signal_len) * tstep) * 10e-9

    events = np.zeros((n_events, 3), dtype=int)
    events[:, 0] = signal_len * len(parcels) + 200 * np.arange(n_events)
    events[:, 2] = 1  # All events have the sample id.

    signal_list = []
    true_idx = np.empty(n_samples, dtype=np.int16)
    for idx, source in enumerate(range(n_samples)):
        idx_source = rng.choice(np.arange(len(parcels)))
        true_idx[idx] = idx_source
        source = parcels[idx_source]

        location = 'center'  # Use the center of the region as a seed.
        extent = 0.
        source = mne.label.select_sources('sample',
                                          source,
                                          location=location,
                                          extent=extent,
                                          subjects_dir=subjects_dir)

        source_simulator = mne.simulation.SourceSimulator(src, tstep=tstep)
        source_simulator.add_data(source, source_time_series, events)

        raw = mne.simulation.simulate_raw(info, source_simulator, forward=fwd)

        if add_noise:
            cov = mne.make_ad_hoc_cov(raw.info)
            mne.simulation.add_noise(raw, cov, iir_filter=[0.2, -0.2, 0.02])

        evoked = mne.Epochs(raw, events, tmax=0.3).average()
        data = evoked.data[:, np.argmax((evoked.data**2).sum(axis=0))]
        signal_list.append(data)

    signal_list = np.array(signal_list)
    # data_labels = [f'e{idx + 1}' for idx in range(signal_list.shape[1])]
    data_labels = evoked.ch_names

    X = pd.DataFrame(signal_list, columns=list(data_labels))
    X['subject_id'] = 0
    X['subject'] = '0'

    y = np.zeros((n_samples, len(parcels)), dtype=int)
    y[np.arange(n_samples), true_idx] = 1

    parcel_vertices = {}
    for idx, parcel in enumerate(parcels, 1):
        parcel_name = str(idx) + parcel.name[-3:]
        parcel_vertices[parcel_name] = parcel.vertices
        parcel.name = parcel_name

    parcel_indices_lh = np.zeros(len(fwd['src'][0]['inuse']), dtype=int)
    parcel_indices_rh = np.zeros(len(fwd['src'][1]['inuse']), dtype=int)
    for label_name, label_idx in parcel_vertices.items():
        label_id = int(label_name[:-3])
        if '-lh' in label_name:
            parcel_indices_lh[label_idx] = label_id
        else:
            parcel_indices_rh[label_idx] = label_id

    # Make sure label numbers different for each hemisphere
    parcel_indices = np.concatenate((parcel_indices_lh, parcel_indices_rh),
                                    axis=0)

    # Now pick vertices that are actually used in the forward
    inuse = np.concatenate((fwd['src'][0]['inuse'], fwd['src'][1]['inuse']),
                           axis=0)

    parcel_indices = parcel_indices[np.where(inuse)[0]]
    assert len(parcel_indices) == lead_field.shape[1]

    lead_field = lead_field[:, parcel_indices != 0]
    parcel_indices = parcel_indices[parcel_indices != 0]

    return X, y, [lead_field], [parcel_indices]
Пример #20
0
def _compute_power_envelopes(subject, kind, freqs):

    ###########################################################################
    # Compute source space
    # -------------------
    src = mne.setup_source_space(subject,
                                 spacing='oct6',
                                 add_dist=False,
                                 subjects_dir=cfg.mne_camcan_freesurfer_path)
    trans = trans_map[subject]
    bem = cfg.mne_camcan_freesurfer_path + \
        "/%s/bem/%s-meg-bem.fif" % (subject, subject)

    ###########################################################################
    # Compute handle MEG data
    # -----------------------

    fname = op.join(cfg.camcan_meg_raw_path, subject, kind,
                    '%s_raw.fif' % kind)

    raw = mne.io.read_raw_fif(fname)
    mne.channels.fix_mag_coil_types(raw.info)
    if DEBUG:
        # raw.crop(0, 180)
        raw.crop(0, 120)
    else:
        raw.crop(0, 300)

    raw = _run_maxfilter(raw, subject, kind)
    _compute_add_ssp_exg(raw)

    # get empty room
    fname_er = op.join(cfg.camcan_meg_path, "emptyroom", subject,
                       "emptyroom_%s.fif" % subject)

    raw_er = mne.io.read_raw_fif(fname_er)
    mne.channels.fix_mag_coil_types(raw.info)

    raw_er = _run_maxfilter(raw_er, subject, kind, coord_frame="meg")
    raw_er.info["projs"] += raw.info["projs"]

    cov = mne.compute_raw_covariance(raw_er, method='oas')
    # compute before band-pass of interest

    event_length = 5.
    event_overlap = 0.
    raw_length = raw.times[-1]
    events = mne.make_fixed_length_events(raw,
                                          duration=event_length,
                                          start=0,
                                          stop=raw_length - event_length)

    #######################################################################
    # Compute the forward and inverse
    # -------------------------------

    info = mne.Epochs(raw,
                      events=events,
                      tmin=0,
                      tmax=event_length,
                      baseline=None,
                      reject=None,
                      preload=False,
                      decim=10).info
    fwd = mne.make_forward_solution(info, trans, src, bem)
    inv = make_inverse_operator(info, fwd, cov)
    del fwd

    #######################################################################
    # Compute label time series and do envelope correlation
    # -----------------------------------------------------
    mne_subjects_dir = "/storage/inria/agramfor/MNE-sample-data/subjects"
    labels = mne.read_labels_from_annot('fsaverage',
                                        'aparc_sub',
                                        subjects_dir=mne_subjects_dir)
    labels = mne.morph_labels(labels,
                              subject_from='fsaverage',
                              subject_to=subject,
                              subjects_dir=cfg.mne_camcan_freesurfer_path)
    labels = [ll for ll in labels if 'unknown' not in ll.name]

    results = dict()
    for fmin, fmax, band in freqs:
        print(f"computing {subject}: {fmin} - {fmax} Hz")
        this_raw = raw.copy()
        this_raw.filter(fmin, fmax, n_jobs=1)
        reject = _get_global_reject_epochs(this_raw, decim=5)

        this_raw.apply_hilbert(envelope=False)

        epochs = mne.Epochs(this_raw,
                            events=events,
                            tmin=0,
                            tmax=event_length,
                            baseline=None,
                            reject=reject,
                            preload=True,
                            decim=5)
        if DEBUG:
            epochs = epochs[:3]

        result = {
            'subject': subject,
            'fmin': fmin,
            'fmax': fmax,
            'band': band,
            'label_names': [ll.name for ll in labels]
        }

        stcs = apply_inverse_epochs(epochs,
                                    inv,
                                    lambda2=1. / 9.,
                                    pick_ori='normal',
                                    method='MNE',
                                    return_generator=True)

        label_ts = np.concatenate(mne.extract_label_time_course(
            stcs, labels, inv['src'], mode="pca_flip", return_generator=False),
                                  axis=-1)

        result['cov'], _ = oas(np.abs(label_ts).T, assume_centered=False)

        for orth in ("pairwise", False):
            corr = envelope_correlation(label_ts[np.newaxis],
                                        combine="mean",
                                        orthogonalize=orth)
            result[f"corr{'_orth' if orth else ''}"] = corr[np.triu_indices(
                len(corr))]

        results[band] = result

        if False:  # failsafe mode with intermediate steps written out
            out_fname = op.join(
                cfg.derivative_path,
                f'{subject + ("-debug" if DEBUG else "")}_'
                f'power_envelopes_{band}.h5')

            mne.externals.h5io.write_hdf5(out_fname, result, overwrite=True)
    return results
Пример #21
0
            'CC120008', 'CC110033', 'CC110101', 'CC110187', 'CC110411',
            'CC110606', 'CC112141', 'CC120049', 'CC120061', 'CC120120'
        ]  # for train
    else:
        data_dir = 'data/test'
        n_samples = 500
        subject_names = [
            'CC120182', 'CC120264', 'CC120309', 'CC120313', 'CC120319',
            'CC120376', 'CC120469', 'CC120550', 'CC120218', 'CC120166'
        ]

    for subject in subject_names:
        subjects_dir = config.get_subjects_dir_subj(subject)

        # morph fsaverage labels to the subject we are using
        parcels_subject = mne.morph_labels(parcels_fsaverage, subject,
                                           'fsaverage', subjects_dir, 'white')

        # PATHS
        # make all the paths
        len_parcels = len(parcels_subject)
        case_specific = (signal_type + '_' + subject + '_' + str(len_parcels) +
                         '_' + str(n_sources_max))

        data_dir_specific = os.path.join(data_dir, 'data_' + case_specific)

        # check if the data directory for the subject already exists
        if not os.path.isdir(data_dir):
            os.mkdir(data_dir)

        if os.path.isdir(data_dir_specific) and not make_new:
            # path exists, skip it