Created
June 17, 2016 20:53
-
-
Save larsoner/498ae0684f6fec8ee2d460b6120e74b5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import os.path as op | |
import numpy as np | |
import mne | |
def select_center_vertex_in_label(src, label): | |
""" Select vertex closest (in Euclidean distance) to the center of mass of | |
the given label. | |
Parameters | |
---------- | |
src : list of dict | |
The source space | |
label : Label | |
the label (read with mne.read_label) | |
Returns | |
------- | |
center_vert : int | |
index of central vertex | |
""" | |
pos = label.pos | |
mean_pos = np.mean(pos, axis=0) | |
dists = np.sqrt(np.sum((pos - mean_pos)**2, axis=1)) | |
hemi_to_ind = {'lh': 0, 'rh': 1} | |
src_sel = np.intersect1d(src[hemi_to_ind[label.hemi]]['vertno'], | |
label.vertices) | |
idx_sel = np.searchsorted(label.vertices, src_sel) | |
center_vertex = idx_sel[np.argmin(dists[idx_sel])] | |
return center_vertex | |
subject = 'sample' | |
subjects_dir = mne.get_config('SUBJECTS_DIR') | |
rrs = [mne.read_surface(op.join(subjects_dir, subject, 'surf', | |
'%s.white' % hemi))[0] | |
for hemi in ['lh', 'rh']] | |
src = mne.read_source_spaces(op.join(mne.datasets.sample.data_path(), | |
'subjects', 'sample', 'bem', | |
'sample-oct-6-src.fif')) | |
for label in mne.read_labels_from_annot(subject): | |
label.values.fill(1.) | |
idx = 0 if label.hemi == 'lh' else 1 | |
# Verify positions | |
# Three reasonable choices for restrictions: | |
restrict_vertices = np.intersect1d(src[idx]['vertno'], label.vertices) # works! | |
# restrict_vertices = label.vertices # AssertionError | |
# restrict_vertices = True # AssertionError (equiv to above) | |
# restrict_vertices = False # AssertionError | |
mne_vert = label.center_of_mass(restrict_vertices=restrict_vertices, | |
surf='white') | |
nick_vert = select_center_vertex_in_label(src, label) | |
nick_vert = label.vertices[nick_vert] | |
assert np.allclose(rrs[idx][label.vertices] / 1000., label.pos) | |
assert mne_vert == nick_vert |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment