def combine_medial_labels(labels, subject='fsaverage', surf='white', dist_limit=0.02, subjects_dir=None): """Combine medial labels.""" from mne.surface import _compute_nearest subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) rrs = dict((hemi, read_surface(op.join(subjects_dir, subject, 'surf', '%s.%s' % (hemi, surf)))[0] / 1000.) for hemi in ('lh', 'rh')) use_labels = list() used = np.zeros(len(labels), bool) logger.info('Matching medial regions for %s labels on %s %s, d=%0.1f mm' % (len(labels), subject, surf, 1000 * dist_limit)) for li1, l1 in enumerate(labels): if used[li1]: continue used[li1] = True use_label = l1.copy() rr1 = rrs[l1.hemi][l1.vertices] for li2 in np.where(~used)[0]: l2 = labels[li2] same_name = (l2.name.replace(l2.hemi, '') == l1.name.replace(l1.hemi, '')) if l2.hemi != l1.hemi and same_name: rr2 = rrs[l2.hemi][l2.vertices] mean_min = np.mean(_compute_nearest( rr1, rr2, return_dists=True)[1]) if mean_min <= dist_limit: use_label += l2 used[li2] = True logger.info(' Matched: ' + l1.name) use_labels.append(use_label) logger.info('Total %d labels' % (len(use_labels),)) return use_labels
def _compute_depth(dip, fname_bem, fname_trans, subject, subjects_dir): """Compute dipole depth.""" trans = _get_trans(fname_trans)[0] bem = read_bem_solution(fname_bem) surf = _bem_find_surface(bem, 'inner_skull') points = surf['rr'] points = apply_trans(trans['trans'], points) depth = _compute_nearest(points, dip.pos, return_dists=True)[1][0] return np.ravel(depth)
def test_compute_nearest(): """Test nearest neighbor searches""" x = np.random.randn(500, 3) x /= np.sqrt(np.sum(x ** 2, axis=1))[:, None] nn_true = np.random.permutation(np.arange(500, dtype=np.int))[:20] y = x[nn_true] nn1 = _compute_nearest(x, y, use_balltree=False) nn2 = _compute_nearest(x, y, use_balltree=True) assert_array_equal(nn_true, nn1) assert_array_equal(nn_true, nn2) # test distance support nnn1 = _compute_nearest(x, y, use_balltree=False, return_dists=True) nnn2 = _compute_nearest(x, y, use_balltree=True, return_dists=True) assert_array_equal(nnn1[0], nn_true) assert_array_equal(nnn1[1], np.zeros_like(nn1)) # all dists should be 0 assert_equal(len(nnn1), len(nnn2)) for nn1, nn2 in zip(nnn1, nnn2): assert_array_equal(nn1, nn2)
def get_atlas_roi_mask(stc, roi, atlas='IXI', atlas_subject=None, subjects_dir=None): """Get ROI mask for a given subject/atlas. Parameters ---------- stc : instance of mne.SourceEstimate or mne.VectorSourceEstimate The source estimate. roi : str The ROI to obtain a mask for. atlas : str The atlas to use. Must be "IXI" or "LBPA40". atlas_subject : str | None Atlas subject to process. Must be one of the (unwarped) subjects "ANTS3-0Months3T", "ANTS6-0Months3T", or "ANTS12-0Months3T". If None, it will be inferred from the number of vertices. Returns ------- mask : ndarray, shape (n_vertices,) The mask. """ import nibabel as nib from mne.utils import _validate_type from mne.surface import _compute_nearest _validate_type(stc, (VolSourceEstimate, VolVectorSourceEstimate), 'stc') subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) if atlas_subject is None: atlas_subject = _VERT_COUNT_MAP[len(stc.vertices)] fname_src = op.join(subjects_dir, atlas_subject, 'bem', '%s-vol5-src.fif' % (atlas_subject,)) src = read_source_spaces(fname_src) mri = op.join(subjects_dir, atlas_subject, 'mri', '%s_brain_ANTS_%s_atlas.mgz' % (atlas_subject, atlas)) if not np.in1d(stc.vertices, src[0]['vertno']).all(): raise RuntimeError('stc does not appear to be created from %s ' 'volumetric source space' % (atlas_subject,)) rr = src[0]['rr'][stc.vertices] mapping = get_atlas_mapping(atlas) vol_id = mapping[roi] mgz = nib.load(mri) mgz_data = mgz.get_fdata() vox_bool = mgz_data == vol_id vox_ijk = np.array(np.where(vox_bool)).T vox_mri_t = mgz.header.get_vox2ras_tkr() vox_mri_t *= np.array([[1e-3, 1e-3, 1e-3, 1]]).T rr_voi = apply_trans(vox_mri_t, vox_ijk) dists = _compute_nearest(rr_voi, rr, return_dists=True)[1] maxdist = np.linalg.norm(vox_mri_t[:3, :3].sum(0) / 2.) mask = (dists <= maxdist) return mask
def test_compute_nearest(): """Test nearest neighbor searches.""" x = rng.randn(500, 3) x /= np.sqrt(np.sum(x ** 2, axis=1))[:, None] nn_true = rng.permutation(np.arange(500, dtype=np.int))[:20] y = x[nn_true] nn1 = _compute_nearest(x, y, method='BallTree') nn2 = _compute_nearest(x, y, method='cKDTree') nn3 = _compute_nearest(x, y, method='cdist') assert_array_equal(nn_true, nn1) assert_array_equal(nn_true, nn2) assert_array_equal(nn_true, nn3) # test distance support nnn1 = _compute_nearest(x, y, method='BallTree', return_dists=True) nnn2 = _compute_nearest(x, y, method='cKDTree', return_dists=True) nnn3 = _compute_nearest(x, y, method='cdist', return_dists=True) assert_array_equal(nnn1[0], nn_true) assert_array_equal(nnn1[1], np.zeros_like(nn1)) # all dists should be 0 assert_equal(len(nnn1), len(nnn2)) for nn1, nn2, nn3 in zip(nnn1, nnn2, nnn3): assert_array_equal(nn1, nn2) assert_array_equal(nn1, nn3)
def _nearest_vol_ind(fwd_vol, fwd, vertices, source_ind): return _compute_nearest( fwd_vol['source_rr'], fwd['src'][0]['rr'][vertices][source_ind][np.newaxis])[0]