def test_indices(): """Test connectivity indexing methods""" n_seeds_test = [1, 3, 4] n_targets_test = [2, 3, 200] for n_seeds in n_seeds_test: for n_targets in n_targets_test: idx = np.random.permutation(np.arange(n_seeds + n_targets)) seeds = idx[:n_seeds] targets = idx[n_seeds:] indices = seed_target_indices(seeds, targets) assert_true(len(indices) == 2) assert_true(len(indices[0]) == len(indices[1])) assert_true(len(indices[0]) == n_seeds * n_targets) for seed in seeds: assert_true(np.sum(indices[0] == seed) == n_targets) for target in targets: assert_true(np.sum(indices[1] == target) == n_seeds)
inverse_operator, lambda2, method, pick_ori="normal") # Restrict the source estimate to the label in the left auditory cortex. stc_label = stc.in_label(label_lh) # Find number and index of vertex with most power. src_pow = np.sum(stc_label.data**2, axis=1) seed_vertno = stc_label.vertices[0][np.argmax(src_pow)] seed_idx = np.searchsorted(stc.vertices[0], seed_vertno) # index in orig stc # Generate index parameter for seed-based connectivity analysis. n_sources = stc.data.shape[0] indices = seed_target_indices([seed_idx], np.arange(n_sources)) ############################################################################### # Compute the inverse solution for each epoch. By using "return_generator=True" # stcs will be a generator object instead of a list. This allows us so to # compute the coherence without having to keep all source estimates in memory. snr = 1.0 # use lower SNR for single epochs lambda2 = 1.0 / snr**2 stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method, pick_ori="normal", return_generator=True)
label=v1_label) stcs_fast_v4 = apply_inverse_epochs(allepochs, inverse_operator, lambda2, method='sLORETA', pick_ori="normal", label=v4_label) # Find index of vertices of interest in original stc idx_v1 = np.searchsorted(stcs_fast[0].vertices[1], stcs_fast_v1[0].vertices[1]) idx_v4 = np.searchsorted(stcs_fast[0].vertices[1], stcs_fast_v4[0].vertices[1]) # Construct indices to estimate connectivity between the label time course indices = seed_target_indices([idx_v1], [idx_v4]) # Compute the WPLI2_debiased in the frequency range fmin = 2. fmax = 40. sfreq = allepochs.info['sfreq'] # the sampling frequency wpli2, freqs, times, n_epochs, n_tapers = spectral_connectivity( stcs_fast, method='wpli2_debiased', sfreq=sfreq, indices=indices, mode='fourier', fmin=fmin, fmax=fmax, n_jobs=1)
event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6), preload=True) # Use 'MEG 2343' as seed seed_ch = 'MEG 2343' picks_ch_names = [raw.ch_names[i] for i in picks] # Create seed-target indices for connectivity computation seed = picks_ch_names.index(seed_ch) targets = np.arange(len(picks)) indices = seed_target_indices(seed, targets) # Define wavelet frequencies and number of cycles cwt_freqs = np.arange(7, 30, 2) cwt_n_cycles = cwt_freqs / 7. # Run the connectivity analysis using 2 parallel jobs sfreq = raw.info['sfreq'] # the sampling frequency con, freqs, times, _, _ = spectral_connectivity(epochs, indices=indices, method='wpli2_debiased', mode='cwt_morlet', sfreq=sfreq, cwt_freqs=cwt_freqs, cwt_n_cycles=cwt_n_cycles, n_jobs=1)
exclude='bads') # Create epochs for left-visual condition event_id, tmin, tmax = 3, -0.2, 0.5 epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6), preload=True) # Use 'MEG 2343' as seed seed_ch = 'MEG 2343' picks_ch_names = [raw.ch_names[i] for i in picks] # Create seed-target indices for connectivity computation seed = picks_ch_names.index(seed_ch) targets = np.arange(len(picks)) indices = seed_target_indices(seed, targets) # Define wavelet frequencies and number of cycles cwt_freqs = np.arange(7, 30, 2) cwt_n_cycles = cwt_freqs / 7. # Run the connectivity analysis using 2 parallel jobs sfreq = raw.info['sfreq'] # the sampling frequency con, freqs, times, _, _ = spectral_connectivity( epochs, indices=indices, method='wpli2_debiased', mode='cwt_morlet', sfreq=sfreq, cwt_freqs=cwt_freqs, cwt_n_cycles=cwt_n_cycles, n_jobs=1) # Mark the seed channel with a value of 1.0, so we can see it in the plot con[np.where(indices[1] == seed)] = 1.0
verbose='error') # Combine the seed time course with the source estimates. There will be a total # of 7500 signals: # index 0: time course extracted from label # index 1..7499: dSPM source space time courses stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method, pick_ori="normal", return_generator=True) comb_ts = list(zip(seed_ts, stcs)) # 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)
verbose='error') # Combine the seed time course with the source estimates. There will be a total # of 7500 signals: # index 0: time course extracted from label # index 1..7499: dSPM source space time courses stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method, pick_ori="normal", return_generator=True) comb_ts = list(zip(seed_ts, stcs)) # 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)
lambda2 = 1.0 / snr ** 2 evoked = epochs.average() stc = apply_inverse(evoked, inverse_operator, lambda2, method, pick_ori="normal") # Restrict the source estimate to the label in the left auditory cortex stc_label = stc.in_label(label_lh) # Find number and index of vertex with most power src_pow = np.sum(stc_label.data ** 2, axis=1) seed_vertno = stc_label.vertno[0][np.argmax(src_pow)] seed_idx = np.searchsorted(stc.vertno[0], seed_vertno) # index in original stc # Generate index parameter for seed-based connectivity analysis n_sources = stc.data.shape[0] indices = seed_target_indices([seed_idx], np.arange(n_sources)) # Compute inverse solution and for each epoch. By using "return_generator=True" # stcs will be a generator object instead of a list. This allows us so to # compute the coherence without having to keep all source estimates in memory. snr = 1.0 # use lower SNR for single epochs lambda2 = 1.0 / snr ** 2 stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method, pick_ori="normal", return_generator=True) # Now we are ready to compute the coherence in the alpha and beta band. # fmin and fmax specify the lower and upper freq. for each band, resp. fmin = (8., 13.) fmax = (13., 30.) sfreq = raw.info['sfreq'] # the sampling frequency
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)
# Find number and index of vertex with most power src_pow = np.sum(stc_label.data ** 2, axis=1) print "src pow" print len(src_pow) print src_pow print np.argmax(src_pow) print seed_vertno = stc_label.vertno[0][np.argmax(src_pow)] #Indices of the vertex with max power in label print seed_vertno seed_idx = np.searchsorted(stc.vertno[0], seed_vertno) # index in original stc ##np.searchsorted: Find indices where elements should be inserted to maintain order. print "Seed Index:", seed_idx # Generate index parameter for seed-based connectivity analysis n_sources = stc.data.shape[0] print "N_Sources:", n_sources indices = seed_target_indices([seed_idx], np.arange(n_sources))#array of seed indices and Targets indices # Compute inverse solution and for each epoch. By using "return_generator=True" # stcs will be a generator object instead of a list. This allows us so to # compute the coherence without having to keep all source estimates in memory. snr = 1.0 # use lower SNR for single epochs lambda2 = 1.0 / snr ** 2 stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method, pick_ori="normal", return_generator=True) # Now we are ready to compute the coherence in the alpha and beta band. # fmin and fmax specify the lower and upper freq. for each band, resp. fmin = (8., 13.) fmax = (13., 25.)
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)
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)