本文整理汇总了Python中mne.read_evokeds函数的典型用法代码示例。如果您正苦于以下问题:Python read_evokeds函数的具体用法?Python read_evokeds怎么用?Python read_evokeds使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了read_evokeds函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_render_report
def test_render_report():
"""Test rendering -*.fif files for mne report.
"""
report = Report(info_fname=raw_fname)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
report.parse_folder(data_path=base_dir)
assert_true(len(w) == 1)
# Check correct paths and filenames
assert_true(raw_fname in report.fnames)
assert_true(event_name in report.fnames)
assert_true(report.data_path == base_dir)
# Check if all files were rendered in the report
fnames = glob.glob(op.join(base_dir, '*.fif'))
bad_name = 'test_ctf_comp_raw-eve.fif'
decrement = any(fname.endswith(bad_name) for fname in fnames)
fnames = [fname for fname in fnames if
fname.endswith(('-eve.fif', '-ave.fif', '-cov.fif',
'-sol.fif', '-fwd.fif', '-inv.fif',
'-src.fif', '-trans.fif', 'raw.fif',
'sss.fif', '-epo.fif')) and
not fname.endswith(bad_name)]
# last file above gets created by another test, and it shouldn't be there
for fname in fnames:
assert_true(''.join(report.html).find(op.basename(fname)) != -1)
assert_equal(len(report.fnames), len(fnames))
assert_equal(len(report.html), len(report.fnames))
evoked1 = read_evokeds(evoked1_fname)
evoked2 = read_evokeds(evoked2_fname)
assert_equal(len(report.fnames) + len(evoked1) + len(evoked2) - 2,
report.initial_id - decrement)
# Check saving functionality
report.data_path = tempdir
report.save(fname=op.join(tempdir, 'report.html'), open_browser=False)
assert_true(op.isfile(op.join(tempdir, 'report.html')))
# Check add_section functionality
fig = evoked1[0].plot(show=False)
report.add_section(figs=fig, # test non-list input
captions=['evoked response'])
assert_equal(len(report.html), len(fnames) + 1)
assert_equal(len(report.html), len(report.fnames))
assert_raises(ValueError, report.add_section, figs=[fig, fig],
captions='H')
# Check saving same report to new filename
report.save(fname=op.join(tempdir, 'report2.html'), open_browser=False)
assert_true(op.isfile(op.join(tempdir, 'report2.html')))
# Check overwriting file
report.save(fname=op.join(tempdir, 'report.html'), open_browser=False,
overwrite=True)
assert_true(op.isfile(op.join(tempdir, 'report.html')))
示例2: test_evoked_arithmetic
def test_evoked_arithmetic():
"""Test evoked arithmetic
"""
ev = read_evokeds(fname, condition=0)
ev1 = EvokedArray(np.ones_like(ev.data), ev.info, ev.times[0], nave=20)
ev2 = EvokedArray(-np.ones_like(ev.data), ev.info, ev.times[0], nave=10)
# combine_evoked([ev1, ev2]) should be the same as ev1 + ev2:
# data should be added according to their `nave` weights
# nave = ev1.nave + ev2.nave
ev = ev1 + ev2
assert_equal(ev.nave, ev1.nave + ev2.nave)
assert_allclose(ev.data, 1. / 3. * np.ones_like(ev.data))
ev = ev1 - ev2
assert_equal(ev.nave, ev1.nave + ev2.nave)
assert_equal(ev.comment, ev1.comment + ' - ' + ev2.comment)
assert_allclose(ev.data, np.ones_like(ev1.data))
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
ev = merge_evoked([ev1, ev2])
assert_true(len(w) >= 1)
assert_allclose(ev.data, 1. / 3. * np.ones_like(ev.data))
# default comment behavior if evoked.comment is None
old_comment1 = ev1.comment
old_comment2 = ev2.comment
ev1.comment = None
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
ev = ev1 - ev2
assert_equal(ev.comment, 'unknown')
ev1.comment = old_comment1
ev2.comment = old_comment2
# equal weighting
ev = combine_evoked([ev1, ev2], weights='equal')
assert_allclose(ev.data, np.zeros_like(ev1.data))
# combine_evoked([ev1, ev2], weights=[1, 0]) should yield the same as ev1
ev = combine_evoked([ev1, ev2], weights=[1, 0])
assert_equal(ev.nave, ev1.nave)
assert_allclose(ev.data, ev1.data)
# simple subtraction (like in oddball)
ev = combine_evoked([ev1, ev2], weights=[1, -1])
assert_allclose(ev.data, 2 * np.ones_like(ev1.data))
assert_raises(ValueError, combine_evoked, [ev1, ev2], weights='foo')
assert_raises(ValueError, combine_evoked, [ev1, ev2], weights=[1])
# grand average
evoked1, evoked2 = read_evokeds(fname, condition=[0, 1], proj=True)
ch_names = evoked1.ch_names[2:]
evoked1.info['bads'] = ['EEG 008'] # test interpolation
evoked1.drop_channels(evoked1.ch_names[:1])
evoked2.drop_channels(evoked2.ch_names[1:2])
gave = grand_average([evoked1, evoked2])
assert_equal(gave.data.shape, [len(ch_names), evoked1.data.shape[1]])
assert_equal(ch_names, gave.ch_names)
assert_equal(gave.nave, 2)
示例3: test_evoked_proj
def test_evoked_proj():
"""Test SSP proj operations
"""
for proj in [True, False]:
ave = read_evokeds(fname, condition=0, proj=proj)
assert_true(all(p['active'] == proj for p in ave.info['projs']))
# test adding / deleting proj
if proj:
assert_raises(ValueError, ave.add_proj, [],
{'remove_existing': True})
assert_raises(ValueError, ave.del_proj, 0)
else:
projs = deepcopy(ave.info['projs'])
n_proj = len(ave.info['projs'])
ave.del_proj(0)
assert_true(len(ave.info['projs']) == n_proj - 1)
ave.add_proj(projs, remove_existing=False)
assert_true(len(ave.info['projs']) == 2 * n_proj - 1)
ave.add_proj(projs, remove_existing=True)
assert_true(len(ave.info['projs']) == n_proj)
ave = read_evokeds(fname, condition=0, proj=False)
data = ave.data.copy()
ave.apply_proj()
assert_allclose(np.dot(ave._projector, data), ave.data)
示例4: test_evoked_resample
def test_evoked_resample():
"""Test for resampling of evoked data
"""
tempdir = _TempDir()
# upsample, write it out, read it in
ave = read_evokeds(fname, 0)
sfreq_normal = ave.info['sfreq']
ave.resample(2 * sfreq_normal)
write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave)
ave_up = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)
# compare it to the original
ave_normal = read_evokeds(fname, 0)
# and compare the original to the downsampled upsampled version
ave_new = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)
ave_new.resample(sfreq_normal)
assert_array_almost_equal(ave_normal.data, ave_new.data, 2)
assert_array_almost_equal(ave_normal.times, ave_new.times)
assert_equal(ave_normal.nave, ave_new.nave)
assert_equal(ave_normal._aspect_kind, ave_new._aspect_kind)
assert_equal(ave_normal.kind, ave_new.kind)
assert_equal(ave_normal.last, ave_new.last)
assert_equal(ave_normal.first, ave_new.first)
# for the above to work, the upsampling just about had to, but
# we'll add a couple extra checks anyway
assert_true(len(ave_up.times) == 2 * len(ave_normal.times))
assert_true(ave_up.data.shape[1] == 2 * ave_normal.data.shape[1])
示例5: test_evoked_io_from_epochs
def test_evoked_io_from_epochs():
"""Test IO of evoked data made from epochs
"""
# offset our tmin so we don't get exactly a zero value when decimating
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
epochs = Epochs(raw, events[:4], event_id, tmin + 0.011, tmax, picks=picks, baseline=(None, 0), decim=5)
assert_true(len(w) == 1)
evoked = epochs.average()
evoked.save(op.join(tempdir, "evoked-ave.fif"))
evoked2 = read_evokeds(op.join(tempdir, "evoked-ave.fif"))[0]
assert_allclose(evoked.data, evoked2.data, rtol=1e-4, atol=1e-20)
assert_allclose(evoked.times, evoked2.times, rtol=1e-4, atol=1 / evoked.info["sfreq"])
# now let's do one with negative time
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
epochs = Epochs(raw, events[:4], event_id, 0.1, tmax, picks=picks, baseline=(0.1, 0.2), decim=5)
evoked = epochs.average()
evoked.save(op.join(tempdir, "evoked-ave.fif"))
evoked2 = read_evokeds(op.join(tempdir, "evoked-ave.fif"))[0]
assert_allclose(evoked.data, evoked2.data, rtol=1e-4, atol=1e-20)
assert_allclose(evoked.times, evoked2.times, rtol=1e-4, atol=1e-20)
# should be equivalent to a cropped original
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
epochs = Epochs(raw, events[:4], event_id, -0.2, tmax, picks=picks, baseline=(0.1, 0.2), decim=5)
evoked = epochs.average()
evoked.crop(0.099, None)
assert_allclose(evoked.data, evoked2.data, rtol=1e-4, atol=1e-20)
assert_allclose(evoked.times, evoked2.times, rtol=1e-4, atol=1e-20)
示例6: test_evoked_standard_error
def test_evoked_standard_error():
"""Test calculation and read/write of standard error
"""
raw, events, picks = _get_data()
tempdir = _TempDir()
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=(None, 0))
evoked = [epochs.average(), epochs.standard_error()]
write_evokeds(op.join(tempdir, 'evoked-ave.fif'), evoked)
evoked2 = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), [0, 1])
evoked3 = [read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 'Unknown'),
read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 'Unknown',
kind='standard_error')]
for evoked_new in [evoked2, evoked3]:
assert_true(evoked_new[0]._aspect_kind ==
FIFF.FIFFV_ASPECT_AVERAGE)
assert_true(evoked_new[0].kind == 'average')
assert_true(evoked_new[1]._aspect_kind ==
FIFF.FIFFV_ASPECT_STD_ERR)
assert_true(evoked_new[1].kind == 'standard_error')
for ave, ave2 in zip(evoked, evoked_new):
assert_array_almost_equal(ave.data, ave2.data)
assert_array_almost_equal(ave.times, ave2.times)
assert_equal(ave.nave, ave2.nave)
assert_equal(ave._aspect_kind, ave2._aspect_kind)
assert_equal(ave.kind, ave2.kind)
assert_equal(ave.last, ave2.last)
assert_equal(ave.first, ave2.first)
示例7: test_io_evoked
def test_io_evoked():
"""Test IO for evoked data (fif + gz) with integer and str args
"""
tempdir = _TempDir()
ave = read_evokeds(fname, 0)
write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave)
ave2 = read_evokeds(op.join(tempdir, 'evoked-ave.fif'))[0]
# This not being assert_array_equal due to windows rounding
assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-3))
assert_array_almost_equal(ave.times, ave2.times)
assert_equal(ave.nave, ave2.nave)
assert_equal(ave._aspect_kind, ave2._aspect_kind)
assert_equal(ave.kind, ave2.kind)
assert_equal(ave.last, ave2.last)
assert_equal(ave.first, ave2.first)
assert_true(repr(ave))
# test compressed i/o
ave2 = read_evokeds(fname_gz, 0)
assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-8))
# test str access
condition = 'Left Auditory'
assert_raises(ValueError, read_evokeds, fname, condition, kind='stderr')
assert_raises(ValueError, read_evokeds, fname, condition,
kind='standard_error')
ave3 = read_evokeds(fname, condition)
assert_array_almost_equal(ave.data, ave3.data, 19)
# test read_evokeds and write_evokeds
aves1 = read_evokeds(fname)[1::2]
aves2 = read_evokeds(fname, [1, 3])
aves3 = read_evokeds(fname, ['Right Auditory', 'Right visual'])
write_evokeds(op.join(tempdir, 'evoked-ave.fif'), aves1)
aves4 = read_evokeds(op.join(tempdir, 'evoked-ave.fif'))
for aves in [aves2, aves3, aves4]:
for [av1, av2] in zip(aves1, aves):
assert_array_almost_equal(av1.data, av2.data)
assert_array_almost_equal(av1.times, av2.times)
assert_equal(av1.nave, av2.nave)
assert_equal(av1.kind, av2.kind)
assert_equal(av1._aspect_kind, av2._aspect_kind)
assert_equal(av1.last, av2.last)
assert_equal(av1.first, av2.first)
assert_equal(av1.comment, av2.comment)
# test warnings on bad filenames
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
fname2 = op.join(tempdir, 'test-bad-name.fif')
write_evokeds(fname2, ave)
read_evokeds(fname2)
assert_naming(w, 'test_evoked.py', 2)
# constructor
assert_raises(TypeError, Evoked, fname)
示例8: test_evoked_detrend
def test_evoked_detrend():
"""Test for detrending evoked data."""
ave = read_evokeds(fname, 0)
ave_normal = read_evokeds(fname, 0)
ave.detrend(0)
ave_normal.data -= np.mean(ave_normal.data, axis=1)[:, np.newaxis]
picks = pick_types(ave.info, meg=True, eeg=True, exclude='bads')
assert_true(np.allclose(ave.data[picks], ave_normal.data[picks],
rtol=1e-8, atol=1e-16))
示例9: test_plot_topomap
def test_plot_topomap():
"""Test topomap plotting
"""
# evoked
warnings.simplefilter("always", UserWarning)
with warnings.catch_warnings(record=True):
evoked = read_evokeds(evoked_fname, "Left Auditory", baseline=(None, 0))
evoked.plot_topomap(0.1, "mag", layout=layout)
plot_evoked_topomap(evoked, None, ch_type="mag")
times = [0.1, 0.2]
plot_evoked_topomap(evoked, times, ch_type="eeg")
plot_evoked_topomap(evoked, times, ch_type="grad")
plot_evoked_topomap(evoked, times, ch_type="planar1")
plot_evoked_topomap(evoked, times, ch_type="planar2")
plot_evoked_topomap(evoked, times, ch_type="grad", show_names=True)
p = plot_evoked_topomap(evoked, times, ch_type="grad", show_names=lambda x: x.replace("MEG", ""))
subplot = [x for x in p.get_children() if isinstance(x, matplotlib.axes.Subplot)][0]
assert_true(
all("MEG" not in x.get_text() for x in subplot.get_children() if isinstance(x, matplotlib.text.Text))
)
# Test title
def get_texts(p):
return [x.get_text() for x in p.get_children() if isinstance(x, matplotlib.text.Text)]
p = plot_evoked_topomap(evoked, times, ch_type="eeg")
assert_equal(len(get_texts(p)), 0)
p = plot_evoked_topomap(evoked, times, ch_type="eeg", title="Custom")
texts = get_texts(p)
assert_equal(len(texts), 1)
assert_equal(texts[0], "Custom")
# delaunay triangulation warning
with warnings.catch_warnings(record=True):
plot_evoked_topomap(evoked, times, ch_type="mag", layout="auto")
assert_raises(
RuntimeError, plot_evoked_topomap, evoked, 0.1, "mag", proj="interactive"
) # projs have already been applied
# change to no-proj mode
evoked = read_evokeds(evoked_fname, "Left Auditory", baseline=(None, 0), proj=False)
plot_evoked_topomap(evoked, 0.1, "mag", proj="interactive")
assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(0.1, 50))
assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])
projs = read_proj(ecg_fname)
projs = [pp for pp in projs if pp["desc"].lower().find("eeg") < 0]
plot_projs_topomap(projs)
plt.close("all")
for ch in evoked.info["chs"]:
if ch["coil_type"] == FIFF.FIFFV_COIL_EEG:
if ch["eeg_loc"] is not None:
ch["eeg_loc"].fill(0)
ch["loc"].fill(0)
assert_raises(RuntimeError, plot_evoked_topomap, evoked, times, ch_type="eeg")
示例10: test_hash_evoked
def test_hash_evoked():
"""Test evoked hashing."""
ave = read_evokeds(fname, 0)
ave_2 = read_evokeds(fname, 0)
assert_equal(hash(ave), hash(ave_2))
# do NOT use assert_equal here, failing output is terrible
assert_true(pickle.dumps(ave) == pickle.dumps(ave_2))
ave_2.data[0, 0] -= 1
assert_not_equal(hash(ave), hash(ave_2))
示例11: test_evoked_to_nitime
def test_evoked_to_nitime():
""" Test to_nitime """
ave = read_evokeds(fname, 0)
evoked_ts = ave.to_nitime()
assert_equal(evoked_ts.data, ave.data)
picks2 = [1, 2]
ave = read_evokeds(fname, 0)
evoked_ts = ave.to_nitime(picks=picks2)
assert_equal(evoked_ts.data, ave.data[picks2])
示例12: test_hash_evoked
def test_hash_evoked():
"""Test evoked hashing."""
ave = read_evokeds(fname, 0)
ave_2 = read_evokeds(fname, 0)
assert hash(ave) == hash(ave_2)
assert ave == ave_2
# do NOT use assert_equal here, failing output is terrible
assert pickle.dumps(ave) == pickle.dumps(ave_2)
ave_2.data[0, 0] -= 1
assert hash(ave) != hash(ave_2)
示例13: test_evoked_aspects
def test_evoked_aspects(aspect_kind, tmpdir):
"""Test handling of evoked aspects."""
# gh-6359
ave = read_evokeds(fname, 0)
ave._aspect_kind = aspect_kind
assert 'Evoked' in repr(ave)
# for completeness let's try a round-trip
temp_fname = op.join(str(tmpdir), 'test-ave.fif')
ave.save(temp_fname)
ave_2 = read_evokeds(temp_fname, condition=0)
assert_allclose(ave.data, ave_2.data)
assert ave.kind == ave_2.kind
示例14: test_plot_trans
def test_plot_trans():
"""Test plotting of -trans.fif files and MEG sensor layouts
"""
evoked = read_evokeds(evoked_fname)[0]
with warnings.catch_warnings(record=True): # 4D weight tables
bti = read_raw_bti(pdf_fname, config_fname, hs_fname, convert=True,
preload=False).info
infos = dict(
Neuromag=evoked.info,
CTF=read_raw_ctf(ctf_fname).info,
BTi=bti,
KIT=read_raw_kit(sqd_fname).info,
)
for system, info in infos.items():
ref_meg = False if system == 'KIT' else True
plot_trans(info, trans_fname, subject='sample', meg_sensors=True,
subjects_dir=subjects_dir, ref_meg=ref_meg)
# KIT ref sensor coil def not defined
assert_raises(RuntimeError, plot_trans, infos['KIT'], None,
meg_sensors=True, ref_meg=True)
info = infos['Neuromag']
assert_raises(ValueError, plot_trans, info, trans_fname,
subject='sample', subjects_dir=subjects_dir,
ch_type='bad-chtype')
assert_raises(TypeError, plot_trans, 'foo', trans_fname,
subject='sample', subjects_dir=subjects_dir)
# no-head version
plot_trans(info, None, meg_sensors=True, dig=True, coord_frame='head')
# EEG only with strange options
with warnings.catch_warnings(record=True) as w:
plot_trans(evoked.copy().pick_types(meg=False, eeg=True).info,
trans=trans_fname, meg_sensors=True)
assert_true(['Cannot plot MEG' in str(ww.message) for ww in w])
示例15: test_plot_topomap_neuromag122
def test_plot_topomap_neuromag122():
"""Test topomap plotting."""
res = 8
fast_test = dict(res=res, contours=0, sensors=False)
evoked = read_evokeds(evoked_fname, 'Left Auditory',
baseline=(None, 0))
evoked.pick_types(meg='grad')
evoked.pick_channels(evoked.ch_names[:122])
ch_names = ['MEG %03d' % k for k in range(1, 123)]
for c in evoked.info['chs']:
c['coil_type'] = FIFF.FIFFV_COIL_NM_122
evoked.rename_channels({c_old: c_new for (c_old, c_new) in
zip(evoked.ch_names, ch_names)})
layout = find_layout(evoked.info)
assert layout.kind.startswith('Neuromag_122')
evoked.plot_topomap(times=[0.1], **fast_test)
proj = Projection(active=False,
desc="test", kind=1,
data=dict(nrow=1, ncol=122,
row_names=None,
col_names=evoked.ch_names, data=np.ones(122)),
explained_var=0.5)
plot_projs_topomap([proj], info=evoked.info, **fast_test)
plot_projs_topomap([proj], layout=layout, **fast_test)
pytest.raises(RuntimeError, plot_projs_topomap, [proj], **fast_test)