本文整理汇总了Python中mne.write_source_spaces函数的典型用法代码示例。如果您正苦于以下问题:Python write_source_spaces函数的具体用法?Python write_source_spaces怎么用?Python write_source_spaces使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了write_source_spaces函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_discrete_source_space
def test_discrete_source_space():
"""Test setting up (and reading/writing) discrete source spaces
"""
src = read_source_spaces(fname)
v = src[0]["vertno"]
# let's make a discrete version with the C code, and with ours
temp_name = op.join(tempdir, "temp-src.fif")
try:
# save
temp_pos = op.join(tempdir, "temp-pos.txt")
np.savetxt(temp_pos, np.c_[src[0]["rr"][v], src[0]["nn"][v]])
# let's try the spherical one (no bem or surf supplied)
run_subprocess(["mne_volume_source_space", "--meters", "--pos", temp_pos, "--src", temp_name])
src_c = read_source_spaces(temp_name)
pos_dict = dict(rr=src[0]["rr"][v], nn=src[0]["nn"][v])
src_new = setup_volume_source_space("sample", None, pos=pos_dict, subjects_dir=subjects_dir)
_compare_source_spaces(src_c, src_new, mode="approx")
assert_allclose(src[0]["rr"][v], src_new[0]["rr"], rtol=1e-3, atol=1e-6)
assert_allclose(src[0]["nn"][v], src_new[0]["nn"], rtol=1e-3, atol=1e-6)
# now do writing
write_source_spaces(temp_name, src_c)
src_c2 = read_source_spaces(temp_name)
_compare_source_spaces(src_c, src_c2)
# now do MRI
assert_raises(ValueError, setup_volume_source_space, "sample", pos=pos_dict, mri=fname_mri)
finally:
if op.isfile(temp_name):
os.remove(temp_name)
示例2: run_forward
def run_forward(subject_id):
subject = "sub%03d" % subject_id
print("processing subject: %s" % subject)
data_path = op.join(meg_dir, subject)
fname_ave = op.join(data_path, '%s-ave.fif' % subject)
fname_fwd = op.join(data_path, '%s-meg-%s-fwd.fif' % (subject, spacing))
fname_trans = op.join(study_path, 'ds117', subject, 'MEG', '%s-trans.fif' % subject)
src = mne.setup_source_space(subject, spacing=spacing,
subjects_dir=subjects_dir, overwrite=True,
n_jobs=1, add_dist=False)
src_fname = op.join(subjects_dir, subject, '%s-src.fif' % spacing)
mne.write_source_spaces(src_fname, src)
bem_model = mne.make_bem_model(subject, ico=4, subjects_dir=subjects_dir,
conductivity=(0.3,))
bem = mne.make_bem_solution(bem_model)
info = mne.read_evokeds(fname_ave, condition=0).info
fwd = mne.make_forward_solution(info, trans=fname_trans, src=src, bem=bem,
fname=None, meg=True, eeg=False,
mindist=mindist, n_jobs=1, overwrite=True)
fwd = mne.convert_forward_solution(fwd, surf_ori=True)
mne.write_forward_solution(fname_fwd, fwd, overwrite=True)
示例3: test_add_source_space_distances_limited
def test_add_source_space_distances_limited():
"""Test adding distances to source space with a dist_limit."""
tempdir = _TempDir()
src = read_source_spaces(fname)
src_new = read_source_spaces(fname)
del src_new[0]['dist']
del src_new[1]['dist']
n_do = 200 # limit this for speed
src_new[0]['vertno'] = src_new[0]['vertno'][:n_do].copy()
src_new[1]['vertno'] = src_new[1]['vertno'][:n_do].copy()
out_name = op.join(tempdir, 'temp-src.fif')
try:
add_source_space_distances(src_new, dist_limit=0.007)
except RuntimeError: # what we throw when scipy version is wrong
raise SkipTest('dist_limit requires scipy > 0.13')
write_source_spaces(out_name, src_new)
src_new = read_source_spaces(out_name)
for so, sn in zip(src, src_new):
assert_array_equal(so['dist_limit'], np.array([-0.007], np.float32))
assert_array_equal(sn['dist_limit'], np.array([0.007], np.float32))
do = so['dist']
dn = sn['dist']
# clean out distances > 0.007 in C code
do.data[do.data > 0.007] = 0
do.eliminate_zeros()
# make sure we have some comparable distances
assert np.sum(do.data < 0.007) > 400
# do comparison over the region computed
d = (do - dn)[:sn['vertno'][n_do - 1]][:, :sn['vertno'][n_do - 1]]
assert_allclose(np.zeros_like(d.data), d.data, rtol=0, atol=1e-6)
示例4: test_write_source_space
def test_write_source_space():
"""Test writing and reading of source spaces
"""
src0 = read_source_spaces(fname, add_geom=False)
write_source_spaces(op.join(tempdir, 'tmp.fif'), src0)
src1 = read_source_spaces(op.join(tempdir, 'tmp.fif'), add_geom=False)
_compare_source_spaces(src0, src1)
示例5: _mne_source_space
def _mne_source_space(subject, src_tag, subjects_dir):
"""Load mne source space
Parameters
----------
subject : str
Subejct
src_tag : str
Spacing (e.g., 'ico-4').
"""
src_file = os.path.join(subjects_dir, subject, 'bem',
'%s-%s-src.fif' % (subject, src_tag))
src, spacing = src_tag.split('-')
if os.path.exists(src_file):
return mne.read_source_spaces(src_file, False)
elif src == 'ico':
ss = mne.setup_source_space(subject, spacing=src + spacing,
subjects_dir=subjects_dir, add_dist=True)
elif src == 'vol':
mri_file = os.path.join(subjects_dir, subject, 'mri', 'orig.mgz')
bem_file = os.path.join(subjects_dir, subject, 'bem',
'sample-5120-5120-5120-bem-sol.fif')
ss = mne.setup_volume_source_space(subject, pos=float(spacing),
mri=mri_file, bem=bem_file,
mindist=0., exclude=0.,
subjects_dir=subjects_dir)
else:
raise ValueError("src_tag=%s" % repr(src_tag))
mne.write_source_spaces(src_file, ss)
return ss
示例6: test_volume_source_space
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)
示例7: test_source_space_from_label
def test_source_space_from_label():
"""Test generating a source space from volume label."""
tempdir = _TempDir()
aseg_fname = op.join(subjects_dir, 'sample', 'mri', 'aseg.mgz')
label_names = get_volume_labels_from_aseg(aseg_fname)
volume_label = label_names[int(np.random.rand() * len(label_names))]
# Test pos as dict
pos = dict()
pytest.raises(ValueError, setup_volume_source_space, 'sample', pos=pos,
volume_label=volume_label, mri=aseg_fname)
# Test no mri provided
pytest.raises(RuntimeError, setup_volume_source_space, 'sample', mri=None,
volume_label=volume_label)
# Test invalid volume label
pytest.raises(ValueError, setup_volume_source_space, 'sample',
volume_label='Hello World!', mri=aseg_fname)
src = setup_volume_source_space('sample', subjects_dir=subjects_dir,
volume_label=volume_label, mri=aseg_fname,
add_interpolator=False)
assert_equal(volume_label, src[0]['seg_name'])
# test reading and writing
out_name = op.join(tempdir, 'temp-src.fif')
write_source_spaces(out_name, src)
src_from_file = read_source_spaces(out_name)
_compare_source_spaces(src, src_from_file, mode='approx')
示例8: test_write_source_space
def test_write_source_space():
"""Test writing and reading of source spaces
"""
src0 = read_source_spaces(fname, add_geom=False)
src0_old = read_source_spaces(fname, add_geom=False)
write_source_spaces(op.join(tempdir, 'tmp.fif'), src0)
src1 = read_source_spaces(op.join(tempdir, 'tmp.fif'), add_geom=False)
for orig in [src0, src0_old]:
for s0, s1 in zip(src0, src1):
for name in ['nuse', 'dist_limit', 'ntri', 'np', 'type', 'id',
'subject_his_id']:
assert_true(s0[name] == s1[name])
for name in ['nn', 'rr', 'inuse', 'vertno', 'nuse_tri',
'coord_frame', 'use_tris', 'tris', 'nearest',
'nearest_dist']:
assert_array_equal(s0[name], s1[name])
for name in ['dist']:
if s0[name] is not None:
assert_true(s1[name].shape == s0[name].shape)
assert_true(len((s0['dist'] - s1['dist']).data) == 0)
for name in ['pinfo']:
if s0[name] is not None:
assert_true(len(s0[name]) == len(s1[name]))
for p1, p2 in zip(s0[name], s1[name]):
assert_true(all(p1 == p2))
# The above "if s0[name] is not None" can be removed once the sample
# dataset is updated to have a source space with distance info
for name in ['working_dir', 'command_line']:
assert_true(src0.info[name] == src1.info[name])
示例9: _get_bf_data
def _get_bf_data(save_fieldtrip=False):
raw, epochs, evoked, data_cov, _, _, _, _, _, fwd = _get_data(proj=False)
if save_fieldtrip is True:
# raw needs to be saved with all channels and picked in FieldTrip
raw.save(op.join(ft_data_path, 'raw.fif'), overwrite=True)
# src (tris are not available in fwd['src'] once imported into MATLAB)
src = fwd['src'].copy()
mne.write_source_spaces(op.join(ft_data_path, 'src.fif'), src)
# pick gradiometers only:
epochs.pick_types(meg='grad')
evoked.pick_types(meg='grad')
# compute covariance matrix
data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.145,
method='empirical')
if save_fieldtrip is True:
# if the covariance matrix and epochs need resaving:
# data covariance:
cov_savepath = op.join(ft_data_path, 'sample_cov')
sample_cov = {'sample_cov': data_cov['data']}
savemat(cov_savepath, sample_cov)
# evoked data:
ev_savepath = op.join(ft_data_path, 'sample_evoked')
data_ev = {'sample_evoked': evoked.data}
savemat(ev_savepath, data_ev)
return evoked, data_cov, fwd
示例10: test_discrete_source_space
def test_discrete_source_space():
"""Test setting up (and reading/writing) discrete source spaces
"""
src = read_source_spaces(fname)
v = src[0]['vertno']
# let's make a discrete version with the C code, and with ours
temp_name = op.join(tempdir, 'temp-src.fif')
try:
# save
temp_pos = op.join(tempdir, 'temp-pos.txt')
np.savetxt(temp_pos, np.c_[src[0]['rr'][v], src[0]['nn'][v]])
# let's try the spherical one (no bem or surf supplied)
run_subprocess(['mne_volume_source_space', '--meters',
'--pos', temp_pos, '--src', temp_name])
src_c = read_source_spaces(temp_name)
src_new = setup_volume_source_space('sample', None,
pos=dict(rr=src[0]['rr'][v],
nn=src[0]['nn'][v]),
subjects_dir=subjects_dir)
_compare_source_spaces(src_c, src_new, mode='approx')
assert_allclose(src[0]['rr'][v], src_new[0]['rr'],
rtol=1e-3, atol=1e-6)
assert_allclose(src[0]['nn'][v], src_new[0]['nn'],
rtol=1e-3, atol=1e-6)
# now do writing
write_source_spaces(temp_name, src_c)
src_c2 = read_source_spaces(temp_name)
_compare_source_spaces(src_c, src_c2)
finally:
if op.isfile(temp_name):
os.remove(temp_name)
示例11: test_setup_source_space
def test_setup_source_space():
"""Test setting up ico, oct, and all source spaces."""
tempdir = _TempDir()
fname_ico = op.join(data_path, 'subjects', 'fsaverage', 'bem',
'fsaverage-ico-5-src.fif')
# first lets test some input params
assert_raises(ValueError, setup_source_space, 'sample', spacing='oct',
add_dist=False, subjects_dir=subjects_dir)
assert_raises(ValueError, setup_source_space, 'sample', spacing='octo',
add_dist=False, subjects_dir=subjects_dir)
assert_raises(ValueError, setup_source_space, 'sample', spacing='oct6e',
add_dist=False, subjects_dir=subjects_dir)
assert_raises(ValueError, setup_source_space, 'sample', spacing='7emm',
add_dist=False, subjects_dir=subjects_dir)
assert_raises(ValueError, setup_source_space, 'sample', spacing='alls',
add_dist=False, subjects_dir=subjects_dir)
assert_raises(IOError, setup_source_space, 'sample', spacing='oct6',
subjects_dir=subjects_dir, add_dist=False)
# ico 5 (fsaverage) - write to temp file
src = read_source_spaces(fname_ico)
temp_name = op.join(tempdir, 'temp-src.fif')
with warnings.catch_warnings(record=True): # sklearn equiv neighbors
warnings.simplefilter('always')
src_new = setup_source_space('fsaverage', temp_name, spacing='ico5',
subjects_dir=subjects_dir, add_dist=False,
overwrite=True)
_compare_source_spaces(src, src_new, mode='approx')
assert_equal(repr(src), repr(src_new))
assert_equal(repr(src).count('surface ('), 2)
assert_array_equal(src[0]['vertno'], np.arange(10242))
assert_array_equal(src[1]['vertno'], np.arange(10242))
# oct-6 (sample) - auto filename + IO
src = read_source_spaces(fname)
temp_name = op.join(tempdir, 'temp-src.fif')
with warnings.catch_warnings(record=True): # sklearn equiv neighbors
warnings.simplefilter('always')
src_new = setup_source_space('sample', None, spacing='oct6',
subjects_dir=subjects_dir,
overwrite=True, add_dist=False)
write_source_spaces(temp_name, src_new, overwrite=True)
_compare_source_spaces(src, src_new, mode='approx', nearest=False)
src_new = read_source_spaces(temp_name)
_compare_source_spaces(src, src_new, mode='approx', nearest=False)
# all source points - no file writing
src_new = setup_source_space('sample', None, spacing='all',
subjects_dir=subjects_dir, add_dist=False)
assert_true(src_new[0]['nuse'] == len(src_new[0]['rr']))
assert_true(src_new[1]['nuse'] == len(src_new[1]['rr']))
# dense source space to hit surf['inuse'] lines of _create_surf_spacing
assert_raises(RuntimeError, setup_source_space, 'sample', None,
spacing='ico6', subjects_dir=subjects_dir, add_dist=False)
示例12: test_write_source_space
def test_write_source_space():
"""Test reading and writing of source spaces."""
tempdir = _TempDir()
src0 = read_source_spaces(fname, patch_stats=False)
write_source_spaces(op.join(tempdir, 'tmp-src.fif'), src0)
src1 = read_source_spaces(op.join(tempdir, 'tmp-src.fif'),
patch_stats=False)
_compare_source_spaces(src0, src1)
# test warnings on bad filenames
src_badname = op.join(tempdir, 'test-bad-name.fif.gz')
with pytest.warns(RuntimeWarning, match='-src.fif'):
write_source_spaces(src_badname, src0)
with pytest.warns(RuntimeWarning, match='-src.fif'):
read_source_spaces(src_badname)
示例13: test_write_source_space
def test_write_source_space():
"""Test reading and writing of source spaces."""
tempdir = _TempDir()
src0 = read_source_spaces(fname, patch_stats=False)
write_source_spaces(op.join(tempdir, 'tmp-src.fif'), src0)
src1 = read_source_spaces(op.join(tempdir, 'tmp-src.fif'),
patch_stats=False)
_compare_source_spaces(src0, src1)
# test warnings on bad filenames
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
src_badname = op.join(tempdir, 'test-bad-name.fif.gz')
write_source_spaces(src_badname, src0)
read_source_spaces(src_badname)
assert_naming(w, 'test_source_space.py', 2)
示例14: test_write_source_space
def test_write_source_space():
"""Test writing and reading of source spaces
"""
src0 = read_source_spaces(fname, add_geom=False)
write_source_spaces(op.join(tempdir, 'tmp-src.fif'), src0)
src1 = read_source_spaces(op.join(tempdir, 'tmp-src.fif'), add_geom=False)
_compare_source_spaces(src0, src1)
# test warnings on bad filenames
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
src_badname = op.join(tempdir, 'test-bad-name.fif.gz')
write_source_spaces(src_badname, src0)
read_source_spaces(src_badname)
print([ww.message for ww in w])
assert_equal(len(w), 2)
示例15: test_add_source_space_distances
def test_add_source_space_distances():
"""Test adding distances to source space."""
tempdir = _TempDir()
src = read_source_spaces(fname)
src_new = read_source_spaces(fname)
del src_new[0]['dist']
del src_new[1]['dist']
n_do = 19 # limit this for speed
src_new[0]['vertno'] = src_new[0]['vertno'][:n_do].copy()
src_new[1]['vertno'] = src_new[1]['vertno'][:n_do].copy()
out_name = op.join(tempdir, 'temp-src.fif')
n_jobs = 2
assert n_do % n_jobs != 0
add_source_space_distances(src_new, n_jobs=n_jobs)
write_source_spaces(out_name, src_new)
src_new = read_source_spaces(out_name)
# iterate over both hemispheres
for so, sn in zip(src, src_new):
v = so['vertno'][:n_do]
assert_array_equal(so['dist_limit'], np.array([-0.007], np.float32))
assert_array_equal(sn['dist_limit'], np.array([np.inf], np.float32))
do = so['dist']
dn = sn['dist']
# clean out distances > 0.007 in C code (some residual), and Python
ds = list()
for d in [do, dn]:
d.data[d.data > 0.007] = 0
d = d[v][:, v]
d.eliminate_zeros()
ds.append(d)
# make sure we actually calculated some comparable distances
assert np.sum(ds[0].data < 0.007) > 10
# do comparison
d = ds[0] - ds[1]
assert_allclose(np.zeros_like(d.data), d.data, rtol=0, atol=1e-9)