本文整理汇总了Python中mne.make_ad_hoc_cov函数的典型用法代码示例。如果您正苦于以下问题:Python make_ad_hoc_cov函数的具体用法?Python make_ad_hoc_cov怎么用?Python make_ad_hoc_cov使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了make_ad_hoc_cov函数的19个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_ad_hoc_cov
def test_ad_hoc_cov(tmpdir):
"""Test ad hoc cov creation and I/O."""
out_fname = op.join(str(tmpdir), 'test-cov.fif')
evoked = read_evokeds(ave_fname)[0]
cov = make_ad_hoc_cov(evoked.info)
cov.save(out_fname)
assert 'Covariance' in repr(cov)
cov2 = read_cov(out_fname)
assert_array_almost_equal(cov['data'], cov2['data'])
std = dict(grad=2e-13, mag=10e-15, eeg=0.1e-6)
cov = make_ad_hoc_cov(evoked.info, std)
cov.save(out_fname)
assert 'Covariance' in repr(cov)
cov2 = read_cov(out_fname)
assert_array_almost_equal(cov['data'], cov2['data'])
开发者ID:Eric89GXL,项目名称:mne-python,代码行数:15,代码来源:test_cov.py
示例2: test_apply_inverse_sphere
def test_apply_inverse_sphere():
"""Test applying an inverse with a sphere model (rank-deficient)."""
evoked = _get_evoked()
evoked.pick_channels(evoked.ch_names[:306:8])
evoked.info['projs'] = []
cov = make_ad_hoc_cov(evoked.info)
sphere = make_sphere_model('auto', 'auto', evoked.info)
fwd = read_forward_solution(fname_fwd)
vertices = [fwd['src'][0]['vertno'][::5],
fwd['src'][1]['vertno'][::5]]
stc = SourceEstimate(np.zeros((sum(len(v) for v in vertices), 1)),
vertices, 0., 1.)
fwd = restrict_forward_to_stc(fwd, stc)
fwd = make_forward_solution(evoked.info, fwd['mri_head_t'], fwd['src'],
sphere, mindist=5.)
evoked = EvokedArray(fwd['sol']['data'].copy(), evoked.info)
assert fwd['sol']['nrow'] == 39
assert fwd['nsource'] == 101
assert fwd['sol']['ncol'] == 303
tempdir = _TempDir()
temp_fname = op.join(tempdir, 'temp-inv.fif')
inv = make_inverse_operator(evoked.info, fwd, cov, loose=1.)
# This forces everything to be float32
write_inverse_operator(temp_fname, inv)
inv = read_inverse_operator(temp_fname)
stc = apply_inverse(evoked, inv, method='eLORETA',
method_params=dict(eps=1e-2))
# assert zero localization bias
assert_array_equal(np.argmax(stc.data, axis=0),
np.repeat(np.arange(101), 3))
开发者ID:teonbrooks,项目名称:mne-python,代码行数:30,代码来源:test_inverse.py
示例3: test_volume_labels_morph
def test_volume_labels_morph(tmpdir):
"""Test generating a source space from volume label."""
# see gh-5224
evoked = mne.read_evokeds(fname_evoked)[0].crop(0, 0)
evoked.pick_channels(evoked.ch_names[:306:8])
evoked.info.normalize_proj()
n_ch = len(evoked.ch_names)
aseg_fname = op.join(subjects_dir, 'sample', 'mri', 'aseg.mgz')
label_names = get_volume_labels_from_aseg(aseg_fname)
src = setup_volume_source_space(
'sample', subjects_dir=subjects_dir, volume_label=label_names[:2],
mri=aseg_fname)
assert len(src) == 2
assert src.kind == 'volume'
n_src = sum(s['nuse'] for s in src)
sphere = make_sphere_model('auto', 'auto', evoked.info)
fwd = make_forward_solution(evoked.info, fname_trans, src, sphere)
assert fwd['sol']['data'].shape == (n_ch, n_src * 3)
inv = make_inverse_operator(evoked.info, fwd, make_ad_hoc_cov(evoked.info),
loose=1.)
stc = apply_inverse(evoked, inv)
assert stc.data.shape == (n_src, 1)
img = stc.as_volume(src, mri_resolution=True)
n_on = np.array(img.dataobj).astype(bool).sum()
assert n_on == 291 # was 291 on `master` before gh-5590
img = stc.as_volume(src, mri_resolution=False)
n_on = np.array(img.dataobj).astype(bool).sum()
assert n_on == 44 # was 20 on `master` before gh-5590
开发者ID:jhouck,项目名称:mne-python,代码行数:28,代码来源:test_morph.py
示例4: test_ad_hoc_cov
def test_ad_hoc_cov():
"""Test ad hoc cov creation and I/O"""
tempdir = _TempDir()
out_fname = op.join(tempdir, 'test-cov.fif')
evoked = read_evokeds(ave_fname)[0]
cov = make_ad_hoc_cov(evoked.info)
cov.save(out_fname)
cov2 = read_cov(out_fname)
assert_array_almost_equal(cov['data'], cov2['data'])
开发者ID:pombreda,项目名称:mne-python,代码行数:9,代码来源:test_cov.py
示例5: test_ad_hoc_cov
def test_ad_hoc_cov():
"""Test ad hoc cov creation and I/O."""
tempdir = _TempDir()
out_fname = op.join(tempdir, "test-cov.fif")
evoked = read_evokeds(ave_fname)[0]
cov = make_ad_hoc_cov(evoked.info)
cov.save(out_fname)
assert_true("Covariance" in repr(cov))
cov2 = read_cov(out_fname)
assert_array_almost_equal(cov["data"], cov2["data"])
开发者ID:joewalter,项目名称:mne-python,代码行数:10,代码来源:test_cov.py
示例6: test_dipole_fitting_ctf
def test_dipole_fitting_ctf():
"""Test dipole fitting with CTF data."""
raw_ctf = read_raw_ctf(fname_ctf).set_eeg_reference()
events = make_fixed_length_events(raw_ctf, 1)
evoked = Epochs(raw_ctf, events, 1, 0, 0, baseline=None).average()
cov = make_ad_hoc_cov(evoked.info)
sphere = make_sphere_model((0., 0., 0.))
# XXX Eventually we should do some better checks about accuracy, but
# for now our CTF phantom fitting tutorials will have to do
# (otherwise we need to add that to the testing dataset, which is
# a bit too big)
fit_dipole(evoked, cov, sphere)
开发者ID:mvdoc,项目名称:mne-python,代码行数:12,代码来源:test_dipole.py
示例7: test_inverse_ctf_comp
def test_inverse_ctf_comp():
"""Test interpolation with compensated CTF data."""
ctf_dir = op.join(testing.data_path(download=False), 'CTF')
raw_fname = op.join(ctf_dir, 'somMDYO-18av.ds')
raw = mne.io.read_raw_ctf(raw_fname)
raw.apply_gradient_compensation(1)
sphere = make_sphere_model()
cov = make_ad_hoc_cov(raw.info)
src = mne.setup_volume_source_space(
pos=dict(rr=[[0., 0., 0.01]], nn=[[0., 1., 0.]]))
fwd = make_forward_solution(raw.info, None, src, sphere, eeg=False)
inv = make_inverse_operator(raw.info, fwd, cov, loose=1.)
apply_inverse_raw(raw, inv, 1. / 9.)
开发者ID:teonbrooks,项目名称:mne-python,代码行数:13,代码来源:test_inverse.py
示例8: get_roi_filter
def get_roi_filter(label_name, fs, channels, show=False, method='sLORETA', lambda2=1):
info = mne.create_info(ch_names=channels, sfreq=fs, montage=mne.channels.read_montage(kind='standard_1005'), ch_types=['eeg' for ch in channels])
mne.utils.set_config("SUBJECTS_DIR", 'av_brain', set_env=True)
noise_cov = mne.make_ad_hoc_cov(info, verbose=None)
fwd = mne.read_forward_solution(r'C:\Users\nsmetanin\PycharmProjects\nfb\tests\sloreta\fsaverage-fwd-1005-1.fif', surf_ori=True)
inv = mne.minimum_norm.make_inverse_operator(info, fwd, noise_cov, loose=0.2, depth=0.8, fixed=True)
inv = mne.minimum_norm.prepare_inverse_operator(inv, nave=1, lambda2=lambda2, method=method)
roi_label = get_roi_by_name(label_name)
K, noise_norm, vertno = _assemble_kernel(inv, label=roi_label, method=method, pick_ori=None)
w = get_filter(K, vertno, inv, roi_label, noise_norm)
if show:
mne.viz.plot_topomap(w, info)
return w
开发者ID:nikolaims,项目名称:nfb,代码行数:13,代码来源:average_brain_min.py
示例9: test_simulate_raw_bem
def test_simulate_raw_bem(raw_data):
"""Test simulation of raw data with BEM."""
raw, src, stc, trans, sphere = raw_data
src = setup_source_space('sample', 'oct1', subjects_dir=subjects_dir)
for s in src:
s['nuse'] = 3
s['vertno'] = src[1]['vertno'][:3]
s['inuse'].fill(0)
s['inuse'][s['vertno']] = 1
# use different / more complete STC here
vertices = [s['vertno'] for s in src]
stc = SourceEstimate(np.eye(sum(len(v) for v in vertices)), vertices,
0, 1. / raw.info['sfreq'])
with pytest.deprecated_call():
raw_sim_sph = simulate_raw(raw, stc, trans, src, sphere, cov=None,
verbose=True)
with pytest.deprecated_call():
raw_sim_bem = simulate_raw(raw, stc, trans, src, bem_fname, cov=None,
n_jobs=2)
# some components (especially radial) might not match that well,
# so just make sure that most components have high correlation
assert_array_equal(raw_sim_sph.ch_names, raw_sim_bem.ch_names)
picks = pick_types(raw.info, meg=True, eeg=True)
n_ch = len(picks)
corr = np.corrcoef(raw_sim_sph[picks][0], raw_sim_bem[picks][0])
assert_array_equal(corr.shape, (2 * n_ch, 2 * n_ch))
med_corr = np.median(np.diag(corr[:n_ch, -n_ch:]))
assert med_corr > 0.65
# do some round-trip localization
for s in src:
transform_surface_to(s, 'head', trans)
locs = np.concatenate([s['rr'][s['vertno']] for s in src])
tmax = (len(locs) - 1) / raw.info['sfreq']
cov = make_ad_hoc_cov(raw.info)
# The tolerance for the BEM is surprisingly high (28) but I get the same
# result when using MNE-C and Xfit, even when using a proper 5120 BEM :(
for use_raw, bem, tol in ((raw_sim_sph, sphere, 2),
(raw_sim_bem, bem_fname, 31)):
events = find_events(use_raw, 'STI 014')
assert len(locs) == 6
evoked = Epochs(use_raw, events, 1, 0, tmax, baseline=None).average()
assert len(evoked.times) == len(locs)
fits = fit_dipole(evoked, cov, bem, trans, min_dist=1.)[0].pos
diffs = np.sqrt(np.sum((locs - fits) ** 2, axis=-1)) * 1000
med_diff = np.median(diffs)
assert med_diff < tol, '%s: %s' % (bem, med_diff)
开发者ID:Eric89GXL,项目名称:mne-python,代码行数:46,代码来源:test_raw.py
示例10: test_inverse_ctf_comp
def test_inverse_ctf_comp():
"""Test interpolation with compensated CTF data."""
raw = mne.io.read_raw_ctf(fname_raw_ctf).crop(0, 0)
raw.apply_gradient_compensation(1)
sphere = make_sphere_model()
cov = make_ad_hoc_cov(raw.info)
src = mne.setup_volume_source_space(
pos=dict(rr=[[0., 0., 0.01]], nn=[[0., 1., 0.]]))
fwd = make_forward_solution(raw.info, None, src, sphere, eeg=False)
raw.apply_gradient_compensation(0)
with pytest.raises(RuntimeError, match='compensation grade mismatch'):
make_inverse_operator(raw.info, fwd, cov, loose=1.)
raw.apply_gradient_compensation(1)
inv = make_inverse_operator(raw.info, fwd, cov, loose=1.)
apply_inverse_raw(raw, inv, 1. / 9.) # smoke test
raw.apply_gradient_compensation(0)
with pytest.raises(RuntimeError, match='compensation grade mismatch'):
apply_inverse_raw(raw, inv, 1. / 9.)
开发者ID:vibhaviswana,项目名称:mne-python,代码行数:18,代码来源:test_inverse.py
示例11: test_accuracy
def test_accuracy():
"""Test dipole fitting to sub-mm accuracy."""
evoked = read_evokeds(fname_evo)[0].crop(0., 0.,)
evoked.pick_types(meg=True, eeg=False)
evoked.pick_channels([c for c in evoked.ch_names[::4]])
for rad, perc_90 in zip((0.09, None), (0.002, 0.004)):
bem = make_sphere_model('auto', rad, evoked.info,
relative_radii=(0.999, 0.998, 0.997, 0.995))
src = read_source_spaces(fname_src)
fwd = make_forward_solution(evoked.info, None, src, bem)
fwd = convert_forward_solution(fwd, force_fixed=True, use_cps=True)
vertices = [src[0]['vertno'], src[1]['vertno']]
n_vertices = sum(len(v) for v in vertices)
amp = 10e-9
data = np.eye(n_vertices + 1)[:n_vertices]
data[-1, -1] = 1.
data *= amp
stc = SourceEstimate(data, vertices, 0., 1e-3, 'sample')
evoked.info.normalize_proj()
sim = simulate_evoked(fwd, stc, evoked.info, cov=None, nave=np.inf)
cov = make_ad_hoc_cov(evoked.info)
dip = fit_dipole(sim, cov, bem, min_dist=0.001)[0]
ds = []
for vi in range(n_vertices):
if vi < len(vertices[0]):
hi = 0
vertno = vi
else:
hi = 1
vertno = vi - len(vertices[0])
vertno = src[hi]['vertno'][vertno]
rr = src[hi]['rr'][vertno]
d = np.sqrt(np.sum((rr - dip.pos[vi]) ** 2))
ds.append(d)
# make sure that our median is sub-mm and the large majority are very
# close (we expect some to be off by a bit e.g. because they are
# radial)
assert_true((np.percentile(ds, [50, 90]) < [0.0005, perc_90]).all())
开发者ID:jdammers,项目名称:mne-python,代码行数:41,代码来源:test_dipole.py
示例12: test_confidence
def test_confidence(tmpdir):
"""Test confidence limits."""
evoked = read_evokeds(fname_evo_full, 'Left Auditory', baseline=(None, 0))
evoked.crop(0.08, 0.08).pick_types() # MEG-only
cov = make_ad_hoc_cov(evoked.info)
sphere = make_sphere_model((0., 0., 0.04), 0.08)
dip_py = fit_dipole(evoked, cov, sphere)[0]
fname_test = op.join(str(tmpdir), 'temp-dip.txt')
dip_py.save(fname_test)
dip_read = read_dipole(fname_test)
with pytest.warns(RuntimeWarning, match="'noise/ft/cm', 'prob'"):
dip_xfit = read_dipole(fname_dip_xfit)
for dip_check in (dip_py, dip_read):
assert_allclose(dip_check.pos, dip_xfit.pos, atol=5e-4) # < 0.5 mm
assert_allclose(dip_check.gof, dip_xfit.gof, atol=5e-1) # < 0.5%
assert_array_equal(dip_check.nfree, dip_xfit.nfree) # exact match
assert_allclose(dip_check.khi2, dip_xfit.khi2, rtol=2e-2) # 2% miss
assert set(dip_check.conf.keys()) == set(dip_xfit.conf.keys())
for key in sorted(dip_check.conf.keys()):
assert_allclose(dip_check.conf[key], dip_xfit.conf[key],
rtol=1.5e-1, err_msg=key)
开发者ID:Eric89GXL,项目名称:mne-python,代码行数:21,代码来源:test_dipole.py
示例13: test_confidence
def test_confidence():
"""Test confidence limits."""
tempdir = _TempDir()
evoked = read_evokeds(fname_evo_full, 'Left Auditory', baseline=(None, 0))
evoked.crop(0.08, 0.08).pick_types() # MEG-only
cov = make_ad_hoc_cov(evoked.info)
sphere = make_sphere_model((0., 0., 0.04), 0.08)
dip_py = fit_dipole(evoked, cov, sphere)[0]
fname_test = op.join(tempdir, 'temp-dip.txt')
dip_py.save(fname_test)
dip_read = read_dipole(fname_test)
with warnings.catch_warnings(record=True) as w:
dip_xfit = read_dipole(fname_dip_xfit)
assert_equal(len(w), 1)
assert_true("['noise/ft/cm', 'prob']" in str(w[0].message))
for dip_check in (dip_py, dip_read):
assert_allclose(dip_check.pos, dip_xfit.pos, atol=5e-4) # < 0.5 mm
assert_allclose(dip_check.gof, dip_xfit.gof, atol=5e-1) # < 0.5%
assert_array_equal(dip_check.nfree, dip_xfit.nfree) # exact match
assert_allclose(dip_check.khi2, dip_xfit.khi2, rtol=2e-2) # 2% miss
assert_equal(set(dip_check.conf.keys()), set(dip_xfit.conf.keys()))
for key in sorted(dip_check.conf.keys()):
assert_allclose(dip_check.conf[key], dip_xfit.conf[key],
rtol=1.5e-1, err_msg=key)
开发者ID:jdammers,项目名称:mne-python,代码行数:24,代码来源:test_dipole.py
示例14: test_simulate_raw_sphere
def test_simulate_raw_sphere(raw_data, tmpdir):
"""Test simulation of raw data with sphere model."""
seed = 42
raw, src, stc, trans, sphere = raw_data
assert len(pick_types(raw.info, meg=False, ecg=True)) == 1
tempdir = str(tmpdir)
# head pos
head_pos_sim = _get_head_pos_sim(raw)
#
# Test raw simulation with basic parameters
#
raw.info.normalize_proj()
cov = read_cov(cov_fname)
cov['projs'] = raw.info['projs']
raw.info['bads'] = raw.ch_names[:1]
with pytest.deprecated_call(match='cov is deprecated'):
raw_sim = simulate_raw(raw, stc, trans, src, sphere, cov,
head_pos=head_pos_sim,
blink=True, ecg=True, random_state=seed,
verbose=True)
with pytest.warns(RuntimeWarning, match='applying projector with'):
raw_sim_2 = simulate_raw(raw, stc, trans_fname, src_fname, sphere,
cov_fname, head_pos=head_pos_sim,
blink=True, ecg=True, random_state=seed)
with pytest.raises(RuntimeError, match='Maximum number of STC iterations'):
simulate_raw(raw.info, [stc] * 5, trans_fname, src_fname, sphere,
cov=None, max_iter=1)
assert_array_equal(raw_sim_2[:][0], raw_sim[:][0])
std = dict(grad=2e-13, mag=10e-15, eeg=0.1e-6)
with pytest.deprecated_call():
raw_sim = simulate_raw(raw, stc, trans, src, sphere,
make_ad_hoc_cov(raw.info, std=std),
head_pos=head_pos_sim, blink=True, ecg=True,
random_state=seed)
with pytest.deprecated_call():
raw_sim_2 = simulate_raw(raw, stc, trans_fname, src_fname, sphere,
cov=std, head_pos=head_pos_sim, blink=True,
ecg=True, random_state=seed)
assert_array_equal(raw_sim_2[:][0], raw_sim[:][0])
sphere_norad = make_sphere_model('auto', None, raw.info)
raw_meg = raw.copy().pick_types()
with pytest.deprecated_call():
raw_sim = simulate_raw(raw_meg, stc, trans, src, sphere_norad,
cov=None,
head_pos=head_pos_sim, blink=True, ecg=True,
random_state=seed)
with pytest.deprecated_call():
raw_sim_2 = simulate_raw(raw_meg, stc, trans_fname, src_fname,
sphere_norad, cov=None, head_pos=head_pos_sim,
blink=True, ecg=True, random_state=seed)
assert_array_equal(raw_sim_2[:][0], raw_sim[:][0])
# Test IO on processed data
test_outname = op.join(tempdir, 'sim_test_raw.fif')
raw_sim.save(test_outname)
raw_sim_loaded = read_raw_fif(test_outname, preload=True)
assert_allclose(raw_sim_loaded[:][0], raw_sim[:][0], rtol=1e-6, atol=1e-20)
del raw_sim, raw_sim_2
# with no cov (no noise) but with artifacts, most time periods should match
# but the EOG/ECG channels should not
for ecg, eog in ((True, False), (False, True), (True, True)):
with pytest.deprecated_call():
raw_sim_3 = simulate_raw(raw, stc, trans, src, sphere,
cov=None, head_pos=head_pos_sim,
blink=eog, ecg=ecg, random_state=seed)
with pytest.deprecated_call():
raw_sim_4 = simulate_raw(raw, stc, trans, src, sphere,
cov=None, head_pos=head_pos_sim,
blink=False, ecg=False, random_state=seed)
picks = np.arange(len(raw.ch_names))
diff_picks = pick_types(raw.info, meg=False, ecg=ecg, eog=eog)
these_picks = np.setdiff1d(picks, diff_picks)
close = np.isclose(raw_sim_3[these_picks][0],
raw_sim_4[these_picks][0], atol=1e-20)
assert np.mean(close) > 0.7
far = ~np.isclose(raw_sim_3[diff_picks][0],
raw_sim_4[diff_picks][0], atol=1e-20)
assert np.mean(far) > 0.99
del raw_sim_3, raw_sim_4
# make sure it works with EEG-only and MEG-only
with pytest.deprecated_call():
raw_sim_meg = simulate_raw(raw.copy().pick_types(meg=True, eeg=False),
stc, trans, src, sphere, cov=None)
raw_sim_eeg = simulate_raw(raw.copy().pick_types(meg=False, eeg=True),
stc, trans, src, sphere, cov=None)
raw_sim_meeg = simulate_raw(raw.copy().pick_types(meg=True, eeg=True),
stc, trans, src, sphere, cov=None)
for this_raw in (raw_sim_meg, raw_sim_eeg, raw_sim_meeg):
add_eog(this_raw, random_state=seed)
for this_raw in (raw_sim_meg, raw_sim_meeg):
add_ecg(this_raw, random_state=seed)
with pytest.raises(RuntimeError, match='only add ECG artifacts if MEG'):
add_ecg(raw_sim_eeg)
assert_allclose(np.concatenate((raw_sim_meg[:][0], raw_sim_eeg[:][0])),
raw_sim_meeg[:][0], rtol=1e-7, atol=1e-20)
del raw_sim_meg, raw_sim_eeg, raw_sim_meeg
#.........这里部分代码省略.........
开发者ID:Eric89GXL,项目名称:mne-python,代码行数:101,代码来源:test_raw.py
示例15: simulate_movement
#.........这里部分代码省略.........
pos = get_chpi_positions(pos, verbose=False)
if isinstance(pos, tuple): # can be an already-loaded pos file
transs, rots, ts = pos
ts -= raw.first_samp / raw.info['sfreq'] # MF files need reref
dev_head_ts = [np.r_[np.c_[r, t[:, np.newaxis]], [[0, 0, 0, 1]]]
for r, t in zip(rots, transs)]
del transs, rots
elif isinstance(pos, dict):
ts = np.array(list(pos.keys()), float)
ts.sort()
dev_head_ts = [pos[float(tt)] for tt in ts]
else:
raise TypeError('unknown pos type %s' % type(pos))
if not (ts >= 0).all(): # pathological if not
raise RuntimeError('Cannot have t < 0 in transform file')
tend = raw.times[-1]
assert not (ts < 0).any()
assert not (ts > tend).any()
if ts[0] > 0:
ts = np.r_[[0.], ts]
dev_head_ts.insert(0, raw.info['dev_head_t']['trans'])
dev_head_ts = [{'trans': d, 'to': raw.info['dev_head_t']['to'],
'from': raw.info['dev_head_t']['from']}
for d in dev_head_ts]
if ts[-1] < tend:
dev_head_ts.append(dev_head_ts[-1])
ts = np.r_[ts, [tend]]
offsets = raw.time_as_index(ts)
offsets[-1] = raw.n_times # fix for roundoff error
assert offsets[-2] != offsets[-1]
del ts
if isinstance(cov, string_types):
assert cov == 'simple'
cov = make_ad_hoc_cov(raw.info, verbose=False)
assert np.array_equal(offsets, np.unique(offsets))
assert len(offsets) == len(dev_head_ts)
approx_events = int((raw.n_times / raw.info['sfreq']) /
(stc.times[-1] - stc.times[0]))
logger.info('Provided parameters will provide approximately %s event%s'
% (approx_events, '' if approx_events == 1 else 's'))
# get HPI freqs and reorder
hpi_freqs = np.array([x['custom_ref'][0]
for x in raw.info['hpi_meas'][0]['hpi_coils']])
n_freqs = len(hpi_freqs)
order = [x['number'] - 1 for x in raw.info['hpi_meas'][0]['hpi_coils']]
assert np.array_equal(np.unique(order), np.arange(n_freqs))
hpi_freqs = hpi_freqs[order]
hpi_order = raw.info['hpi_results'][0]['order'] - 1
assert np.array_equal(np.unique(hpi_order), np.arange(n_freqs))
hpi_freqs = hpi_freqs[hpi_order]
# extract necessary info
picks = pick_types(raw.info, meg=True, eeg=True) # for simulation
meg_picks = pick_types(raw.info, meg=True, eeg=False) # for CHPI
fwd_info = pick_info(raw.info, picks)
fwd_info['projs'] = []
logger.info('Setting up raw data simulation using %s head position%s'
% (len(dev_head_ts), 's' if len(dev_head_ts) != 1 else ''))
raw.preload_data(verbose=False)
if isinstance(stc, VolSourceEstimate):
verts = [stc.vertices]
else:
verts = stc.vertices
src = _restrict_source_space_to(src, verts)
开发者ID:staulu,项目名称:mnefun,代码行数:67,代码来源:_simulate.py
示例16: where
# activate. Here we use a sine wave at 18 Hz with a peak amplitude
# of 10 nAm.
source_time_series = np.sin(2. * np.pi * 18. * np.arange(100) * tstep) * 10e-9
# Define when the activity occurs using events. The first column is the sample
# of the event, the second is not used, and the third is the event id. Here the
# events occur every 200 samples.
n_events = 50
events = np.zeros((n_events, 3))
events[:, 0] = 100 + 200 * np.arange(n_events) # Events sample.
events[:, 2] = 1 # All events have the sample id.
# Create simulated source activity. Here we use a SourceSimulator whose
# add_data method is key. It specified where (label), what
# (source_time_series), and when (events) an event type will occur.
source_simulator = mne.simulation.SourceSimulator(src, tstep=tstep)
source_simulator.add_data(label, source_time_series, events)
# Project the source time series to sensor space and add some noise. The source
# simulator can be given directly to the simulate_raw function.
raw = mne.simulation.simulate_raw(info, source_simulator, forward=fwd)
cov = mne.make_ad_hoc_cov(raw.info)
mne.simulation.add_noise(raw, cov, iir_filter=[0.2, -0.2, 0.04])
raw.plot()
# Plot evoked data to get another view of the simulated raw data.
events = mne.find_events(raw)
epochs = mne.Epochs(raw, events, 1, tmin=-0.05, tmax=0.2)
evoked = epochs.average()
evoked.plot()
开发者ID:Eric89GXL,项目名称:mne-python,代码行数:30,代码来源:plot_source_simulator.py
示例17: test_simulate_raw_sphere
def test_simulate_raw_sphere():
"""Test simulation of raw data with sphere model."""
seed = 42
raw, src, stc, trans, sphere = _get_data()
assert len(pick_types(raw.info, meg=False, ecg=True)) == 1
# head pos
head_pos_sim = dict()
# these will be at 1., 2., ... sec
shifts = [[0.001, 0., -0.001], [-0.001, 0.001, 0.]]
for time_key, shift in enumerate(shifts):
# Create 4x4 matrix transform and normalize
temp_trans = deepcopy(raw.info['dev_head_t'])
temp_trans['trans'][:3, 3] += shift
head_pos_sim[time_key + 1.] = temp_trans['trans']
#
# Test raw simulation with basic parameters
#
raw_sim = simulate_raw(raw, stc, trans, src, sphere, read_cov(cov_fname),
head_pos=head_pos_sim,
blink=True, ecg=True, random_state=seed)
raw_sim_2 = simulate_raw(raw, stc, trans_fname, src_fname, sphere,
cov_fname, head_pos=head_pos_sim,
blink=True, ecg=True, random_state=seed)
assert_array_equal(raw_sim_2[:][0], raw_sim[:][0])
std = dict(grad=2e-13, mag=10e-15, eeg=0.1e-6)
raw_sim = simulate_raw(raw, stc, trans, src, sphere,
make_ad_hoc_cov(raw.info, std=std),
head_pos=head_pos_sim, blink=True, ecg=True,
random_state=seed)
raw_sim_2 = simulate_raw(raw, stc, trans_fname, src_fname, sphere,
cov=std, head_pos=head_pos_sim, blink=True,
ecg=True, random_state=seed)
assert_array_equal(raw_sim_2[:][0], raw_sim[:][0])
sphere_norad = make_sphere_model('auto', None, raw.info)
raw_meg = raw.copy().pick_types()
raw_sim = simulate_raw(raw_meg, stc, trans, src, sphere_norad,
make_ad_hoc_cov(raw.info, std=None),
head_pos=head_pos_sim, blink=True, ecg=True,
random_state=seed)
raw_sim_2 = simulate_raw(raw_meg, stc, trans_fname, src_fname,
sphere_norad,
cov='simple', head_pos=head_pos_sim, blink=True,
ecg=True, random_state=seed)
assert_array_equal(raw_sim_2[:][0], raw_sim[:][0])
# Test IO on processed data
tempdir = _TempDir()
test_outname = op.join(tempdir, 'sim_test_raw.fif')
raw_sim.save(test_outname)
raw_sim_loaded = read_raw_fif(test_outname, preload=True)
assert_allclose(raw_sim_loaded[:][0], raw_sim[:][0], rtol=1e-6, atol=1e-20)
del raw_sim, raw_sim_2
# with no cov (no noise) but with artifacts, most time periods should match
# but the EOG/ECG channels should not
for ecg, eog in ((True, False), (False, True), (True, True)):
raw_sim_3 = simulate_raw(raw, stc, trans, src, sphere,
cov=None, head_pos=head_pos_sim,
blink=eog, ecg=ecg, random_state=seed)
raw_sim_4 = simulate_raw(raw, stc, trans, src, sphere,
cov=None, head_pos=head_pos_sim,
blink=False, ecg=False, random_state=seed)
picks = np.arange(len(raw.ch_names))
diff_picks = pick_types(raw.info, meg=False, ecg=ecg, eog=eog)
these_picks = np.setdiff1d(picks, diff_picks)
close = np.isclose(raw_sim_3[these_picks][0],
raw_sim_4[these_picks][0], atol=1e-20)
assert np.mean(close) > 0.7
far = ~np.isclose(raw_sim_3[diff_picks][0],
raw_sim_4[diff_picks][0], atol=1e-20)
assert np.mean(far) > 0.99
del raw_sim_3, raw_sim_4
# make sure it works with EEG-only and MEG-only
raw_sim_meg = simulate_raw(raw.copy().pick_types(meg=True, eeg=False),
stc, trans, src, sphere, cov=None,
ecg=True, blink=True, random_state=seed)
raw_sim_eeg = simulate_raw(raw.copy().pick_types(meg=False, eeg=True),
stc, trans, src, sphere, cov=None,
ecg=True, blink=True, random_state=seed)
raw_sim_meeg = simulate_raw(raw.copy().pick_types(meg=True, eeg=True),
stc, trans, src, sphere, cov=None,
ecg=True, blink=True, random_state=seed)
assert_allclose(np.concatenate((raw_sim_meg[:][0], raw_sim_eeg[:][0])),
raw_sim_meeg[:][0], rtol=1e-7, atol=1e-20)
del raw_sim_meg, raw_sim_eeg, raw_sim_meeg
# check that raw-as-info is supported
raw_sim = simulate_raw(raw, stc, trans, src, sphere, cov=None)
n_samp = int(round(raw.info['sfreq']))
for use_raw in (raw, raw.info):
raw_sim_2 = simulate_raw(use_raw, stc, trans, src, sphere, cov=None,
duration=1.)
assert len(raw_sim_2.times) == n_samp
assert_allclose(raw_sim[:, :n_samp][0],
raw_sim_2[:, :n_samp][0], rtol=1e-5, atol=1e-30)
del raw_sim, raw_sim_2
#.........这里部分代码省略.........
开发者ID:kambysese,项目名称:mne-python,代码行数:101,代码来源:test_raw.py
示例18: test_lcmv_vector
def test_lcmv_vector():
"""Test vector LCMV solutions."""
info = mne.io.read_raw_fif(fname_raw).info
# For speed and for rank-deficiency calculation simplicity,
# just use grads:
info = mne.pick_info(info, mne.pick_types(info, meg='grad', exclude=()))
info.update(bads=[], projs=[])
forward = mne.read_forward_solution(fname_fwd)
forward = mne.pick_channels_forward(forward, info['ch_names'])
vertices = [s['vertno'][::100] for s in forward['src']]
n_vertices = sum(len(v) for v in vertices)
assert 5 < n_vertices < 20
amplitude = 100e-9
stc = mne.SourceEstimate(amplitude * np.eye(n_vertices), vertices,
0, 1. / info['sfreq'])
forward_sim = mne.convert_forward_solution(forward, force_fixed=True,
use_cps=True, copy=True)
forward_sim = mne.forward.restrict_forward_to_stc(forward_sim, stc)
noise_cov = mne.make_ad_hoc_cov(info)
noise_cov.update(data=np.diag(noise_cov['data']), diag=False)
evoked = simulate_evoked(forward_sim, stc, info, noise_cov, nave=1)
source_nn = forward_sim['source_nn']
source_rr = forward_sim['source_rr']
# Figure out our indices
mask = np.concatenate([np.in1d(s['vertno'], v)
for s, v in zip(forward['src'], vertices)])
mapping = np.where(mask)[0]
assert_array_equal(source_rr, forward['source_rr'][mapping])
# Don't check NN because we didn't rotate to surf ori
del forward_sim
#
# Let's do minimum norm as a sanity check (dipole_fit is slower)
#
inv = make_inverse_operator(info, forward, noise_cov, loose=1.)
stc_vector_mne = apply_inverse(evoked, inv, pick_ori='vector')
mne_ori = stc_vector_mne.data[mapping, :, np.arange(n_vertices)]
mne_ori /= np.linalg.norm(mne_ori, axis=-1)[:, np.newaxis]
mne_angles = np.rad2deg(np.arccos(np.sum(mne_ori * source_nn, axis=-1)))
assert np.mean(mne_angles) < 35
#
# Now let's do LCMV
#
data_cov = mne.make_ad_hoc_cov(info) # just a stub for later
with pytest.raises(ValueError, match='pick_ori must be one of'):
make_lcmv(info, forward, data_cov, 0.05, noise_cov, pick_ori='bad')
lcmv_ori = list()
for ti in range(n_vertices):
this_evoked = evoked.copy().crop(evoked.times[ti], evoked.times[ti])
data_cov['data'] = (np.outer(this_evoked.data, this_evoked.data) +
noise_cov['data'])
vals = linalg.svdvals(data_cov['data'])
assert vals[0] / vals[-1] < 1e5 # not rank deficient
filters = make_lcmv(info, forward, data_cov, 0.05, noise_cov)
filters_vector = make_lcmv(info, forward, data_cov, 0.05, noise_cov,
pick_ori='vector')
stc = apply_lcmv(this_evoked, filters)
assert isinstance(stc, mne.SourceEstimate)
stc_vector = apply_lcmv(this_evoked, filters_vector)
assert isinstance(stc_vector, mne.VectorSourceEstimate)
assert_allclose(stc.data, stc_vector.magnitude().data)
# Check the orientation by pooling across some neighbors, as LCMV can
# have some "holes" at the points of interest
idx = np.where(cdist(forward['source_rr'], source_rr[[ti]]) < 0.02)[0]
lcmv_ori.append(np.mean(stc_vector.data[idx, :, 0], axis=0))
lcmv_ori[-1] /= np.linalg.norm(lcmv_ori[-1])
lcmv_angles = np.rad2deg(np.arccos(np.sum(lcmv_ori * source_nn, axis=-1)))
assert np.mean(lcmv_angles) < 55
开发者ID:SherazKhan,项目名称:mne-python,代码行数:70,代码来源:test_lcmv.py
示例19: QApplication
a = QApplication([])
rej, spatial, top = ICADialog.get_rejection(data.T, channels, fs, mode='ica', states=None)[:3]
data = rej.apply(data.T).T
standard_montage = mne.channels.read_montage(kind='standard_1005')
standard_montage_names = [name.upper() for name in standard_montage.ch_names]
for j, channel in enumerate(channels):
channels[j] = standard_montage.ch_names[standard_montage_names.index(channel.upper())]
# create info
info = mne.create_info(ch_names=channels, sfreq=fs, montage=mne.channels.read_montage(kind='standard_1005'), ch_types=['eeg' for ch in channels])
# raw instance
raw = mne.io.RawArray(data, info)
#raw.set_eeg_reference()
#noise_cov = mne.compute_raw_covariance(raw)
noise_cov = mne.make_ad_hoc_cov(info, verbose=None)
# forward solution
#fwd = mne.make_forward_solution(info, trans=trans, src=src, bem=bem, fname='fsaverage-fwd.fif', meg=False, eeg=True, mindist=5.)
fwd = mne.read_forward_solution(r'C:\Users\nsmetanin\PycharmProjects\nfb\tests\sloreta\fsaverage-fwd-1005-2.fif', surf_ori=True)
# inverse
from mne.minimum_norm.inverse import _assemble_kernel
inv = mne.minimum_norm.make_inverse_operator(info, fwd, noise_cov, loose=0.2, depth=0.8, fixed=True)
lambdas = [1000, 100, 10, 1, 0.1, 0.05, 0.01, 0.005, 0.001, 0.0001]
f, axes = plt.subplots(2, len(lambdas))
开发者ID:nikolaims,项目名称:nfb,代码行数:31,代码来源:average_brain_reg.py
注:本文中的mne.make_ad_hoc_cov函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论