Beispiel #1
0
def test_psi():
    """Test Phase Slope Index (PSI) estimation"""

    psi, freqs, times, n_epochs, n_tapers = phase_slope_index(data,
                                                              mode='fourier',
                                                              sfreq=sfreq)
    assert_true(psi[1, 0, 0] < 0)
    assert_true(psi[2, 0, 0] > 0)

    indices = (np.array([0]), np.array([1]))
    psi_2, freqs, times, n_epochs, n_tapers = phase_slope_index(
        data, mode='fourier', sfreq=sfreq, indices=indices)

    # the measure is symmetric (sign flip)
    assert_array_almost_equal(psi_2[0, 0], -psi[1, 0, 0])

    cwt_freqs = np.arange(5., 20, 0.5)
    psi_cwt, freqs, times, n_epochs, n_tapers = phase_slope_index(
        data,
        mode='cwt_morlet',
        sfreq=sfreq,
        cwt_frequencies=cwt_freqs,
        indices=indices)

    assert_true(np.all(psi_cwt > 0))
    assert_true(psi_cwt.shape[-1] == n_times)
Beispiel #2
0
def test_psi():
    """Test Phase Slope Index (PSI) estimation"""
    sfreq = 50.
    n_signals = 3
    n_epochs = 10
    n_times = 500
    rng = np.random.RandomState(42)
    data = rng.randn(n_epochs, n_signals, n_times)

    # simulate time shifts
    for i in range(n_epochs):
        data[i, 1, 10:] = data[i, 0, :-10]  # signal 0 is ahead
        data[i, 2, :-10] = data[i, 0, 10:]  # signal 2 is ahead

    psi, freqs, times, n_epochs, n_tapers = phase_slope_index(data,
        mode='fourier', sfreq=sfreq)
    assert_true(psi[1, 0, 0] < 0)
    assert_true(psi[2, 0, 0] > 0)

    indices = (np.array([0]), np.array([1]))
    psi_2, freqs, times, n_epochs, n_tapers = phase_slope_index(data,
        mode='fourier', sfreq=sfreq, indices=indices)

    # the measure is symmetric (sign flip)
    assert_array_almost_equal(psi_2[0, 0], -psi[1, 0, 0])

    cwt_freqs = np.arange(5., 20, 0.5)
    psi_cwt, freqs, times, n_epochs, n_tapers = phase_slope_index(data,
        mode='cwt_morlet', sfreq=sfreq, cwt_frequencies=cwt_freqs,
        indices=indices)

    assert_true(np.all(psi_cwt > 0))
    assert_true(psi_cwt.shape[-1] == n_times)
Beispiel #3
0
def test_psi():
    """Test Phase Slope Index (PSI) estimation"""

    psi, freqs, times, n_epochs, n_tapers = phase_slope_index(data, mode="fourier", sfreq=sfreq)
    assert_true(psi[1, 0, 0] < 0)
    assert_true(psi[2, 0, 0] > 0)

    indices = (np.array([0]), np.array([1]))
    psi_2, freqs, times, n_epochs, n_tapers = phase_slope_index(data, mode="fourier", sfreq=sfreq, indices=indices)

    # the measure is symmetric (sign flip)
    assert_array_almost_equal(psi_2[0, 0], -psi[1, 0, 0])

    cwt_freqs = np.arange(5.0, 20, 0.5)
    psi_cwt, freqs, times, n_epochs, n_tapers = phase_slope_index(
        data, mode="cwt_morlet", sfreq=sfreq, cwt_frequencies=cwt_freqs, indices=indices
    )

    assert_true(np.all(psi_cwt > 0))
    assert_true(psi_cwt.shape[-1] == n_times)
Beispiel #4
0
def get_psi_feats(df, sfreq=125., band='alpha'):

    electrodes = df.columns

    df = df.copy()
    alpha_filter = get_filter(sfreq=sfreq, band=band)

    df = df[electrodes]
    for el in electrodes:
        df[el] = np.convolve(alpha_filter, df[el], 'same')

    vals = df.values
    vals = vals.transpose(1, 0)
    vals = vals[None, :, :]

    psi, freqs, times, n_epochs, _ = phase_slope_index(vals,
                                                       sfreq=sfreq,
                                                       verbose=False)
    d = {}
    for i in range(psi.shape[0]):
        for j in range(i):
            d[get_col_name('psi', band, electrodes[i],
                           electrodes[j])] = psi[i, j, 0]
    return d
# Construct indices to estimate connectivity between the label time course
# and all source space time courses
vertices = [src[i]['vertno'] for i in range(2)]
n_signals_tot = 1 + len(vertices[0]) + len(vertices[1])

indices = seed_target_indices([0], np.arange(1, n_signals_tot))

# Compute the PSI in the frequency range 8Hz..30Hz. We exclude the baseline
# period from the connectivity estimation
fmin = 8.
fmax = 30.
tmin_con = 0.
sfreq = raw.info['sfreq']  # the sampling frequency

psi, freqs, times, n_epochs, _ = phase_slope_index(
    comb_ts, mode='multitaper', indices=indices, sfreq=sfreq,
    fmin=fmin, fmax=fmax, tmin=tmin_con)

# Generate a SourceEstimate with the PSI. This is simple since we used a single
# seed (inspect the indices variable to see how the PSI scores are arranged in
# the output)
psi_stc = mne.SourceEstimate(psi, vertices=vertices, tmin=0, tstep=1,
                             subject='sample')

# Now we can visualize the PSI using the plot method. We use a custom colormap
# to show signed values
v_max = np.max(np.abs(psi))
brain = psi_stc.plot(surface='inflated', hemi='lh',
                     time_label='Phase Slope Index (PSI)',
                     subjects_dir=subjects_dir,
                     clim=dict(kind='percent', pos_lims=(95, 97.5, 100)))
                                             subjects_dir=subjects_dir)

        seed_ts_slow_mt = mne.extract_label_time_course(stcs_slow,
                                                        vertex_mt,
                                                        src,
                                                        mode='mean_flip',
                                                        verbose='error')

        # Combine the seed time course with the source estimates.
        comb_ts_slow = list(zip(seed_ts_slow_v1, seed_ts_slow_mt))

        # Construct indices to estimate connectivity between the label time course
        # and all source space time courses
        vertices = [src[i]['vertno'] for i in range(2)]

        indices = (np.array([0]), np.array([1]))

        # Compute the PSI in the frequency range 11Hz-17Hz.
        fmin = 11.
        fmax = 17.
        sfreq = slow_epo_isi.info['sfreq']  # the sampling frequency

        psi_slow, freqs, times, n_epochs, _ = phase_slope_index(
            comb_ts_slow,
            mode='fourier',
            sfreq=sfreq,
            indices=indices,
            fmin=fmin,
            fmax=fmax)
        psi_slow_v1_mt[vert_num_mt] = np.array(psi_slow[0][0])
    psi_slow_v1_mt_all[vert_num_v1] = psi_slow_v1_mt
# Construct indices to estimate connectivity between the label time course
# and all source space time courses
vertices = [src[i]['vertno'] for i in range(2)]
n_signals_tot = 1 + len(vertices[0]) + len(vertices[1])

indices = seed_target_indices([0], np.arange(1, n_signals_tot))

# Compute the PSI in the frequency range 10Hz-20Hz. We exclude the baseline
# period from the connectivity estimation.
fmin = 10.
fmax = 20.
tmin_con = 0.
sfreq = epochs.info['sfreq']  # the sampling frequency

psi, freqs, times, n_epochs, _ = phase_slope_index(
    comb_ts, mode='multitaper', indices=indices, sfreq=sfreq,
    fmin=fmin, fmax=fmax, tmin=tmin_con)

# Generate a SourceEstimate with the PSI. This is simple since we used a single
# seed (inspect the indices variable to see how the PSI scores are arranged in
# the output)
psi_stc = mne.SourceEstimate(psi, vertices=vertices, tmin=0, tstep=1,
                             subject='sample')

# Now we can visualize the PSI using the :meth:`~mne.SourceEstimate.plot`
# method. We use a custom colormap to show signed values
v_max = np.max(np.abs(psi))
brain = psi_stc.plot(surface='inflated', hemi='lh',
                     time_label='Phase Slope Index (PSI)',
                     subjects_dir=subjects_dir,
                     clim=dict(kind='percent', pos_lims=(95, 97.5, 100)))
    idx_v1 = np.searchsorted(stcs[0].vertices[1], stcs_v1[0].vertices[1])
    idx_mt = np.searchsorted(stcs[0].vertices[1], stcs_mt[0].vertices[1])

    # Construct indices to estimate connectivity between the label time course
    indices = seed_target_indices([idx_v1], [idx_mt])

    # Compute the WPLI2_debiased in the frequency range
    fmin = 8.
    fmax = 15.
    sfreq = fast_epo_isi.info['sfreq']  # the sampling frequency

    # Compute the PSI in the frequency range 8Hz-15Hz.
    psi, freqs, times, n_epochs, _ = phase_slope_index(stcs,
                                                       mode='fourier',
                                                       sfreq=sfreq,
                                                       indices=indices,
                                                       fmin=fmin,
                                                       fmax=fmax,
                                                       n_jobs=1)
    # Average over values between all vertices [v1_vertices * mt_vertices]
    psi_avg = psi.mean(0)
    all_v1_mt.append(psi_avg)
stop = timeit.default_timer()
time = stop - start

# Save
np.save(savepath + 'psi/' + 'all_v1_mt_vertices_fast_fastepo', all_v1_mt)
all_subj = np.load(savepath + 'psi/' + 'all_v1_mt_vertices_fast_fastepo.npy')
plt.scatter(np.arange(42), all_subj[:, 0])
plt.plot(np.arange(42), np.zeros(42), 'r--')
plt.title('PSI between V1 and MT for all subjects')
Beispiel #9
0
            vertices = [np.arange(10242), np.arange(10242)]

            n_signals_tot = 1 + len(vertices[0]) + len(vertices[1])

            indices = seed_target_indices([0], np.arange(1, n_signals_tot))

            fmin = 8.
            fmax = 12.
            tmin_con = 0.
            sfreq = C.sfreq  # the sampling frequency

            psi, freqs, times, n_epochs, n_tapers = phase_slope_index(
                comb_ts_sd,
                indices=indices,
                sfreq=sfreq,
                mode='fourier',
                fmin=fmin,
                fmax=fmax,
                tmin=tmin,
                tmax=tmax,
                n_jobs=6)

            psi_stc = mne.SourceEstimate(psi,
                                         vertices=vertices,
                                         tmin=0,
                                         tstep=1,
                                         subject=sub_to)

            # Now we can visualize the PSI using the :meth:`~mne.SourceEstimate.plot`
            # method. We use a custom colormap to show signed values
            v_max = np.max(np.abs(psi))
            brain = psi_stc.plot(surface='inflated',
Beispiel #10
0
         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[i][k][f][win]= morph_SD.apply(psi_stc_SD)
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)
# Construct indices to estimate connectivity between the label time course
# and all source space time courses
vertices = [src[i]['vertno'] for i in range(2)]
n_signals_tot = 1 + len(vertices[0]) + len(vertices[1])

indices = seed_target_indices([0], np.arange(1, n_signals_tot))

# Compute the PSI in the frequency range 11Hz-17Hz.
fmin = 11.
fmax = 17.
sfreq = slow_epo_isi.info['sfreq']  # the sampling frequency

psi_slow, freqs, times, n_epochs, _ = phase_slope_index(comb_ts_slow,
                                                        mode='multitaper',
                                                        indices=indices,
                                                        sfreq=sfreq,
                                                        fmin=fmin,
                                                        fmax=fmax)

psi_fast, freqs, times, n_epochs, _ = phase_slope_index(comb_ts_fast,
                                                        mode='multitaper',
                                                        indices=indices,
                                                        sfreq=sfreq,
                                                        fmin=fmin,
                                                        fmax=fmax)

# Generate a SourceEstimate with the PSI. This is simple since we used a single
# seed (inspect the indices variable to see how the PSI scores are arranged in
# the output)
psi_slow_stc = mne.SourceEstimate(psi_slow,
                                  vertices=vertices,