# ----------------------------------------------------- labels = mne.read_labels_from_annot(subject, 'aparc_sub', subjects_dir=subjects_dir) epochs.apply_hilbert() # faster to apply in sensor space stcs = apply_inverse_epochs(epochs, inv, lambda2=1. / 9., pick_ori='normal', return_generator=True) label_ts = mne.extract_label_time_course(stcs, labels, inv['src'], return_generator=True) corr = envelope_correlation(label_ts, verbose=True) # let's plot this matrix fig, ax = plt.subplots(figsize=(4, 4)) ax.imshow(corr, cmap='viridis', clim=np.percentile(corr, [5, 95])) fig.tight_layout() ############################################################################## # Compute the degree and plot it # ------------------------------ # sphinx_gallery_thumbnail_number = 2 threshold_prop = 0.15 # percentage of strongest edges to keep in the graph degree = mne.connectivity.degree(corr, threshold_prop=threshold_prop) stc = mne.labels_to_stc(labels, degree) stc = stc.in_label(
filters = make_lcmv(epochs.info, fwd, data_cov, 0.05, cov, pick_ori='max-power', weight_norm='nai') del fwd ############################################################################## # Compute label time series and do envelope correlation # ----------------------------------------------------- epochs.apply_hilbert() # faster to do in sensor space stcs = apply_lcmv_epochs(epochs, filters, return_generator=True) corr = envelope_correlation(stcs, verbose=True) ############################################################################## # Compute the degree and plot it # ------------------------------ degree = mne.connectivity.degree(corr, 0.15) stc = mne.VolSourceEstimate(degree, src[0]['vertno'], 0, 1, 'bst_resting') brain = stc.plot(src, clim=dict(kind='percent', lims=[75, 85, 95]), colormap='gnuplot', subjects_dir=subjects_dir, mode='glass_brain') ############################################################################## # References
def test_envelope_correlation(): """Test the envelope correlation function.""" rng = np.random.RandomState(0) data = rng.randn(2, 4, 64) data_hilbert = hilbert(data, axis=-1) corr_orig = _compute_corrs_orig(data_hilbert) assert (0 <= corr_orig).all() assert (corr_orig < 1).all() # using complex data corr = envelope_correlation(data_hilbert) assert_allclose(corr, corr_orig) # using callable corr = envelope_correlation(data_hilbert, combine=lambda data: np.mean(data, axis=0)) assert_allclose(corr, corr_orig) # do Hilbert internally, and don't combine corr = envelope_correlation(data, combine=None) assert corr.shape == (data.shape[0], ) + corr_orig.shape corr = np.mean(corr, axis=0) assert_allclose(corr, corr_orig) # degenerate with pytest.raises(ValueError, match='float'): envelope_correlation(data.astype(int)) with pytest.raises(ValueError, match='entry in data must be 2D'): envelope_correlation(data[np.newaxis]) with pytest.raises(ValueError, match='n_nodes mismatch'): envelope_correlation([rng.randn(2, 8), rng.randn(3, 8)]) with pytest.raises(ValueError, match='mean or callable'): envelope_correlation(data, 1.) with pytest.raises(ValueError, match='Combine option'): envelope_correlation(data, 'foo') with pytest.raises(ValueError, match='Invalid value.*orthogonalize.*'): envelope_correlation(data, orthogonalize='foo') corr_plain = envelope_correlation(data, combine=None, orthogonalize=False) assert corr_plain.shape == (data.shape[0], ) + corr_orig.shape assert np.min(corr_plain) < 0 corr_plain_mean = np.mean(corr_plain, axis=0) assert_allclose(np.diag(corr_plain_mean), 1) np_corr = np.array([np.corrcoef(np.abs(x)) for x in data_hilbert]) assert_allclose(corr_plain, np_corr) # check against FieldTrip, which uses the square-log-norm version # from scipy.io import savemat # savemat('data.mat', dict(data_hilbert=data_hilbert)) # matlab # load data # ft_connectivity_powcorr_ortho(reshape(data_hilbert(1,:,:), [4, 64])) # ft_connectivity_powcorr_ortho(reshape(data_hilbert(2,:,:), [4, 64])) ft_vals = np.array([ [[np.nan, 0.196734553900236, 0.063173148355451, -0.242638384630448], [0.196734553900236, np.nan, 0.041799775495150, -0.088205187548542], [0.063173148355451, 0.041799775495150, np.nan, 0.090331428512317], [-0.242638384630448, -0.088205187548542, 0.090331428512317, np.nan]], [[np.nan, -0.013270857462890, 0.185200598081295, 0.140284351572544], [-0.013270857462890, np.nan, 0.150981508043722, -0.000671809276372], [0.185200598081295, 0.150981508043722, np.nan, 0.137460244313337], [0.140284351572544, -0.000671809276372, 0.137460244313337, np.nan]], ], float) ft_vals[np.isnan(ft_vals)] = 0 corr_log = envelope_correlation(data, combine=None, log=True, absolute=False) assert_allclose(corr_log, ft_vals)
epochs = mne.Epochs(raw, events=events, tmin=0, tmax=.5, baseline=None, reject=dict(), preload=True) del raw src = mne.read_source_spaces(src) fwd = mne.make_forward_solution(epochs.info, trans, src, bem) inv = make_inverse_operator(epochs.info, fwd, cov) del fwd, src labels = mne.read_labels_from_annot(subject, 'aparc', subjects_dir=subjects_dir) epochs.apply_hilbert() stcs = apply_inverse_epochs(epochs, inv, lambda2=1. / 9., method='sLORETA', pick_ori='normal', return_generator=True) label_ts = mne.extract_label_time_course(stcs, labels, inv['src'], return_generator=True) corr = envelope_correlation(label_ts) np.fill_diagonal(corr, 0) b = np.tril(corr, k=0) np.save(os.path.join('path for result files to be saved', i + D), b)
def test_envelope_correlation(): """Test the envelope correlation function.""" rng = np.random.RandomState(0) data = rng.randn(2, 4, 64) data_hilbert = hilbert(data, axis=-1) corr_orig = _compute_corrs_orig(data_hilbert) assert (0 < corr_orig).all() assert (corr_orig < 1).all() # using complex data corr = envelope_correlation(data_hilbert) assert_allclose(corr, corr_orig) # do Hilbert internally, and don't combine corr = envelope_correlation(data, combine=None) assert corr.shape == (data.shape[0], ) + corr_orig.shape corr = np.median(corr, axis=0) assert_allclose(corr, corr_orig) # degenerate with pytest.raises(ValueError, match='float'): envelope_correlation(data.astype(int)) with pytest.raises(ValueError, match='entry in data must be 2D'): envelope_correlation(data[np.newaxis]) with pytest.raises(ValueError, match='n_nodes mismatch'): envelope_correlation([rng.randn(2, 8), rng.randn(3, 8)]) with pytest.raises(TypeError, match='instance of str or None'): envelope_correlation(data, 1.) with pytest.raises(ValueError, match='Unknown combine option'): envelope_correlation(data, 'foo')
def run_correlation(subjects_dir, subject, volume_spacing, freq, ortho_bool): num_threads(8) ortho_flag = str(ortho_bool) frequency = str(freq) DATA_DIR = Path(f'{subjects_dir}', f'{subject}', 'mne_files') eye_proj1 = f'{DATA_DIR}/{subject}_eyes1-proj.fif.gz' eye_proj2 = f'{DATA_DIR}/{subject}_eyes2-proj.fif.gz' fname_meg = f'{DATA_DIR}/{subject}_ses-rest_task-rest.fif' t1_fname = os.path.join(subjects_dir, subject, 'mri', 'T1.mgz') heartbeat_proj = f'{DATA_DIR}/{subject}_heartbeat-proj.fif.gz' fwd_fname = f'{DATA_DIR}/{subject}_{volume_spacing}-fwd.fif.gz' src_fname = f'{DATA_DIR}/{subject}_{volume_spacing}-src.fif.gz' cov_fname = f'{DATA_DIR}/{subject}-cov_{volume_spacing}.fif.gz' raw_cov_fname = f'{DATA_DIR}/{subject}-rawcov_{volume_spacing}.fif.gz' raw_proj = f'{DATA_DIR}/{subject}_ses-rest_task-rest_proj.fif.gz' source_voxel_coords = f'{DATA_DIR}/{subject}_coords_{volume_spacing}.pkl' corr_file_acLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_acLeft.npy' corr_file_scLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_scLeft.npy' corr_file_vcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_vcLeft.npy' corr_file_mtLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mtLeft.npy' corr_file_mtlLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mtlLeft.npy' corr_file_smcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_smcLeft.npy' corr_file_lpcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_lpcLeft.npy' corr_file_dpfcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_dpfcLeft.npy' corr_file_tmpcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_tmpcLeft.npy' corr_file_acRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_acRight.npy' corr_file_scRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_scRight.npy' corr_file_vcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_vcRight.npy' corr_file_mtRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mtRight.npy' corr_file_mtlRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mtlRight.npy' corr_file_smcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_smcRight.npy' corr_file_lpcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_lpcRight.npy' corr_file_dpfcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_dpfcRight.npy' corr_file_tmpcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_tmpcRight.npy' corr_file_mpfc = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mpfc.npy' corr_file_sma = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_sma.npy' check_for_files = [] check_for_files.append(corr_file_acLeft) check_for_files.append(corr_file_scLeft) check_for_files.append(corr_file_vcLeft) check_for_files.append(corr_file_mtLeft) check_for_files.append(corr_file_mtlLeft) check_for_files.append(corr_file_smcLeft) check_for_files.append(corr_file_lpcLeft) check_for_files.append(corr_file_dpfcLeft) check_for_files.append(corr_file_tmpcLeft) check_for_files.append(corr_file_acRight) check_for_files.append(corr_file_scRight) check_for_files.append(corr_file_vcRight) check_for_files.append(corr_file_mtRight) check_for_files.append(corr_file_mtlRight) check_for_files.append(corr_file_smcRight) check_for_files.append(corr_file_lpcRight) check_for_files.append(corr_file_dpfcRight) check_for_files.append(corr_file_tmpcRight) check_for_files.append(corr_file_mpfc) check_for_files.append(corr_file_sma) file_exist = [f for f in check_for_files if os.path.isfile(f)] file_not_exist = list(set(file_exist) ^ set(check_for_files)) if not file_not_exist: print('SC, AC, VC correlation files exists...') else: trans = f'/home/senthilp/caesar/camcan/cc700/camcan_coreg-master/trans/{subject}-trans.fif' # The transformation file obtained by coregistration file_trans = pathlib.Path(trans) file_ss = pathlib.Path(src_fname) file_fm = pathlib.Path(fwd_fname) file_proj = pathlib.Path(raw_proj) file_cov = pathlib.Path(cov_fname) file_rawcov = pathlib.Path(raw_cov_fname) t1 = nib.load(t1_fname) if not file_trans.exists(): print (f'{trans} File doesnt exist...') sys.exit(0) #info = mne.io.read_info(fname_meg) # plot_registration(info, trans, subject, subjects_dir) if not file_ss.exists(): src = compute_SourceSpace(subject, subjects_dir, src_fname, source_voxel_coords, plot=True, ss='volume', volume_spacing=volume_spacing) seed_l_sc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SSC_Left']) seed_r_sc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SSC_Right']) seed_l_ac = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['AC_Left']) seed_r_ac = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['AC_Right']) seed_l_vc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['VC_Left']) seed_r_vc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['VC_Right']) seed_l_mt = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MT+_Left']) seed_r_mt = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MT+_Right']) seed_l_mtl = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MTL_Left']) seed_r_mtl = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MTL_Right']) seed_l_smc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SMC_Left']) seed_r_smc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SMC_Right']) seed_l_lpc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['LPC_Left']) seed_r_lpc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['LPC_Right']) seed_l_dpfc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['DPFC_Left']) seed_r_dpfc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['DPFC_Right']) seed_l_tmpc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['TMPC_Left']) seed_r_tmpc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['TMPC_Right']) seed_mpfc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MPFC_MidBrain']) seed_sma = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SMA_MidBrain']) src_inuse = np.where(src[0]['inuse'] == 1) loc_l_sc = src_inuse[0][0] loc_r_sc = src_inuse[0][1] loc_l_ac = src_inuse[0][2] loc_r_ac = src_inuse[0][3] loc_l_vc = src_inuse[0][4] loc_r_vc = src_inuse[0][5] loc_l_mt = src_inuse[0][6] loc_r_mt = src_inuse[0][7] loc_l_mtl = src_inuse[0][8] loc_r_mtl = src_inuse[0][9] loc_l_smc = src_inuse[0][10] loc_r_smc = src_inuse[0][11] loc_l_lpc = src_inuse[0][12] loc_r_lpc = src_inuse[0][13] loc_l_dpfc = src_inuse[0][14] loc_r_dpfc = src_inuse[0][15] loc_l_tmpc = src_inuse[0][16] loc_r_tmpc = src_inuse[0][17] loc_mpfc = src_inuse[0][18] loc_sma = src_inuse[0][19] src[0]['rr'][loc_l_sc] = seed_l_sc src[0]['rr'][loc_r_sc] = seed_r_sc src[0]['rr'][loc_l_ac] = seed_l_ac src[0]['rr'][loc_r_ac] = seed_r_ac src[0]['rr'][loc_l_vc] = seed_l_vc src[0]['rr'][loc_r_vc] = seed_r_vc src[0]['rr'][loc_l_mt] = seed_l_mt src[0]['rr'][loc_r_mt] = seed_r_mt src[0]['rr'][loc_l_mtl] = seed_l_mtl src[0]['rr'][loc_r_mtl] = seed_r_mtl src[0]['rr'][loc_l_smc] = seed_l_smc src[0]['rr'][loc_r_smc] = seed_r_smc src[0]['rr'][loc_l_lpc] = seed_l_lpc src[0]['rr'][loc_r_lpc] = seed_r_lpc src[0]['rr'][loc_l_dpfc] = seed_l_dpfc src[0]['rr'][loc_r_dpfc] = seed_r_dpfc src[0]['rr'][loc_l_tmpc] = seed_l_tmpc src[0]['rr'][loc_r_tmpc] = seed_r_tmpc src[0]['rr'][loc_mpfc] = seed_mpfc src[0]['rr'][loc_sma] = seed_sma src.save(src_fname, overwrite=True) src = mne.read_source_spaces(src_fname) #view_SS_brain(subject, subjects_dir, src) if not file_fm.exists(): forward_model(subject, subjects_dir, fname_meg, trans, src, fwd_fname) fwd = mne.read_forward_solution(fwd_fname) # sensitivty_plot(subject, subjects_dir, fwd) raw = mne.io.read_raw_fif(fname_meg, verbose='error', preload=True) srate = raw.info['sfreq'] n_time_samps = raw.n_times time_secs = raw.times ch_names = raw.ch_names n_chan = len(ch_names) freq_res = srate/n_time_samps print('\n') print('-------------------------- Data summary-------------------------------') print(f'Subject {subject}') print(f"Frequency resolution {freq_res} Hz") print(f"The first few channel names are {ch_names[:3]}") print(f"The last time sample at {time_secs[-1]} seconds.") print(f"Sampling Frequency (No of time points/sec) {srate} Hz") print(f"Miscellaneous acquisition info {raw.info['description']}") print(f"Bad channels marked during data acquisition {raw.info['bads']}") print(f"Convert time in sec ( 60s ) to ingeter index {raw.time_as_index(60)}") # Convert time to indices print(f"The raw data object has {n_time_samps} time samples and {n_chan} channels.") print('------------------------------------------------------------------------') print('\n') # raw.plot(n_channels=10, scalings='auto', title='Data from arrays', show=True, block=True) if not file_proj.exists(): projs_ecg, _ = compute_proj_ecg(raw, n_grad=1, n_mag=2, ch_name='ECG063') projs_eog1, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='EOG061') projs_eog2, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='EOG062') if projs_ecg is not None: mne.write_proj(heartbeat_proj, projs_ecg) # Saving projectors raw.info['projs'] += projs_ecg if projs_eog1 is not None: mne.write_proj(eye_proj1, projs_eog1) raw.info['projs'] += projs_eog1 if projs_eog2 is not None: mne.write_proj(eye_proj2, projs_eog2) raw.info['projs'] += projs_eog2 raw.apply_proj() raw.save(raw_proj, proj=True, overwrite=True) print(raw_proj) raw_proj_applied = mne.io.read_raw_fif(raw_proj, verbose='error', preload=True) print(f'High-pass filtering data at 0.5 Hz') raw_proj_applied.filter(l_freq=0.5, h_freq=None, method='iir') if not file_cov.exists(): cov = mne.compute_raw_covariance(raw_proj_applied) # compute before band-pass of interest mne.write_cov(cov_fname, cov) cov = mne.read_cov(cov_fname) # cov.plot(raw.info, proj=True, exclude='bads', show_svd=False # raw_proj_applied.crop(tmax=10) do_epochs = False l_freq = freq-2.0 h_freq = freq+2.0 print(f'Band pass filter data [{l_freq}, {h_freq}]') raw_proj_filtered = raw_proj_applied.filter(l_freq=l_freq, h_freq=h_freq) if do_epochs: print('Segmenting raw data...') events = mne.make_fixed_length_events(raw_proj_filtered, duration=5.) raw_proj_filtered = mne.Epochs(raw_proj_filtered, events=events, tmin=0, tmax=5., baseline=None, preload=True) data_cov = mne.compute_covariance(raw_proj_filtered) else: if not file_rawcov.exists(): data_cov = mne.compute_raw_covariance(raw_proj_filtered) mne.write_cov(raw_cov_fname, data_cov) else: data_cov = mne.read_cov(file_rawcov) filters = make_lcmv(raw_proj_filtered.info, fwd, data_cov, 0.05, cov, pick_ori='max-power', weight_norm='nai') raw_proj_filtered_comp = raw_proj_filtered.apply_hilbert() if do_epochs: stcs = apply_lcmv_epochs(raw_proj_filtered_comp, filters, return_generator=False) else: stcs = apply_lcmv_raw(raw_proj_filtered_comp, filters, verbose=True) stcs = [stcs] # Power Envelope Correlation print(f'Computing Power Envelope Correlation for {subject}....Orthogonalize {ortho_flag}') all_corr = envelope_correlation(stcs, combine=None, orthogonalize=False, log=False, absolute=True, verbose=None) np.save(corr_file_scLeft, all_corr[seed_left_sc]) np.save(corr_file_acLeft, all_corr[seed_left_ac]) np.save(corr_file_vcLeft, all_corr[seed_left_vc]) np.save(corr_file_mtLeft, all_corr[seed_left_mt]) np.save(corr_file_mtlLeft, all_corr[seed_left_mtl]) np.save(corr_file_smcLeft, all_corr[seed_left_smc]) np.save(corr_file_lpcLeft, all_corr[seed_left_lpc]) np.save(corr_file_dpfcLeft, all_corr[seed_left_dpfc]) np.save(corr_file_tmpcLeft, all_corr[seed_left_tmpc]) np.save(corr_file_scRight, all_corr[seed_right_sc]) np.save(corr_file_acRight, all_corr[seed_right_ac]) np.save(corr_file_vcRight, all_corr[seed_right_vc]) np.save(corr_file_mtRight, all_corr[seed_right_mt]) np.save(corr_file_mtlRight, all_corr[seed_right_mtl]) np.save(corr_file_smcRight, all_corr[seed_right_smc]) np.save(corr_file_lpcRight, all_corr[seed_right_lpc]) np.save(corr_file_dpfcRight, all_corr[seed_right_dpfc]) np.save(corr_file_tmpcRight, all_corr[seed_right_tmpc]) np.save(corr_file_mpfc, all_corr[seed_mpfc_index]) np.save(corr_file_sma, all_corr[seed_sma_index]) del stcs
pos = 15. # 1.5 cm is very broad, done here for speed! src = mne.setup_volume_source_space('bst_resting', pos, bem=bem, subjects_dir=subjects_dir, verbose=True) fwd = mne.make_forward_solution(epochs.info, trans, src, bem) data_cov = mne.compute_covariance(epochs) filters = make_lcmv(epochs.info, fwd, data_cov, 0.05, cov, pick_ori='max-power', weight_norm='nai') del fwd ############################################################################## # Compute label time series and do envelope correlation # ----------------------------------------------------- epochs.apply_hilbert() # faster to do in sensor space stcs = apply_lcmv_epochs(epochs, filters, return_generator=True) corr = envelope_correlation(stcs, verbose=True) ############################################################################## # Compute the degree and plot it # ------------------------------ degree = mne.connectivity.degree(corr, 0.15) stc = mne.VolSourceEstimate(degree, src[0]['vertno'], 0, 1, 'bst_resting') brain = stc.plot( src, clim=dict(kind='percent', lims=[75, 85, 95]), colormap='gnuplot', subjects_dir=subjects_dir, mode='glass_brain') ############################################################################## # References # ---------- # .. [1] Hipp JF, Hawellek DJ, Corbetta M, Siegel M, Engel AK (2012)
def test_envelope_correlation(): """Test the envelope correlation function.""" rng = np.random.RandomState(0) data = rng.randn(2, 4, 64) data_hilbert = hilbert(data, axis=-1) corr_orig = _compute_corrs_orig(data_hilbert) assert (0 < corr_orig).all() assert (corr_orig < 1).all() # using complex data corr = envelope_correlation(data_hilbert) assert_allclose(corr, corr_orig) # do Hilbert internally, and don't combine corr = envelope_correlation(data, combine=None) assert corr.shape == (data.shape[0],) + corr_orig.shape corr = np.median(corr, axis=0) assert_allclose(corr, corr_orig) # degenerate with pytest.raises(ValueError, match='float'): envelope_correlation(data.astype(int)) with pytest.raises(ValueError, match='entry in data must be 2D'): envelope_correlation(data[np.newaxis]) with pytest.raises(ValueError, match='n_nodes mismatch'): envelope_correlation([rng.randn(2, 8), rng.randn(3, 8)]) with pytest.raises(TypeError, match='instance of str or None'): envelope_correlation(data, 1.) with pytest.raises(ValueError, match='Unknown combine option'): envelope_correlation(data, 'foo')
def test_envelope_correlation(): """Test the envelope correlation function.""" rng = np.random.RandomState(0) data = rng.randn(2, 4, 64) data_hilbert = hilbert(data, axis=-1) corr_orig = _compute_corrs_orig(data_hilbert) assert (0 < corr_orig).all() assert (corr_orig < 1).all() # using complex data corr = envelope_correlation(data_hilbert) assert_allclose(corr, corr_orig) # using callable corr = envelope_correlation(data_hilbert, combine=lambda data: np.mean(data, axis=0)) assert_allclose(corr, corr_orig) # do Hilbert internally, and don't combine corr = envelope_correlation(data, combine=None) assert corr.shape == (data.shape[0], ) + corr_orig.shape corr = np.mean(corr, axis=0) assert_allclose(corr, corr_orig) # degenerate with pytest.raises(ValueError, match='float'): envelope_correlation(data.astype(int)) with pytest.raises(ValueError, match='entry in data must be 2D'): envelope_correlation(data[np.newaxis]) with pytest.raises(ValueError, match='n_nodes mismatch'): envelope_correlation([rng.randn(2, 8), rng.randn(3, 8)]) with pytest.raises(ValueError, match='mean or callable'): envelope_correlation(data, 1.) with pytest.raises(ValueError, match='Combine option'): envelope_correlation(data, 'foo') with pytest.raises(ValueError, match='Invalid value.*orthogonalize.*'): envelope_correlation(data, orthogonalize='foo') corr_plain = envelope_correlation(data, combine=None, orthogonalize=False) assert corr_plain.shape == (data.shape[0], ) + corr_orig.shape assert np.min(corr_plain) < 0 corr_plain_mean = np.mean(corr_plain, axis=0) assert_allclose(np.diag(corr_plain_mean), 1) np_corr = np.array([np.corrcoef(np.abs(x)) for x in data_hilbert]) assert_allclose(corr_plain, np_corr)
# epoch raw into 5 sec trials print(' \nLoading ...%s' % op.relpath(eps_fname, defaults.megdata)) for ix, (kk, vv) in enumerate(defaults.bands.items()): hp, lp = vv label_ts = funcs.extract_labels_timeseries(subject, raw, hp, lp, cov, fwd, defaults.subjects_dir, eps_fname, fslabels, return_generator=True) corr_mats[si, ix] = envelope_correlation(label_ts) # Compute pairwise degree source connectivity amongst labels degrees[si, ix] = mne.connectivity.degree(corr_mats[si, ix]) fout_ = op.join(eps_dir, '%s_%s_fcDs.h5' % (subject, kk)) write_hdf5(fname=fout_, data={ 'corr': corr_mats[si, ix], 'deg': degrees[si, ix] }, overwrite=True) plt.close('all') for ix, (kk, vv) in enumerate(defaults.bands.items()): corr_ = corr_mats[:, ix].mean(0) # Plot group narrow-band corr matrix fig, ax = plt.subplots(figsize=(4, 4)) img = ax.imshow(corr_,
def run_correlation(subjects_dir, subject, volume_spacing, freq): num_threads(8) frequency = str(freq) DATA_DIR = Path(f'{subjects_dir}', f'{subject}', 'mne_files') eye_proj1 = f'{DATA_DIR}/{subject}_eyes1-proj.fif.gz' eye_proj2 = f'{DATA_DIR}/{subject}_eyes2-proj.fif.gz' fname_meg = f'{DATA_DIR}/{subject}_ses-rest_task-rest.fif' t1_fname = os.path.join(subjects_dir, subject, 'mri', 'T1.mgz') heartbeat_proj = f'{DATA_DIR}/{subject}_heartbeat-proj.fif.gz' fwd_fname = f'{DATA_DIR}/{subject}_{volume_spacing}-fwd-label.fif.gz' src_fname = f'{DATA_DIR}/{subject}_{volume_spacing}-src-label.fif.gz' cov_fname = f'{DATA_DIR}/{subject}-cov_{volume_spacing}-label.fif.gz' raw_cov_fname = f'{DATA_DIR}/{subject}-rawcov_{volume_spacing}-label.fif.gz' raw_proj = f'{DATA_DIR}/{subject}_ses-rest_task-rest_proj-label.fif.gz' source_voxel_coords = f'{DATA_DIR}/{subject}_coords_{volume_spacing}.pkl' freesurfer_label = f'{DATA_DIR}/{subject}_freesurferlabel_{volume_spacing}-label.pkl' corr_true_file_label = f'{DATA_DIR}/{subject}_corr_ortho_true_{volume_spacing}_{frequency}_label.npy' check_for_files = [] check_for_files.append(corr_true_file_label) file_exist = [f for f in check_for_files if os.path.isfile(f)] file_not_exist = list(set(file_exist) ^ set(check_for_files)) if not file_not_exist: print('correlation files exists...') else: trans = f'/home/senthilp/caesar/camcan/cc700/camcan_coreg-master/trans/{subject}-trans.fif' # The transformation file obtained by coregistration file_trans = pathlib.Path(trans) file_ss = pathlib.Path(src_fname) file_fm = pathlib.Path(fwd_fname) file_proj = pathlib.Path(raw_proj) file_cov = pathlib.Path(cov_fname) file_rawcov = pathlib.Path(raw_cov_fname) t1 = nib.load(t1_fname) if not file_trans.exists(): print (f'{trans} File doesnt exist...') sys.exit(0) info = mne.io.read_info(fname_meg) # plot_registration(info, trans, subject, subjects_dir) print(file_ss) if not file_ss.exists(): src = compute_SourceSpace(subject, subjects_dir, src_fname, source_voxel_coords, plot=True, ss='volume', volume_spacing=volume_spacing) src.save(src_fname, overwrite=True) src = mne.read_source_spaces(src_fname) #view_SS_brain(subject, subjects_dir, src) if not file_fm.exists(): forward_model(subject, subjects_dir, fname_meg, trans, src, fwd_fname) fwd = mne.read_forward_solution(fwd_fname) # sensitivty_plot(subject, subjects_dir, fwd) raw = mne.io.read_raw_fif(fname_meg, verbose='error', preload=True) srate = raw.info['sfreq'] n_time_samps = raw.n_times time_secs = raw.times ch_names = raw.ch_names n_chan = len(ch_names) freq_res = srate/n_time_samps print('\n') print('-------------------------- Data summary-------------------------------') print(f'Subject {subject}') print(f"Frequency resolution {freq_res} Hz") print(f"The first few channel names are {ch_names[:3]}") print(f"The last time sample at {time_secs[-1]} seconds.") print(f"Sampling Frequency (No of time points/sec) {srate} Hz") print(f"Miscellaneous acquisition info {raw.info['description']}") print(f"Bad channels marked during data acquisition {raw.info['bads']}") print(f"Convert time in sec ( 60s ) to ingeter index {raw.time_as_index(60)}") # Convert time to indices print(f"The raw data object has {n_time_samps} time samples and {n_chan} channels.") print('------------------------------------------------------------------------') print('\n') # raw.plot(n_channels=10, scalings='auto', title='Data from arrays', show=True, block=True) if not file_proj.exists(): projs_ecg, _ = compute_proj_ecg(raw, n_grad=1, n_mag=2, ch_name='ECG063') projs_eog1, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='EOG061') projs_eog2, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='EOG062') if projs_ecg is not None: mne.write_proj(heartbeat_proj, projs_ecg) # Saving projectors raw.info['projs'] += projs_ecg if projs_eog1 is not None: mne.write_proj(eye_proj1, projs_eog1) raw.info['projs'] += projs_eog1 if projs_eog2 is not None: mne.write_proj(eye_proj2, projs_eog2) raw.info['projs'] += projs_eog2 raw.apply_proj() raw.save(raw_proj, proj=True, overwrite=True) print(raw_proj) raw_proj_applied = mne.io.read_raw_fif(raw_proj, verbose='error', preload=True) print(f'High-pass filtering data at 0.5 Hz') raw_proj_applied.filter(l_freq=0.5, h_freq=None, method='iir') if not file_cov.exists(): cov = mne.compute_raw_covariance(raw_proj_applied) # compute before band-pass of interest mne.write_cov(cov_fname, cov) cov = mne.read_cov(cov_fname) # cov.plot(raw.info, proj=True, exclude='bads', show_svd=False # raw_proj_applied.crop(tmax=10) do_epochs = False l_freq = freq-2.0 h_freq = freq+2.0 print(f'Band pass filter data [{l_freq}, {h_freq}]') raw_proj_filtered = raw_proj_applied.filter(l_freq=l_freq, h_freq=h_freq) if do_epochs: print('Segmenting raw data...') events = mne.make_fixed_length_events(raw_proj_filtered, duration=5.) raw_proj_filtered = mne.Epochs(raw_proj_filtered, events=events, tmin=0, tmax=5., baseline=None, preload=True) data_cov = mne.compute_covariance(raw_proj_filtered) else: if not file_rawcov.exists(): data_cov = mne.compute_raw_covariance(raw_proj_filtered) mne.write_cov(raw_cov_fname, data_cov) else: data_cov = mne.read_cov(file_rawcov) filters = make_lcmv(raw_proj_filtered.info, fwd, data_cov, 0.05, cov, pick_ori='max-power', weight_norm='nai') raw_proj_filtered_comp = raw_proj_filtered.apply_hilbert() if do_epochs: stcs = apply_lcmv_epochs(raw_proj_filtered_comp, filters, return_generator=False) else: stcs = apply_lcmv_raw(raw_proj_filtered_comp, filters, verbose=True) print('Extracting label time course...') atlas = f'{subjects_dir}/{subject}/mri/aparc.a2009s+aseg.mgz' label_ts = mne.extract_label_time_course(stcs, atlas, fwd['src'], return_generator=False) label_ts = [label_ts] # Power Envelope Correlation print(f'Computing Power Envelope Correlation for {subject}....Orthogonalize True') all_corr = envelope_correlation(label_ts, combine=None, orthogonalize="pairwise", log=True, absolute=True, verbose=None) print(f'Correlation saved to {corr_true_file_label}') np.save(corr_true_file_label, all_corr) del stcs