def test_make_bem_model(tmpdir, kwargs, fname): """Test BEM model creation from Python with I/O.""" fname_temp = tmpdir.join('temp-bem.fif') with catch_logging() as log: model = make_bem_model('sample', ico=2, subjects_dir=subjects_dir, verbose=True, **kwargs) log = log.getvalue() if len(kwargs.get('conductivity', (0, 0, 0))) == 1: assert 'distance' not in log else: assert re.search(r'urfaces is approximately *3\.4 mm', log) is not None assert re.search(r'inner skull CM is *0\.65 *-9\.62 *43\.85 mm', log) is not None model_c = read_bem_surfaces(fname) _compare_bem_surfaces(model, model_c) write_bem_surfaces(fname_temp, model) model_read = read_bem_surfaces(fname_temp) _compare_bem_surfaces(model, model_c) _compare_bem_surfaces(model_read, model_c) # bad conductivity with pytest.raises(ValueError, match='conductivity must be'): make_bem_model('sample', 4, [0.3, 0.006], subjects_dir=subjects_dir)
def __make_bem_individual(sub, fs_sub_dir, outdir, single_layers): """ :param sub: :param fs_sub_dir: :param single_layers: :return: """ # see if file exists and skip if so if os.path.isfile(f'{outdir}/{sub}-5120-5120-5120-bem.fif'): print(f'{sub} has full file skipping') model = mne.read_bem_surfaces(f'{outdir}/{sub}-5120-5120-5120-bem.fif') solname = f'{outdir}/{sub}-5120-5120-5120-bem-sol.fif' # if single layers is true check for this, if not we want to try full model elif os.path.isfile(f'{outdir}/{sub}-5120-5120-5120-single-bem.fif'): if single_layers: print(f'{sub} has single layer file skipping') model = mne.read_bem_surfaces( f'{outdir}/{sub}-5120-5120-5120-single-bem.fif') solname = f'{outdir}/{sub}-5120-5120-5120-single-bem-sol.fif' else: # make model try: model = mne.make_bem_model(sub, subjects_dir=fs_sub_dir) bemname = f'{outdir}/{sub}-5120-5120-5120-bem.fif' solname = f'{outdir}/{sub}-5120-5120-5120-bem-sol.fif' except: print('failed to make BEM model with input') if single_layers: try: print( 'falling back to single layer model due to BEM suckiness' ) model = mne.make_bem_model(sub, subjects_dir=fs_sub_dir, conductivity=[0.3]) bemname = f'{outdir}/{sub}-5120-5120-5120-single-bem.fif' solname = f'{outdir}/{sub}-5120-5120-5120-single-bem-sol.fif' except: print(f'oops that also failed for {sub}') return '' else: print('wont allow single layer model so skipping') return '' # save model mne.write_bem_surfaces(bemname, model) # save to source dir bem_sol = mne.make_bem_solution(model) # make bem solution using model mne.write_bem_solution(solname, bem_sol) # save as well to the outdir return solname
def test_io_bem_surfaces(): """Testing reading of bem surfaces """ surf = read_bem_surfaces(fname, add_geom=True) surf = read_bem_surfaces(fname, add_geom=False) print "Number of surfaces : %d" % len(surf) write_bem_surface('bem_surf.fif', surf[0]) surf_read = read_bem_surfaces('bem_surf.fif', add_geom=False) for key in surf[0].keys(): assert_array_almost_equal(surf[0][key], surf_read[0][key])
def test_io_bem_surfaces(): """Test reading of bem surfaces """ tempdir = _TempDir() surf = read_bem_surfaces(fname, add_geom=True) surf = read_bem_surfaces(fname, add_geom=False) print("Number of surfaces : %d" % len(surf)) write_bem_surface(op.join(tempdir, 'bem_surf.fif'), surf[0]) surf_read = read_bem_surfaces(op.join(tempdir, 'bem_surf.fif'), add_geom=False) for key in surf[0].keys(): assert_array_almost_equal(surf[0][key], surf_read[0][key])
def test_bem_model(): """Test BEM model creation from Python with I/O""" tempdir = _TempDir() fname_temp = op.join(tempdir, "temp-bem.fif") for kwargs, fname in zip((dict(), dict(conductivity=[0.3])), [fname_bem_3, fname_bem_1]): model = make_bem_model("sample", ico=2, subjects_dir=subjects_dir, **kwargs) model_c = read_bem_surfaces(fname) _compare_bem_surfaces(model, model_c) write_bem_surfaces(fname_temp, model) model_read = read_bem_surfaces(fname_temp) _compare_bem_surfaces(model, model_c) _compare_bem_surfaces(model_read, model_c) assert_raises( ValueError, make_bem_model, "sample", conductivity=[0.3, 0.006], subjects_dir=subjects_dir # bad conductivity )
def test_bem_model(): """Test BEM model creation from Python with I/O""" tempdir = _TempDir() fname_temp = op.join(tempdir, 'temp-bem.fif') for kwargs, fname in zip((dict(), dict(conductivity=[0.3])), [fname_bem_3, fname_bem_1]): model = make_bem_model('sample', ico=2, subjects_dir=subjects_dir, **kwargs) model_c = read_bem_surfaces(fname) _compare_bem_surfaces(model, model_c) write_bem_surfaces(fname_temp, model) model_read = read_bem_surfaces(fname_temp) _compare_bem_surfaces(model, model_c) _compare_bem_surfaces(model_read, model_c) assert_raises(ValueError, make_bem_model, 'sample', # bad conductivity conductivity=[0.3, 0.006], subjects_dir=subjects_dir)
def plot_BEM_surface(subject, fnout_img=None): """"Reads in and plots the BEM surface.""" # get name of BEM-file subjects_dir = os.environ.get('SUBJECTS_DIR') fn_bem = os.path.join(subjects_dir, subject, 'bem', subject + "-5120-5120-5120-bem-sol.fif") surfaces = mne.read_bem_surfaces(fn_bem, add_geom=True) print "Number of surfaces : %d" % len(surfaces) # Show result head_col = (0.95, 0.83, 0.83) # light pink skull_col = (0.91, 0.89, 0.67) brain_col = (0.67, 0.89, 0.91) # light blue colors = [head_col, skull_col, brain_col] # create figure and plot results fig_BEM = mlab.figure(size=(1200, 1200), bgcolor=(0, 0, 0)) for c, surf in zip(colors, surfaces): points = surf['rr'] faces = surf['tris'] mlab.triangular_mesh(points[:, 0], points[:, 1], points[:, 2], faces, color=c, opacity=0.3) # save result if fnout_img is not None: mlab.savefig(fnout_img, figure=fig_BEM, size=(1200, 1200)) mlab.close(all=True)
def get_bem_artifacts( template, montage_name="HGSN129-montage.fif", subjects_dir=None, include_vol_src=True, labels_vol=('Left-Amygdala', 'Left-Caudate', 'Left-Hippocampus', 'Left-Pallidum', 'Left-Putamen', 'Left-Thalamus', 'Right-Amygdala', 'Right-Caudate', 'Right-Hippocampus', 'Right-Pallidum', 'Right-Putamen', 'Right-Thalamus'), force_vol_computation=False): if subjects_dir is None: subjects_dir = Path(os.environ["SUBJECTS_DIR"]) if template == "fsaverage": fs_dir = mne.datasets.fetch_fsaverage(verbose=True) trans = 'fsaverage' # MNE has a built-in fsaverage transformation surface_src = op.join(fs_dir, 'bem', 'fsaverage-ico-5-src.fif') bem_solution = op.join(fs_dir, 'bem', 'fsaverage-5120-5120-5120-bem-sol.fif') bem_model = None montage = mne.channels.make_standard_montage('GSN-HydroCel-129') return montage, trans, bem_model, bem_solution, surface_src montage = mne.channels.read_dig_fif( str(Path(subjects_dir) / template / "montages" / montage_name)) trans = mne.channels.compute_native_head_t(montage) bem_model = mne.read_bem_surfaces( str( Path(subjects_dir) / template / "bem" / f"{template}-5120-5120-5120-bem.fif")) bem_solution = mne.read_bem_solution( str( Path(subjects_dir) / template / "bem" / f"{template}-5120-5120-5120-bem-sol.fif")) if not include_vol_src: surface_src = mne.read_source_spaces( str( Path(subjects_dir) / template / "bem" / f"{template}-oct-6-src.fif")) return montage, trans, bem_model, bem_solution, surface_src mixed_src_file_path = Path( subjects_dir) / template / "bem" / f"{template}-mixed-src.fif" if not mixed_src_file_path.exists() or force_vol_computation: surface_src = mne.read_source_spaces( str( Path(subjects_dir) / template / "bem" / f"{template}-oct-6-src.fif")) volume_src = mne.setup_volume_source_space(template, pos=5.0, bem=bem_solution, add_interpolator=True, volume_label=labels_vol) mixed_src = surface_src + volume_src mixed_src.save(str(mixed_src_file_path), overwrite=True) mixed_src = mne.read_source_spaces(str(mixed_src_file_path)) return montage, trans, bem_model, bem_solution, mixed_src
def test_volume_source_space(): """Test setting up volume source spaces """ tempdir = _TempDir() src = read_source_spaces(fname_vol) temp_name = op.join(tempdir, 'temp-src.fif') surf = read_bem_surfaces(fname_bem, s_id=FIFF.FIFFV_BEM_SURF_ID_BRAIN) surf['rr'] *= 1e3 # convert to mm # The one in the testing dataset (uses bem as bounds) for bem, surf in zip((fname_bem, None), (None, surf)): src_new = setup_volume_source_space('sample', temp_name, pos=7.0, bem=bem, surface=surf, mri='T1.mgz', subjects_dir=subjects_dir) src[0]['subject_his_id'] = 'sample' # XXX: to make comparison pass _compare_source_spaces(src, src_new, mode='approx') del src_new src_new = read_source_spaces(temp_name) _compare_source_spaces(src, src_new, mode='approx') assert_raises( IOError, setup_volume_source_space, 'sample', temp_name, pos=7.0, bem=None, surface='foo', # bad surf mri=fname_mri, subjects_dir=subjects_dir) assert_equal(repr(src), repr(src_new)) assert_equal(src.kind, 'volume')
def test_volume_source_space(): """Test setting up volume source spaces.""" tempdir = _TempDir() src = read_source_spaces(fname_vol) temp_name = op.join(tempdir, 'temp-src.fif') surf = read_bem_surfaces(fname_bem, s_id=FIFF.FIFFV_BEM_SURF_ID_BRAIN) surf['rr'] *= 1e3 # convert to mm # The one in the testing dataset (uses bem as bounds) for bem, surf in zip((fname_bem, None), (None, surf)): src_new = setup_volume_source_space( 'sample', pos=7.0, bem=bem, surface=surf, mri='T1.mgz', subjects_dir=subjects_dir) write_source_spaces(temp_name, src_new, overwrite=True) src[0]['subject_his_id'] = 'sample' # XXX: to make comparison pass _compare_source_spaces(src, src_new, mode='approx') del src_new src_new = read_source_spaces(temp_name) _compare_source_spaces(src, src_new, mode='approx') pytest.raises(IOError, setup_volume_source_space, 'sample', pos=7.0, bem=None, surface='foo', # bad surf mri=fname_mri, subjects_dir=subjects_dir) assert repr(src) == repr(src_new) assert src.kind == 'volume' # Spheres sphere = make_sphere_model(r0=(0., 0., 0.), head_radius=0.1, relative_radii=(0.9, 1.0), sigmas=(0.33, 1.0)) src = setup_volume_source_space(pos=10) src_new = setup_volume_source_space(pos=10, sphere=sphere) _compare_source_spaces(src, src_new, mode='exact') pytest.raises(ValueError, setup_volume_source_space, sphere='foo') # Need a radius sphere = make_sphere_model(head_radius=None) pytest.raises(ValueError, setup_volume_source_space, sphere=sphere)
def test_make_scalp_surfaces_topology(tmp_path, monkeypatch): """Test topology checks for make_scalp_surfaces.""" pytest.importorskip('pyvista') subjects_dir = tmp_path subject = 'test' surf_dir = subjects_dir / subject / 'surf' makedirs(surf_dir) surf = _get_ico_surface(2) surf['rr'] *= 100 # mm write_surface(surf_dir / 'lh.seghead', surf['rr'], surf['tris']) # make it so that decimation really messes up the mesh just by deleting # the last N tris def _decimate_surface(points, triangles, n_triangles): assert len(triangles) >= n_triangles return points, triangles[:n_triangles] monkeypatch.setattr(mne.bem, 'decimate_surface', _decimate_surface) # TODO: These two errors should probably have the same class... # Not enough neighbors monkeypatch.setattr(mne.bem, '_tri_levels', dict(sparse=315)) with pytest.raises(ValueError, match='.*have fewer than three.*'): make_scalp_surfaces(subject, subjects_dir, force=False, verbose=True) monkeypatch.setattr(mne.bem, '_tri_levels', dict(sparse=319)) # Incomplete surface (sum of solid angles) with pytest.raises(RuntimeError, match='.*is not complete.*'): make_scalp_surfaces(subject, subjects_dir, force=False, verbose=True, overwrite=True) bem_dir = subjects_dir / subject / 'bem' sparse_path = (bem_dir / f'{subject}-head-sparse.fif') assert not sparse_path.is_file() # These are ignorable monkeypatch.setattr(mne.bem, '_tri_levels', dict(sparse=315)) with pytest.warns(RuntimeWarning, match='.*have fewer than three.*'): make_scalp_surfaces(subject, subjects_dir, force=True, overwrite=True) surf, = read_bem_surfaces(sparse_path, on_defects='ignore') assert len(surf['tris']) == 315 monkeypatch.setattr(mne.bem, '_tri_levels', dict(sparse=319)) with pytest.warns(RuntimeWarning, match='.*is not complete.*'): make_scalp_surfaces(subject, subjects_dir, force=True, overwrite=True) surf, = read_bem_surfaces(sparse_path, on_defects='ignore') assert len(surf['tris']) == 319
def test_bem_solution(): """Test making a BEM solution from Python with I/O""" # test degenerate conditions surf = read_bem_surfaces(fname_bem_1)[0] assert_raises(RuntimeError, _ico_downsample, surf, 10) # bad dec grade s_bad = dict(tris=surf['tris'][1:], ntri=surf['ntri'] - 1, rr=surf['rr']) assert_raises(RuntimeError, _ico_downsample, s_bad, 1) # not isomorphic s_bad = dict(tris=surf['tris'].copy(), ntri=surf['ntri'], rr=surf['rr']) # bad triangulation s_bad['tris'][0] = [0, 0, 0] assert_raises(RuntimeError, _ico_downsample, s_bad, 1) s_bad['id'] = 1 assert_raises(RuntimeError, _assert_complete_surface, s_bad) s_bad = dict(tris=surf['tris'], ntri=surf['ntri'], rr=surf['rr'].copy()) s_bad['rr'][0] = 0. assert_raises(RuntimeError, _get_ico_map, surf, s_bad) surfs = read_bem_surfaces(fname_bem_3) assert_raises(RuntimeError, _assert_inside, surfs[0], surfs[1]) # outside surfs[0]['id'] = 100 # bad surfs assert_raises(RuntimeError, _order_surfaces, surfs) surfs[1]['rr'] /= 1000. assert_raises(RuntimeError, _check_surface_size, surfs[1]) # actually test functionality tempdir = _TempDir() fname_temp = op.join(tempdir, 'temp-bem-sol.fif') # use a model and solution made in Python conductivities = [(0.3, ), (0.3, 0.006, 0.3)] fnames = [fname_bem_sol_1, fname_bem_sol_3] for cond, fname in zip(conductivities, fnames): for model_type in ('python', 'c'): if model_type == 'python': model = make_bem_model('sample', conductivity=cond, ico=2, subjects_dir=subjects_dir) else: model = fname_bem_1 if len(cond) == 1 else fname_bem_3 solution = make_bem_solution(model) solution_c = read_bem_solution(fname) _compare_bem_solutions(solution, solution_c) write_bem_solution(fname_temp, solution) solution_read = read_bem_solution(fname_temp) _compare_bem_solutions(solution, solution_c) _compare_bem_solutions(solution_read, solution_c)
def test_make_bem_model(tmpdir): """Test BEM model creation from Python with I/O.""" tempdir = str(tmpdir) fname_temp = op.join(tempdir, 'temp-bem.fif') for kwargs, fname in zip((dict(), dict(conductivity=[0.3])), [fname_bem_3, fname_bem_1]): model = make_bem_model('sample', ico=2, subjects_dir=subjects_dir, **kwargs) model_c = read_bem_surfaces(fname) _compare_bem_surfaces(model, model_c) write_bem_surfaces(fname_temp, model) model_read = read_bem_surfaces(fname_temp) _compare_bem_surfaces(model, model_c) _compare_bem_surfaces(model_read, model_c) # bad conductivity with pytest.raises(ValueError, match='conductivity must be'): make_bem_model('sample', 4, [0.3, 0.006], subjects_dir=subjects_dir)
def test_volume_source_space(tmpdir): """Test setting up volume source spaces.""" src = read_source_spaces(fname_vol) temp_name = tmpdir.join('temp-src.fif') surf = read_bem_surfaces(fname_bem, s_id=FIFF.FIFFV_BEM_SURF_ID_BRAIN) surf['rr'] *= 1e3 # convert to mm bem_sol = read_bem_solution(fname_bem_3_sol) bem = read_bem_solution(fname_bem_sol) # The one in the testing dataset (uses bem as bounds) for this_bem, this_surf in zip( (bem, fname_bem, fname_bem_3, bem_sol, fname_bem_3_sol, None), (None, None, None, None, None, surf)): src_new = setup_volume_source_space('sample', pos=7.0, bem=this_bem, surface=this_surf, subjects_dir=subjects_dir) write_source_spaces(temp_name, src_new, overwrite=True) src[0]['subject_his_id'] = 'sample' # XXX: to make comparison pass _compare_source_spaces(src, src_new, mode='approx') del src_new src_new = read_source_spaces(temp_name) _compare_source_spaces(src, src_new, mode='approx') with pytest.raises(IOError, match='surface file.*not found'): setup_volume_source_space('sample', surface='foo', mri=fname_mri, subjects_dir=subjects_dir) bem['surfs'][-1]['coord_frame'] = FIFF.FIFFV_COORD_HEAD with pytest.raises(ValueError, match='BEM is not in MRI coord.* got head'): setup_volume_source_space('sample', bem=bem, mri=fname_mri, subjects_dir=subjects_dir) bem['surfs'] = bem['surfs'][:-1] # no inner skull surf with pytest.raises(ValueError, match='Could not get inner skul.*from BEM'): setup_volume_source_space('sample', bem=bem, mri=fname_mri, subjects_dir=subjects_dir) del bem assert repr(src) == repr(src_new) assert ' MB' in repr(src) assert src.kind == 'volume' # Spheres sphere = make_sphere_model(r0=(0., 0., 0.), head_radius=0.1, relative_radii=(0.9, 1.0), sigmas=(0.33, 1.0)) src = setup_volume_source_space(pos=10, sphere=(0., 0., 0., 0.09)) src_new = setup_volume_source_space(pos=10, sphere=sphere) _compare_source_spaces(src, src_new, mode='exact') with pytest.raises(ValueError, match='sphere, if str'): setup_volume_source_space(sphere='foo') # Need a radius sphere = make_sphere_model(head_radius=None) with pytest.raises(ValueError, match='be spherical with multiple layers'): setup_volume_source_space(sphere=sphere)
def test_io_bem(tmpdir, ext): """Test reading and writing of bem surfaces and solutions.""" import h5py temp_bem = op.join(str(tmpdir), f'temp-bem.{ext}') # model with pytest.raises(ValueError, match='BEM data not found'): read_bem_surfaces(fname_raw) with pytest.raises(ValueError, match='surface with id 10'): read_bem_surfaces(fname_bem_3, s_id=10) surf = read_bem_surfaces(fname_bem_3, patch_stats=True) surf = read_bem_surfaces(fname_bem_3, patch_stats=False) write_bem_surfaces(temp_bem, surf[0]) with pytest.raises(IOError, match='exists'): write_bem_surfaces(temp_bem, surf[0]) write_bem_surfaces(temp_bem, surf[0], overwrite=True) if ext == 'h5': with h5py.File(temp_bem, 'r'): # make sure it's valid pass surf_read = read_bem_surfaces(temp_bem, patch_stats=False) _compare_bem_surfaces(surf, surf_read) # solution with pytest.raises(RuntimeError, match='No BEM solution found'): read_bem_solution(fname_bem_3) temp_sol = op.join(str(tmpdir), f'temp-sol.{ext}') sol = read_bem_solution(fname_bem_sol_3) assert 'BEM' in repr(sol) write_bem_solution(temp_sol, sol) sol_read = read_bem_solution(temp_sol) _compare_bem_solutions(sol, sol_read) sol = read_bem_solution(fname_bem_sol_1) with pytest.raises(RuntimeError, match='BEM does not have.*triangulation'): _bem_find_surface(sol, 3)
def test_make_bem_model(tmpdir): """Test BEM model creation from Python with I/O.""" fname_temp = tmpdir.join('temp-bem.fif') for kwargs, fname in zip((dict(), dict(conductivity=[0.3])), [fname_bem_3, fname_bem_1]): model = make_bem_model('sample', ico=2, subjects_dir=subjects_dir, **kwargs) model_c = read_bem_surfaces(fname) _compare_bem_surfaces(model, model_c) write_bem_surfaces(fname_temp, model) model_read = read_bem_surfaces(fname_temp) _compare_bem_surfaces(model, model_c) _compare_bem_surfaces(model_read, model_c) # bad conductivity with pytest.raises(ValueError, match='conductivity must be'): make_bem_model('sample', 4, [0.3, 0.006], subjects_dir=subjects_dir)
def test_bem_solution(): """Test making a BEM solution from Python with I/O.""" # test degenerate conditions surf = read_bem_surfaces(fname_bem_1)[0] pytest.raises(RuntimeError, _ico_downsample, surf, 10) # bad dec grade s_bad = dict(tris=surf['tris'][1:], ntri=surf['ntri'] - 1, rr=surf['rr']) pytest.raises(RuntimeError, _ico_downsample, s_bad, 1) # not isomorphic s_bad = dict(tris=surf['tris'].copy(), ntri=surf['ntri'], rr=surf['rr']) # bad triangulation s_bad['tris'][0] = [0, 0, 0] pytest.raises(RuntimeError, _ico_downsample, s_bad, 1) s_bad['id'] = 1 pytest.raises(RuntimeError, _assert_complete_surface, s_bad) s_bad = dict(tris=surf['tris'], ntri=surf['ntri'], rr=surf['rr'].copy()) s_bad['rr'][0] = 0. pytest.raises(RuntimeError, _get_ico_map, surf, s_bad) surfs = read_bem_surfaces(fname_bem_3) pytest.raises(RuntimeError, _assert_inside, surfs[0], surfs[1]) # outside surfs[0]['id'] = 100 # bad surfs pytest.raises(RuntimeError, _order_surfaces, surfs) surfs[1]['rr'] /= 1000. pytest.raises(RuntimeError, _check_surface_size, surfs[1]) # actually test functionality tempdir = _TempDir() fname_temp = op.join(tempdir, 'temp-bem-sol.fif') # use a model and solution made in Python conductivities = [(0.3,), (0.3, 0.006, 0.3)] fnames = [fname_bem_sol_1, fname_bem_sol_3] for cond, fname in zip(conductivities, fnames): for model_type in ('python', 'c'): if model_type == 'python': model = make_bem_model('sample', conductivity=cond, ico=2, subjects_dir=subjects_dir) else: model = fname_bem_1 if len(cond) == 1 else fname_bem_3 solution = make_bem_solution(model) solution_c = read_bem_solution(fname) _compare_bem_solutions(solution, solution_c) write_bem_solution(fname_temp, solution) solution_read = read_bem_solution(fname_temp) _compare_bem_solutions(solution, solution_c) _compare_bem_solutions(solution_read, solution_c)
def repeat_coreg(subject, subjects_dir=None, subjects_dir_old=None, overwrite=False, verbose=None): """Repeat a mne coreg warping of an MRI. This is useful for example when bugs are fixed with :func:`mne.scale_mri`. .. warning:: This function should not be used when the parameters in ``'MRI scaling parameters.cfg'`` have been changed. Parameters ---------- subject : str The subject name. subjects_dir : str | None The subjects directory where the redone subject should go. The template/surrogate MRI must also be in this directory. subjects_dir_old : str | None The subjects directory where the old subject is. Can be None to use ``subjects_dir``. overwrite : bool If True (default False), overwrite an existing subject directory if it exists. verbose : str | None The verbose level to use. Returns ------- out_dir : str The output subject directory. """ subjects_dir = mne.utils.get_subjects_dir(subjects_dir) if subjects_dir_old is None: subjects_dir_old = subjects_dir config = mne.coreg.read_mri_cfg(subject, subjects_dir_old) n_params = config.pop('n_params') assert n_params in (3, 1), n_params out_dir = op.join(subjects_dir, subject) mne.coreg.scale_mri(subject_to=subject, subjects_dir=subjects_dir, labels=True, annot=True, overwrite=overwrite, **config) for pattern in ('-5120', '-5120-5120-5120', 'inner_skull'): fname_bem = op.join(subjects_dir, subject, 'bem', f'{subject}{pattern}-bem.fif') fname_sol = fname_bem[:-4] + '-sol.fif' if op.isfile(fname_bem) and not op.isfile(fname_sol): bem = mne.read_bem_surfaces(fname_bem) sol = mne.make_bem_solution(bem) mne.write_bem_solution(fname_sol, sol) return out_dir
def test_io_bem(tmpdir): """Test reading and writing of bem surfaces and solutions.""" temp_bem = op.join(str(tmpdir), 'temp-bem.fif') pytest.raises(ValueError, read_bem_surfaces, fname_raw) pytest.raises(ValueError, read_bem_surfaces, fname_bem_3, s_id=10) surf = read_bem_surfaces(fname_bem_3, patch_stats=True) surf = read_bem_surfaces(fname_bem_3, patch_stats=False) write_bem_surfaces(temp_bem, surf[0]) surf_read = read_bem_surfaces(temp_bem, patch_stats=False) _compare_bem_surfaces(surf, surf_read) pytest.raises(RuntimeError, read_bem_solution, fname_bem_3) temp_sol = op.join(str(tmpdir), 'temp-sol.fif') sol = read_bem_solution(fname_bem_sol_3) assert 'BEM' in repr(sol) write_bem_solution(temp_sol, sol) sol_read = read_bem_solution(temp_sol) _compare_bem_solutions(sol, sol_read) sol = read_bem_solution(fname_bem_sol_1) pytest.raises(RuntimeError, _bem_find_surface, sol, 3)
def test_make_scalp_surfaces(tmp_path, monkeypatch): """Test mne make_scalp_surfaces.""" pytest.importorskip('nibabel') pytest.importorskip('pyvista') check_usage(mne_make_scalp_surfaces) has = 'SUBJECTS_DIR' in os.environ # Copy necessary files to avoid FreeSurfer call tempdir = str(tmp_path) surf_path = op.join(subjects_dir, 'sample', 'surf') surf_path_new = op.join(tempdir, 'sample', 'surf') os.mkdir(op.join(tempdir, 'sample')) os.mkdir(surf_path_new) subj_dir = op.join(tempdir, 'sample', 'bem') os.mkdir(subj_dir) cmd = ('-s', 'sample', '--subjects-dir', tempdir) monkeypatch.setattr( mne.bem, 'decimate_surface', lambda points, triangles, n_triangles: (points, triangles)) dense_fname = op.join(subj_dir, 'sample-head-dense.fif') medium_fname = op.join(subj_dir, 'sample-head-medium.fif') with ArgvSetter(cmd, disable_stdout=False, disable_stderr=False): monkeypatch.delenv('FREESURFER_HOME', None) with pytest.raises(RuntimeError, match='The FreeSurfer environ'): mne_make_scalp_surfaces.run() shutil.copy(op.join(surf_path, 'lh.seghead'), surf_path_new) monkeypatch.setenv('FREESURFER_HOME', tempdir) mne_make_scalp_surfaces.run() assert op.isfile(dense_fname) assert op.isfile(medium_fname) with pytest.raises(IOError, match='overwrite'): mne_make_scalp_surfaces.run() # actually check the outputs head_py = read_bem_surfaces(dense_fname) assert_equal(len(head_py), 1) head_py = head_py[0] head_c = read_bem_surfaces( op.join(subjects_dir, 'sample', 'bem', 'sample-head-dense.fif'))[0] assert_allclose(head_py['rr'], head_c['rr']) if not has: assert 'SUBJECTS_DIR' not in os.environ
def test_make_scalp_surfaces(): """Test mne make_scalp_surfaces.""" check_usage(mne_make_scalp_surfaces) # Copy necessary files to avoid FreeSurfer call tempdir = _TempDir() surf_path = op.join(subjects_dir, 'sample', 'surf') surf_path_new = op.join(tempdir, 'sample', 'surf') os.mkdir(op.join(tempdir, 'sample')) os.mkdir(surf_path_new) subj_dir = op.join(tempdir, 'sample', 'bem') os.mkdir(subj_dir) shutil.copy(op.join(surf_path, 'lh.seghead'), surf_path_new) orig_fs = os.getenv('FREESURFER_HOME', None) if orig_fs is not None: del os.environ['FREESURFER_HOME'] cmd = ('-s', 'sample', '--subjects-dir', tempdir) os.environ['_MNE_TESTING_SCALP'] = 'true' dense_fname = op.join(subj_dir, 'sample-head-dense.fif') medium_fname = op.join(subj_dir, 'sample-head-medium.fif') try: with ArgvSetter(cmd, disable_stdout=False, disable_stderr=False): pytest.raises(RuntimeError, mne_make_scalp_surfaces.run) os.environ['FREESURFER_HOME'] = tempdir # don't actually use it mne_make_scalp_surfaces.run() assert op.isfile(dense_fname) assert op.isfile(medium_fname) pytest.raises(IOError, mne_make_scalp_surfaces.run) # no overwrite finally: if orig_fs is not None: os.environ['FREESURFER_HOME'] = orig_fs else: del os.environ['FREESURFER_HOME'] del os.environ['_MNE_TESTING_SCALP'] # actually check the outputs head_py = read_bem_surfaces(dense_fname) assert_equal(len(head_py), 1) head_py = head_py[0] head_c = read_bem_surfaces(op.join(subjects_dir, 'sample', 'bem', 'sample-head-dense.fif'))[0] assert_allclose(head_py['rr'], head_c['rr'])
def test_make_scalp_surfaces(): """Test mne make_scalp_surfaces.""" check_usage(mne_make_scalp_surfaces) # Copy necessary files to avoid FreeSurfer call tempdir = _TempDir() surf_path = op.join(subjects_dir, 'sample', 'surf') surf_path_new = op.join(tempdir, 'sample', 'surf') os.mkdir(op.join(tempdir, 'sample')) os.mkdir(surf_path_new) subj_dir = op.join(tempdir, 'sample', 'bem') os.mkdir(subj_dir) shutil.copy(op.join(surf_path, 'lh.seghead'), surf_path_new) orig_fs = os.getenv('FREESURFER_HOME', None) if orig_fs is not None: del os.environ['FREESURFER_HOME'] cmd = ('-s', 'sample', '--subjects-dir', tempdir) os.environ['_MNE_TESTING_SCALP'] = 'true' dense_fname = op.join(subj_dir, 'sample-head-dense.fif') medium_fname = op.join(subj_dir, 'sample-head-medium.fif') try: with ArgvSetter(cmd, disable_stdout=False, disable_stderr=False): assert_raises(RuntimeError, mne_make_scalp_surfaces.run) os.environ['FREESURFER_HOME'] = tempdir # don't actually use it mne_make_scalp_surfaces.run() assert_true(op.isfile(dense_fname)) assert_true(op.isfile(medium_fname)) assert_raises(IOError, mne_make_scalp_surfaces.run) # no overwrite finally: if orig_fs is not None: os.environ['FREESURFER_HOME'] = orig_fs else: del os.environ['FREESURFER_HOME'] del os.environ['_MNE_TESTING_SCALP'] # actually check the outputs head_py = read_bem_surfaces(dense_fname) assert_equal(len(head_py), 1) head_py = head_py[0] head_c = read_bem_surfaces( op.join(subjects_dir, 'sample', 'bem', 'sample-head-dense.fif'))[0] assert_allclose(head_py['rr'], head_c['rr'])
def test_io_bem(): """Test reading and writing of bem surfaces and solutions.""" tempdir = _TempDir() temp_bem = op.join(tempdir, 'temp-bem.fif') pytest.raises(ValueError, read_bem_surfaces, fname_raw) pytest.raises(ValueError, read_bem_surfaces, fname_bem_3, s_id=10) surf = read_bem_surfaces(fname_bem_3, patch_stats=True) surf = read_bem_surfaces(fname_bem_3, patch_stats=False) write_bem_surfaces(temp_bem, surf[0]) surf_read = read_bem_surfaces(temp_bem, patch_stats=False) _compare_bem_surfaces(surf, surf_read) pytest.raises(RuntimeError, read_bem_solution, fname_bem_3) temp_sol = op.join(tempdir, 'temp-sol.fif') sol = read_bem_solution(fname_bem_sol_3) assert 'BEM' in repr(sol) write_bem_solution(temp_sol, sol) sol_read = read_bem_solution(temp_sol) _compare_bem_solutions(sol, sol_read) sol = read_bem_solution(fname_bem_sol_1) pytest.raises(RuntimeError, _bem_find_surface, sol, 3)
def test_setup_forward_model(tmpdir): """Test mne setup_source_space.""" check_usage(mne_setup_forward_model, force_help=True) # Using the sample dataset subjects_dir = op.join(testing.data_path(download=False), 'subjects') use_fname = op.join(tmpdir, "model-bem.fif") # Test command with ArgvSetter(('--model', use_fname, '-d', subjects_dir, '-s', 'sample', '--ico', '3', '--verbose')): mne_setup_forward_model.run() model = read_bem_surfaces(use_fname) assert len(model) == 3
def test_make_scalp_surfaces(): """Test mne make_scalp_surfaces.""" check_usage(mne_make_scalp_surfaces) # Copy necessary files to avoid FreeSurfer call tempdir = _TempDir() surf_path = op.join(subjects_dir, "sample", "surf") surf_path_new = op.join(tempdir, "sample", "surf") os.mkdir(op.join(tempdir, "sample")) os.mkdir(surf_path_new) subj_dir = op.join(tempdir, "sample", "bem") os.mkdir(subj_dir) shutil.copy(op.join(surf_path, "lh.seghead"), surf_path_new) orig_fs = os.getenv("FREESURFER_HOME", None) if orig_fs is not None: del os.environ["FREESURFER_HOME"] cmd = ("-s", "sample", "--subjects-dir", tempdir) os.environ["_MNE_TESTING_SCALP"] = "true" dense_fname = op.join(subj_dir, "sample-head-dense.fif") medium_fname = op.join(subj_dir, "sample-head-medium.fif") try: with ArgvSetter(cmd, disable_stdout=False, disable_stderr=False): assert_raises(RuntimeError, mne_make_scalp_surfaces.run) os.environ["FREESURFER_HOME"] = tempdir # don't actually use it mne_make_scalp_surfaces.run() assert_true(op.isfile(dense_fname)) assert_true(op.isfile(medium_fname)) assert_raises(IOError, mne_make_scalp_surfaces.run) # no overwrite finally: if orig_fs is not None: os.environ["FREESURFER_HOME"] = orig_fs else: del os.environ["FREESURFER_HOME"] del os.environ["_MNE_TESTING_SCALP"] # actually check the outputs head_py = read_bem_surfaces(dense_fname) assert_equal(len(head_py), 1) head_py = head_py[0] head_c = read_bem_surfaces(op.join(subjects_dir, "sample", "bem", "sample-head-dense.fif"))[0] assert_allclose(head_py["rr"], head_c["rr"])
def test_io_head_bem(tmpdir): """Test reading and writing of defective head surfaces.""" head = read_bem_surfaces(fname_dense_head)[0] fname_defect = op.join(str(tmpdir), 'temp-head-defect.fif') # create defects head['rr'][0] = np.array([-0.01487014, -0.04563854, -0.12660208]) head['tris'][0] = np.array([21919, 21918, 21907]) with pytest.raises(RuntimeError, match='topological defects:'): write_head_bem(fname_defect, head['rr'], head['tris']) with pytest.warns(RuntimeWarning, match='topological defects:'): write_head_bem(fname_defect, head['rr'], head['tris'], on_defects='warn') # test on_defects in read_bem_surfaces with pytest.raises(RuntimeError, match='topological defects:'): read_bem_surfaces(fname_defect) with pytest.warns(RuntimeWarning, match='topological defects:'): head_defect = read_bem_surfaces(fname_defect, on_defects='warn')[0] assert head['id'] == head_defect['id'] == FIFF.FIFFV_BEM_SURF_ID_HEAD assert np.allclose(head['rr'], head_defect['rr']) assert np.allclose(head['tris'], head_defect['tris'])
def test_setup_forward_model(tmp_path): """Test mne setup_forward_model.""" check_usage(mne_setup_forward_model, force_help=True) # Using the sample dataset use_fname = op.join(tmp_path, "model-bem.fif") # Test command with ArgvSetter(('--model', use_fname, '-d', subjects_dir, '--homog', '-s', 'sample', '--ico', '3', '--verbose')): mne_setup_forward_model.run() model = read_bem_surfaces(use_fname) assert len(model) == 1 sol_fname = op.splitext(use_fname)[0] + '-sol.fif' read_bem_solution(sol_fname)
def test_make_scalp_surfaces(tmpdir): """Test mne make_scalp_surfaces.""" check_usage(mne_make_scalp_surfaces) has = 'SUBJECTS_DIR' in os.environ # Copy necessary files to avoid FreeSurfer call tempdir = str(tmpdir) surf_path = op.join(subjects_dir, 'sample', 'surf') surf_path_new = op.join(tempdir, 'sample', 'surf') os.mkdir(op.join(tempdir, 'sample')) os.mkdir(surf_path_new) subj_dir = op.join(tempdir, 'sample', 'bem') os.mkdir(subj_dir) shutil.copy(op.join(surf_path, 'lh.seghead'), surf_path_new) cmd = ('-s', 'sample', '--subjects-dir', tempdir) with modified_env(**{'_MNE_TESTING_SCALP': 'true'}): dense_fname = op.join(subj_dir, 'sample-head-dense.fif') medium_fname = op.join(subj_dir, 'sample-head-medium.fif') with ArgvSetter(cmd, disable_stdout=False, disable_stderr=False): with modified_env(FREESURFER_HOME=None): pytest.raises(RuntimeError, mne_make_scalp_surfaces.run) with modified_env(FREESURFER_HOME=tempdir): mne_make_scalp_surfaces.run() assert op.isfile(dense_fname) assert op.isfile(medium_fname) with pytest.raises(IOError, match='overwrite'): mne_make_scalp_surfaces.run() # actually check the outputs head_py = read_bem_surfaces(dense_fname) assert_equal(len(head_py), 1) head_py = head_py[0] head_c = read_bem_surfaces(op.join(subjects_dir, 'sample', 'bem', 'sample-head-dense.fif'))[0] assert_allclose(head_py['rr'], head_c['rr']) if not has: assert 'SUBJECTS_DIR' not in os.environ
def __init__(self, bem, unit='m'): if isinstance(bem, basestring): bem = mne.read_bem_surfaces(bem)[0] pts = bem['rr'] tri = bem['tris'] if unit == 'mm': pts *= 1000 elif unit == 'm': pass else: raise ValueError('Unit: %r' % unit) super(geom_bem, self).__init__(pts, tri)
def makeBem(subj): camcan_root = os.environ['CAMCAN_ROOT'] bemmodel_fname = camcan_root + 'processed/cc700/mri/pipeline/release004/BIDSsep/megraw/' + subj + '/meg/' + subj + \ '-5120-5120-5120-singles-bem.fif' bemsolution_fname = camcan_root + 'processed/cc700/mri/pipeline/release004/BIDSsep/megraw/' + subj + '/meg/' + \ subj + '-5120-5120-5120-singles-bem-sol.fif' try: model = mne.read_bem_surfaces(bemmodel_fname) except IOError: model = mne.make_bem_model(subj, conductivity=[0.3]) mne.write_bem_surfaces(bemmodel_fname, model) try: bem_sol = mne.read_bem_solution(bemsolution_fname) except IOError: bem_sol = mne.make_bem_solution(model) mne.write_bem_solution(bemsolution_fname, bem_sol) return bem_sol
def check_bem(sbj_id, sbj_dir, raw_info, trans_fname, report): import os.path as op import mne from mne.viz import plot_bem, plot_trans from mayavi import mlab import numpy as np ### plot bem surfs to MRI in the 3 different views fig1 = plot_bem(subject=sbj_id, subjects_dir=sbj_dir, orientation='axial', show=False) fig2 = plot_bem(subject=sbj_id, subjects_dir=sbj_dir, orientation='sagittal', show=False) fig3 = plot_bem(subject=sbj_id, subjects_dir=sbj_dir, orientation='coronal', show=False) report.add_figs_to_section([fig1, fig2, fig3], captions=['axial view', 'sagittal view', 'coronal view'], section='BEM surfaces') ### plot bem surf and source space bem_fname = op.join(sbj_dir, sbj_id + '/bem/%s-5120-bem-sol.fif' % sbj_id) surf = mne.read_bem_surfaces(bem_fname, patch_stats=True) print 'Number of surfaces : %d' % len(surf) brain_col = (0.95, 0.83, 0.83) cortex_col = (0.91, 0.89, 0.67) points = surf[0]['rr'] faces = surf[0]['tris'] fig4 = mlab.figure(size=(600, 600), bgcolor=(0, 0, 0)) mlab.triangular_mesh(points[:, 0], points[:, 1], points[:, 2], faces, color=brain_col, opacity=0.3) src_fname = op.join(sbj_dir, sbj_id + '/bem/%s-ico-5-src.fif' % sbj_id) src = mne.read_source_spaces(src_fname) lh_points = src[0]['rr'] lh_faces = src[0]['tris'] rh_points = src[1]['rr'] rh_faces = src[1]['tris'] mlab.triangular_mesh(lh_points[:, 0], lh_points[:, 1], lh_points[:, 2], lh_faces, color=cortex_col, opacity=0.8) mlab.triangular_mesh(rh_points[:, 0], rh_points[:, 1], rh_points[:, 2], rh_faces, color=cortex_col, opacity=0.8) picks = mne.pick_types(raw_info, meg=True, ref_meg=False, eeg=False, stim=False, eog=False, exclude='bads') ### plot sensors sens_loc = [ raw_info['chs'][picks[i]]['loc'][:3] for i in range(len(picks)) ] sens_loc = np.array(sens_loc) mlab.points3d(sens_loc[:, 0], sens_loc[:, 1], sens_loc[:, 2], color=(1, 1, 1), opacity=1, scale_factor=0.005) report.add_figs_to_section(fig4, captions=['source space'], section='BEM cortex sensors') fig5 = plot_trans(raw_info, trans_fname, subject=sbj_id, subjects_dir=sbj_dir) report.add_figs_to_section(fig5, captions=['MEG <-> MRI coregistration quality'], section='MEG <-> MRI')
def visualize_bem(bem_dir, subject, vis_as='src', color='green', preview=True): bem = mne.read_bem_surfaces( op.join(bem_dir.format(subject), '{0}-bem-model.fif'.format(subject))) if vis_as == 'src': im_bem = SourceObj('bem', bem[0]['rr'], color=color, alpha=1., symbol='diamond', radius_min=3.) elif vis_as == 'vol': im_bem = BrainObj('vol_bem', vertices=bem[0]['rr'], faces=bem[0]['tris'], normals=bem[0]['nn'], translucent=True) if preview == True: im_bem.preview(bgcolor='black') return im_bem
def run(): """Run command.""" from mne.commands.utils import get_optparser, _add_verbose_flag parser = get_optparser(__file__) parser.add_option('--bem', dest='bem_fname', help='The name of the file containing the ' 'triangulations of the BEM surfaces and the ' 'conductivities of the compartments. The standard ' 'ending for this file is -bem.fif.', metavar="FILE") parser.add_option('--sol', dest='bem_sol_fname', help='The name of the resulting file containing BEM ' 'solution (geometry matrix). It uses the linear ' 'collocation approach. The file should end with ' '-bem-sof.fif.', metavar='FILE', default=None) _add_verbose_flag(parser) options, args = parser.parse_args() bem_fname = options.bem_fname bem_sol_fname = options.bem_sol_fname verbose = True if options.verbose is not None else False if bem_fname is None: parser.print_help() sys.exit(1) if bem_sol_fname is None: base, _ = os.path.splitext(bem_fname) bem_sol_fname = base + '-sol.fif' bem_model = mne.read_bem_surfaces(bem_fname, patch_stats=False, verbose=verbose) bem_solution = mne.make_bem_solution(bem_model, verbose=verbose) mne.write_bem_solution(bem_sol_fname, bem_solution)
def test_volume_source_space(): """Test setting up volume source spaces """ tempdir = _TempDir() src = read_source_spaces(fname_vol) temp_name = op.join(tempdir, 'temp-src.fif') surf = read_bem_surfaces(fname_bem, s_id=FIFF.FIFFV_BEM_SURF_ID_BRAIN) surf['rr'] *= 1e3 # convert to mm # The one in the testing dataset (uses bem as bounds) for bem, surf in zip((fname_bem, None), (None, surf)): src_new = setup_volume_source_space('sample', temp_name, pos=7.0, bem=bem, surface=surf, mri=fname_mri, subjects_dir=subjects_dir) _compare_source_spaces(src, src_new, mode='approx') del src_new src_new = read_source_spaces(temp_name) _compare_source_spaces(src, src_new, mode='approx') assert_raises(IOError, setup_volume_source_space, 'sample', temp_name, pos=7.0, bem=None, surface='foo', # bad surf mri=fname_mri, subjects_dir=subjects_dir)
def create_head(self): path = mne.datasets.sample.data_path() surf = mne.read_bem_surfaces(path + '/subjects/sample/bem/sample-head.fif')[0] points, triangles = surf['rr'], surf['tris'] # reduce to 30000 triangles: points_dec, triangles_dec = decimate_surface(points, triangles, n_triangles=30000) p, t = points_dec, triangles_dec mesh_data = gl.MeshData(p, t) mesh_item = gl.GLMeshItem(meshdata=mesh_data, computeNormals=True, shader='viewNormalColor', glOptions='translucent') mesh_item.translate(0, 0, -20) mesh_item.rotate(90, 1, 0, 0) mesh_item.scale(650, 650, 650) mesh_item.setColor([0, 0, 1, 0.4]) self.view.addItem(mesh_item)
def _get_source_stuff(self): # Get source stuffs # Get path of subject folder subject_path = os.path.join(RAW_DIR, self.running_name) def _path(ext): # Method to get file path that ends with [ext] return os.path.join(subject_path, f'{self.subject_name}{ext}') # Read source space src = mne.read_source_spaces(_path('-src.fif')) # Read bem surfaces model = mne.read_bem_surfaces(_path('-bem.fif')) # Read bem solution bem_sol = mne.read_bem_solution(_path('-bem-sol.fif')) # Read trans matrix trans = mne.read_trans(_path('-trans.fif')) # Return return dict(src=src, model=model, bem_sol=bem_sol, trans=trans)
def test_volume_source_space(): """Test setting up volume source spaces.""" tempdir = _TempDir() src = read_source_spaces(fname_vol) temp_name = op.join(tempdir, 'temp-src.fif') surf = read_bem_surfaces(fname_bem, s_id=FIFF.FIFFV_BEM_SURF_ID_BRAIN) surf['rr'] *= 1e3 # convert to mm # The one in the testing dataset (uses bem as bounds) for bem, surf in zip((fname_bem, None), (None, surf)): src_new = setup_volume_source_space( 'sample', pos=7.0, bem=bem, surface=surf, mri='T1.mgz', subjects_dir=subjects_dir) write_source_spaces(temp_name, src_new, overwrite=True) src[0]['subject_his_id'] = 'sample' # XXX: to make comparison pass _compare_source_spaces(src, src_new, mode='approx') del src_new src_new = read_source_spaces(temp_name) _compare_source_spaces(src, src_new, mode='approx') assert_raises(IOError, setup_volume_source_space, 'sample', pos=7.0, bem=None, surface='foo', # bad surf mri=fname_mri, subjects_dir=subjects_dir) assert_equal(repr(src), repr(src_new)) assert_equal(src.kind, 'volume')
############################################################################### # Show result on 3D source space try: from enthought.mayavi import mlab except: from mayavi import mlab rh_points, rh_faces = mne.read_surface(fname_surf_lh) rh_points /= 1000. coord_trans = mne.transforms.invert_transform(mne.read_trans(fname_trans)) coord_trans = coord_trans['trans'] rh_points = mne.transforms.apply_trans(coord_trans, rh_points) mlab.figure(size=(600, 600), bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) # show brain surface after proper coordinate system transformation brain_surface = mne.read_bem_surfaces(fname_bem, patch_stats=True)[0] points = brain_surface['rr'] faces = brain_surface['tris'] points = mne.transforms.apply_trans(coord_trans, points) mlab.triangular_mesh(points[:, 0], points[:, 1], points[:, 2], faces, color=(1, 1, 0), opacity=0.1) # show one cortical surface mlab.triangular_mesh(rh_points[:, 0], rh_points[:, 1], rh_points[:, 2], rh_faces, color=(0.7, ) * 3, opacity=0.3) # show dipole as small cones dipoles = mlab.quiver3d(dip.pos[:, 0], dip.pos[:, 1], dip.pos[:, 2], dip.ori[:, 0], dip.ori[:, 1], dip.ori[:, 2], opacity=0.8, scale_factor=4e-3, scalars=dip.times, mode='cone', colormap='RdBu')
fsaverage_path = op.join(op.dirname(mne.__file__), 'data', 'fsaverage') data_path = mne.datasets.sample.data_path() subjects_dir = op.join(data_path, 'subjects') ############################################################################### # Load the source digitization, destination surfaces, and source surfaces # (with everything in head coordinates): # Digitization info = mne.io.read_info(op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')) hsp = mne.bem.get_fitting_dig(info, ('cardinal', 'extra')) # Destination head surface fsaverage_surfs = [mne.read_bem_surfaces(op.join(fsaverage_path, 'fsaverage-%s.fif' % kind))[0] for kind in ('head', 'inner_skull-bem')] fsaverage_trans = mne.read_trans(op.join(fsaverage_path, 'fsaverage-trans.fif')) for surf in fsaverage_surfs: mne.surface.transform_surface_to(surf, 'head', fsaverage_trans, copy=False) # Some source surfaces to transform as examples sample_surfs = mne.read_bem_surfaces( op.join(subjects_dir, 'sample', 'bem', 'sample-5120-bem.fif')) sample_trans = mne.read_trans(op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw-trans.fif')) for surf in sample_surfs: mne.surface.transform_surface_to(surf, 'head', sample_trans, copy=False) ###############################################################################
def test_io_bem_surfaces(): """Testing reading of bem surfaces """ surf = mne.read_bem_surfaces(fname, add_geom=False) surf = mne.read_bem_surfaces(fname, add_geom=True) print "Number of surfaces : %d" % len(surf)
Reading BEM surfaces from a forward solution ============================================ """ # Author: Alexandre Gramfort <*****@*****.**> # # License: BSD (3-clause) print __doc__ import mne fname = os.environ['MNE_SAMPLE_DATASET_PATH'] fname += '/subjects/sample/bem/sample-5120-5120-5120-bem-sol.fif' surfaces = mne.read_bem_surfaces(fname) print "Number of surfaces : %d" % len(surfaces) ############################################################################### # Show result head_col = (0.95, 0.83, 0.83) # light pink skull_col = (0.91, 0.89, 0.67) brain_col = (0.67, 0.89, 0.91) # light blue colors = [head_col, skull_col, brain_col] # 3D source space from enthought.mayavi import mlab mlab.clf() for c, surf in zip(colors, surfaces):
using a cloud of digitization points for coordinate alignment instead of e.g. EEG-cap positions. """ # Authors: Denis Engemann <*****@*****.**> # Alexandre Gramfort <*****@*****.**> # # License: BSD (3-clause) import mne from mne.surface import decimate_surface print(__doc__) path = mne.datasets.sample.data_path() surf = mne.read_bem_surfaces(path + '/subjects/sample/bem/sample-head.fif')[0] points, triangles = surf['rr'], surf['tris'] # reduce to 30000 meshes equaling ${SUBJECT}-head-medium.fif output from # mne_make_scalp_surfaces.py and mne_make_scalp_surfaces points_dec, triangles_dec = decimate_surface(points, triangles, n_triangles=30000) from mayavi import mlab # noqa head_col = (0.95, 0.83, 0.83) # light pink p, t = points_dec, triangles_dec mlab.triangular_mesh(p[:, 0], p[:, 1], p[:, 2], t, color=head_col)
Reading BEM surfaces from a forward solution ============================================ """ # Author: Alexandre Gramfort <*****@*****.**> # # License: BSD (3-clause) print(__doc__) import mne from mne.datasets import sample data_path = sample.data_path() fname = data_path + '/subjects/sample/bem/sample-5120-5120-5120-bem-sol.fif' surfaces = mne.read_bem_surfaces(fname, add_geom=True) print("Number of surfaces : %d" % len(surfaces)) ############################################################################### # Show result head_col = (0.95, 0.83, 0.83) # light pink skull_col = (0.91, 0.89, 0.67) brain_col = (0.67, 0.89, 0.91) # light blue colors = [head_col, skull_col, brain_col] # 3D source space try: from enthought.mayavi import mlab except: from mayavi import mlab
def _run(subjects_dir, subject, force, overwrite, verbose=None): this_env = copy.copy(os.environ) this_env['SUBJECTS_DIR'] = subjects_dir this_env['SUBJECT'] = subject if 'SUBJECTS_DIR' not in this_env: raise RuntimeError('The environment variable SUBJECTS_DIR should ' 'be set') if not op.isdir(subjects_dir): raise RuntimeError('subjects directory %s not found, specify using ' 'the environment variable SUBJECTS_DIR or ' 'the command line option --subjects-dir') if 'MNE_ROOT' not in this_env: raise RuntimeError('MNE_ROOT environment variable is not set') if 'FREESURFER_HOME' not in this_env: raise RuntimeError('The FreeSurfer environment needs to be set up ' 'for this script') force = '--force' if force else '--check' subj_path = op.join(subjects_dir, subject) if not op.exists(subj_path): raise RuntimeError('%s does not exits. Please check your subject ' 'directory path.' % subj_path) if op.exists(op.join(subj_path, 'mri', 'T1.mgz')): mri = 'T1.mgz' else: mri = 'T1' logger.info('1. Creating a dense scalp tessellation with mkheadsurf...') def check_seghead(surf_path=op.join(subj_path, 'surf')): for k in ['/lh.seghead', '/lh.smseghead']: surf = surf_path + k if op.exists(surf_path + k) else None if surf is not None: break return surf my_seghead = check_seghead() if my_seghead is None: run_subprocess(['mkheadsurf', '-subjid', subject, '-srcvol', mri], env=this_env) surf = check_seghead() if surf is None: raise RuntimeError('mkheadsurf did not produce the standard output ' 'file.') dense_fname = '{0}/{1}/bem/{1}-head-dense.fif'.format(subjects_dir, subject) logger.info('2. Creating %s ...' % dense_fname) _check_file(dense_fname, overwrite) run_subprocess(['mne_surf2bem', '--surf', surf, '--id', '4', force, '--fif', dense_fname], env=this_env) levels = 'medium', 'sparse' my_surf = mne.read_bem_surfaces(dense_fname)[0] tris = [30000, 2500] if os.getenv('_MNE_TESTING_SCALP', 'false') == 'true': tris = [len(my_surf['tris'])] # don't actually decimate for ii, (n_tri, level) in enumerate(zip(tris, levels), 3): logger.info('%i. Creating %s tessellation...' % (ii, level)) logger.info('%i.1 Decimating the dense tessellation...' % ii) points, tris = mne.decimate_surface(points=my_surf['rr'], triangles=my_surf['tris'], n_triangles=n_tri) other_fname = dense_fname.replace('dense', level) logger.info('%i.2 Creating %s' % (ii, other_fname)) _check_file(other_fname, overwrite) tempdir = _TempDir() surf_fname = tempdir + '/tmp-surf.surf' # convert points to meters, make mne_analyze happy mne.write_surface(surf_fname, points * 1e3, tris) # XXX for some reason --check does not work here. try: run_subprocess(['mne_surf2bem', '--surf', surf_fname, '--id', '4', '--force', '--fif', other_fname], env=this_env) finally: del tempdir
if not overwrite: print 'Use the --overwrite option to replace exisiting surfaces.' sys.exit() surf = check_seghead() if surf is None: print 'mkheadsurf did not produce the standard output file.' sys.exit(1) fif = '{0}/{1}/bem/{1}-head-dense.fif'.format(subj_dir, subject) print '2. Creating %s ...' % fif cmd = 'mne_surf2bem --surf %s --id 4 %s --fif %s' % (surf, force, fif) my_run_cmd(cmd, 'Failed to create %s, see above' % fif) levels = 'medium', 'sparse' for ii, (n_tri, level) in enumerate(zip([30000, 2500], levels), 3): my_surf = mne.read_bem_surfaces(fif)[0] print '%i. Creating medium grade tessellation...' % ii print '%i.1 Decimating the dense tessellation...' % ii points, tris = mne.decimate_surface(points=my_surf['rr'], triangles=my_surf['tris'], n_triangles=n_tri) out_fif = fif.replace('dense', level) print '%i.2 Creating %s' % (ii, out_fif) surf_fname = '/tmp/tmp-surf.surf' # convert points to meters, make mne_analyze happy mne.write_surface(surf_fname, points * 1e3, tris) # XXX for some reason --check does not work here. cmd = 'mne_surf2bem --surf %s --id 4 --force --fif %s' cmd %= (surf_fname, out_fif) my_run_cmd(cmd, 'Failed to create %s, see above' % out_fif) os.remove(surf_fname)
# # mne.write_head_bem(op.join(head_dir, 'sample-head.fif'), coords, faces, # overwrite=True) ############################################################################### # High-resolution head # ~~~~~~~~~~~~~~~~~~~~ # # We use :func:`mne.read_bem_surfaces` to read the head surface files. After # editing, we again output the head file with :func:`mne.write_head_bem`. # Here we use ``-head.fif`` for speed. # If ``-head-dense.fif`` does not exist, you need to run # ``mne make_scalp_surfaces`` first. # [0] because a list of surfaces is returned surf = mne.read_bem_surfaces(op.join(head_dir, 'sample-head.fif'))[0] # For consistency only coords = surf['rr'] faces = surf['tris'] # Write the head as an .obj file for editing mne.write_surface(op.join(conv_dir, 'sample-head.obj'), coords, faces, overwrite=True) # Usually here you would go and edit your meshes. # # Here we just use the same surface as if it were fixed # Read in the .obj file
channel = 'EEG065' idx = [fpower.ch_names.index(channel)] fpower.plot(idx, title='Faces power %s' % channel, baseline=(-0.1, 0.0), mode='logratio', show=False) spower.plot(idx, title='Scrambled power %s' % channel, baseline=(-0.1, 0.0), mode='logratio', show=False) fitc.plot(idx, title='Faces ITC %s' % channel, baseline=(-0.1, 0.0), mode='logratio', show=False) sitc.plot(idx, title='Scrambled ITC %s' % channel, baseline=(-0.1, 0.0), mode='logratio') ############################################################################### # Trans fname_trans = op.join(study_path, 'ds117', subject, 'MEG', '%s-trans.fif' % subject) bem = mne.read_bem_surfaces(op.join(subjects_dir, subject, 'bem', '%s-5120-bem.fif' % subject)) src = mne.read_source_spaces( op.join(subjects_dir, subject, 'bem', '%s-oct6-src.fif' % subject)) aln = mne.viz.plot_alignment( raw.info, fname_trans, subject=subject, subjects_dir=subjects_dir, src=src, surfaces=['outer_skin', 'inner_skull'], dig=True, coord_frame='meg') aln.scene.parallel_projection = True fig, axes = plt.subplots(1, 3, figsize=(6.5, 2.5), facecolor='k') from mayavi import mlab # noqa: E402 for ai, angle in enumerate((180, 90, 0)): mlab.view(angle, 90, focalpoint=(0., 0., 0.), distance=0.6) view = mlab.screenshot() mask_w = (view == 0).all(axis=-1).all(axis=1) mask_h = (view == 0).all(axis=-1).all(axis=0) view = view[~mask_w][:, ~mask_h] axes[ai].set_axis_off()
# Author: Alexandre Gramfort <*****@*****.**> # # License: BSD (3-clause) print(__doc__) import numpy as np import mne from mne.datasets import sample data_path = sample.data_path() fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-oct-6-fwd.fif' dip_fname = data_path + '/MEG/sample/sample_audvis_set1.dip' bem_fname = data_path + '/subjects/sample/bem/sample-5120-bem-sol.fif' brain_surface = mne.read_bem_surfaces(bem_fname, add_geom=True)[0] points = brain_surface['rr'] faces = brain_surface['tris'] fwd = mne.read_forward_solution(fwd_fname) src = fwd['src'] # read dipoles time, pos, amplitude, ori, gof = mne.read_dip(dip_fname) print("Time (ms): %s" % time) print("Amplitude (nAm): %s" % amplitude) print("GOF (%%): %s" % gof) # only plot those for which GOF is above 50% pos = pos[gof > 50.]
Plot BEM surfaces used for forward solution generation. """ # Author: Alexandre Gramfort <*****@*****.**> # # License: BSD (3-clause) import mne from mne.datasets import sample print(__doc__) data_path = sample.data_path() fname = data_path + '/subjects/sample/bem/sample-5120-5120-5120-bem-sol.fif' surfaces = mne.read_bem_surfaces(fname, patch_stats=True) print("Number of surfaces : %d" % len(surfaces)) ############################################################################### # Show result head_col = (0.95, 0.83, 0.83) # light pink skull_col = (0.91, 0.89, 0.67) brain_col = (0.67, 0.89, 0.91) # light blue colors = [head_col, skull_col, brain_col] # 3D source space from mayavi import mlab # noqa mlab.figure(size=(600, 600), bgcolor=(0, 0, 0)) for c, surf in zip(colors, surfaces):
using a cloud of digitization points for coordinate alignment instead of e.g. EEG-cap positions. """ print(__doc__) # Authors: Denis Engemann <*****@*****.**> # Alexandre Gramfort <*****@*****.**> # # License: BSD (3-clause) import mne from mne.surface import decimate_surface path = mne.datasets.sample.data_path() surf = mne.read_bem_surfaces(path + '/subjects/sample/bem/sample-head.fif')[0] points, triangles = surf['rr'], surf['tris'] # reduce to 30000 meshes equaling ${SUBJECT}-head-medium.fif output from # mne_make_scalp_surfaces.py and mne_make_scalp_surfaces points_dec, triangles_dec = decimate_surface(points, triangles, n_triangles=30000) try: from enthought.mayavi import mlab except: from mayavi import mlab head_col = (0.95, 0.83, 0.83) # light pink