本文整理汇总了Python中mne.Epochs.copy方法的典型用法代码示例。如果您正苦于以下问题:Python Epochs.copy方法的具体用法?Python Epochs.copy怎么用?Python Epochs.copy使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mne.Epochs
的用法示例。
在下文中一共展示了Epochs.copy方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_cov_mismatch
# 需要导入模块: from mne import Epochs [as 别名]
# 或者: from mne.Epochs import copy [as 别名]
def test_cov_mismatch():
"""Test estimation with MEG<->Head mismatch."""
raw = read_raw_fif(raw_fname).crop(0, 5).load_data()
events = find_events(raw, stim_channel='STI 014')
raw.pick_channels(raw.ch_names[:5])
raw.add_proj([], remove_existing=True)
epochs = Epochs(raw, events, None, tmin=-0.2, tmax=0., preload=True)
for kind in ('shift', 'None'):
epochs_2 = epochs.copy()
# This should be fine
with warnings.catch_warnings(record=True) as w:
compute_covariance([epochs, epochs_2])
assert_equal(len(w), 0)
if kind == 'shift':
epochs_2.info['dev_head_t']['trans'][:3, 3] += 0.001
else: # None
epochs_2.info['dev_head_t'] = None
assert_raises(ValueError, compute_covariance, [epochs, epochs_2])
assert_equal(len(w), 0)
compute_covariance([epochs, epochs_2], on_mismatch='ignore')
assert_equal(len(w), 0)
compute_covariance([epochs, epochs_2], on_mismatch='warn')
assert_raises(ValueError, compute_covariance, epochs,
on_mismatch='x')
assert_true(any('transform mismatch' in str(ww.message) for ww in w))
# This should work
epochs.info['dev_head_t'] = None
epochs_2.info['dev_head_t'] = None
compute_covariance([epochs, epochs_2], method=None)
示例2: test_epochs_copy
# 需要导入模块: from mne import Epochs [as 别名]
# 或者: from mne.Epochs import copy [as 别名]
def test_epochs_copy():
"""Test copy epochs
"""
epochs = Epochs(
raw, events[:5], event_id, tmin, tmax, picks=picks, baseline=(None, 0), preload=True, reject=reject, flat=flat
)
copied = epochs.copy()
assert_array_equal(epochs._data, copied._data)
epochs = Epochs(
raw, events[:5], event_id, tmin, tmax, picks=picks, baseline=(None, 0), preload=False, reject=reject, flat=flat
)
copied = epochs.copy()
data = epochs.get_data()
copied_data = copied.get_data()
assert_array_equal(data, copied_data)
示例3: test_cov_mismatch
# 需要导入模块: from mne import Epochs [as 别名]
# 或者: from mne.Epochs import copy [as 别名]
def test_cov_mismatch():
"""Test estimation with MEG<->Head mismatch."""
raw = read_raw_fif(raw_fname, add_eeg_ref=False).crop(0, 5).load_data()
events = find_events(raw, stim_channel="STI 014")
raw.pick_channels(raw.ch_names[:5])
raw.add_proj([], remove_existing=True)
epochs = Epochs(raw, events, None, tmin=-0.2, tmax=0.0, preload=True, add_eeg_ref=False)
for kind in ("shift", "None"):
epochs_2 = epochs.copy()
# This should be fine
with warnings.catch_warnings(record=True) as w:
compute_covariance([epochs, epochs_2])
assert_equal(len(w), 0)
if kind == "shift":
epochs_2.info["dev_head_t"]["trans"][:3, 3] += 0.001
else: # None
epochs_2.info["dev_head_t"] = None
assert_raises(ValueError, compute_covariance, [epochs, epochs_2])
assert_equal(len(w), 0)
compute_covariance([epochs, epochs_2], on_mismatch="ignore")
assert_equal(len(w), 0)
compute_covariance([epochs, epochs_2], on_mismatch="warn")
assert_raises(ValueError, compute_covariance, epochs, on_mismatch="x")
assert_true(any("transform mismatch" in str(ww.message) for ww in w))
# This should work
epochs.info["dev_head_t"] = None
epochs_2.info["dev_head_t"] = None
compute_covariance([epochs, epochs_2], method=None)
示例4: test_cov_mismatch
# 需要导入模块: from mne import Epochs [as 别名]
# 或者: from mne.Epochs import copy [as 别名]
def test_cov_mismatch():
"""Test estimation with MEG<->Head mismatch."""
raw = read_raw_fif(raw_fname).crop(0, 5).load_data()
events = find_events(raw, stim_channel='STI 014')
raw.pick_channels(raw.ch_names[:5])
raw.add_proj([], remove_existing=True)
epochs = Epochs(raw, events, None, tmin=-0.2, tmax=0., preload=True)
for kind in ('shift', 'None'):
epochs_2 = epochs.copy()
# This should be fine
compute_covariance([epochs, epochs_2])
if kind == 'shift':
epochs_2.info['dev_head_t']['trans'][:3, 3] += 0.001
else: # None
epochs_2.info['dev_head_t'] = None
pytest.raises(ValueError, compute_covariance, [epochs, epochs_2])
compute_covariance([epochs, epochs_2], on_mismatch='ignore')
with pytest.raises(RuntimeWarning, match='transform mismatch'):
compute_covariance([epochs, epochs_2], on_mismatch='warn')
pytest.raises(ValueError, compute_covariance, epochs,
on_mismatch='x')
# This should work
epochs.info['dev_head_t'] = None
epochs_2.info['dev_head_t'] = None
compute_covariance([epochs, epochs_2], method=None)
示例5: test_ica_full_data_recovery
# 需要导入模块: from mne import Epochs [as 别名]
# 或者: from mne.Epochs import copy [as 别名]
def test_ica_full_data_recovery(method):
"""Test recovery of full data when no source is rejected."""
# Most basic recovery
_skip_check_picard(method)
raw = read_raw_fif(raw_fname).crop(0.5, stop).load_data()
events = read_events(event_name)
picks = pick_types(raw.info, meg=True, stim=False, ecg=False,
eog=False, exclude='bads')[:10]
with pytest.warns(RuntimeWarning, match='projection'):
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True)
evoked = epochs.average()
n_channels = 5
data = raw._data[:n_channels].copy()
data_epochs = epochs.get_data()
data_evoked = evoked.data
raw.set_annotations(Annotations([0.5], [0.5], ['BAD']))
methods = [method]
for method in methods:
stuff = [(2, n_channels, True), (2, n_channels // 2, False)]
for n_components, n_pca_components, ok in stuff:
ica = ICA(n_components=n_components, random_state=0,
max_pca_components=n_pca_components,
n_pca_components=n_pca_components,
method=method, max_iter=1)
with pytest.warns(UserWarning, match=None): # sometimes warns
ica.fit(raw, picks=list(range(n_channels)))
raw2 = ica.apply(raw.copy(), exclude=[])
if ok:
assert_allclose(data[:n_channels], raw2._data[:n_channels],
rtol=1e-10, atol=1e-15)
else:
diff = np.abs(data[:n_channels] - raw2._data[:n_channels])
assert (np.max(diff) > 1e-14)
ica = ICA(n_components=n_components, method=method,
max_pca_components=n_pca_components,
n_pca_components=n_pca_components, random_state=0)
with pytest.warns(None): # sometimes warns
ica.fit(epochs, picks=list(range(n_channels)))
epochs2 = ica.apply(epochs.copy(), exclude=[])
data2 = epochs2.get_data()[:, :n_channels]
if ok:
assert_allclose(data_epochs[:, :n_channels], data2,
rtol=1e-10, atol=1e-15)
else:
diff = np.abs(data_epochs[:, :n_channels] - data2)
assert (np.max(diff) > 1e-14)
evoked2 = ica.apply(evoked.copy(), exclude=[])
data2 = evoked2.data[:n_channels]
if ok:
assert_allclose(data_evoked[:n_channels], data2,
rtol=1e-10, atol=1e-15)
else:
diff = np.abs(evoked.data[:n_channels] - data2)
assert (np.max(diff) > 1e-14)
pytest.raises(ValueError, ICA, method='pizza-decomposision')
示例6: test_ica_full_data_recovery
# 需要导入模块: from mne import Epochs [as 别名]
# 或者: from mne.Epochs import copy [as 别名]
def test_ica_full_data_recovery():
"""Test recovery of full data when no source is rejected"""
# Most basic recovery
raw = Raw(raw_fname).crop(0.5, stop, copy=False)
raw.load_data()
events = read_events(event_name)
picks = pick_types(raw.info, meg=True, stim=False, ecg=False,
eog=False, exclude='bads')[:10]
with warnings.catch_warnings(record=True): # bad proj
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True)
evoked = epochs.average()
n_channels = 5
data = raw._data[:n_channels].copy()
data_epochs = epochs.get_data()
data_evoked = evoked.data
for method in ['fastica']:
stuff = [(2, n_channels, True), (2, n_channels // 2, False)]
for n_components, n_pca_components, ok in stuff:
ica = ICA(n_components=n_components,
max_pca_components=n_pca_components,
n_pca_components=n_pca_components,
method=method, max_iter=1)
with warnings.catch_warnings(record=True):
ica.fit(raw, picks=list(range(n_channels)))
raw2 = ica.apply(raw.copy(), exclude=[])
if ok:
assert_allclose(data[:n_channels], raw2._data[:n_channels],
rtol=1e-10, atol=1e-15)
else:
diff = np.abs(data[:n_channels] - raw2._data[:n_channels])
assert_true(np.max(diff) > 1e-14)
ica = ICA(n_components=n_components,
max_pca_components=n_pca_components,
n_pca_components=n_pca_components)
with warnings.catch_warnings(record=True):
ica.fit(epochs, picks=list(range(n_channels)))
epochs2 = ica.apply(epochs.copy(), exclude=[])
data2 = epochs2.get_data()[:, :n_channels]
if ok:
assert_allclose(data_epochs[:, :n_channels], data2,
rtol=1e-10, atol=1e-15)
else:
diff = np.abs(data_epochs[:, :n_channels] - data2)
assert_true(np.max(diff) > 1e-14)
evoked2 = ica.apply(evoked.copy(), exclude=[])
data2 = evoked2.data[:n_channels]
if ok:
assert_allclose(data_evoked[:n_channels], data2,
rtol=1e-10, atol=1e-15)
else:
diff = np.abs(evoked.data[:n_channels] - data2)
assert_true(np.max(diff) > 1e-14)
assert_raises(ValueError, ICA, method='pizza-decomposision')
示例7: test_equalize_channels
# 需要导入模块: from mne import Epochs [as 别名]
# 或者: from mne.Epochs import copy [as 别名]
def test_equalize_channels():
"""Test equalization of channels
"""
epochs1 = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), proj=False)
epochs2 = epochs1.copy()
ch_names = epochs1.ch_names[2:]
epochs1.drop_channels(epochs1.ch_names[:1])
epochs2.drop_channels(epochs2.ch_names[1:2])
my_comparison = [epochs1, epochs2]
equalize_channels(my_comparison)
for e in my_comparison:
assert_equal(ch_names, e.ch_names)
示例8: test_epochs_proj_mixin
# 需要导入模块: from mne import Epochs [as 别名]
# 或者: from mne.Epochs import copy [as 别名]
def test_epochs_proj_mixin():
"""Test SSP proj methods from ProjMixin class
"""
for proj in [True, False]:
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), proj=proj)
assert_true(all(p['active'] == proj for p in epochs.info['projs']))
# test adding / deleting proj
if proj:
epochs.get_data()
assert_true(all(p['active'] == proj for p in epochs.info['projs']))
assert_raises(ValueError, epochs.add_proj, epochs.info['projs'][0],
{'remove_existing': True})
assert_raises(ValueError, epochs.add_proj, 'spam')
assert_raises(ValueError, epochs.del_proj, 0)
else:
projs = deepcopy(epochs.info['projs'])
n_proj = len(epochs.info['projs'])
epochs.del_proj(0)
assert_true(len(epochs.info['projs']) == n_proj - 1)
epochs.add_proj(projs, remove_existing=False)
assert_true(len(epochs.info['projs']) == 2 * n_proj - 1)
epochs.add_proj(projs, remove_existing=True)
assert_true(len(epochs.info['projs']) == n_proj)
for preload in [True, False]:
print 'preload is %s' % preload
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), proj=False, preload=preload,
add_eeg_ref=True, verbose=True)
epochs2 = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), proj=True, preload=preload,
add_eeg_ref=True)
assert_allclose(epochs.copy().apply_proj().get_data()[0],
epochs2.get_data()[0])
# make sure the preprocssing works on copies by calling
# get_data twice
assert_array_equal(epochs2.get_data(), epochs2.get_data())
data = epochs.get_data().copy()
data2 = np.array([e for e in epochs])
assert_array_equal(data, data2)
epochs.apply_proj()
assert_array_equal(epochs._projector, epochs2._projector)
assert_allclose(epochs._data, epochs2.get_data())
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=None, proj=False, add_eeg_ref=True)
data = epochs.get_data().copy()
epochs.apply_proj()
assert_allclose(np.dot(epochs._projector, data[0]), epochs._data[0])
示例9: test_apply_reference
# 需要导入模块: from mne import Epochs [as 别名]
# 或者: from mne.Epochs import copy [as 别名]
def test_apply_reference():
"""Test base function for rereferencing"""
raw = Raw(fif_fname, preload=True)
# Rereference raw data by creating a copy of original data
reref, ref_data = _apply_reference(
raw.copy(), ref_from=['EEG 001', 'EEG 002'])
assert_true(reref.info['custom_ref_applied'])
_test_reference(raw, reref, ref_data, ['EEG 001', 'EEG 002'])
# The CAR reference projection should have been removed by the function
assert_true(not _has_eeg_average_ref_proj(reref.info['projs']))
# Test that disabling the reference does not break anything
reref, ref_data = _apply_reference(raw, [])
assert_array_equal(raw._data, reref._data)
# Test that data is modified in place when copy=False
reref, ref_data = _apply_reference(raw, ['EEG 001', 'EEG 002'])
assert_true(raw is reref)
# Test re-referencing Epochs object
raw = Raw(fif_fname, preload=False, add_eeg_ref=False)
events = read_events(eve_fname)
picks_eeg = pick_types(raw.info, meg=False, eeg=True)
epochs = Epochs(raw, events=events, event_id=1, tmin=-0.2, tmax=0.5,
picks=picks_eeg, preload=True)
reref, ref_data = _apply_reference(
epochs.copy(), ref_from=['EEG 001', 'EEG 002'])
assert_true(reref.info['custom_ref_applied'])
_test_reference(epochs, reref, ref_data, ['EEG 001', 'EEG 002'])
# Test re-referencing Evoked object
evoked = epochs.average()
reref, ref_data = _apply_reference(
evoked.copy(), ref_from=['EEG 001', 'EEG 002'])
assert_true(reref.info['custom_ref_applied'])
_test_reference(evoked, reref, ref_data, ['EEG 001', 'EEG 002'])
# Test invalid input
raw_np = Raw(fif_fname, preload=False)
assert_raises(RuntimeError, _apply_reference, raw_np, ['EEG 001'])
示例10: extract_X_and_y
# 需要导入模块: from mne import Epochs [as 别名]
# 或者: from mne.Epochs import copy [as 别名]
def extract_X_and_y(raw_nparray, raw_info, opts, verbose=False):
# need to make a new RawArray, because once we apply filter, we mutate its internal _data
raw = RawArray(raw_nparray, raw_info, verbose=verbose)
picks = pick_types(raw.info, eeg=True)
picks = getChannelSubsetMotorBand()
# picks = getChannelSubsetFront()
# picks = getChannelSubsetBack()
# print picks
# Apply band-pass filter
raw._data[picks] = lfilter(opts.b, opts.a, raw._data[picks])
consecutive = True
train_events = mne.find_events(raw, shortest_event=0, consecutive=consecutive, verbose=verbose)
train_epochs = Epochs(
raw,
train_events,
opts.event_labels,
tmin=opts.epoch_full_tmin,
tmax=opts.epoch_full_tmax,
proj=True,
picks=picks,
baseline=None,
preload=True,
add_eeg_ref=False,
verbose=verbose,
)
epochs_trimmed = train_epochs.copy().crop(tmin=opts.epoch_trim_tmin, tmax=opts.epoch_trim_tmax)
if verbose:
print "train: epochs", epochs_trimmed
X = epochs_trimmed.get_data()
y = epochs_trimmed.events[:, -1] - 2
if verbose:
print "y", y.shape
return [X, y]
示例11: test_generalization_across_time
# 需要导入模块: from mne import Epochs [as 别名]
# 或者: from mne.Epochs import copy [as 别名]
def test_generalization_across_time():
"""Test time generalization decoding
"""
from sklearn.svm import SVC
raw = io.Raw(raw_fname, preload=False)
events = read_events(event_name)
picks = pick_types(raw.info, meg='mag', stim=False, ecg=False,
eog=False, exclude='bads')
picks = picks[0:2]
decim = 30
# Test on time generalization within one condition
with warnings.catch_warnings(record=True):
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True, decim=decim)
# Test default running
gat = GeneralizationAcrossTime()
assert_equal("<GAT | no fit, no prediction, no score>", "%s" % gat)
with warnings.catch_warnings(record=True):
gat.fit(epochs)
assert_equal("<GAT | fitted, start : -0.200 (s), stop : 0.499 (s), no "
"prediction, no score>", '%s' % gat)
gat.predict(epochs)
assert_equal("<GAT | fitted, start : -0.200 (s), stop : 0.499 (s), "
"predict_type : 'predict' on 15 epochs, no score>",
"%s" % gat)
gat.score(epochs)
assert_equal("<GAT | fitted, start : -0.200 (s), stop : 0.499 (s), "
"predict_type : 'predict' on 15 epochs,\n scored "
"(accuracy_score)>", "%s" % gat)
with warnings.catch_warnings(record=True):
gat.fit(epochs, y=epochs.events[:, 2])
old_type = gat.predict_type
gat.predict_type = 'foo'
assert_raises(ValueError, gat.predict, epochs)
gat.predict_type = old_type
old_mode = gat.predict_mode
gat.predict_mode = 'super-foo-mode'
assert_raises(ValueError, gat.predict, epochs)
gat.predict_mode = old_mode
gat.score(epochs, y=epochs.events[:, 2])
assert_true("accuracy_score" in '%s' % gat.scorer_)
epochs2 = epochs.copy()
# check _DecodingTime class
assert_equal("<DecodingTime | start: -0.200 (s), stop: 0.499 (s), step: "
"0.047 (s), length: 0.047 (s), n_time_windows: 15>",
"%s" % gat.train_times)
assert_equal("<DecodingTime | start: -0.200 (s), stop: 0.499 (s), step: "
"0.047 (s), length: 0.047 (s), n_time_windows: 15 x 15>",
"%s" % gat.test_times_)
# the y-check
gat.predict_mode = 'mean-prediction'
epochs2.events[:, 2] += 10
assert_raises(ValueError, gat.score, epochs2)
gat.predict_mode = 'cross-validation'
# Test basics
# --- number of trials
assert_true(gat.y_train_.shape[0] ==
gat.y_true_.shape[0] ==
gat.y_pred_.shape[2] == 14)
# --- number of folds
assert_true(np.shape(gat.estimators_)[1] == gat.cv)
# --- length training size
assert_true(len(gat.train_times['slices']) == 15 ==
np.shape(gat.estimators_)[0])
# --- length testing sizes
assert_true(len(gat.test_times_['slices']) == 15 ==
np.shape(gat.scores_)[0])
assert_true(len(gat.test_times_['slices'][0]) == 15 ==
np.shape(gat.scores_)[1])
# Test longer time window
gat = GeneralizationAcrossTime(train_times={'length': .100})
with warnings.catch_warnings(record=True):
gat2 = gat.fit(epochs)
assert_true(gat is gat2) # return self
assert_true(hasattr(gat2, 'cv_'))
assert_true(gat2.cv_ != gat.cv)
scores = gat.score(epochs)
assert_true(isinstance(scores, list)) # type check
assert_equal(len(scores[0]), len(scores)) # shape check
assert_equal(len(gat.test_times_['slices'][0][0]), 2)
# Decim training steps
gat = GeneralizationAcrossTime(train_times={'step': .100})
with warnings.catch_warnings(record=True):
gat.fit(epochs)
gat.score(epochs)
assert_equal(len(gat.scores_), 8)
# Test start stop training
gat = GeneralizationAcrossTime(train_times={'start': 0.090,
#.........这里部分代码省略.........
示例12: test_epochs_proj_mixin
# 需要导入模块: from mne import Epochs [as 别名]
# 或者: from mne.Epochs import copy [as 别名]
def test_epochs_proj_mixin():
"""Test SSP proj methods from ProjMixin class
"""
for proj in [True, False]:
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks, baseline=(None, 0), proj=proj)
assert_true(all(p["active"] == proj for p in epochs.info["projs"]))
# test adding / deleting proj
if proj:
epochs.get_data()
assert_true(all(p["active"] == proj for p in epochs.info["projs"]))
assert_raises(ValueError, epochs.add_proj, epochs.info["projs"][0], {"remove_existing": True})
assert_raises(ValueError, epochs.add_proj, "spam")
assert_raises(ValueError, epochs.del_proj, 0)
else:
projs = deepcopy(epochs.info["projs"])
n_proj = len(epochs.info["projs"])
epochs.del_proj(0)
assert_true(len(epochs.info["projs"]) == n_proj - 1)
epochs.add_proj(projs, remove_existing=False)
assert_true(len(epochs.info["projs"]) == 2 * n_proj - 1)
epochs.add_proj(projs, remove_existing=True)
assert_true(len(epochs.info["projs"]) == n_proj)
# catch no-gos.
# wrong proj argument
assert_raises(
ValueError, Epochs, raw, events[:4], event_id, tmin, tmax, picks=picks, baseline=(None, 0), proj="crazy"
)
# delayed without reject params
assert_raises(
RuntimeError,
Epochs,
raw,
events[:4],
event_id,
tmin,
tmax,
picks=picks,
baseline=(None, 0),
proj="delayed",
reject=None,
)
for preload in [True, False]:
epochs = Epochs(
raw,
events[:4],
event_id,
tmin,
tmax,
picks=picks,
baseline=(None, 0),
proj="delayed",
preload=preload,
add_eeg_ref=True,
verbose=True,
reject=reject,
)
epochs2 = Epochs(
raw,
events[:4],
event_id,
tmin,
tmax,
picks=picks,
baseline=(None, 0),
proj=True,
preload=preload,
add_eeg_ref=True,
reject=reject,
)
assert_allclose(epochs.copy().apply_proj().get_data()[0], epochs2.get_data()[0])
# make sure data output is constant across repeated calls
# e.g. drop bads
assert_array_equal(epochs.get_data(), epochs.get_data())
assert_array_equal(epochs2.get_data(), epochs2.get_data())
# test epochs.next calls
data = epochs.get_data().copy()
data2 = np.array([e for e in epochs])
assert_array_equal(data, data2)
# cross application from processing stream 1 to 2
epochs.apply_proj()
assert_array_equal(epochs._projector, epochs2._projector)
assert_allclose(epochs._data, epochs2.get_data())
# test mixin against manual application
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks, baseline=None, proj=False, add_eeg_ref=True)
data = epochs.get_data().copy()
epochs.apply_proj()
assert_allclose(np.dot(epochs._projector, data[0]), epochs._data[0])
示例13: Epochs
# 需要导入模块: from mne import Epochs [as 别名]
# 或者: from mne.Epochs import copy [as 别名]
# Extract epochs from filtered data, padded by window size
epochs = Epochs(raw_filter, events, event_id, tmin - w_size, tmax + w_size,
proj=False, baseline=None, preload=True)
epochs.drop_bad()
y = le.fit_transform(epochs.events[:, 2])
# Roll covariance, csp and lda over time
for t, w_time in enumerate(centered_w_times):
# Center the min and max of the window
w_tmin = w_time - w_size / 2.
w_tmax = w_time + w_size / 2.
# Crop data into time-window of interest
X = epochs.copy().crop(w_tmin, w_tmax).get_data()
# Save mean scores over folds for each frequency and time window
tf_scores[freq, t] = np.mean(cross_val_score(estimator=clf, X=X, y=y,
scoring='roc_auc', cv=cv,
n_jobs=1), axis=0)
###############################################################################
# Plot time-frequency results
# Set up time frequency object
av_tfr = AverageTFR(create_info(['freq'], sfreq), tf_scores[np.newaxis, :],
centered_w_times, freqs[1:], 1)
chance = np.mean(y) # set chance level to white in the plot
av_tfr.plot([0], vmin=chance, title="Time-Frequency Decoding Scores",
示例14: test_ica_core
# 需要导入模块: from mne import Epochs [as 别名]
# 或者: from mne.Epochs import copy [as 别名]
def test_ica_core(method):
"""Test ICA on raw and epochs."""
_skip_check_picard(method)
raw = read_raw_fif(raw_fname).crop(1.5, stop).load_data()
# XXX. The None cases helped revealing bugs but are time consuming.
test_cov = read_cov(test_cov_name)
events = read_events(event_name)
picks = pick_types(raw.info, meg=True, stim=False, ecg=False,
eog=False, exclude='bads')
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True)
noise_cov = [None, test_cov]
# removed None cases to speed up...
n_components = [2, 1.0] # for future dbg add cases
max_pca_components = [3]
picks_ = [picks]
methods = [method]
iter_ica_params = product(noise_cov, n_components, max_pca_components,
picks_, methods)
# # test init catchers
pytest.raises(ValueError, ICA, n_components=3, max_pca_components=2)
pytest.raises(ValueError, ICA, n_components=2.3, max_pca_components=2)
# test essential core functionality
for n_cov, n_comp, max_n, pcks, method in iter_ica_params:
# Test ICA raw
ica = ICA(noise_cov=n_cov, n_components=n_comp,
max_pca_components=max_n, n_pca_components=max_n,
random_state=0, method=method, max_iter=1)
pytest.raises(ValueError, ica.__contains__, 'mag')
print(ica) # to test repr
# test fit checker
pytest.raises(RuntimeError, ica.get_sources, raw)
pytest.raises(RuntimeError, ica.get_sources, epochs)
# test decomposition
with pytest.warns(UserWarning, match='did not converge'):
ica.fit(raw, picks=pcks, start=start, stop=stop)
repr(ica) # to test repr
assert ('mag' in ica) # should now work without error
# test re-fit
unmixing1 = ica.unmixing_matrix_
with pytest.warns(UserWarning, match='did not converge'):
ica.fit(raw, picks=pcks, start=start, stop=stop)
assert_array_almost_equal(unmixing1, ica.unmixing_matrix_)
raw_sources = ica.get_sources(raw)
# test for #3804
assert_equal(raw_sources._filenames, [None])
print(raw_sources)
# test for gh-6271 (scaling of ICA traces)
fig = raw_sources.plot()
assert len(fig.axes[0].lines) in (4, 5)
for line in fig.axes[0].lines[1:-1]: # first and last are markers
y = line.get_ydata()
assert np.ptp(y) < 10
plt.close('all')
sources = raw_sources[:, :][0]
assert (sources.shape[0] == ica.n_components_)
# test preload filter
raw3 = raw.copy()
raw3.preload = False
pytest.raises(RuntimeError, ica.apply, raw3,
include=[1, 2])
#######################################################################
# test epochs decomposition
ica = ICA(noise_cov=n_cov, n_components=n_comp,
max_pca_components=max_n, n_pca_components=max_n,
random_state=0, method=method)
with pytest.warns(None): # sometimes warns
ica.fit(epochs, picks=picks)
data = epochs.get_data()[:, 0, :]
n_samples = np.prod(data.shape)
assert_equal(ica.n_samples_, n_samples)
print(ica) # to test repr
sources = ica.get_sources(epochs).get_data()
assert (sources.shape[1] == ica.n_components_)
pytest.raises(ValueError, ica.score_sources, epochs,
target=np.arange(1))
# test preload filter
epochs3 = epochs.copy()
epochs3.preload = False
pytest.raises(RuntimeError, ica.apply, epochs3,
include=[1, 2])
# test for bug with whitener updating
_pre_whitener = ica.pre_whitener_.copy()
epochs._data[:, 0, 10:15] *= 1e12
#.........这里部分代码省略.........
示例15: test_generalization_across_time
# 需要导入模块: from mne import Epochs [as 别名]
# 或者: from mne.Epochs import copy [as 别名]
def test_generalization_across_time():
"""Test time generalization decoding
"""
from sklearn.svm import SVC
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import mean_squared_error
raw = io.Raw(raw_fname, preload=False)
events = read_events(event_name)
picks = pick_types(raw.info, meg='mag', stim=False, ecg=False,
eog=False, exclude='bads')
picks = picks[0:2]
decim = 30
# Test on time generalization within one condition
with warnings.catch_warnings(record=True):
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True, decim=decim)
# Test default running
gat = GeneralizationAcrossTime()
assert_equal("<GAT | no fit, no prediction, no score>", "%s" % gat)
assert_raises(ValueError, gat.fit, epochs, picks='foo')
with warnings.catch_warnings(record=True):
# check classic fit + check manual picks
gat.fit(epochs, picks=[0])
# check optional y as array
gat.fit(epochs, y=epochs.events[:, 2])
# check optional y as list
gat.fit(epochs, y=epochs.events[:, 2].tolist())
assert_equal(len(gat.picks_), len(gat.ch_names), 1)
assert_equal("<GAT | fitted, start : -0.200 (s), stop : 0.499 (s), no "
"prediction, no score>", '%s' % gat)
assert_equal(gat.ch_names, epochs.ch_names)
gat.predict(epochs)
assert_equal("<GAT | fitted, start : -0.200 (s), stop : 0.499 (s), "
"predicted 14 epochs, no score>",
"%s" % gat)
gat.score(epochs)
gat.score(epochs, y=epochs.events[:, 2])
gat.score(epochs, y=epochs.events[:, 2].tolist())
assert_equal("<GAT | fitted, start : -0.200 (s), stop : 0.499 (s), "
"predicted 14 epochs,\n scored "
"(accuracy_score)>", "%s" % gat)
with warnings.catch_warnings(record=True):
gat.fit(epochs, y=epochs.events[:, 2])
old_mode = gat.predict_mode
gat.predict_mode = 'super-foo-mode'
assert_raises(ValueError, gat.predict, epochs)
gat.predict_mode = old_mode
gat.score(epochs, y=epochs.events[:, 2])
assert_true("accuracy_score" in '%s' % gat.scorer_)
epochs2 = epochs.copy()
# check _DecodingTime class
assert_equal("<DecodingTime | start: -0.200 (s), stop: 0.499 (s), step: "
"0.047 (s), length: 0.047 (s), n_time_windows: 15>",
"%s" % gat.train_times)
assert_equal("<DecodingTime | start: -0.200 (s), stop: 0.499 (s), step: "
"0.047 (s), length: 0.047 (s), n_time_windows: 15 x 15>",
"%s" % gat.test_times_)
# the y-check
gat.predict_mode = 'mean-prediction'
epochs2.events[:, 2] += 10
gat_ = copy.deepcopy(gat)
assert_raises(ValueError, gat_.score, epochs2)
gat.predict_mode = 'cross-validation'
# Test basics
# --- number of trials
assert_true(gat.y_train_.shape[0] ==
gat.y_true_.shape[0] ==
len(gat.y_pred_[0][0]) == 14)
# --- number of folds
assert_true(np.shape(gat.estimators_)[1] == gat.cv)
# --- length training size
assert_true(len(gat.train_times['slices']) == 15 ==
np.shape(gat.estimators_)[0])
# --- length testing sizes
assert_true(len(gat.test_times_['slices']) == 15 ==
np.shape(gat.scores_)[0])
assert_true(len(gat.test_times_['slices'][0]) == 15 ==
np.shape(gat.scores_)[1])
# Test longer time window
gat = GeneralizationAcrossTime(train_times={'length': .100})
with warnings.catch_warnings(record=True):
gat2 = gat.fit(epochs)
assert_true(gat is gat2) # return self
assert_true(hasattr(gat2, 'cv_'))
assert_true(gat2.cv_ != gat.cv)
scores = gat.score(epochs)
assert_true(isinstance(scores, list)) # type check
assert_equal(len(scores[0]), len(scores)) # shape check
assert_equal(len(gat.test_times_['slices'][0][0]), 2)
# Decim training steps
gat = GeneralizationAcrossTime(train_times={'step': .100})
#.........这里部分代码省略.........