本文整理汇总了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函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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'])
示例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))
示例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
示例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'])
示例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"])
示例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)
示例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.)
示例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
示例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)
示例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.)
示例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())
示例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)
示例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)
示例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
#.........这里部分代码省略.........
示例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)