def test_summarize_clusters(kind): """Test cluster summary stcs.""" src_surf = SourceSpaces( [dict(vertno=np.arange(10242), type='surf') for _ in range(2)]) assert src_surf.kind == 'surface' src_vol = SourceSpaces([dict(vertno=np.arange(10), type='vol')]) assert src_vol.kind == 'volume' if kind == 'surface': src = src_surf klass = SourceEstimate elif kind == 'volume': src = src_vol klass = VolSourceEstimate else: assert kind == 'mixed' src = src_surf + src_vol klass = MixedSourceEstimate n_vertices = sum(len(s['vertno']) for s in src) clu = (np.random.random([1, n_vertices]), [ (np.array([0]), np.array([0, 2, 4])) ], np.array([0.02, 0.1]), np.array([12, -14, 30])) kwargs = dict() if kind == 'volume': with pytest.raises(ValueError, match='did not match'): summarize_clusters_stc(clu) assert len(src) == 1 kwargs['vertices'] = [src[0]['vertno']] elif kind == 'mixed': kwargs['vertices'] = src stc_sum = summarize_clusters_stc(clu, **kwargs) assert isinstance(stc_sum, klass) assert stc_sum.data.shape[1] == 2 clu[2][0] = 0.3 with pytest.raises(RuntimeError, match='No significant'): summarize_clusters_stc(clu, **kwargs)
def test_vec_stc_basic(klass, kind): """Test (vol)vector source estimate.""" nn = np.array([ [1, 0, 0], [0, 1, 0], [0, 0, 1], [np.sqrt(1 / 3.)] * 3 ]) data = np.array([ [1, 0, 0], [0, 2, 0], [3, 0, 0], [1, 1, 1], ])[:, :, np.newaxis] if klass is VolVectorSourceEstimate: src = SourceSpaces([dict(nn=nn, type=kind)]) verts = np.arange(4) else: src = SourceSpaces([dict(nn=nn[:2], type=kind), dict(nn=nn[2:], type=kind)]) verts = [np.array([0, 1]), np.array([0, 1])] stc = klass(data, verts, 0, 1, 'foo') # Magnitude of the vectors assert_array_equal(stc.magnitude().data[:, 0], [1, 2, 3, np.sqrt(3)]) # Vector components projected onto the vertex normals if kind == 'vol': with pytest.raises(RuntimeError, match='surface or discrete'): stc.normal(src) return normal = stc.normal(src) assert_array_equal(normal.data[:, 0], [1, 2, 0, np.sqrt(3)]) stc = klass(data[:, :, 0], verts, 0, 1) # upbroadcast assert stc.data.shape == (len(data), 3, 1) # Bad data with pytest.raises(ValueError, match='of length 3'): klass(data[:, :2], verts, 0, 1) data = data[:, :, np.newaxis] with pytest.raises(ValueError, match='3 dimensions for .*VectorSource'): klass(data, verts, 0, 1)
def test_make_forward_solution_discrete(): """Test making and converting a forward solution with discrete src.""" # smoke test for depth weighting and discrete source spaces src = read_source_spaces(fname_src)[0] src = SourceSpaces([src] + setup_volume_source_space( pos=dict(rr=src['rr'][src['vertno'][:3]].copy(), nn=src['nn'][src['vertno'][:3]].copy()))) sphere = make_sphere_model() fwd = make_forward_solution(fname_raw, fname_trans, src, sphere, meg=True, eeg=False) convert_forward_solution(fwd, surf_ori=True)
def merge_volume_source_space(sss, name='Volume'): """Merge multiple volume source spaces into one Notes ----- Only intended to work properly if ``sss`` is the output of a single :func:`mne.setup_volume_source_space` call. """ if len(sss) <= 1: return sss assert all(ss['type'] == 'vol' for ss in sss) ss = sss[0] ss['vertno'] = np.unique(np.concatenate([ss['vertno'] for ss in sss])) ss['inuse'] = reduce(np.logical_or, (ss['inuse'] for ss in sss)) ss['nuse'] = ss['inuse'].sum() ss['seg_name'] = str(name) del ss['neighbor_vert'] return SourceSpaces([ss], sss.info)
def test_save_vol_stc_as_nifti(): """Save the stc as a nifti file and export.""" import nibabel as nib tempdir = _TempDir() with warnings.catch_warnings(record=True): warnings.simplefilter('always') src = read_source_spaces(fname_vsrc) vol_fname = op.join(tempdir, 'stc.nii.gz') # now let's actually read a MNE-C processed file stc = read_source_estimate(fname_vol, 'sample') assert_true(isinstance(stc, VolSourceEstimate)) stc.save_as_volume(vol_fname, src, dest='surf', mri_resolution=False) with warnings.catch_warnings(record=True): # nib<->numpy img = nib.load(vol_fname) assert_true(img.shape == src[0]['shape'] + (len(stc.times), )) with warnings.catch_warnings(record=True): # nib<->numpy t1_img = nib.load(fname_t1) stc.save_as_volume(op.join(tempdir, 'stc.nii.gz'), src, dest='mri', mri_resolution=True) with warnings.catch_warnings(record=True): # nib<->numpy img = nib.load(vol_fname) assert_true(img.shape == t1_img.shape + (len(stc.times), )) assert_allclose(img.affine, t1_img.affine, atol=1e-5) # export without saving img = stc.as_volume(src, dest='mri', mri_resolution=True) assert_true(img.shape == t1_img.shape + (len(stc.times), )) assert_allclose(img.affine, t1_img.affine, atol=1e-5) src = SourceSpaces([src[0], src[0]]) stc = VolSourceEstimate(np.r_[stc.data, stc.data], [stc.vertices, stc.vertices], tmin=stc.tmin, tstep=stc.tstep) img = stc.as_volume(src, dest='mri', mri_resolution=False) assert_true(img.shape == src[0]['shape'] + (len(stc.times), ))
def test_save_vol_stc_as_nifti(tmpdir): """Save the stc as a nifti file and export.""" import nibabel as nib src = read_source_spaces(fname_vsrc) vol_fname = tmpdir.join('stc.nii.gz') # now let's actually read a MNE-C processed file stc = read_source_estimate(fname_vol, 'sample') assert (isinstance(stc, VolSourceEstimate)) stc.save_as_volume(vol_fname, src, dest='surf', mri_resolution=False) with pytest.warns(None): # nib<->numpy img = nib.load(str(vol_fname)) assert (img.shape == src[0]['shape'] + (len(stc.times), )) with pytest.warns(None): # nib<->numpy t1_img = nib.load(fname_t1) stc.save_as_volume(tmpdir.join('stc.nii.gz'), src, dest='mri', mri_resolution=True) with pytest.warns(None): # nib<->numpy img = nib.load(str(vol_fname)) assert (img.shape == t1_img.shape + (len(stc.times), )) assert_allclose(img.affine, t1_img.affine, atol=1e-5) # export without saving img = stc.as_volume(src, dest='mri', mri_resolution=True) assert (img.shape == t1_img.shape + (len(stc.times), )) assert_allclose(img.affine, t1_img.affine, atol=1e-5) src = SourceSpaces([src[0], src[0]]) stc = VolSourceEstimate(np.r_[stc.data, stc.data], [stc.vertices, stc.vertices], tmin=stc.tmin, tstep=stc.tstep, subject='sample') img = stc.as_volume(src, dest='mri', mri_resolution=False) assert (img.shape == src[0]['shape'] + (len(stc.times), ))
def prune_volume_source_space(sss, grade, n=1, mirror=True, remove_midline=False): """Remove sources that have ``n`` or fewer neighboring sources""" assert len(sss) == 1 ss = sss[0].copy() assert ss['type'] == 'vol' if 'neighbor_vert' in ss: del ss['neighbor_vert'] if remove_midline: rm = ss['rr'][ss['vertno']][:, 0] == 0 ss['inuse'][ss['vertno'][rm]] = 0 ss['vertno'] = ss['vertno'][~rm] if mirror: coord_tuples = tuple(map(tuple, ss['rr'])) vertex_list = list(ss['vertno']) coord_id = {coord: v for v, coord in enumerate(coord_tuples)} for v in ss['vertno']: r, a, s = ss['rr'][v] v_mirror = coord_id[-r, a, s] if v_mirror not in vertex_list: vertex_list.append(v_mirror) vertex_list.sort() ss['vertno'] = np.array(vertex_list, dtype=ss['vertno'].dtype) ss['inuse'][ss['vertno']] = 1 dist = grade * .0011 while True: coords = ss['rr'][ss['vertno']] neighbors = _point_graph(coords, dist) keep = np.array([np.sum(neighbors == i) > n for i in range(len(coords))]) if np.all(keep): break ss['inuse'][ss['vertno'][~keep]] = 0 ss['vertno'] = ss['vertno'][keep] ss['nuse'] = len(ss['vertno']) assert ss['inuse'].sum() == ss['nuse'] assert np.all(np.flatnonzero(ss['inuse']) == ss['vertno']) return SourceSpaces([ss], sss.info)
def get_brain_surf_sources(subject, fname_surf_L=None, fname_surf_R=None, fname_tex_L=None, fname_tex_R=None, trans=False, fname_atlas=None, fname_color=None): """compute surface sources Parameters ---------- subject : str The name of the subject fname_surf_L : None | str The filename of the surface of the left hemisphere fname_surf_R : None | str The filename of the surface of the right hemisphere fname_tex_L : None | str The filename of the texture surface of the right hemisphere The texture is used to select areas in the surface fname_tex_R : None | str The filename of the texture surface of the left hemisphere trans : str | None The filename that contains transformation matrix for surface fname_atlas : str | None The filename of the area atlas fname_color : Brain surfer instance The filename of color atlas Returns ------- surf_src : instance of mne.SourceSpace Surface source space surf_labels : instace of mne.Labels Surface MarsAtlas labels ------- """ list_hemi = ['lh', 'rh'] fname_surf = [fname_surf_L, fname_surf_R] fname_tex = [fname_tex_L, fname_tex_R] print('\nBuilding surface areas.....') # Get surfaces surfaces = [] surf_labels = [] for hemi_surf, hemi_tex, hemi in zip(fname_surf, fname_tex, list_hemi): if hemi_surf is not None and hemi_tex is not None: # Create surface areas surface = get_surface(hemi_surf, subject=subject, hemi=hemi, trans=trans) labels_hemi = get_surface_labels(surface, texture=hemi_tex, hemi=hemi, subject=subject, fname_atlas=fname_atlas, fname_color=fname_color) # Delete WM (values of texture 0 and 42) bad_areas = [0, 42] if bad_areas is not None: # bad = labels_hemi = list(np.delete(labels_hemi, bad_areas, axis=0)) # MNE accepts hemispheric labels as a single object that keeps the sum of all single labels labels_sum = [] for l in labels_hemi: if type(labels_sum) == list: labels_sum = l else: labels_sum += l surfaces.append(surface) surf_labels.append(labels_sum) print('\nSet sources on MarsAtlas cortical areas') surf_src = SourceSpaces(surfaces) print('[done]') return surf_src, surf_labels
def test_vec_stc_basic(tmpdir, klass, kind): """Test (vol)vector source estimate.""" nn = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [np.sqrt(1 / 3.)] * 3]) data = np.array([ [1, 0, 0], [0, 2, 0], [3, 0, 0], [1, 1, 1], ])[:, :, np.newaxis] magnitudes = np.linalg.norm(data, axis=1)[:, 0] normals = np.array([1, 2, 0, np.sqrt(3)]) vol_kind = kind if kind in ('discrete', 'vol') else 'vol' vol_src = SourceSpaces([dict(nn=nn, type=vol_kind)]) assert vol_src.kind == dict(vol='volume').get(vol_kind, vol_kind) vol_verts = [np.arange(4)] surf_src = SourceSpaces( [dict(nn=nn[:2], type='surf'), dict(nn=nn[2:], type='surf')]) assert surf_src.kind == 'surface' surf_verts = [np.array([0, 1]), np.array([0, 1])] if klass is VolVectorSourceEstimate: src = vol_src verts = vol_verts elif klass is VectorSourceEstimate: src = surf_src verts = surf_verts if klass is MixedVectorSourceEstimate: src = surf_src + vol_src verts = surf_verts + vol_verts assert src.kind == 'mixed' data = np.tile(data, (2, 1, 1)) magnitudes = np.tile(magnitudes, 2) normals = np.tile(normals, 2) stc = klass(data, verts, 0, 1, 'foo') # Magnitude of the vectors assert_array_equal(stc.magnitude().data[:, 0], magnitudes) # Vector components projected onto the vertex normals if kind in ('vol', 'mixed'): with pytest.raises(RuntimeError, match='surface or discrete'): stc.normal(src) else: normal = stc.normal(src) assert_array_equal(normal.data[:, 0], normals) out_name = tmpdir.join('temp.h5') stc.save(out_name) stc_read = read_source_estimate(out_name) assert_allclose(stc.data, stc_read.data) assert len(stc.vertices) == len(stc_read.vertices) for v1, v2 in zip(stc.vertices, stc_read.vertices): assert_array_equal(v1, v2) stc = klass(data[:, :, 0], verts, 0, 1) # upbroadcast assert stc.data.shape == (len(data), 3, 1) # Bad data with pytest.raises(ValueError, match='must have shape.*3'): klass(data[:, :2], verts, 0, 1) data = data[:, :, np.newaxis] with pytest.raises(ValueError, match='3 dimensions for .*VectorSource'): klass(data, verts, 0, 1)