def test_labels_to_stc(): """Test labels_to_stc.""" labels = read_labels_from_annot( 'sample', 'aparc', subjects_dir=subjects_dir) values = np.random.RandomState(0).randn(len(labels)) with pytest.raises(ValueError, match='1 or 2 dim'): labels_to_stc(labels, values[:, np.newaxis, np.newaxis]) with pytest.raises(ValueError, match=r'values\.shape'): labels_to_stc(labels, values[np.newaxis]) stc = labels_to_stc(labels, values) for value, label in zip(values, labels): stc_label = stc.in_label(label) assert (stc_label.data == value).all() stc = read_source_estimate(stc_fname, 'sample')
def run_degreeMapping(subjects_dir, subject, volume_spacing, freq): frequency = str(freq) DATA_DIR = Path(f'{subjects_dir}', f'{subject}', 'mne_files') fwd_fname = f'{DATA_DIR}/{subject}_{volume_spacing}-fwd-label.fif.gz' label_degree = f'{DATA_DIR}/{subject}_degreeMasked_{volume_spacing}_{frequency}.npy' degree_mapped = f'{DATA_DIR}/{subject}_degreeMapped_{volume_spacing}_{frequency}.npy' degree = np.load(label_degree) degree = np.sum(degree > 0, axis=0) fwd = mne.read_forward_solution(fwd_fname) fname_aseg = f'{subjects_dir}/{subject}/mri/aparc.a2009s+aseg.mgz' stc = mne.labels_to_stc(fname_aseg, degree, src=fwd['src']) degree_values = stc.data[:, 0] print(f'Degree saved to {degree_mapped}') np.save(degree_mapped, degree_values)
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( mne.Label(inv['src'][0]['vertno'], hemi='lh') + mne.Label(inv['src'][1]['vertno'], hemi='rh')) brain = stc.plot(clim=dict(kind='percent', lims=[75, 85, 95]), colormap='gnuplot', subjects_dir=subjects_dir, views='dorsal', hemi='both', smoothing_steps=25, time_label='Beta band') ############################################################################## # References # ---------- # .. [1] Hipp JF, Hawellek DJ, Corbetta M, Siegel M, Engel AK (2012)
xytext = xy + [0.01, 1] ax.annotate(label_names[lidx], xy, xytext, arrowprops=dict(arrowstyle='->'), color='r') ax.set(xlim=stc.times[[0, -1]], xlabel='Time (s)', ylabel='Activation') for key in ('right', 'top'): ax.spines[key].set_visible(False) fig.tight_layout() ############################################################################### # And we can project these label time courses back to their original # locations and see how the plot has been smoothed: stc_back = mne.labels_to_stc(fname_aseg, label_tc, src=src) stc_back.plot(src, subjects_dir=subjects_dir, mode='glass_brain') ############################################################################### # Vector Source Estimates # ----------------------- # If we choose to use ``pick_ori='vector'`` in # :func:`apply_inverse <mne.minimum_norm.apply_inverse>` fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif' inv = read_inverse_operator(fname_inv) stc = apply_inverse(evoked, inv, lambda2, 'dSPM', pick_ori='vector') brain = stc.plot(subject='sample', subjects_dir=subjects_dir, initial_time=initial_time, brain_kwargs=dict(silhouette=True))
# compute ROI degree degree[si, ix] = mne.connectivity.degree(aec, threshold_prop=0.2) # if not np.allclose(laplacian, degree[si, ix]): # warnings.warn("mne.connectivity.degree NOT equal to laplacian") print(f" Completed in {(time.time() - t0) / 60:0.1f} min") h5io.write_hdf5( out_fname, dict(degree=degree[si], laplacian=laplacian[si]), overwrite=True, ) # visualize connectivity on fsaverage for ix, (kk, vv) in enumerate(defaults.bands.items()): grab = np.mean(degree[:, ix], axis=0) # avg across subjects for this band this_stc = mne.labels_to_stc(rois, grab, src=src_fs) assert this_stc.data.shape == (20484, 1) brain = this_stc.plot( subject="fsaverage", clim=dict(kind="percent", lims=[75, 85, 95]), colormap="gnuplot", subjects_dir=defaults.subjects_dir, views="dorsal", hemi="both", time_viewer=False, show_traces=False, smoothing_steps="nearest", time_label="%s band" % kk, ) brain.save_image( op.join(
cv=cv, n_permutations=n_permutations, n_jobs=n_jobs, random_state=0, verbose=1) print('Completed in %0.1f min:' % ((time.time() - t0) / 60., )) print('Accuracy: %0.3f%%' % (100 * perf, )) print('Significance: %f' % (p, )) reg = clf.steps[1][1] reg.fit(clf.steps[0][1].fit_transform(X), y=y) coef = reg.coef_ coef.shape = (len(ages), len(measures), len(freq_idx), 448) coef = np.abs(coef).max(0).max(0) assert len(labels) == coef.shape[-1] for ii, fi in enumerate(freq_idx): stc = mne.labels_to_stc(labels, coef[ii]) brain = stc.plot(views=['lat', 'med'], hemi='split', smoothing_steps=1, clim=dict(kind='value', lims=[0.012, 0.024, 0.036]), colormap='viridis', colorbar=False, size=(800, 800), time_label=freqs[fi]) brain.save_image('maxs_%s.png' % (freqs[fi], )) brain.close() if plot_correlations: # naively compute correlation coefficients and plot a few this_X = X - X.mean(0) this_X /= np.linalg.norm(this_X, axis=0)
stcs, rois, fwd["src"], return_generator=True, verbose=True ) # compute ROI level envelop power aec = envelope_correlation(label_ts) assert aec.shape == (len(rois), len(rois)) # compute ROI laplacian as per Ginset # TODO cite paper _, deg_lap = csgraph.laplacian(aec, return_diag=True) data[si, ix] = deg_lap # compute ROI degree degree = mne.connectivity.degree(aec, threshold_prop=0.2) # if not np.allclose(deg_lap, degree): # warnings.warn("mne.connectivity.degree NOT equal to laplacian") stc = mne.labels_to_stc(rois, degree) stc = stc.in_label( mne.Label(inv["src"][0]["vertno"], hemi="lh") + mne.Label(inv["src"][1]["vertno"], hemi="rh") ) morph = mne.compute_source_morph( stc, subject_from=None, subject_to="fsaverage", subjects_dir=defaults.subjects_dir, ) a_lst[kk].append(morph.apply(stc)) A_lst.append(a_lst) arrayostcs = np.array([[v[ii] for ii in defaults.bands] for v in A_lst]).squeeze() src = mne.read_source_spaces(