MRG: Modernize testing (#5308)

* ENH: Modernize tests

* FIX: Fix for newer traits

* FIX: Looser Subplot type check

* FIX: Fix docstring check

* FIX: Spelling

* FIX: Makefile
This commit is contained in:
Eric Larson
2018-07-06 10:18:33 -04:00
committed by Alexandre Gramfort
parent a44caaa3a5
commit 1442cc4b8c
126 changed files with 2422 additions and 2547 deletions
+5 -5
View File
@@ -14,7 +14,7 @@ matrix:
# No data + style testing
- os: linux
env: DEPS=nodata MNE_DONTWRITE_HOME=true MNE_FORCE_SERIAL=true MNE_SKIP_NETWORK_TEST=1
CONDA_DEPENDENCIES="numpy scipy matplotlib sphinx nose pytest pytest-cov"
CONDA_DEPENDENCIES="numpy scipy matplotlib sphinx pytest pytest-cov"
PIP_DEPENDENCIES="flake8 numpydoc codespell git+git://github.com/PyCQA/pydocstyle.git codecov check-manifest pytest-sugar"
OPTION="--doctest-ignore-import-errors"
@@ -45,21 +45,21 @@ matrix:
# 2.7 Old dependencies
- os: linux
env: PYTHON_VERSION=2.7
CONDA_DEPENDENCIES="numpy=1.8 scipy=0.12 matplotlib=1.3 pandas=0.13 scikit-learn=0.15 nose pytest pytest-cov"
CONDA_DEPENDENCIES="numpy=1.8 scipy=0.12 matplotlib=1.3 pandas=0.13 scikit-learn=0.15 pytest pytest-cov"
SPLIT=0
- os: linux
env: PYTHON_VERSION=2.7
CONDA_DEPENDENCIES="numpy=1.8 scipy=0.12 matplotlib=1.3 pandas=0.13 scikit-learn=0.15 nose pytest pytest-cov"
CONDA_DEPENDENCIES="numpy=1.8 scipy=0.12 matplotlib=1.3 pandas=0.13 scikit-learn=0.15 pytest pytest-cov"
SPLIT=1
# Minimal
- os: linux
env: DEPS=minimial
CONDA_DEPENDENCIES="numpy scipy matplotlib nose pytest pytest-cov"
CONDA_DEPENDENCIES="numpy scipy matplotlib pytest pytest-cov"
SPLIT=0
- os: linux
env: DEPS=minimial
CONDA_DEPENDENCIES="numpy scipy matplotlib nose pytest pytest-cov"
CONDA_DEPENDENCIES="numpy scipy matplotlib pytest pytest-cov"
SPLIT=1
# Setup anaconda
+2 -3
View File
@@ -104,7 +104,7 @@ codespell-error: # running on travis
pydocstyle:
@echo "Running pydocstyle"
@pydocstyle
@pydocstyle mne
docstring:
@echo "Running docstring tests"
@@ -134,5 +134,4 @@ build-doc-stable:
cd doc; make clean
cd doc; DISPLAY=:1.0 xvfb-run -n 1 -s "-screen 0 1280x1024x24 -noreset -ac +extension GLX +render" make html_stable
docstyle:
@pydocstyle
docstyle: pydocstyle
-1
View File
@@ -16,7 +16,6 @@ dependencies:
- pillow
- statsmodels
- jupyter
- nose
- pytest
- pytest-cov
- sphinx
-1
View File
@@ -15,7 +15,6 @@ dependencies:
- pillow
- statsmodels
- jupyter
- nose
- pytest
- pytest-cov
- sphinx
+3 -3
View File
@@ -2,7 +2,7 @@
# Britta Westner
#
# License: BSD 3 clause
from __future__ import print_function
import warnings
import os.path as op
import copy as cp
@@ -22,7 +22,7 @@ from mne.externals.six import advance_iterator
from mne.proj import compute_proj_evoked, make_projector
# Note that if this is the first test file, this will apply to all subsequent
# tests in a full nosetest:
# tests in a full test:
warnings.simplefilter('always') # ensure we can verify expected warnings
data_path = testing.data_path(download=False)
@@ -40,7 +40,7 @@ fname_label = op.join(subjects_dir, 'sample', 'label', 'aparc',
def _load_forward():
"""Load forward models"""
"""Load forward models."""
fwd_free = mne.read_forward_solution(fname_fwd)
fwd_free = mne.pick_types_forward(fwd_free, meg=True, eeg=False)
fwd_free = mne.convert_forward_solution(fwd_free, surf_ori=False)
+44 -46
View File
@@ -2,7 +2,6 @@ from copy import deepcopy
import os.path as op
import pytest
from nose.tools import assert_true, assert_raises
import numpy as np
from scipy import linalg
from scipy.spatial.distance import cdist
@@ -196,8 +195,8 @@ def test_lcmv():
max_stc = stc.data[idx]
tmax = stc.times[np.argmax(max_stc)]
assert_true(0.09 < tmax < 0.105, tmax)
assert_true(0.9 < np.max(max_stc) < 3., np.max(max_stc))
assert 0.09 < tmax < 0.105, tmax
assert 0.9 < np.max(max_stc) < 3., np.max(max_stc)
if fwd is forward:
# Test picking normal orientation (surface source space only)
@@ -212,12 +211,12 @@ def test_lcmv():
max_stc = stc_normal.data[idx]
tmax = stc_normal.times[np.argmax(max_stc)]
assert_true(0.04 < tmax < 0.11, tmax)
assert_true(0.4 < np.max(max_stc) < 2., np.max(max_stc))
assert 0.04 < tmax < 0.11, tmax
assert 0.4 < np.max(max_stc) < 2., np.max(max_stc)
# The amplitude of normal orientation results should always be
# smaller than free orientation results
assert_true((np.abs(stc_normal.data) <= stc.data).all())
assert (np.abs(stc_normal.data) <= stc.data).all()
# Test picking source orientation maximizing output source power
filters = make_lcmv(evoked.info, fwd, data_cov, reg=0.01,
@@ -229,8 +228,8 @@ def test_lcmv():
max_stc = np.abs(stc_max_power.data[idx])
tmax = stc.times[np.argmax(max_stc)]
assert_true(0.08 < tmax < 0.11, tmax)
assert_true(0.8 < np.max(max_stc) < 3., np.max(max_stc))
assert 0.08 < tmax < 0.11, tmax
assert 0.8 < np.max(max_stc) < 3., np.max(max_stc)
stc_max_power.data[:, :] = np.abs(stc_max_power.data)
@@ -244,7 +243,7 @@ def test_lcmv():
mean_stc_max_pow = \
stc_max_power.extract_label_time_course(label, fwd['src'],
mode='mean')
assert_true((np.abs(mean_stc - mean_stc_max_pow) < 0.5).all())
assert ((np.abs(mean_stc - mean_stc_max_pow) < 0.5).all())
# Test NAI weight normalization:
filters = make_lcmv(evoked.info, fwd, data_cov, reg=0.01,
@@ -269,7 +268,7 @@ def test_lcmv():
bem=sphere, eeg=False, meg=True)
# Test that we get an error if not reducing rank
assert_raises(ValueError, make_lcmv, evoked.info, fwd_sphere, data_cov,
pytest.raises(ValueError, make_lcmv, evoked.info, fwd_sphere, data_cov,
reg=0.1, noise_cov=noise_cov, weight_norm='unit-noise-gain',
pick_ori='max-power', reduce_rank=False)
@@ -286,44 +285,44 @@ def test_lcmv():
max_stc = stc_sphere.data[idx]
tmax = stc_sphere.times[np.argmax(max_stc)]
assert_true(0.08 < tmax < 0.11, tmax)
assert_true(0.4 < np.max(max_stc) < 2., np.max(max_stc))
assert 0.08 < tmax < 0.11, tmax
assert 0.4 < np.max(max_stc) < 2., np.max(max_stc)
# Test if fixed forward operator is detected when picking normal or
# max-power orientation
assert_raises(ValueError, make_lcmv, evoked.info, forward_fixed, data_cov,
pytest.raises(ValueError, make_lcmv, evoked.info, forward_fixed, data_cov,
reg=0.01, noise_cov=noise_cov, pick_ori='normal')
assert_raises(ValueError, make_lcmv, evoked.info, forward_fixed, data_cov,
pytest.raises(ValueError, make_lcmv, evoked.info, forward_fixed, data_cov,
reg=0.01, noise_cov=noise_cov, pick_ori='max-power')
# Test if non-surface oriented forward operator is detected when picking
# normal orientation
assert_raises(ValueError, make_lcmv, evoked.info, forward, data_cov,
pytest.raises(ValueError, make_lcmv, evoked.info, forward, data_cov,
reg=0.01, noise_cov=noise_cov, pick_ori='normal')
# Test if volume forward operator is detected when picking normal
# orientation
assert_raises(ValueError, make_lcmv, evoked.info, forward_vol, data_cov,
pytest.raises(ValueError, make_lcmv, evoked.info, forward_vol, data_cov,
reg=0.01, noise_cov=noise_cov, pick_ori='normal')
# Test if missing of noise covariance matrix is detected when more than
# one channel type is present in the data
assert_raises(ValueError, make_lcmv, evoked.info, forward_vol,
pytest.raises(ValueError, make_lcmv, evoked.info, forward_vol,
data_cov=data_cov, reg=0.01, noise_cov=None,
pick_ori='max-power')
# Test if not-yet-implemented orientation selections raise error with
# neural activity index
assert_raises(NotImplementedError, make_lcmv, evoked.info,
pytest.raises(NotImplementedError, make_lcmv, evoked.info,
forward_surf_ori, data_cov, reg=0.01, noise_cov=noise_cov,
pick_ori='normal', weight_norm='nai')
assert_raises(NotImplementedError, make_lcmv, evoked.info, forward_vol,
pytest.raises(NotImplementedError, make_lcmv, evoked.info, forward_vol,
data_cov, reg=0.01, noise_cov=noise_cov, pick_ori=None,
weight_norm='nai')
# Test if no weight-normalization and max-power source orientation throws
# an error
assert_raises(NotImplementedError, make_lcmv, evoked.info, forward_vol,
pytest.raises(NotImplementedError, make_lcmv, evoked.info, forward_vol,
data_cov, reg=0.01, noise_cov=noise_cov,
pick_ori='max-power', weight_norm=None)
@@ -332,7 +331,7 @@ def test_lcmv():
evoked_ch.pick_channels(evoked_ch.ch_names[1:])
filters = make_lcmv(evoked.info, forward_vol, data_cov, reg=0.01,
noise_cov=noise_cov)
assert_raises(ValueError, apply_lcmv, evoked_ch, filters,
pytest.raises(ValueError, apply_lcmv, evoked_ch, filters,
max_ori_out='signed')
# Test if discrepancies in channel selection of data and fwd model are
@@ -351,15 +350,15 @@ def test_lcmv():
# Test if non-matching SSP projection is detected in application of filter
raw_proj = deepcopy(raw)
raw_proj.del_proj()
assert_raises(ValueError, apply_lcmv_raw, raw_proj, filters,
pytest.raises(ValueError, apply_lcmv_raw, raw_proj, filters,
max_ori_out='signed')
# Test if setting reduce_rank to True returns a NotImplementedError
# when no orientation selection is done or pick_ori='normal'
assert_raises(NotImplementedError, make_lcmv, evoked.info, forward_vol,
pytest.raises(NotImplementedError, make_lcmv, evoked.info, forward_vol,
data_cov, noise_cov=noise_cov, pick_ori=None,
weight_norm='nai', reduce_rank=True)
assert_raises(NotImplementedError, make_lcmv, evoked.info,
pytest.raises(NotImplementedError, make_lcmv, evoked.info,
forward_surf_ori, data_cov, noise_cov=noise_cov,
pick_ori='normal', weight_norm='nai', reduce_rank=True)
@@ -373,7 +372,7 @@ def test_lcmv():
assert_array_equal(stcs[0].data, advance_iterator(stcs_).data)
epochs.drop_bad()
assert_true(len(epochs.events) == len(stcs))
assert (len(epochs.events) == len(stcs))
# average the single trial estimates
stc_avg = np.zeros_like(stcs[0].data)
@@ -418,9 +417,9 @@ def test_lcmv_raw():
# make sure we get an stc with vertices only in the lh
vertno = [forward['src'][0]['vertno'], forward['src'][1]['vertno']]
assert_true(len(stc.vertices[0]) == len(np.intersect1d(vertno[0],
label.vertices)))
assert_true(len(stc.vertices[1]) == 0)
assert len(stc.vertices[0]) == len(np.intersect1d(vertno[0],
label.vertices))
assert len(stc.vertices[1]) == 0
@testing.requires_testing_data
@@ -436,8 +435,8 @@ def test_lcmv_source_power():
max_source_idx = np.argmax(stc_source_power.data)
max_source_power = np.max(stc_source_power.data)
assert_true(max_source_idx == 0, max_source_idx)
assert_true(0.4 < max_source_power < 2.4, max_source_power)
assert max_source_idx == 0, max_source_idx
assert 0.4 < max_source_power < 2.4, max_source_power
# Test picking normal orientation and using a list of CSD matrices
stc_normal = _lcmv_source_power(
@@ -446,22 +445,21 @@ def test_lcmv_source_power():
# The normal orientation results should always be smaller than free
# orientation results
assert_true((np.abs(stc_normal.data[:, 0]) <=
stc_source_power.data[:, 0]).all())
assert (np.abs(stc_normal.data[:, 0]) <= stc_source_power.data[:, 0]).all()
# Test if fixed forward operator is detected when picking normal
# orientation
assert_raises(ValueError, _lcmv_source_power, raw.info, forward_fixed,
pytest.raises(ValueError, _lcmv_source_power, raw.info, forward_fixed,
noise_cov, data_cov, pick_ori="normal")
# Test if non-surface oriented forward operator is detected when picking
# normal orientation
assert_raises(ValueError, _lcmv_source_power, raw.info, forward, noise_cov,
pytest.raises(ValueError, _lcmv_source_power, raw.info, forward, noise_cov,
data_cov, pick_ori="normal")
# Test if volume forward operator is detected when picking normal
# orientation
assert_raises(ValueError, _lcmv_source_power, epochs.info, forward_vol,
pytest.raises(ValueError, _lcmv_source_power, epochs.info, forward_vol,
noise_cov, data_cov, pick_ori="normal")
@@ -530,13 +528,13 @@ def test_tf_lcmv():
reg=reg, label=label, weight_norm='unit-noise-gain')
source_power.append(stc_source_power.data)
assert_raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax,
pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax,
tstep, win_lengths, freq_bins, reg=reg, label=label)
stcs = tf_lcmv(epochs, forward, noise_covs, tmin, tmax, tstep,
win_lengths, freq_bins, reg=reg, label=label, raw=raw)
assert_true(len(stcs) == len(freq_bins))
assert_true(stcs[0].shape[1] == 4)
assert (len(stcs) == len(freq_bins))
assert (stcs[0].shape[1] == 4)
# Averaging all time windows that overlap the time period 0 to 100 ms
source_power = np.mean(source_power, axis=0)
@@ -548,31 +546,31 @@ def test_tf_lcmv():
assert_array_almost_equal(stc.data[:, 2], source_power[:, 0])
# Test if using unsupported max-power orientation is detected
assert_raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax,
pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax,
tstep, win_lengths, freq_bins=freq_bins,
pick_ori='max-power')
# Test if incorrect number of noise CSDs is detected
# Test if incorrect number of noise covariances is detected
assert_raises(ValueError, tf_lcmv, epochs, forward, [noise_covs[0]], tmin,
pytest.raises(ValueError, tf_lcmv, epochs, forward, [noise_covs[0]], tmin,
tmax, tstep, win_lengths, freq_bins)
# Test if freq_bins and win_lengths incompatibility is detected
assert_raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax,
pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax,
tstep, win_lengths=[0, 1, 2], freq_bins=freq_bins)
# Test if time step exceeding window lengths is detected
assert_raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax,
pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax,
tstep=0.15, win_lengths=[0.2, 0.1], freq_bins=freq_bins)
# Test if missing of noise covariance matrix is detected when more than
# one channel type is present in the data
assert_raises(ValueError, tf_lcmv, epochs, forward, noise_covs=None,
pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs=None,
tmin=tmin, tmax=tmax, tstep=tstep, win_lengths=win_lengths,
freq_bins=freq_bins)
# Test if unsupported weight normalization specification is detected
assert_raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax,
pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax,
tstep, win_lengths, freq_bins, weight_norm='nai')
# Test unsupported pick_ori (vector not supported here)
@@ -585,7 +583,7 @@ def test_tf_lcmv():
baseline=(None, 0), preload=True)
epochs_preloaded._raw = None
with warnings.catch_warnings(record=True): # not enough samples
assert_raises(ValueError, tf_lcmv, epochs_preloaded, forward,
pytest.raises(ValueError, tf_lcmv, epochs_preloaded, forward,
noise_covs, tmin, tmax, tstep, win_lengths, freq_bins)
with warnings.catch_warnings(record=True): # not enough samples
@@ -607,7 +605,7 @@ def test_reg_pinv():
# specific warning
with warnings.catch_warnings(record=True) as w:
_reg_pinv(a, reg=0.)
assert_true(any('deficient' in str(ww.message) for ww in w))
assert (any('deficient' in str(ww.message) for ww in w))
def test_eig_inv():
+14 -16
View File
@@ -8,8 +8,7 @@ import numpy as np
from scipy import linalg
import warnings
from nose.tools import assert_true, assert_equal
from numpy.testing import assert_array_equal
from numpy.testing import assert_array_equal, assert_equal
import mne
from mne.datasets import testing
@@ -90,8 +89,8 @@ def _check_dipoles(dipoles, fwd, stc, evoked, residual=None):
len(src[0]['vertno'])]
# Check the position of the two dipoles
assert_true(dipoles[0].pos[0] in np.array([pos1, pos2]))
assert_true(dipoles[1].pos[0] in np.array([pos1, pos2]))
assert (dipoles[0].pos[0] in np.array([pos1, pos2]))
assert (dipoles[1].pos[0] in np.array([pos1, pos2]))
ori1 = fwd['source_nn'][np.where(src[0]['vertno'] ==
stc.vertices[0])[0]][0]
@@ -100,20 +99,19 @@ def _check_dipoles(dipoles, fwd, stc, evoked, residual=None):
len(src[0]['vertno'])][0]
# Check the orientation of the dipoles
assert_true(np.max(np.abs(np.dot(dipoles[0].ori[0],
np.array([ori1, ori2]).T))) > 0.99)
assert (np.max(np.abs(np.dot(dipoles[0].ori[0],
np.array([ori1, ori2]).T))) > 0.99)
assert_true(np.max(np.abs(np.dot(dipoles[1].ori[0],
np.array([ori1, ori2]).T))) > 0.99)
assert (np.max(np.abs(np.dot(dipoles[1].ori[0],
np.array([ori1, ori2]).T))) > 0.99)
if residual is not None:
picks_grad = mne.pick_types(residual.info, meg='grad')
picks_mag = mne.pick_types(residual.info, meg='mag')
rel_tol = 0.02
for picks in [picks_grad, picks_mag]:
assert_true(linalg.norm(residual.data[picks], ord='fro') <
rel_tol *
linalg.norm(evoked.data[picks], ord='fro'))
assert (linalg.norm(residual.data[picks], ord='fro') <
rel_tol * linalg.norm(evoked.data[picks], ord='fro'))
@testing.requires_testing_data
@@ -133,8 +131,8 @@ def test_rap_music_simulated():
dipoles = rap_music(sim_evoked, forward_fixed, noise_cov,
n_dipoles=n_dipoles)
_check_dipoles(dipoles, forward_fixed, stc, sim_evoked)
assert_true(0.98 < dipoles[0].gof.max() < 1.)
assert_true(dipoles[0].gof.min() >= 0.)
assert (0.98 < dipoles[0].gof.max() < 1.)
assert (dipoles[0].gof.min() >= 0.)
assert_array_equal(dipoles[0].gof, dipoles[1].gof)
nave = 100000 # add a tiny amount of noise to the simulated evokeds
@@ -173,11 +171,11 @@ def test_rap_music_sphere():
assert_equal((pos[:, 0] < 0).sum(), 1)
assert_equal((pos[:, 0] > 0).sum(), 1)
# Check the amplitude scale
assert_true(1e-10 < dipoles[0].amplitude[0] < 1e-7)
assert (1e-10 < dipoles[0].amplitude[0] < 1e-7)
# Check the orientation
dip_fit = mne.fit_dipole(evoked, noise_cov, sphere)[0]
assert_true(np.max(np.abs(np.dot(dip_fit.ori, dipoles[0].ori[0]))) > 0.99)
assert_true(np.max(np.abs(np.dot(dip_fit.ori, dipoles[1].ori[0]))) > 0.99)
assert (np.max(np.abs(np.dot(dip_fit.ori, dipoles[0].ori[0]))) > 0.99)
assert (np.max(np.abs(np.dot(dip_fit.ori, dipoles[1].ori[0]))) > 0.99)
run_tests_if_main()
+64 -65
View File
@@ -12,8 +12,7 @@ import warnings
import pytest
import numpy as np
from scipy.io import savemat
from numpy.testing import assert_array_equal
from nose.tools import assert_raises, assert_true, assert_equal, assert_false
from numpy.testing import assert_array_equal, assert_equal
from mne.channels import (rename_channels, read_ch_connectivity,
find_ch_connectivity, make_1020_channel_selections)
@@ -45,25 +44,25 @@ def test_reorder_channels():
def test_rename_channels():
"""Test rename channels"""
"""Test rename channels."""
info = read_info(raw_fname)
# Error Tests
# Test channel name exists in ch_names
mapping = {'EEG 160': 'EEG060'}
assert_raises(ValueError, rename_channels, info, mapping)
pytest.raises(ValueError, rename_channels, info, mapping)
# Test improper mapping configuration
mapping = {'MEG 2641': 1.0}
assert_raises(TypeError, rename_channels, info, mapping)
pytest.raises(TypeError, rename_channels, info, mapping)
# Test non-unique mapping configuration
mapping = {'MEG 2641': 'MEG 2642'}
assert_raises(ValueError, rename_channels, info, mapping)
pytest.raises(ValueError, rename_channels, info, mapping)
# Test bad input
assert_raises(ValueError, rename_channels, info, 1.)
assert_raises(ValueError, rename_channels, info, 1.)
pytest.raises(ValueError, rename_channels, info, 1.)
pytest.raises(ValueError, rename_channels, info, 1.)
# Test name too long (channel names must be less than 15 characters)
A16 = 'A' * 16
mapping = {'MEG 2641': A16}
assert_raises(ValueError, rename_channels, info, mapping)
pytest.raises(ValueError, rename_channels, info, mapping)
# Test successful changes
# Test ch_name and ch_names are changed
@@ -71,14 +70,14 @@ def test_rename_channels():
info2['bads'] = ['EEG 060', 'EOG 061']
mapping = {'EEG 060': 'EEG060', 'EOG 061': 'EOG061'}
rename_channels(info2, mapping)
assert_true(info2['chs'][374]['ch_name'] == 'EEG060')
assert_true(info2['ch_names'][374] == 'EEG060')
assert_true(info2['chs'][375]['ch_name'] == 'EOG061')
assert_true(info2['ch_names'][375] == 'EOG061')
assert info2['chs'][374]['ch_name'] == 'EEG060'
assert info2['ch_names'][374] == 'EEG060'
assert info2['chs'][375]['ch_name'] == 'EOG061'
assert info2['ch_names'][375] == 'EOG061'
assert_array_equal(['EEG060', 'EOG061'], info2['bads'])
info2 = deepcopy(info)
rename_channels(info2, lambda x: x.replace(' ', ''))
assert_true(info2['chs'][373]['ch_name'] == 'EEG059')
assert info2['chs'][373]['ch_name'] == 'EEG059'
info2 = deepcopy(info)
info2['bads'] = ['EEG 060', 'EEG 060']
rename_channels(info2, mapping)
@@ -86,65 +85,65 @@ def test_rename_channels():
def test_set_channel_types():
"""Test set_channel_types"""
"""Test set_channel_types."""
raw = read_raw_fif(raw_fname)
# Error Tests
# Test channel name exists in ch_names
mapping = {'EEG 160': 'EEG060'}
assert_raises(ValueError, raw.set_channel_types, mapping)
pytest.raises(ValueError, raw.set_channel_types, mapping)
# Test change to illegal channel type
mapping = {'EOG 061': 'xxx'}
assert_raises(ValueError, raw.set_channel_types, mapping)
pytest.raises(ValueError, raw.set_channel_types, mapping)
# Test changing type if in proj (avg eeg ref here)
mapping = {'EEG 058': 'ecog', 'EEG 059': 'ecg', 'EEG 060': 'eog',
'EOG 061': 'seeg', 'MEG 2441': 'eeg', 'MEG 2443': 'eeg',
'MEG 2442': 'hbo'}
assert_raises(RuntimeError, raw.set_channel_types, mapping)
pytest.raises(RuntimeError, raw.set_channel_types, mapping)
# Test type change
raw2 = read_raw_fif(raw_fname)
raw2.info['bads'] = ['EEG 059', 'EEG 060', 'EOG 061']
with warnings.catch_warnings(record=True): # MEG channel change
assert_raises(RuntimeError, raw2.set_channel_types, mapping) # has prj
pytest.raises(RuntimeError, raw2.set_channel_types, mapping) # has prj
raw2.add_proj([], remove_existing=True)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
raw2.set_channel_types(mapping)
assert_true(len(w) >= 1, msg=[str(ww.message) for ww in w])
assert_true(all('The unit for channel' in str(ww.message) for ww in w))
assert len(w) >= 1, [str(ww.message) for ww in w]
assert all('The unit for channel' in str(ww.message) for ww in w)
info = raw2.info
assert_true(info['chs'][372]['ch_name'] == 'EEG 058')
assert_true(info['chs'][372]['kind'] == FIFF.FIFFV_ECOG_CH)
assert_true(info['chs'][372]['unit'] == FIFF.FIFF_UNIT_V)
assert_true(info['chs'][372]['coil_type'] == FIFF.FIFFV_COIL_EEG)
assert_true(info['chs'][373]['ch_name'] == 'EEG 059')
assert_true(info['chs'][373]['kind'] == FIFF.FIFFV_ECG_CH)
assert_true(info['chs'][373]['unit'] == FIFF.FIFF_UNIT_V)
assert_true(info['chs'][373]['coil_type'] == FIFF.FIFFV_COIL_NONE)
assert_true(info['chs'][374]['ch_name'] == 'EEG 060')
assert_true(info['chs'][374]['kind'] == FIFF.FIFFV_EOG_CH)
assert_true(info['chs'][374]['unit'] == FIFF.FIFF_UNIT_V)
assert_true(info['chs'][374]['coil_type'] == FIFF.FIFFV_COIL_NONE)
assert_true(info['chs'][375]['ch_name'] == 'EOG 061')
assert_true(info['chs'][375]['kind'] == FIFF.FIFFV_SEEG_CH)
assert_true(info['chs'][375]['unit'] == FIFF.FIFF_UNIT_V)
assert_true(info['chs'][375]['coil_type'] == FIFF.FIFFV_COIL_EEG)
assert info['chs'][372]['ch_name'] == 'EEG 058'
assert info['chs'][372]['kind'] == FIFF.FIFFV_ECOG_CH
assert info['chs'][372]['unit'] == FIFF.FIFF_UNIT_V
assert info['chs'][372]['coil_type'] == FIFF.FIFFV_COIL_EEG
assert info['chs'][373]['ch_name'] == 'EEG 059'
assert info['chs'][373]['kind'] == FIFF.FIFFV_ECG_CH
assert info['chs'][373]['unit'] == FIFF.FIFF_UNIT_V
assert info['chs'][373]['coil_type'] == FIFF.FIFFV_COIL_NONE
assert info['chs'][374]['ch_name'] == 'EEG 060'
assert info['chs'][374]['kind'] == FIFF.FIFFV_EOG_CH
assert info['chs'][374]['unit'] == FIFF.FIFF_UNIT_V
assert info['chs'][374]['coil_type'] == FIFF.FIFFV_COIL_NONE
assert info['chs'][375]['ch_name'] == 'EOG 061'
assert info['chs'][375]['kind'] == FIFF.FIFFV_SEEG_CH
assert info['chs'][375]['unit'] == FIFF.FIFF_UNIT_V
assert info['chs'][375]['coil_type'] == FIFF.FIFFV_COIL_EEG
for idx in pick_channels(raw.ch_names, ['MEG 2441', 'MEG 2443']):
assert_true(info['chs'][idx]['kind'] == FIFF.FIFFV_EEG_CH)
assert_true(info['chs'][idx]['unit'] == FIFF.FIFF_UNIT_V)
assert_true(info['chs'][idx]['coil_type'] == FIFF.FIFFV_COIL_EEG)
assert info['chs'][idx]['kind'] == FIFF.FIFFV_EEG_CH
assert info['chs'][idx]['unit'] == FIFF.FIFF_UNIT_V
assert info['chs'][idx]['coil_type'] == FIFF.FIFFV_COIL_EEG
idx = pick_channels(raw.ch_names, ['MEG 2442'])[0]
assert_true(info['chs'][idx]['kind'] == FIFF.FIFFV_FNIRS_CH)
assert_true(info['chs'][idx]['unit'] == FIFF.FIFF_UNIT_MOL)
assert_true(info['chs'][idx]['coil_type'] == FIFF.FIFFV_COIL_FNIRS_HBO)
assert info['chs'][idx]['kind'] == FIFF.FIFFV_FNIRS_CH
assert info['chs'][idx]['unit'] == FIFF.FIFF_UNIT_MOL
assert info['chs'][idx]['coil_type'] == FIFF.FIFFV_COIL_FNIRS_HBO
# Test meaningful error when setting channel type with unknown unit
raw.info['chs'][0]['unit'] = 0.
ch_types = {raw.ch_names[0]: 'misc'}
assert_raises(ValueError, raw.set_channel_types, ch_types)
pytest.raises(ValueError, raw.set_channel_types, ch_types)
def test_read_ch_connectivity():
"""Test reading channel connectivity templates"""
"""Test reading channel connectivity templates."""
tempdir = _TempDir()
a = partial(np.array, dtype='<U7')
# no pep8
@@ -164,24 +163,24 @@ def test_read_ch_connectivity():
assert_equal(x.shape, (3, 3))
assert_equal(x[0, 1], False)
assert_equal(x[0, 2], True)
assert_true(np.all(x.diagonal()))
assert_raises(ValueError, read_ch_connectivity, mat_fname, [0, 3])
assert np.all(x.diagonal())
pytest.raises(ValueError, read_ch_connectivity, mat_fname, [0, 3])
ch_connectivity, ch_names = read_ch_connectivity(mat_fname, picks=[0, 2])
assert_equal(ch_connectivity.shape[0], 2)
assert_equal(len(ch_names), 2)
ch_names = ['EEG01', 'EEG02', 'EEG03']
neighbors = [['EEG02'], ['EEG04'], ['EEG02']]
assert_raises(ValueError, _ch_neighbor_connectivity, ch_names, neighbors)
pytest.raises(ValueError, _ch_neighbor_connectivity, ch_names, neighbors)
neighbors = [['EEG02'], ['EEG01', 'EEG03'], ['EEG 02']]
assert_raises(ValueError, _ch_neighbor_connectivity, ch_names[:2],
pytest.raises(ValueError, _ch_neighbor_connectivity, ch_names[:2],
neighbors)
neighbors = [['EEG02'], 'EEG01', ['EEG 02']]
assert_raises(ValueError, _ch_neighbor_connectivity, ch_names, neighbors)
pytest.raises(ValueError, _ch_neighbor_connectivity, ch_names, neighbors)
connectivity, ch_names = read_ch_connectivity('neuromag306mag')
assert_equal(connectivity.shape, (102, 102))
assert_equal(len(ch_names), 102)
assert_raises(ValueError, read_ch_connectivity, 'bananas!')
pytest.raises(ValueError, read_ch_connectivity, 'bananas!')
# In EGI 256, E31 sensor has no neighbour
a = partial(np.array)
@@ -200,9 +199,9 @@ def test_read_ch_connectivity():
x = ch_connectivity.todense()
assert_equal(x.shape[0], len(ch_names))
assert_equal(x.shape, (4, 4))
assert_true(np.all(x.diagonal()))
assert_false(np.any(x[0, 1:]))
assert_false(np.any(x[1:, 0]))
assert np.all(x.diagonal())
assert not np.any(x[0, 1:])
assert not np.any(x[1:, 0])
# Check for neighbours consistency. If a sensor is marked as a neighbour,
# then it should also have its neighbours defined.
@@ -218,11 +217,11 @@ def test_read_ch_connectivity():
mat = dict(neighbours=nbh)
mat_fname = op.join(tempdir, 'test_error_mat.mat')
savemat(mat_fname, mat, oned_as='row')
assert_raises(ValueError, read_ch_connectivity, mat_fname)
pytest.raises(ValueError, read_ch_connectivity, mat_fname)
def test_get_set_sensor_positions():
"""Test get/set functions for sensor positions"""
"""Test get/set functions for sensor positions."""
raw1 = read_raw_fif(raw_fname)
picks = pick_types(raw1.info, meg=False, eeg=True)
pos = np.array([ch['loc'][:3] for ch in raw1.info['chs']])[picks]
@@ -230,7 +229,7 @@ def test_get_set_sensor_positions():
assert_array_equal(raw_pos, pos)
ch_name = raw1.info['ch_names'][13]
assert_raises(ValueError, raw1._set_channel_positions, [1, 2], ['name'])
pytest.raises(ValueError, raw1._set_channel_positions, [1, 2], ['name'])
raw2 = read_raw_fif(raw_fname)
raw2.info['chs'][13]['loc'][:3] = np.array([1, 2, 3])
raw1._set_channel_positions([[1, 2, 3]], [ch_name])
@@ -240,14 +239,14 @@ def test_get_set_sensor_positions():
@testing.requires_testing_data
def test_1020_selection():
"""Test making a 10/20 selection dict"""
"""Test making a 10/20 selection dict."""
base_dir = op.join(testing.data_path(download=False), 'EEGLAB')
raw_fname = op.join(base_dir, 'test_raw.set')
loc_fname = op.join(base_dir, 'test_chans.locs')
raw = read_raw_eeglab(raw_fname, montage=loc_fname)
for input in ("a_string", 100, raw, [1, 2]):
assert_raises(TypeError, make_1020_channel_selections, input)
pytest.raises(TypeError, make_1020_channel_selections, input)
sels = make_1020_channel_selections(raw.info)
# are all frontal channels placed before all occipital channels?
@@ -256,12 +255,12 @@ def test_1020_selection():
if raw.ch_names[pick].startswith("F")])
ps = max([ii for ii, pick in enumerate(picks)
if raw.ch_names[pick].startswith("O")])
assert_true(fs > ps)
assert fs > ps
# are channels in the correct selection?
fz_c3_c4 = [raw.ch_names.index(ch) for ch in ("Fz", "C3", "C4")]
for channel, roi in zip(fz_c3_c4, ("Midline", "Left", "Right")):
assert_true(channel in sels[roi])
assert channel in sels[roi]
@testing.requires_testing_data
@@ -277,7 +276,7 @@ def test_find_ch_connectivity():
# Silly test for checking the number of neighbors.
assert_equal(conn.getnnz(), sizes[ch_type])
assert_equal(len(ch_names), nchans[ch_type])
assert_raises(ValueError, find_ch_connectivity, raw.info, None)
pytest.raises(ValueError, find_ch_connectivity, raw.info, None)
# Test computing the conn matrix with gradiometers.
conn, ch_names = _compute_ch_connectivity(raw.info, 'grad')
@@ -291,14 +290,14 @@ def test_find_ch_connectivity():
bti_config_name = op.join(data_path, 'BTi', 'erm_HFH', 'config')
raw = read_raw_bti(bti_fname, bti_config_name, None)
_, ch_names = find_ch_connectivity(raw.info, 'mag')
assert_true('A1' in ch_names)
assert 'A1' in ch_names
ctf_fname = op.join(data_path, 'CTF', 'testdata_ctf_short.ds')
raw = read_raw_ctf(ctf_fname)
_, ch_names = find_ch_connectivity(raw.info, 'mag')
assert_true('MLC11' in ch_names)
assert 'MLC11' in ch_names
assert_raises(ValueError, find_ch_connectivity, raw.info, 'eog')
pytest.raises(ValueError, find_ch_connectivity, raw.info, 'eog')
run_tests_if_main()
+15 -16
View File
@@ -4,7 +4,6 @@ import warnings
import numpy as np
from numpy.testing import (assert_allclose, assert_array_equal)
import pytest
from nose.tools import assert_raises, assert_equal, assert_true
from mne import io, pick_types, pick_channels, read_events, Epochs
from mne.channels.interpolation import _make_interpolation_matrix
@@ -19,7 +18,7 @@ event_id_2 = 2
def _load_data():
"""Helper function to load data."""
"""Load data."""
# It is more memory efficient to load data in a separate
# function so it's loaded on-demand
raw = io.read_raw_fif(raw_fname)
@@ -44,7 +43,7 @@ def _load_data():
@pytest.mark.slowtest
def test_interpolation():
"""Test interpolation"""
"""Test interpolation."""
raw, epochs, epochs_eeg, epochs_meg = _load_data()
# It's a trade of between speed and accuracy. If every second channel is
@@ -57,7 +56,7 @@ def test_interpolation():
evoked_eeg = epochs_eeg.average()
with warnings.catch_warnings(record=True) as w:
evoked_eeg.interpolate_bads()
assert_true(any('Doing nothing' in str(ww.message) for ww in w))
assert any('Doing nothing' in str(ww.message) for ww in w)
# create good and bad channels for EEG
epochs_eeg.info['bads'] = []
@@ -73,7 +72,7 @@ def test_interpolation():
pos_good = pos[goods_idx]
pos_bad = pos[bads_idx]
interpolation = _make_interpolation_matrix(pos_good, pos_bad)
assert_equal(interpolation.shape, (1, len(epochs_eeg.ch_names) - 1))
assert interpolation.shape == (1, len(epochs_eeg.ch_names) - 1)
ave_after = np.dot(interpolation, evoked_eeg.data[goods_idx])
epochs_eeg.info['bads'] = ['EEG 012']
@@ -84,26 +83,26 @@ def test_interpolation():
# check that interpolation fails when preload is False
epochs_eeg.preload = False
assert_raises(RuntimeError, epochs_eeg.interpolate_bads)
pytest.raises(RuntimeError, epochs_eeg.interpolate_bads)
epochs_eeg.preload = True
# check that interpolation changes the data in raw
raw_eeg = io.RawArray(data=epochs_eeg._data[0], info=epochs_eeg.info)
raw_before = raw_eeg._data[bads_idx]
raw_after = raw_eeg.interpolate_bads()._data[bads_idx]
assert_equal(np.all(raw_before == raw_after), False)
assert not np.all(raw_before == raw_after)
# check that interpolation fails when preload is False
for inst in [raw, epochs]:
assert hasattr(inst, 'preload')
inst.preload = False
inst.info['bads'] = [inst.ch_names[1]]
assert_raises(RuntimeError, inst.interpolate_bads)
pytest.raises(RuntimeError, inst.interpolate_bads)
# check that interpolation works with few channels
raw_few = raw.copy().crop(0, 0.1).load_data()
raw_few.pick_channels(raw_few.ch_names[:1] + raw_few.ch_names[3:4])
assert_equal(len(raw_few.ch_names), 2)
assert len(raw_few.ch_names) == 2
raw_few.del_proj()
raw_few.info['bads'] = [raw_few.ch_names[-1]]
orig_data = raw_few[1][0]
@@ -111,8 +110,8 @@ def test_interpolation():
raw_few.interpolate_bads(reset_bads=False)
assert len(w) == 0
new_data = raw_few[1][0]
assert_true((new_data == 0).mean() < 0.5)
assert_true(np.corrcoef(new_data, orig_data)[0, 1] > 0.1)
assert (new_data == 0).mean() < 0.5
assert np.corrcoef(new_data, orig_data)[0, 1] > 0.1
# check that interpolation works when non M/EEG channels are present
# before MEG channels
@@ -135,23 +134,23 @@ def test_interpolation():
raw_meg.info.normalize_proj()
data2 = raw_meg.interpolate_bads(reset_bads=False)[pick, :][0][0]
assert_true(np.corrcoef(data1, data2)[0, 1] > thresh)
assert np.corrcoef(data1, data2)[0, 1] > thresh
# the same number of bads as before
assert_true(len(raw_meg.info['bads']) == len(raw_meg.info['bads']))
assert len(raw_meg.info['bads']) == len(raw_meg.info['bads'])
# MEG -- epochs
data1 = epochs_meg.get_data()[:, pick, :].ravel()
epochs_meg.info.normalize_proj()
epochs_meg.interpolate_bads()
data2 = epochs_meg.get_data()[:, pick, :].ravel()
assert_true(np.corrcoef(data1, data2)[0, 1] > thresh)
assert_true(len(epochs_meg.info['bads']) == 0)
assert np.corrcoef(data1, data2)[0, 1] > thresh
assert len(epochs_meg.info['bads']) == 0
# MEG -- evoked
data1 = evoked.data[pick]
evoked.info.normalize_proj()
data2 = evoked.interpolate_bads().data[pick]
assert_true(np.corrcoef(data1, data2)[0, 1] > thresh)
assert np.corrcoef(data1, data2)[0, 1] > thresh
run_tests_if_main()
+38 -38
View File
@@ -1,4 +1,3 @@
from __future__ import print_function
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Denis Engemann <denis.engemann@gmail.com>
# Martin Luessi <mluessi@nmr.mgh.harvard.edu>
@@ -14,8 +13,9 @@ import matplotlib
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_array_equal,
assert_allclose)
from nose.tools import assert_equal, assert_true, assert_raises
assert_allclose, assert_equal)
import pytest
from mne.channels import (make_eeg_layout, make_grid_layout, read_layout,
find_layout)
from mne.channels.layout import (_box_size, _auto_topomap_coords,
@@ -40,7 +40,7 @@ fname_kit_umd = op.join(io_dir, 'kit', 'tests', 'data', 'test_umd-raw.sqd')
def _get_test_info():
"""Helper to make test info"""
"""Make test info."""
test_info = _empty_info(1000)
loc = np.array([0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0., 1.],
dtype=np.float32)
@@ -60,31 +60,30 @@ def _get_test_info():
def test_io_layout_lout():
"""Test IO with .lout files"""
"""Test IO with .lout files."""
tempdir = _TempDir()
layout = read_layout('Vectorview-all', scale=False)
layout.save(op.join(tempdir, 'foobar.lout'))
layout_read = read_layout(op.join(tempdir, 'foobar.lout'), path='./',
scale=False)
assert_array_almost_equal(layout.pos, layout_read.pos, decimal=2)
assert_true(layout.names, layout_read.names)
assert layout.names == layout_read.names
print(layout) # test repr
def test_io_layout_lay():
"""Test IO with .lay files"""
"""Test IO with .lay files."""
tempdir = _TempDir()
layout = read_layout('CTF151', scale=False)
layout.save(op.join(tempdir, 'foobar.lay'))
layout_read = read_layout(op.join(tempdir, 'foobar.lay'), path='./',
scale=False)
assert_array_almost_equal(layout.pos, layout_read.pos, decimal=2)
assert_true(layout.names, layout_read.names)
assert layout.names == layout_read.names
def test_auto_topomap_coords():
"""Test mapping of coordinates in 3D space to 2D"""
"""Test mapping of coordinates in 3D space to 2D."""
info = read_info(fif_fname)
picks = pick_types(info, meg=False, eeg=True, eog=False, stim=False)
@@ -114,33 +113,33 @@ def test_auto_topomap_coords():
# Test plotting mag topomap without channel locations: it should fail
mag_picks = pick_types(info, meg='mag')
assert_raises(ValueError, _auto_topomap_coords, info, mag_picks)
pytest.raises(ValueError, _auto_topomap_coords, info, mag_picks)
# Test function with too many EEG digitization points: it should fail
info['dig'].append({'r': [1, 2, 3], 'kind': FIFF.FIFFV_POINT_EEG})
assert_raises(ValueError, _auto_topomap_coords, info, picks)
pytest.raises(ValueError, _auto_topomap_coords, info, picks)
# Test function with too little EEG digitization points: it should fail
info['dig'] = info['dig'][:-2]
assert_raises(ValueError, _auto_topomap_coords, info, picks)
pytest.raises(ValueError, _auto_topomap_coords, info, picks)
# Electrode positions must be unique
info['dig'].append(info['dig'][-1])
assert_raises(ValueError, _auto_topomap_coords, info, picks)
pytest.raises(ValueError, _auto_topomap_coords, info, picks)
# Test function without EEG digitization points: it should fail
info['dig'] = [d for d in info['dig'] if d['kind'] != FIFF.FIFFV_POINT_EEG]
assert_raises(RuntimeError, _auto_topomap_coords, info, picks)
pytest.raises(RuntimeError, _auto_topomap_coords, info, picks)
# Test function without any digitization points, it should fail
info['dig'] = None
assert_raises(RuntimeError, _auto_topomap_coords, info, picks)
pytest.raises(RuntimeError, _auto_topomap_coords, info, picks)
info['dig'] = []
assert_raises(RuntimeError, _auto_topomap_coords, info, picks)
pytest.raises(RuntimeError, _auto_topomap_coords, info, picks)
def test_make_eeg_layout():
"""Test creation of EEG layout"""
"""Test creation of EEG layout."""
tempdir = _TempDir()
tmp_name = 'foo'
lout_name = 'test_raw'
@@ -157,16 +156,16 @@ def test_make_eeg_layout():
assert_array_equal(lout_orig.names, lout_new.names)
# Test input validation
assert_raises(ValueError, make_eeg_layout, info, radius=-0.1)
assert_raises(ValueError, make_eeg_layout, info, radius=0.6)
assert_raises(ValueError, make_eeg_layout, info, width=-0.1)
assert_raises(ValueError, make_eeg_layout, info, width=1.1)
assert_raises(ValueError, make_eeg_layout, info, height=-0.1)
assert_raises(ValueError, make_eeg_layout, info, height=1.1)
pytest.raises(ValueError, make_eeg_layout, info, radius=-0.1)
pytest.raises(ValueError, make_eeg_layout, info, radius=0.6)
pytest.raises(ValueError, make_eeg_layout, info, width=-0.1)
pytest.raises(ValueError, make_eeg_layout, info, width=1.1)
pytest.raises(ValueError, make_eeg_layout, info, height=-0.1)
pytest.raises(ValueError, make_eeg_layout, info, height=1.1)
def test_make_grid_layout():
"""Test creation of grid layout"""
"""Test creation of grid layout."""
tempdir = _TempDir()
tmp_name = 'bar'
lout_name = 'test_ica'
@@ -181,17 +180,17 @@ def test_make_grid_layout():
# Test creating grid layout with specified number of columns
layout = make_grid_layout(_get_test_info(), n_col=2)
# Vertical positions should be equal
assert_true(layout.pos[0, 1] == layout.pos[1, 1])
assert layout.pos[0, 1] == layout.pos[1, 1]
# Horizontal positions should be unequal
assert_true(layout.pos[0, 0] != layout.pos[1, 0])
assert layout.pos[0, 0] != layout.pos[1, 0]
# Box sizes should be equal
assert_array_equal(layout.pos[0, 3:], layout.pos[1, 3:])
def test_find_layout():
"""Test finding layout"""
"""Test finding layout."""
import matplotlib.pyplot as plt
assert_raises(ValueError, find_layout, _get_test_info(), ch_type='meep')
pytest.raises(ValueError, find_layout, _get_test_info(), ch_type='meep')
sample_info = read_info(fif_fname)
grads = pick_types(sample_info, meg='grad')
@@ -210,8 +209,8 @@ def test_find_layout():
sample_info5 = pick_info(sample_info, eegs)
lout = find_layout(sample_info, ch_type=None)
assert_equal(lout.kind, 'Vectorview-all')
assert_true(all(' ' in k for k in lout.names))
assert lout.kind == 'Vectorview-all'
assert all(' ' in k for k in lout.names)
lout = find_layout(sample_info2, ch_type='meg')
assert_equal(lout.kind, 'Vectorview-all')
@@ -219,7 +218,7 @@ def test_find_layout():
# test new vector-view
lout = find_layout(sample_info4, ch_type=None)
assert_equal(lout.kind, 'Vectorview-all')
assert_true(all(' ' not in k for k in lout.names))
assert all(' ' not in k for k in lout.names)
lout = find_layout(sample_info, ch_type='grad')
assert_equal(lout.kind, 'Vectorview-grad')
@@ -298,8 +297,8 @@ def test_box_size():
rng = np.random.RandomState(42)
points = rng.rand(100, 2)
width, height = _box_size(points)
assert_true(width is not None)
assert_true(height is not None)
assert width is not None
assert height is not None
# Test specifying an existing width.
points = [(0.25, 0.25), (0.75, 0.25), (0.5, 0.75)]
@@ -349,19 +348,20 @@ def test_generate_2d_layout():
# Correct points ordering / minmaxing
comp_1, comp_2 = [(5, 0), (7, 0)]
assert_true(lt.pos[:, :2].max() == 1)
assert_true(lt.pos[:, :2].min() == 0)
assert lt.pos[:, :2].max() == 1
assert lt.pos[:, :2].min() == 0
with np.errstate(invalid='ignore'): # divide by zero
assert_allclose(xy[comp_2] / float(xy[comp_1]),
lt.pos[comp_2] / float(lt.pos[comp_1]))
assert_allclose(lt.pos[0, [2, 3]], [w, h])
# Correct number elements
assert_true(lt.pos.shape[1] == 4)
assert_true(len(lt.box) == 4)
assert lt.pos.shape[1] == 4
assert len(lt.box) == 4
# Make sure background image normalizing is correct
lt_bg = generate_2d_layout(xy, bg_image=bg_image)
assert_allclose(lt_bg.pos[:, :2].max(), xy.max() / float(sbg))
run_tests_if_main()
+30 -30
View File
@@ -6,14 +6,14 @@ import os
import os.path as op
import warnings
from nose.tools import assert_equal, assert_true, assert_raises
import pytest
import numpy as np
from scipy.io import savemat
from numpy.testing import (assert_array_equal, assert_almost_equal,
assert_allclose, assert_array_almost_equal,
assert_array_less)
assert_array_less, assert_equal)
from mne.tests.common import assert_dig_allclose
from mne.channels.montage import (read_montage, _set_montage, read_dig_montage,
get_builtin_montages)
@@ -81,15 +81,15 @@ def test_documented():
elif start is not None and li > start and line.startswith('===='):
stop = li
break
assert_true(start is not None)
assert_true(stop is not None)
assert (start is not None)
assert (stop is not None)
kinds = [line.split(' ')[0] for line in lines[start:stop]]
kinds = [kind for kind in kinds if kind != '']
montages = os.listdir(op.join(op.dirname(_mne_file), 'channels', 'data',
'montages'))
montages = sorted(op.splitext(m)[0] for m in montages)
assert_equal(len(set(montages)), len(montages))
assert_equal(len(set(kinds)), len(kinds), msg=sorted(kinds))
assert_equal(len(set(kinds)), len(kinds), err_msg=str(sorted(kinds)))
assert_equal(set(montages), set(kinds))
@@ -193,7 +193,7 @@ def test_montage():
fid.write(text)
montage = read_montage(fname)
if kind in ('sfp', 'txt'):
assert_true('very_very_very_long_name' in montage.ch_names)
assert ('very_very_very_long_name' in montage.ch_names)
assert_equal(len(montage.ch_names), 4)
assert_equal(len(montage.ch_names), len(montage.pos))
assert_equal(montage.pos.shape, (4, 3))
@@ -282,7 +282,7 @@ def test_montage():
data=np.zeros((len(montage.ch_names), 1)), info=info, tmin=0)
# test return type as well as set montage
assert_true(isinstance(evoked.set_montage(montage), type(evoked)))
assert (isinstance(evoked.set_montage(montage), type(evoked)))
pos3 = np.array([c['loc'][:3] for c in evoked.info['chs']])
assert_array_equal(pos3, montage.pos)
@@ -293,28 +293,28 @@ def test_montage():
info = create_info(montage.ch_names + ['foo', 'bar'], 1e3,
['eeg'] * (len(montage.ch_names) + 2))
_set_montage(info, montage)
assert_true(len(w) == 1)
assert (len(w) == 1)
# Channel names can be treated case insensitive
with warnings.catch_warnings(record=True) as w:
info = create_info(['FP1', 'af7', 'AF3'], 1e3, ['eeg'] * 3)
_set_montage(info, montage)
assert_true(len(w) == 0)
assert (len(w) == 0)
# Unless there is a collision in names
with warnings.catch_warnings(record=True) as w:
info = create_info(['FP1', 'Fp1', 'AF3'], 1e3, ['eeg'] * 3)
assert_true(info['dig'] is None)
assert (info['dig'] is None)
_set_montage(info, montage)
assert_equal(len(info['dig']), 5) # 2 EEG w/pos, 3 fiducials
assert_true(len(w) == 1)
assert (len(w) == 1)
with warnings.catch_warnings(record=True) as w:
montage.ch_names = ['FP1', 'Fp1', 'AF3']
info = create_info(['fp1', 'AF3'], 1e3, ['eeg', 'eeg'])
assert_true(info['dig'] is None)
assert (info['dig'] is None)
_set_montage(info, montage, set_dig=False)
assert_true(info['dig'] is None)
assert_true(len(w) == 1)
assert (info['dig'] is None)
assert (len(w) == 1)
# test get_pos2d method
montage = read_montage("standard_1020")
@@ -323,19 +323,19 @@ def test_montage():
fz = montage.get_pos2d()[montage.ch_names.index("Fz")]
oz = montage.get_pos2d()[montage.ch_names.index("Oz")]
f1 = montage.get_pos2d()[montage.ch_names.index("F1")]
assert_true(c3[0] < 0) # left hemisphere
assert_true(c4[0] > 0) # right hemisphere
assert_true(fz[1] > 0) # frontal
assert_true(oz[1] < 0) # occipital
assert (c3[0] < 0) # left hemisphere
assert (c4[0] > 0) # right hemisphere
assert (fz[1] > 0) # frontal
assert (oz[1] < 0) # occipital
assert_allclose(fz[0], 0, atol=1e-2) # midline
assert_allclose(oz[0], 0, atol=1e-2) # midline
assert_true(f1[0] < 0 and f1[1] > 0) # left frontal
assert (f1[0] < 0 and f1[1] > 0) # left frontal
# test get_builtin_montages function
montages = get_builtin_montages()
assert_true(len(montages) > 0) # MNE should always ship with montages
assert_true("standard_1020" in montages) # 10/20 montage
assert_true("standard_1005" in montages) # 10/05 montage
assert (len(montages) > 0) # MNE should always ship with montages
assert ("standard_1020" in montages) # 10/20 montage
assert ("standard_1005" in montages) # 10/05 montage
@testing.requires_testing_data
@@ -350,7 +350,7 @@ def test_read_locs():
def test_read_dig_montage():
"""Test read_dig_montage"""
"""Test read_dig_montage."""
names = ['nasion', 'lpa', 'rpa', '1', '2', '3', '4', '5']
montage = read_dig_montage(hsp, hpi, elp, names, transform=False)
elp_points = _read_dig_points(elp)
@@ -360,7 +360,7 @@ def test_read_dig_montage():
assert_array_equal(montage.elp, elp_points)
assert_array_equal(montage.hsp, hsp_points)
assert_array_equal(montage.hpi, hpi_points)
assert_true(montage.dev_head_t is None)
assert (montage.dev_head_t is None)
montage = read_dig_montage(hsp, hpi, elp, names,
transform=True, dev_head_t=True)
# check coordinate transformation
@@ -390,7 +390,7 @@ def test_read_dig_montage():
assert_allclose(montage_cm.hsp, montage.hsp * 10.)
assert_allclose(montage_cm.elp, montage.elp * 10.)
assert_array_equal(montage_cm.hpi, montage.hpi)
assert_raises(ValueError, read_dig_montage, hsp, hpi, elp, names,
pytest.raises(ValueError, read_dig_montage, hsp, hpi, elp, names,
unit='km')
# extra columns
extra_hsp = op.join(tempdir, 'test.txt')
@@ -404,7 +404,7 @@ def test_read_dig_montage():
fout.write(line.rstrip() + b' 0.0 0.0 0.0\n')
with warnings.catch_warnings(record=True) as w:
montage_extra = read_dig_montage(extra_hsp, hpi, elp, names)
assert_true(len(w) == 1 and all('columns' in str(ww.message) for ww in w))
assert (len(w) == 1 and all('columns' in str(ww.message) for ww in w))
assert_allclose(montage_extra.hsp, montage.hsp)
assert_allclose(montage_extra.elp, montage.elp)
@@ -432,7 +432,7 @@ def test_set_dig_montage():
info = create_info(['Test Ch'], 1e3, ['eeg'])
with warnings.catch_warnings(record=True) as w: # test ch pos not set
_set_montage(info, use_mon)
assert_true(all('not set' in str(ww.message) for ww in w))
assert (all('not set' in str(ww.message) for ww in w))
hs = np.array([p['r'] for i, p in enumerate(info['dig'])
if p['kind'] == FIFF.FIFFV_POINT_EXTRA])
nasion_dig = np.array([p['r'] for p in info['dig']
@@ -467,7 +467,7 @@ def test_fif_dig_montage():
# Make a BrainVision file like the one the user would have had
with warnings.catch_warnings(record=True) as w:
raw_bv = read_raw_brainvision(bv_fname, preload=True)
assert_true(any('will be dropped' in str(ww.message) for ww in w))
assert (any('will be dropped' in str(ww.message) for ww in w))
raw_bv_2 = raw_bv.copy()
mapping = dict()
for ii, ch_name in enumerate(raw_bv.ch_names[:-1]):
@@ -504,7 +504,7 @@ def test_fif_dig_montage():
# Roundtrip of non-FIF start
names = ['nasion', 'lpa', 'rpa', '1', '2', '3', '4', '5']
montage = read_dig_montage(hsp, hpi, elp, names, transform=False)
assert_raises(RuntimeError, montage.save, fname_temp) # must be head coord
pytest.raises(RuntimeError, montage.save, fname_temp) # must be head coord
montage = read_dig_montage(hsp, hpi, elp, names)
_check_roundtrip(montage, fname_temp)
@@ -550,7 +550,7 @@ def test_set_montage():
raw.set_montage('mgh60') # test loading with string argument
new_pos = np.array([ch['loc'][:3] for ch in raw.info['chs']
if ch['ch_name'].startswith('EEG')])
assert_true((orig_pos != new_pos).all())
assert ((orig_pos != new_pos).all())
r0 = _fit_sphere(new_pos)[1]
assert_allclose(r0, [0., -0.016, 0.], atol=1e-3)
# mgh70 has no 61/62/63/64 (these are EOG/ECG)
+15 -15
View File
@@ -4,8 +4,8 @@ from os import path as op
import shutil
import glob
import warnings
import pytest
from nose.tools import assert_true, assert_raises
from numpy.testing import assert_equal, assert_allclose
from mne import concatenate_raws, read_bem_surfaces
@@ -32,14 +32,14 @@ warnings.simplefilter('always')
def check_usage(module, force_help=False):
"""Helper to ensure we print usage"""
"""Ensure we print usage."""
args = ('--help',) if force_help else ()
with ArgvSetter(args) as out:
try:
module.run()
except SystemExit:
pass
assert_true('Usage: ' in out.stdout.getvalue())
assert 'Usage: ' in out.stdout.getvalue()
@pytest.mark.slowtest
@@ -82,9 +82,9 @@ def test_clean_eog_ecg():
with ArgvSetter(('-i', use_fname, '--quiet')):
mne_clean_eog_ecg.run()
fnames = glob.glob(op.join(tempdir, '*proj.fif'))
assert_true(len(fnames) == 2) # two projs
assert len(fnames) == 2 # two projs
fnames = glob.glob(op.join(tempdir, '*-eve.fif'))
assert_true(len(fnames) == 3) # raw plus two projs
assert len(fnames) == 3 # raw plus two projs
@pytest.mark.slowtest
@@ -103,14 +103,14 @@ def test_compute_proj_ecg_eog():
with warnings.catch_warnings(record=True): # too few samples
fun.run()
fnames = glob.glob(op.join(tempdir, '*proj.fif'))
assert_true(len(fnames) == 1)
assert len(fnames) == 1
fnames = glob.glob(op.join(tempdir, '*-eve.fif'))
assert_true(len(fnames) == 1)
assert len(fnames) == 1
def test_coreg():
"""Test mne coreg."""
assert_true(hasattr(mne_coreg, 'run'))
assert hasattr(mne_coreg, 'run')
def test_kit2fiff():
@@ -143,12 +143,12 @@ def test_make_scalp_surfaces():
medium_fname = op.join(subj_dir, 'sample-head-medium.fif')
try:
with ArgvSetter(cmd, disable_stdout=False, disable_stderr=False):
assert_raises(RuntimeError, mne_make_scalp_surfaces.run)
pytest.raises(RuntimeError, mne_make_scalp_surfaces.run)
os.environ['FREESURFER_HOME'] = tempdir # don't actually use it
mne_make_scalp_surfaces.run()
assert_true(op.isfile(dense_fname))
assert_true(op.isfile(medium_fname))
assert_raises(IOError, mne_make_scalp_surfaces.run) # no overwrite
assert op.isfile(dense_fname)
assert op.isfile(medium_fname)
pytest.raises(IOError, mne_make_scalp_surfaces.run) # no overwrite
finally:
if orig_fs is not None:
os.environ['FREESURFER_HOME'] = orig_fs
@@ -176,9 +176,9 @@ def test_maxfilter():
mne_maxfilter.run()
finally:
del os.environ['_MNE_MAXFILTER_TEST']
assert_true(len(w) == 1)
assert len(w) == 1
for check in ('maxfilter', '-trans', '-movecomp'):
assert_true(check in out.stdout.getvalue(), check)
assert check in out.stdout.getvalue(), check
@pytest.mark.slowtest
@@ -195,7 +195,7 @@ def test_report():
'-s', 'sample', '--no-browser', '-m', '30')):
mne_report.run()
fnames = glob.glob(op.join(tempdir, '*.html'))
assert_true(len(fnames) == 1)
assert len(fnames) == 1
def test_surf2bem():
+5 -6
View File
@@ -1,12 +1,11 @@
import numpy as np
from numpy.testing import assert_array_almost_equal
from nose.tools import assert_true
from mne.connectivity import phase_slope_index
def test_psi():
"""Test Phase Slope Index (PSI) estimation"""
"""Test Phase Slope Index (PSI) estimation."""
sfreq = 50.
n_signals = 3
n_epochs = 10
@@ -21,8 +20,8 @@ def test_psi():
psi, freqs, times, n_epochs, n_tapers = phase_slope_index(
data, mode='fourier', sfreq=sfreq)
assert_true(psi[1, 0, 0] < 0)
assert_true(psi[2, 0, 0] > 0)
assert psi[1, 0, 0] < 0
assert psi[2, 0, 0] > 0
indices = (np.array([0]), np.array([1]))
psi_2, freqs, times, n_epochs, n_tapers = phase_slope_index(
@@ -36,5 +35,5 @@ def test_psi():
data, mode='cwt_morlet', sfreq=sfreq, cwt_freqs=cwt_freqs,
indices=indices)
assert_true(np.all(psi_cwt > 0))
assert_true(psi_cwt.shape[-1] == n_times)
assert np.all(psi_cwt > 0)
assert psi_cwt.shape[-1] == n_times
+36 -39
View File
@@ -3,7 +3,6 @@ import warnings
import numpy as np
from numpy.testing import assert_array_almost_equal
import pytest
from nose.tools import assert_true, assert_raises
from mne.connectivity import spectral_connectivity
from mne.connectivity.spectral import _CohEst, _get_n_epochs
@@ -16,7 +15,7 @@ warnings.simplefilter('always')
def _stc_gen(data, sfreq, tmin, combo=False):
"""Simulate a SourceEstimate generator"""
"""Simulate a SourceEstimate generator."""
vertices = [np.arange(data.shape[1]), np.empty(0)]
for d in data:
if not combo:
@@ -33,9 +32,9 @@ def _stc_gen(data, sfreq, tmin, combo=False):
@pytest.mark.slowtest
def test_spectral_connectivity():
"""Test frequency-domain connectivity methods"""
"""Test frequency-domain connectivity methods."""
# Use a case known to have no spurious correlations (it would bad if
# nosetests could randomly fail):
# tests could randomly fail):
rng = np.random.RandomState(0)
trans_bandwidth = 2.
@@ -60,17 +59,17 @@ def test_spectral_connectivity():
data = np.transpose(data, [1, 0, 2])
# First we test some invalid parameters:
assert_raises(ValueError, spectral_connectivity, data, method='notamethod')
assert_raises(ValueError, spectral_connectivity, data,
pytest.raises(ValueError, spectral_connectivity, data, method='notamethod')
pytest.raises(ValueError, spectral_connectivity, data,
mode='notamode')
# test invalid fmin fmax settings
assert_raises(ValueError, spectral_connectivity, data, fmin=10,
pytest.raises(ValueError, spectral_connectivity, data, fmin=10,
fmax=10 + 0.5 * (sfreq / float(n_times)))
assert_raises(ValueError, spectral_connectivity, data, fmin=10, fmax=5)
assert_raises(ValueError, spectral_connectivity, data, fmin=(0, 11),
pytest.raises(ValueError, spectral_connectivity, data, fmin=10, fmax=5)
pytest.raises(ValueError, spectral_connectivity, data, fmin=(0, 11),
fmax=(5, 10))
assert_raises(ValueError, spectral_connectivity, data, fmin=(11,),
pytest.raises(ValueError, spectral_connectivity, data, fmin=(11,),
fmax=(12, 15))
methods = ['coh', 'cohy', 'imcoh', ['plv', 'ppc', 'pli', 'pli2_unbiased',
@@ -108,7 +107,7 @@ def test_spectral_connectivity():
mt_bandwidth=mt_bandwidth, cwt_freqs=cwt_freqs,
cwt_n_cycles=cwt_n_cycles)
assert_true(n == n_epochs)
assert (n == n_epochs)
assert_array_almost_equal(times_data, times)
if mode == 'multitaper':
@@ -125,29 +124,26 @@ def test_spectral_connectivity():
(fstart - trans_bandwidth * 2,
fend + trans_bandwidth * 2))
if method == 'coh':
assert_true(np.all(con[1, 0, gidx[0]:gidx[1]] > upper_t),
con[1, 0, gidx[0]:gidx[1]].min())
assert np.all(con[1, 0, gidx[0]:gidx[1]] > upper_t), \
con[1, 0, gidx[0]:gidx[1]].min()
# we see something for zero-lag
assert_true(np.all(con[1, 0, :bidx[0]] < lower_t))
assert_true(np.all(con[1, 0, bidx[1]:] < lower_t),
con[1, 0, bidx[1:]].max())
assert (np.all(con[1, 0, :bidx[0]] < lower_t))
assert np.all(con[1, 0, bidx[1]:] < lower_t), \
con[1, 0, bidx[1:]].max()
elif method == 'cohy':
# imaginary coh will be zero
check = np.imag(con[1, 0, gidx[0]:gidx[1]])
assert_true(np.all(check < lower_t), check.max())
assert np.all(check < lower_t), check.max()
# we see something for zero-lag
assert_true(np.all(np.abs(con[1, 0, gidx[0]:gidx[1]]) >
upper_t))
assert_true(np.all(np.abs(con[1, 0, :bidx[0]]) <
lower_t))
assert_true(np.all(np.abs(con[1, 0, bidx[1]:]) <
lower_t))
assert np.all(np.abs(con[1, 0, gidx[0]:gidx[1]]) > upper_t)
assert np.all(np.abs(con[1, 0, :bidx[0]]) < lower_t)
assert np.all(np.abs(con[1, 0, bidx[1]:]) < lower_t)
elif method == 'imcoh':
# imaginary coh will be zero
assert_true(np.all(con[1, 0, gidx[0]:gidx[1]] < lower_t))
assert_true(np.all(con[1, 0, :bidx[0]] < lower_t))
assert_true(np.all(con[1, 0, bidx[1]:] < lower_t),
con[1, 0, bidx[1]:].max())
assert np.all(con[1, 0, gidx[0]:gidx[1]] < lower_t)
assert np.all(con[1, 0, :bidx[0]] < lower_t)
assert np.all(con[1, 0, bidx[1]:] < lower_t), \
con[1, 0, bidx[1]:].max()
# compute same connections using indices and 2 jobs
indices = np.tril_indices(n_signals, -1)
@@ -165,8 +161,8 @@ def test_spectral_connectivity():
cwt_freqs=cwt_freqs,
cwt_n_cycles=cwt_n_cycles, n_jobs=2)
assert_true(isinstance(con2, list))
assert_true(len(con2) == len(test_methods))
assert (isinstance(con2, list))
assert (len(con2) == len(test_methods))
if method == 'coh':
assert_array_almost_equal(con2[0], con2[1])
@@ -177,15 +173,15 @@ def test_spectral_connectivity():
# we get the same result for the probed connections
assert_array_almost_equal(freqs, freqs2)
assert_array_almost_equal(con[indices], con2)
assert_true(n == n2)
assert (n == n2)
assert_array_almost_equal(times_data, times2)
else:
# we get the same result for the probed connections
assert_true(len(con) == len(con2))
assert (len(con) == len(con2))
for c, c2 in zip(con, con2):
assert_array_almost_equal(freqs, freqs2)
assert_array_almost_equal(c[indices], c2)
assert_true(n == n2)
assert (n == n2)
assert_array_almost_equal(times_data, times2)
# compute same connections for two bands, fskip=1, and f. avg.
@@ -198,11 +194,11 @@ def test_spectral_connectivity():
mt_bandwidth=mt_bandwidth, cwt_freqs=cwt_freqs,
cwt_n_cycles=cwt_n_cycles)
assert_true(isinstance(freqs3, list))
assert_true(len(freqs3) == len(fmin))
assert (isinstance(freqs3, list))
assert (len(freqs3) == len(fmin))
for i in range(len(freqs3)):
assert_true(np.all((freqs3[i] >= fmin[i]) &
(freqs3[i] <= fmax[i])))
assert np.all((freqs3[i] >= fmin[i]) &
(freqs3[i] <= fmax[i]))
# average con2 "manually" and we get the same result
if not isinstance(method, list):
@@ -219,9 +215,10 @@ def test_spectral_connectivity():
# test _get_n_epochs
full_list = list(range(10))
out_lens = np.array([len(x) for x in _get_n_epochs(full_list, 4)])
assert_true((out_lens == np.array([4, 4, 2])).all())
assert ((out_lens == np.array([4, 4, 2])).all())
out_lens = np.array([len(x) for x in _get_n_epochs(full_list, 11)])
assert_true(len(out_lens) > 0)
assert_true(out_lens[0] == 10)
assert (len(out_lens) > 0)
assert (out_lens[0] == 10)
run_tests_if_main()
+6 -7
View File
@@ -1,11 +1,10 @@
import numpy as np
from nose.tools import assert_true
from mne.connectivity import seed_target_indices
def test_indices():
"""Test connectivity indexing methods"""
"""Test connectivity indexing methods."""
n_seeds_test = [1, 3, 4]
n_targets_test = [2, 3, 200]
rng = np.random.RandomState(42)
@@ -15,10 +14,10 @@ def test_indices():
seeds = idx[:n_seeds]
targets = idx[n_seeds:]
indices = seed_target_indices(seeds, targets)
assert_true(len(indices) == 2)
assert_true(len(indices[0]) == len(indices[1]))
assert_true(len(indices[0]) == n_seeds * n_targets)
assert len(indices) == 2
assert len(indices[0]) == len(indices[1])
assert len(indices[0]) == n_seeds * n_targets
for seed in seeds:
assert_true(np.sum(indices[0] == seed) == n_targets)
assert np.sum(indices[0] == seed) == n_targets
for target in targets:
assert_true(np.sum(indices[1] == target) == n_seeds)
assert np.sum(indices[1] == target) == n_seeds
+8 -4
View File
@@ -5,8 +5,6 @@
from functools import partial
import numpy as np
from ...utils import verbose, get_config
from ..utils import (has_dataset, _data_path, _data_path_doc,
_get_version, _version_doc)
@@ -22,6 +20,7 @@ def data_path(path=None, force_update=False, update_path=True, download=True,
update_path=update_path, name='sample',
download=download)
data_path.__doc__ = _data_path_doc.format(name='sample',
conf='MNE_DATASETS_SAMPLE_PATH')
@@ -29,6 +28,7 @@ data_path.__doc__ = _data_path_doc.format(name='sample',
def get_version(): # noqa: D103
return _get_version('sample')
get_version.__doc__ = _version_doc.format(name='sample')
@@ -39,5 +39,9 @@ def _skip_sample_data():
skip = skip_testing or not has_sample_data()
return skip
requires_sample_data = np.testing.dec.skipif(_skip_sample_data,
'Requires sample dataset')
def requires_sample_data(func):
"""Skip testing data test."""
import pytest
return pytest.mark.skipif(_skip_sample_data(),
reason='Requires sample dataset')(func)
+8 -4
View File
@@ -4,8 +4,6 @@
from functools import partial
import numpy as np
from ...utils import verbose, get_config
from ..utils import (has_dataset, _data_path, _data_path_doc,
_get_version, _version_doc)
@@ -21,6 +19,7 @@ def data_path(path=None, force_update=False, update_path=True, download=True,
update_path=update_path, name='spm',
download=download)
data_path.__doc__ = _data_path_doc.format(name='spm',
conf='MNE_DATASETS_SPM_DATA_PATH')
@@ -28,6 +27,7 @@ data_path.__doc__ = _data_path_doc.format(name='spm',
def get_version(): # noqa: D103
return _get_version('spm')
get_version.__doc__ = _version_doc.format(name='spm')
@@ -37,5 +37,9 @@ def _skip_spm_data():
skip = skip_testing or not has_spm_data()
return skip
requires_spm_data = np.testing.dec.skipif(_skip_spm_data,
'Requires spm dataset')
def requires_spm_data(func):
"""Skip testing data test."""
import pytest
return pytest.mark.skipif(_skip_spm_data(),
reason='Requires spm dataset')(func)
+8 -4
View File
@@ -5,8 +5,6 @@
from functools import partial
import numpy as np
from ...utils import verbose, get_config
from ..utils import (has_dataset, _data_path, _data_path_doc,
_get_version, _version_doc)
@@ -26,6 +24,7 @@ def data_path(path=None, force_update=False, update_path=True,
update_path=update_path, name='testing',
download=download)
data_path.__doc__ = _data_path_doc.format(name='testing',
conf='MNE_DATASETS_TESTING_PATH')
@@ -33,6 +32,7 @@ data_path.__doc__ = _data_path_doc.format(name='testing',
def get_version(): # noqa: D103
return _get_version('testing')
get_version.__doc__ = _version_doc.format(name='testing')
@@ -44,5 +44,9 @@ def _skip_testing_data():
skip = skip_testing or not has_testing_data()
return skip
requires_testing_data = np.testing.dec.skipif(_skip_testing_data,
'Requires testing dataset')
def requires_testing_data(func):
"""Skip testing data test."""
import pytest
return pytest.mark.skipif(_skip_testing_data(),
reason='Requires testing dataset')(func)
+8 -9
View File
@@ -1,6 +1,5 @@
import os
from os import path as op
from nose.tools import assert_true, assert_equal
from mne import datasets
from mne.externals.six import string_types
@@ -17,16 +16,16 @@ def test_datasets():
else:
dataset = getattr(datasets, dname)
if dataset.data_path(download=False) != '':
assert_true(isinstance(dataset.get_version(), string_types))
assert isinstance(dataset.get_version(), string_types)
else:
assert_true(dataset.get_version() is None)
assert dataset.get_version() is None
tempdir = _TempDir()
# don't let it read from the config file to get the directory,
# force it to look for the default
os.environ['_MNE_FAKE_HOME_DIR'] = tempdir
try:
assert_equal(datasets.utils._get_path(None, 'foo', 'bar'),
op.join(tempdir, 'mne_data'))
assert (datasets.utils._get_path(None, 'foo', 'bar') ==
op.join(tempdir, 'mne_data'))
finally:
del os.environ['_MNE_FAKE_HOME_DIR']
@@ -37,8 +36,8 @@ def test_megsim():
data_dir = _TempDir()
paths = datasets.megsim.load_data(
'index', 'text', 'text', path=data_dir, update_path=False)
assert_equal(len(paths), 1)
assert_true(paths[0].endswith('index.html'))
assert len(paths) == 1
assert paths[0].endswith('index.html')
@requires_good_network
@@ -47,8 +46,8 @@ def test_downloads():
# Try actually downloading a dataset
data_dir = _TempDir()
path = datasets._fake.data_path(path=data_dir, update_path=False)
assert_true(op.isfile(op.join(path, 'bar')))
assert_true(datasets._fake.get_version() is None)
assert op.isfile(op.join(path, 'bar'))
assert datasets._fake.get_version() is None
run_tests_if_main()
+14 -13
View File
@@ -4,8 +4,10 @@
# License: BSD (3-clause)
import numpy as np
from numpy.testing import assert_array_equal, assert_array_almost_equal
from nose.tools import assert_true, assert_equal, assert_raises
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
assert_equal)
import pytest
from mne.fixes import is_regressor, is_classifier
from mne.utils import requires_version
from mne.decoding.base import (_get_inverse_funcs, LinearModel, get_coef,
@@ -36,7 +38,6 @@ def _make_data(n_samples=1000, n_features=5, n_targets=3):
The forward model, mapping the latent variables (=Y) to the measured
data (=X).
"""
# Define Y latent factors
np.random.seed(0)
cov_Y = np.eye(n_targets) * 10 + np.random.rand(n_targets, n_targets)
@@ -63,10 +64,10 @@ def test_get_coef():
from sklearn.linear_model import Ridge, LinearRegression
lm = LinearModel()
assert_true(is_classifier(lm))
assert (is_classifier(lm))
lm = LinearModel(Ridge())
assert_true(is_regressor(lm))
assert (is_regressor(lm))
# Define a classifier, an invertible transformer and an non-invertible one.
@@ -99,7 +100,7 @@ def test_get_coef():
for expected_n, est in good_estimators:
est.fit(X, y)
assert_true(expected_n == len(_get_inverse_funcs(est)))
assert (expected_n == len(_get_inverse_funcs(est)))
bad_estimators = [
Clf(), # no preprocessing
@@ -124,15 +125,15 @@ def test_get_coef():
coefs = clf.model.coef_
assert_array_equal(filters, coefs[0])
patterns = get_coef(clf, 'patterns_', False)
assert_true(filters[0] != patterns[0])
assert (filters[0] != patterns[0])
n_chans = X.shape[1]
assert_array_equal(filters.shape, patterns.shape, [n_chans, n_chans])
# Inverse transform linear model
filters_inv = get_coef(clf, 'filters_', True)
assert_true(filters[0] != filters_inv[0])
assert (filters[0] != filters_inv[0])
patterns_inv = get_coef(clf, 'patterns_', True)
assert_true(patterns[0] != patterns_inv[0])
assert (patterns[0] != patterns_inv[0])
# Check with search_light and combination of preprocessing ending with sl:
slider = SlidingEstimator(make_pipeline(StandardScaler(), lm))
@@ -178,7 +179,7 @@ def test_linearmodel():
clf.fit(X, y)
assert_equal(clf.filters_.shape, (n_features,))
assert_equal(clf.patterns_.shape, (n_features,))
assert_raises(ValueError, clf.fit, np.random.rand(n, n_features, 99), y)
pytest.raises(ValueError, clf.fit, np.random.rand(n, n_features, 99), y)
# check multi-target fit
n_targets = 5
@@ -187,7 +188,7 @@ def test_linearmodel():
clf.fit(X, Y)
assert_equal(clf.filters_.shape, (n_targets, n_features))
assert_equal(clf.patterns_.shape, (n_targets, n_features))
assert_raises(ValueError, clf.fit, X, np.random.rand(n, n_features, 99))
pytest.raises(ValueError, clf.fit, X, np.random.rand(n, n_features, 99))
@requires_version('sklearn', '0.18')
@@ -222,7 +223,7 @@ def test_cross_val_multiscore():
# raise an error if scoring is defined at cross-val-score level and
# search light, because search light does not return a 1-dimensional
# prediction.
assert_raises(ValueError, cross_val_multiscore, clf, X, y, cv=cv,
pytest.raises(ValueError, cross_val_multiscore, clf, X, y, cv=cv,
scoring='roc_auc')
clf = SlidingEstimator(LogisticRegression(), scoring='roc_auc')
scores_auc = cross_val_multiscore(clf, X, y, cv=cv, n_jobs=1)
@@ -243,7 +244,7 @@ def test_cross_val_multiscore():
manual = cross_val(clf, X, y, cv=StratifiedKFold(2))
auto = cross_val(clf, X, y, cv=2)
assert_array_equal(manual, auto)
assert_raises(ValueError, cross_val, clf, X, y, cv=KFold(2))
pytest.raises(ValueError, cross_val, clf, X, y, cv=KFold(2))
manual = cross_val(reg, X, y, cv=KFold(2))
auto = cross_val(reg, X, y, cv=2)
+37 -38
View File
@@ -7,10 +7,10 @@
import os.path as op
from nose.tools import assert_true, assert_raises, assert_equal, assert_greater
import pytest
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_array_equal
from numpy.testing import (assert_array_almost_equal, assert_array_equal,
assert_equal)
from mne import io, Epochs, read_events, pick_types
from mne.decoding.csp import CSP, _ajd_pham, SPoC
@@ -49,8 +49,7 @@ def simulate_data(target, n_trials=100, n_channels=10, random_state=42):
@pytest.mark.slowtest
def test_csp():
"""Test Common Spatial Patterns algorithm on epochs
"""
"""Test Common Spatial Patterns algorithm on epochs."""
raw = io.read_raw_fif(raw_fname, preload=False)
events = read_events(event_name)
picks = pick_types(raw.info, meg=True, stim=False, ecg=False,
@@ -64,15 +63,15 @@ def test_csp():
y = epochs.events[:, -1]
# Init
assert_raises(ValueError, CSP, n_components='foo', norm_trace=False)
pytest.raises(ValueError, CSP, n_components='foo', norm_trace=False)
for reg in ['foo', -0.1, 1.1]:
csp = CSP(reg=reg, norm_trace=False)
assert_raises(ValueError, csp.fit, epochs_data, epochs.events[:, -1])
pytest.raises(ValueError, csp.fit, epochs_data, epochs.events[:, -1])
for reg in ['oas', 'ledoit_wolf', 0, 0.5, 1.]:
CSP(reg=reg, norm_trace=False)
for cov_est in ['foo', None]:
assert_raises(ValueError, CSP, cov_est=cov_est, norm_trace=False)
assert_raises(ValueError, CSP, norm_trace='foo')
pytest.raises(ValueError, CSP, cov_est=cov_est, norm_trace=False)
pytest.raises(ValueError, CSP, norm_trace='foo')
for cov_est in ['concat', 'epoch']:
CSP(cov_est=cov_est, norm_trace=False)
@@ -88,16 +87,16 @@ def test_csp():
# Transform
X = csp.fit_transform(epochs_data, y)
sources = csp.transform(epochs_data)
assert_true(sources.shape[1] == n_components)
assert_true(csp.filters_.shape == (n_channels, n_channels))
assert_true(csp.patterns_.shape == (n_channels, n_channels))
assert (sources.shape[1] == n_components)
assert (csp.filters_.shape == (n_channels, n_channels))
assert (csp.patterns_.shape == (n_channels, n_channels))
assert_array_almost_equal(sources, X)
# Test data exception
assert_raises(ValueError, csp.fit, epochs_data,
pytest.raises(ValueError, csp.fit, epochs_data,
np.zeros_like(epochs.events))
assert_raises(ValueError, csp.fit, epochs, y)
assert_raises(ValueError, csp.transform, epochs)
pytest.raises(ValueError, csp.fit, epochs, y)
pytest.raises(ValueError, csp.transform, epochs)
# Test plots
epochs.pick_types(meg='mag')
@@ -123,27 +122,27 @@ def test_csp():
# Test average power transform
n_components = 2
assert_true(csp.transform_into == 'average_power')
assert (csp.transform_into == 'average_power')
feature_shape = [len(epochs_data), n_components]
X_trans = dict()
for log in (None, True, False):
csp = CSP(n_components=n_components, log=log, norm_trace=False)
assert_true(csp.log is log)
assert (csp.log is log)
Xt = csp.fit_transform(epochs_data, epochs.events[:, 2])
assert_array_equal(Xt.shape, feature_shape)
X_trans[str(log)] = Xt
# log=None => log=True
assert_array_almost_equal(X_trans['None'], X_trans['True'])
# Different normalization return different transform
assert_true(np.sum((X_trans['True'] - X_trans['False']) ** 2) > 1.)
assert (np.sum((X_trans['True'] - X_trans['False']) ** 2) > 1.)
# Check wrong inputs
assert_raises(ValueError, CSP, transform_into='average_power', log='foo')
pytest.raises(ValueError, CSP, transform_into='average_power', log='foo')
# Test csp space transform
csp = CSP(transform_into='csp_space', norm_trace=False)
assert_true(csp.transform_into == 'csp_space')
assert (csp.transform_into == 'csp_space')
for log in ('foo', True, False):
assert_raises(ValueError, CSP, transform_into='csp_space', log=log,
pytest.raises(ValueError, CSP, transform_into='csp_space', log=log,
norm_trace=False)
n_components = 2
csp = CSP(n_components=n_components, transform_into='csp_space',
@@ -164,12 +163,12 @@ def test_csp():
# check the first pattern match the mixing matrix
# the sign might change
corr = np.abs(np.corrcoef(csp.patterns_[0, :].T, A[:, 0])[0, 1])
assert_greater(np.abs(corr), 0.99)
assert np.abs(corr) > 0.99
# check output
out = csp.transform(X)
corr = np.abs(np.corrcoef(out[:, 0], y)[0, 1])
assert_greater(np.abs(corr), 0.95)
assert np.abs(corr) > 0.95
@requires_sklearn
@@ -192,39 +191,38 @@ def test_regularized_csp():
csp.fit(epochs_data, epochs.events[:, -1])
y = epochs.events[:, -1]
X = csp.fit_transform(epochs_data, y)
assert_true(csp.filters_.shape == (n_channels, n_channels))
assert_true(csp.patterns_.shape == (n_channels, n_channels))
assert (csp.filters_.shape == (n_channels, n_channels))
assert (csp.patterns_.shape == (n_channels, n_channels))
assert_array_almost_equal(csp.fit(epochs_data, y).
transform(epochs_data), X)
# test init exception
assert_raises(ValueError, csp.fit, epochs_data,
pytest.raises(ValueError, csp.fit, epochs_data,
np.zeros_like(epochs.events))
assert_raises(ValueError, csp.fit, epochs, y)
assert_raises(ValueError, csp.transform, epochs)
pytest.raises(ValueError, csp.fit, epochs, y)
pytest.raises(ValueError, csp.transform, epochs)
csp.n_components = n_components
sources = csp.transform(epochs_data)
assert_true(sources.shape[1] == n_components)
assert (sources.shape[1] == n_components)
@requires_sklearn
def test_csp_pipeline():
"""Test if CSP works in a pipeline
"""
"""Test if CSP works in a pipeline."""
from sklearn.svm import SVC
from sklearn.pipeline import Pipeline
csp = CSP(reg=1, norm_trace=False)
svc = SVC()
pipe = Pipeline([("CSP", csp), ("SVC", svc)])
pipe.set_params(CSP__reg=0.2)
assert_true(pipe.get_params()["CSP__reg"] == 0.2)
assert (pipe.get_params()["CSP__reg"] == 0.2)
def test_ajd():
"""Test if Approximate joint diagonalization implementation obtains same
results as the Matlab implementation by Pham Dinh-Tuan.
"""
"""Test approximate joint diagonalization."""
# The implementation shuold obtain the same
# results as the Matlab implementation by Pham Dinh-Tuan.
# Generate a set of cavariances matrices for test purpose
n_times, n_channels = 10, 3
seed = np.random.RandomState(0)
@@ -243,6 +241,7 @@ def test_ajd():
def test_spoc():
"""Test SPoC."""
X = np.random.randn(10, 10, 20)
y = np.random.randn(10)
@@ -258,10 +257,10 @@ def test_spoc():
assert_array_equal(spoc.patterns_.shape, [10, 10])
# check y
assert_raises(ValueError, spoc.fit, X, y * 0)
pytest.raises(ValueError, spoc.fit, X, y * 0)
# Check that doesn't take CSP-spcific input
assert_raises(TypeError, SPoC, cov_est='epoch')
pytest.raises(TypeError, SPoC, cov_est='epoch')
# Check mixing matrix on simulated data
rs = np.random.RandomState(42)
@@ -274,9 +273,9 @@ def test_spoc():
# check the first patterns match the mixing matrix
corr = np.abs(np.corrcoef(spoc.patterns_[0, :].T, A[:, 0])[0, 1])
assert_greater(np.abs(corr), 0.99)
assert np.abs(corr) > 0.99
# check output
out = spoc.transform(X)
corr = np.abs(np.corrcoef(out[:, 0], y)[0, 1])
assert_greater(np.abs(corr), 0.85)
assert np.abs(corr) > 0.85
+7 -7
View File
@@ -4,8 +4,8 @@
import os.path as op
import numpy as np
from numpy.testing import assert_array_almost_equal
from nose.tools import assert_equal, assert_raises
from numpy.testing import assert_array_almost_equal, assert_equal
import pytest
from mne import io, Epochs, read_events, pick_types
from mne.utils import requires_version, check_version, run_tests_if_main
@@ -34,10 +34,10 @@ def test_ems():
picks = picks[1:13:3]
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True)
assert_raises(ValueError, compute_ems, epochs, ['aud_l', 'vis_l'])
pytest.raises(ValueError, compute_ems, epochs, ['aud_l', 'vis_l'])
epochs.equalize_event_counts(epochs.event_id)
assert_raises(KeyError, compute_ems, epochs, ['blah', 'hahah'])
pytest.raises(KeyError, compute_ems, epochs, ['blah', 'hahah'])
surrogates, filters, conditions = compute_ems(epochs)
assert_equal(list(set(conditions)), [1, 3])
@@ -49,7 +49,7 @@ def test_ems():
n_expected = sum([len(epochs[k]) for k in ['aud_l', 'vis_l']])
assert_raises(ValueError, compute_ems, epochs)
pytest.raises(ValueError, compute_ems, epochs)
surrogates, filters, conditions = compute_ems(epochs, ['aud_r', 'vis_l'])
assert_equal(n_expected, len(surrogates))
assert_equal(n_expected, len(conditions))
@@ -66,8 +66,8 @@ def test_ems():
cv = StratifiedKFold(epochs.events[:, 2])
compute_ems(epochs, cv=cv)
compute_ems(epochs, cv=2)
assert_raises(ValueError, compute_ems, epochs, cv='foo')
assert_raises(ValueError, compute_ems, epochs, cv=len(epochs) + 1)
pytest.raises(ValueError, compute_ems, epochs, cv='foo')
pytest.raises(ValueError, compute_ems, epochs, cv=len(epochs) + 1)
raw.close()
# EMS transformer, check that identical to compute_ems
+25 -26
View File
@@ -4,10 +4,10 @@
import warnings
import os.path as op
from nose.tools import assert_raises, assert_true, assert_equal
import pytest
import numpy as np
from numpy.testing import assert_array_equal, assert_allclose
from numpy.testing import assert_array_equal, assert_allclose, assert_equal
from mne import io, pick_types
from mne.fixes import einsum
@@ -86,7 +86,7 @@ def test_rank_deficiency():
pred = rf.predict(eeg)
assert_equal(y.shape, pred.shape)
corr = np.corrcoef(y.ravel(), pred.ravel())[0, 1]
assert_true(corr > 0.995, msg=corr)
assert corr > 0.995
def test_time_delay():
@@ -113,9 +113,9 @@ def test_time_delay():
((-.1, .1), 10)]
for (tmin, tmax), isfreq in test_tlims:
# sfreq must be int/float
assert_raises(TypeError, _delay_time_series, X, tmin, tmax, sfreq=[1])
pytest.raises(TypeError, _delay_time_series, X, tmin, tmax, sfreq=[1])
# Delays must be int/float
assert_raises(TypeError, _delay_time_series, X,
pytest.raises(TypeError, _delay_time_series, X,
np.complex(tmin), tmax, 1)
# Make sure swapaxes works
start, stop = int(round(tmin * isfreq)), int(round(tmax * isfreq)) + 1
@@ -129,8 +129,8 @@ def test_time_delay():
expected = np.where((X_delayed != 0).all(-1).all(-1))[0]
got = np.arange(len(X_delayed))[keep]
assert_array_equal(got, expected)
assert_true(X_delayed[keep].shape[-1] > 0)
assert_true((X_delayed[keep] == 0).sum() == 0)
assert X_delayed[keep].shape[-1] > 0
assert (X_delayed[keep] == 0).sum() == 0
del_zero = int(round(-tmin * isfreq))
for ii in range(-2, 3):
@@ -179,41 +179,41 @@ def test_receptive_field():
y_pred = rf.predict(X)
assert_allclose(y[rf.valid_samples_], y_pred[rf.valid_samples_], atol=1e-2)
scores = rf.score(X, y)
assert_true(scores > .99)
assert scores > .99
assert_allclose(rf.coef_.T.ravel(), w, atol=1e-2)
# Make sure different input shapes work
rf.fit(X[:, np.newaxis:, ], y[:, np.newaxis])
rf.fit(X, y[:, np.newaxis])
assert_raises(ValueError, rf.fit, X[..., np.newaxis], y)
assert_raises(ValueError, rf.fit, X[:, 0], y)
assert_raises(ValueError, rf.fit, X[..., np.newaxis],
pytest.raises(ValueError, rf.fit, X[..., np.newaxis], y)
pytest.raises(ValueError, rf.fit, X[:, 0], y)
pytest.raises(ValueError, rf.fit, X[..., np.newaxis],
np.tile(y[..., np.newaxis], [2, 1, 1]))
# stim features must match length of input data
assert_raises(ValueError, rf.fit, X[:, :1], y)
pytest.raises(ValueError, rf.fit, X[:, :1], y)
# auto-naming features
rf = ReceptiveField(tmin, tmax, 1, estimator=mod)
rf.fit(X, y)
assert_equal(rf.feature_names, ['feature_%s' % ii for ii in [0, 1, 2]])
# X/y same n timepoints
assert_raises(ValueError, rf.fit, X, y[:-2])
pytest.raises(ValueError, rf.fit, X, y[:-2])
# Float becomes ridge
rf = ReceptiveField(tmin, tmax, 1, ['one', 'two', 'three'],
estimator=0, patterns=True)
str(rf) # repr works before fit
rf.fit(X, y)
assert_true(isinstance(rf.estimator_, TimeDelayingRidge))
assert isinstance(rf.estimator_, TimeDelayingRidge)
str(rf) # repr works after fit
rf = ReceptiveField(tmin, tmax, 1, ['one'], estimator=0, patterns=True)
rf.fit(X[:, [0]], y)
str(rf) # repr with one feature
# Should only accept estimators or floats
rf = ReceptiveField(tmin, tmax, 1, estimator='foo', patterns=True)
assert_raises(ValueError, rf.fit, X, y)
pytest.raises(ValueError, rf.fit, X, y)
rf = ReceptiveField(tmin, tmax, 1, estimator=np.array([1, 2, 3]))
assert_raises(ValueError, rf.fit, X, y)
pytest.raises(ValueError, rf.fit, X, y)
# tmin must be <= tmax
rf = ReceptiveField(5, 4, 1, patterns=True)
assert_raises(ValueError, rf.fit, X, y)
pytest.raises(ValueError, rf.fit, X, y)
# scorers
for key, val in _SCORERS.items():
rf = ReceptiveField(tmin, tmax, 1, ['one'],
@@ -224,11 +224,11 @@ def test_receptive_field():
multioutput='raw_values'),
rf.score(X[:, [0]], y), rtol=1e-2)
# Need 2D input
assert_raises(ValueError, _SCORERS['corrcoef'], y.ravel(), y_pred,
pytest.raises(ValueError, _SCORERS['corrcoef'], y.ravel(), y_pred,
multioutput='raw_values')
# Need correct scorers
rf = ReceptiveField(tmin, tmax, 1., scoring='foo')
assert_raises(ValueError, rf.fit, X, y)
pytest.raises(ValueError, rf.fit, X, y)
def test_time_delaying_fast_calc():
@@ -380,7 +380,7 @@ def test_receptive_field_1d():
model.predict(use_x)[model.valid_samples_],
y[model.valid_samples_], atol=1e-2)
score = np.mean(model.score(use_x, y))
assert_true(score > 0.9999, msg=score)
assert score > 0.9999
@requires_version('sklearn', '0.17')
@@ -417,10 +417,10 @@ def test_receptive_field_nd():
assert_allclose(model.coef_, expected, atol=1e-1)
tdr = TimeDelayingRidge(slim[0], slim[1], 1., 0.01, reg_type='foo')
model = ReceptiveField(slim[0], slim[1], 1., estimator=tdr)
assert_raises(ValueError, model.fit, x, y)
pytest.raises(ValueError, model.fit, x, y)
tdr = TimeDelayingRidge(slim[0], slim[1], 1., 0.01, reg_type=['laplacian'])
model = ReceptiveField(slim[0], slim[1], 1., estimator=tdr)
assert_raises(ValueError, model.fit, x, y)
pytest.raises(ValueError, model.fit, x, y)
# Now check the intercept_
tdr = TimeDelayingRidge(slim[0], slim[1], 1., 0.)
@@ -469,7 +469,7 @@ def test_receptive_field_nd():
model.fit(x_off, y)
assert_allclose(model.estimator_.intercept_, 0., atol=1e-7)
score = np.mean(model.score(x_off, y))
assert_true(score > 0.6, msg=score)
assert score > 0.6
@requires_version('sklearn', '0.17')
@@ -523,9 +523,8 @@ def test_inverse_coef():
if estimator and not check_version('numpy', '1.13'):
continue
assert_equal(len(w), 1)
assert_true(any(x in str(w[0].message).lower()
for x in ('singular', 'scipy.linalg.solve')),
msg=str(w[0].message))
assert any(x in str(w[0].message).lower()
for x in ('singular', 'scipy.linalg.solve'))
run_tests_if_main()
+27 -25
View File
@@ -4,14 +4,16 @@
import numpy as np
from numpy.testing import assert_array_equal
from nose.tools import assert_raises, assert_true, assert_equal
from numpy.testing import assert_array_equal, assert_equal
import pytest
from mne.utils import requires_version
from mne.decoding.search_light import SlidingEstimator, GeneralizingEstimator
from mne.decoding.transformer import Vectorizer
def make_data():
"""Make data."""
n_epochs, n_chan, n_time = 50, 32, 10
X = np.random.rand(n_epochs, n_chan, n_time)
y = np.arange(n_epochs) % 2
@@ -24,7 +26,7 @@ def make_data():
@requires_version('sklearn', '0.17')
def test_search_light():
"""Test SlidingEstimator"""
"""Test SlidingEstimator."""
from sklearn.linear_model import Ridge, LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.metrics import roc_auc_score, make_scorer
@@ -34,33 +36,33 @@ def test_search_light():
X, y = make_data()
n_epochs, _, n_time = X.shape
# init
assert_raises(ValueError, SlidingEstimator, 'foo')
pytest.raises(ValueError, SlidingEstimator, 'foo')
sl = SlidingEstimator(Ridge())
assert_true(not is_classifier(sl))
assert (not is_classifier(sl))
sl = SlidingEstimator(LogisticRegression())
assert_true(is_classifier(sl))
assert (is_classifier(sl))
# fit
assert_equal(sl.__repr__()[:18], '<SlidingEstimator(')
sl.fit(X, y)
assert_equal(sl.__repr__()[-28:], ', fitted with 10 estimators>')
assert_raises(ValueError, sl.fit, X[1:], y)
assert_raises(ValueError, sl.fit, X[:, :, 0], y)
pytest.raises(ValueError, sl.fit, X[1:], y)
pytest.raises(ValueError, sl.fit, X[:, :, 0], y)
sl.fit(X, y, sample_weight=np.ones_like(y))
# transforms
assert_raises(ValueError, sl.predict, X[:, :, :2])
pytest.raises(ValueError, sl.predict, X[:, :, :2])
y_pred = sl.predict(X)
assert_true(y_pred.dtype == int)
assert (y_pred.dtype == int)
assert_array_equal(y_pred.shape, [n_epochs, n_time])
y_proba = sl.predict_proba(X)
assert_true(y_proba.dtype == float)
assert (y_proba.dtype == float)
assert_array_equal(y_proba.shape, [n_epochs, n_time, 2])
# score
score = sl.score(X, y)
assert_array_equal(score.shape, [n_time])
assert_true(np.sum(np.abs(score)) != 0)
assert_true(score.dtype == float)
assert (np.sum(np.abs(score)) != 0)
assert (score.dtype == float)
sl = SlidingEstimator(LogisticRegression())
assert_equal(sl.scoring, None)
@@ -69,7 +71,7 @@ def test_search_light():
for scoring in ['foo', 999]:
sl = SlidingEstimator(LogisticRegression(), scoring=scoring)
sl.fit(X, y)
assert_raises((ValueError, TypeError), sl.score, X, y)
pytest.raises((ValueError, TypeError), sl.score, X, y)
# Check sklearn's roc_auc fix: scikit-learn/scikit-learn#6874
# -- 3 class problem
@@ -77,7 +79,7 @@ def test_search_light():
scoring='roc_auc')
y = np.arange(len(X)) % 3
sl.fit(X, y)
assert_raises(ValueError, sl.score, X, y)
pytest.raises(ValueError, sl.score, X, y)
# -- 2 class problem not in [0, 1]
y = np.arange(len(X)) % 2 + 1
sl.fit(X, y)
@@ -89,7 +91,7 @@ def test_search_light():
# Cannot pass a metric as a scoring parameter
sl1 = SlidingEstimator(LogisticRegression(), scoring=roc_auc_score)
sl1.fit(X, y)
assert_raises(ValueError, sl1.score, X, y)
pytest.raises(ValueError, sl1.score, X, y)
# Now use string as scoring
sl1 = SlidingEstimator(LogisticRegression(), scoring='roc_auc')
@@ -98,7 +100,7 @@ def test_search_light():
X = rng.randn(*X.shape) # randomize X to avoid AUCs in [0, 1]
score_sl = sl1.score(X, y)
assert_array_equal(score_sl.shape, [n_time])
assert_true(score_sl.dtype == float)
assert (score_sl.dtype == float)
# Check that scoring was applied adequately
scoring = make_scorer(roc_auc_score, needs_threshold=True)
@@ -149,12 +151,12 @@ def test_search_light():
pipe = SlidingEstimator(BaggingClassifier(None, 2), n_jobs=n_jobs)
pipe.fit(X, y)
pipe.score(X, y)
assert_true(isinstance(pipe.estimators_[0], BaggingClassifier))
assert (isinstance(pipe.estimators_[0], BaggingClassifier))
@requires_version('sklearn', '0.17')
def test_generalization_light():
"""Test GeneralizingEstimator"""
"""Test GeneralizingEstimator."""
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
@@ -171,9 +173,9 @@ def test_generalization_light():
# transforms
y_pred = gl.predict(X)
assert_array_equal(y_pred.shape, [n_epochs, n_time, n_time])
assert_true(y_pred.dtype == int)
assert (y_pred.dtype == int)
y_proba = gl.predict_proba(X)
assert_true(y_proba.dtype == float)
assert (y_proba.dtype == float)
assert_array_equal(y_proba.shape, [n_epochs, n_time, n_time, 2])
# transform to different datasize
@@ -183,8 +185,8 @@ def test_generalization_light():
# score
score = gl.score(X[:, :, :3], y)
assert_array_equal(score.shape, [n_time, 3])
assert_true(np.sum(np.abs(score)) != 0)
assert_true(score.dtype == float)
assert (np.sum(np.abs(score)) != 0)
assert (score.dtype == float)
gl = GeneralizingEstimator(LogisticRegression(), scoring='roc_auc')
gl.fit(X, y)
@@ -195,14 +197,14 @@ def test_generalization_light():
for scoring in ['foo', 999]:
gl = GeneralizingEstimator(LogisticRegression(), scoring=scoring)
gl.fit(X, y)
assert_raises((ValueError, TypeError), gl.score, X, y)
pytest.raises((ValueError, TypeError), gl.score, X, y)
# Check sklearn's roc_auc fix: scikit-learn/scikit-learn#6874
# -- 3 class problem
gl = GeneralizingEstimator(LogisticRegression(), scoring='roc_auc')
y = np.arange(len(X)) % 3
gl.fit(X, y)
assert_raises(ValueError, gl.score, X, y)
pytest.raises(ValueError, gl.score, X, y)
# -- 2 class problem not in [0, 1]
y = np.arange(len(X)) % 2 + 1
gl.fit(X, y)
+4 -2
View File
@@ -5,20 +5,22 @@
import numpy as np
from numpy.testing import assert_array_equal
from nose.tools import assert_raises
import pytest
from mne.utils import requires_sklearn
from mne.decoding.time_frequency import TimeFrequency
@requires_sklearn
def test_timefrequency():
"""Test TimeFrequency."""
from sklearn.base import clone
# Init
n_freqs = 3
freqs = np.linspace(20, 30, n_freqs)
tf = TimeFrequency(freqs, sfreq=100)
for output in ['avg_power', 'foo', None]:
assert_raises(ValueError, TimeFrequency, freqs, output=output)
pytest.raises(ValueError, TimeFrequency, freqs, output=output)
tf = clone(tf)
# Fit
+22 -22
View File
@@ -7,9 +7,9 @@ import warnings
import os.path as op
import numpy as np
from nose.tools import assert_true, assert_raises, assert_equal
import pytest
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
assert_allclose)
assert_allclose, assert_equal)
from mne import io, read_events, Epochs, pick_types
from mne.decoding import (Scaler, FilterEstimator, PSDEstimator, Vectorizer,
@@ -46,10 +46,10 @@ def test_scaler():
epochs_data_t = epochs_data.transpose([1, 0, 2])
for method, info in zip(methods, infos):
if method == 'median' and not check_version('sklearn', '0.17'):
assert_raises(ValueError, Scaler, info, method)
pytest.raises(ValueError, Scaler, info, method)
continue
if method == 'mean' and not check_version('sklearn', ''):
assert_raises(ImportError, Scaler, info, method)
pytest.raises(ImportError, Scaler, info, method)
continue
scaler = Scaler(info, method)
X = scaler.fit_transform(epochs_data, y)
@@ -80,13 +80,13 @@ def test_scaler():
assert_array_almost_equal(epochs_data, Xi)
# Test init exception
assert_raises(ValueError, Scaler, None, None)
assert_raises(ValueError, scaler.fit, epochs, y)
assert_raises(ValueError, scaler.transform, epochs)
pytest.raises(ValueError, Scaler, None, None)
pytest.raises(ValueError, scaler.fit, epochs, y)
pytest.raises(ValueError, scaler.transform, epochs)
epochs_bad = Epochs(raw, events, event_id, 0, 0.01,
picks=np.arange(len(raw.ch_names))) # non-data chs
scaler = Scaler(epochs_bad.info, None)
assert_raises(ValueError, scaler.fit, epochs_bad.get_data(), y)
pytest.raises(ValueError, scaler.fit, epochs_bad.get_data(), y)
def test_filterestimator():
@@ -105,7 +105,7 @@ def test_filterestimator():
y = epochs.events[:, -1]
with warnings.catch_warnings(record=True): # stop freq attenuation warning
X = filt.fit_transform(epochs_data, y)
assert_true(X.shape == epochs_data.shape)
assert (X.shape == epochs_data.shape)
assert_array_equal(filt.fit(epochs_data, y).transform(epochs_data), X)
filt = FilterEstimator(epochs.info, l_freq=None, h_freq=40,
@@ -118,7 +118,7 @@ def test_filterestimator():
filt = FilterEstimator(epochs.info, l_freq=1, h_freq=1)
y = epochs.events[:, -1]
with warnings.catch_warnings(record=True): # stop freq attenuation warning
assert_raises(ValueError, filt.fit_transform, epochs_data, y)
pytest.raises(ValueError, filt.fit_transform, epochs_data, y)
filt = FilterEstimator(epochs.info, l_freq=40, h_freq=None,
filter_length='auto',
@@ -127,8 +127,8 @@ def test_filterestimator():
X = filt.fit_transform(epochs_data, y)
# Test init exception
assert_raises(ValueError, filt.fit, epochs, y)
assert_raises(ValueError, filt.transform, epochs)
pytest.raises(ValueError, filt.fit, epochs, y)
pytest.raises(ValueError, filt.transform, epochs)
def test_psdestimator():
@@ -145,12 +145,12 @@ def test_psdestimator():
y = epochs.events[:, -1]
X = psd.fit_transform(epochs_data, y)
assert_true(X.shape[0] == epochs_data.shape[0])
assert (X.shape[0] == epochs_data.shape[0])
assert_array_equal(psd.fit(epochs_data, y).transform(epochs_data), X)
# Test init exception
assert_raises(ValueError, psd.fit, epochs, y)
assert_raises(ValueError, psd.transform, epochs)
pytest.raises(ValueError, psd.fit, epochs, y)
pytest.raises(ValueError, psd.transform, epochs)
def test_vectorizer():
@@ -173,8 +173,8 @@ def test_vectorizer():
# check if raised errors are working correctly
vect.fit(np.random.rand(105, 12, 3))
assert_raises(ValueError, vect.transform, np.random.rand(105, 12, 3, 1))
assert_raises(ValueError, vect.inverse_transform,
pytest.raises(ValueError, vect.transform, np.random.rand(105, 12, 3, 1))
pytest.raises(ValueError, vect.inverse_transform,
np.random.rand(102, 12, 12))
@@ -192,7 +192,7 @@ def test_unsupervised_spatial_filter():
preload=True, baseline=None, verbose=False)
# Test estimator
assert_raises(ValueError, UnsupervisedSpatialFilter, KernelRidge(2))
pytest.raises(ValueError, UnsupervisedSpatialFilter, KernelRidge(2))
# Test fit
X = epochs.get_data()
@@ -211,7 +211,7 @@ def test_unsupervised_spatial_filter():
# Test with average param
usf = UnsupervisedSpatialFilter(PCA(4), average=True)
usf.fit_transform(X)
assert_raises(ValueError, UnsupervisedSpatialFilter, PCA(4), 2)
pytest.raises(ValueError, UnsupervisedSpatialFilter, PCA(4), 2)
def test_temporal_filter():
@@ -223,18 +223,18 @@ def test_temporal_filter():
(10., 20., 5., 'auto'), (None, None, 100., '5hz'))
for low, high, sf, ltrans in values:
filt = TemporalFilter(low, high, sf, ltrans, fir_design='firwin')
assert_raises(ValueError, filt.fit_transform, X)
pytest.raises(ValueError, filt.fit_transform, X)
# Add tests for different combinations of l_freq and h_freq
for low, high in ((5., 15.), (None, 15.), (5., None)):
filt = TemporalFilter(low, high, sfreq=100., fir_design='firwin')
Xt = filt.fit_transform(X)
assert_array_equal(filt.fit_transform(X), Xt)
assert_true(X.shape == Xt.shape)
assert (X.shape == Xt.shape)
# Test fit and transform numpy type check
with warnings.catch_warnings(record=True):
assert_raises(TypeError, filt.transform, [1, 2])
pytest.raises(TypeError, filt.transform, [1, 2])
# Test with 2 dimensional data array
X = np.random.rand(101, 500)
-78
View File
@@ -16,7 +16,6 @@ from __future__ import division
import inspect
from distutils.version import LooseVersion
import re
import warnings
import numpy as np
@@ -938,83 +937,6 @@ def assert_is_not(expr1, expr2, msg=None):
assert_true(expr1 is not expr2, msg)
assert_raises_regex_impl = None
# from numpy 1.9.1
def assert_raises_regex(exception_class, expected_regexp,
callable_obj=None, *args, **kwargs):
"""
Fail unless an exception of class exception_class and with message that
matches expected_regexp is thrown by callable when invoked with arguments
args and keyword arguments kwargs.
Name of this function adheres to Python 3.2+ reference, but should work in
all versions down to 2.6.
"""
__tracebackhide__ = True # Hide traceback for py.test
import nose
global assert_raises_regex_impl
if assert_raises_regex_impl is None:
try:
# Python 3.2+
assert_raises_regex_impl = nose.tools.assert_raises_regex
except AttributeError:
try:
# 2.7+
assert_raises_regex_impl = nose.tools.assert_raises_regexp
except AttributeError:
# 2.6
# This class is copied from Python2.7 stdlib almost verbatim
class _AssertRaisesContext(object):
def __init__(self, expected, expected_regexp=None):
self.expected = expected
self.expected_regexp = expected_regexp
def failureException(self, msg):
return AssertionError(msg)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, tb):
if exc_type is None:
try:
exc_name = self.expected.__name__
except AttributeError:
exc_name = str(self.expected)
raise self.failureException(
"{0} not raised".format(exc_name))
if not issubclass(exc_type, self.expected):
# let unexpected exceptions pass through
return False
self.exception = exc_value # store for later retrieval
if self.expected_regexp is None:
return True
expected_regexp = self.expected_regexp
if isinstance(expected_regexp, basestring):
expected_regexp = re.compile(expected_regexp)
if not expected_regexp.search(str(exc_value)):
raise self.failureException(
'"%s" does not match "%s"' %
(expected_regexp.pattern, str(exc_value)))
return True
def impl(cls, regex, callable_obj, *a, **kw):
mgr = _AssertRaisesContext(cls, regex)
if callable_obj is None:
return mgr
with mgr:
callable_obj(*a, **kw)
assert_raises_regex_impl = impl
return assert_raises_regex_impl(exception_class, expected_regexp,
callable_obj, *args, **kwargs)
def _read_volume_info(fobj):
"""An implementation of nibabel.freesurfer.io._read_volume_info, since old
versions of nibabel (<=2.1.0) don't have it.
+21 -21
View File
@@ -5,7 +5,7 @@ from numpy.polynomial import legendre
from numpy.testing import (assert_allclose, assert_array_equal, assert_equal,
assert_array_almost_equal)
from scipy.interpolate import interp1d
from nose.tools import assert_raises, assert_true
import pytest
from mne.forward import _make_surface_mapping, make_field_map
@@ -114,21 +114,21 @@ def test_make_field_map_eeg():
evoked.info['bads'] = ['MEG 2443', 'EEG 053'] # add some bads
surf = get_head_surf('sample', subjects_dir=subjects_dir)
# we must have trans if surface is in MRI coords
assert_raises(ValueError, _make_surface_mapping, evoked.info, surf, 'eeg')
pytest.raises(ValueError, _make_surface_mapping, evoked.info, surf, 'eeg')
evoked.pick_types(meg=False, eeg=True)
fmd = make_field_map(evoked, trans_fname,
subject='sample', subjects_dir=subjects_dir)
# trans is necessary for EEG only
assert_raises(RuntimeError, make_field_map, evoked, None,
pytest.raises(RuntimeError, make_field_map, evoked, None,
subject='sample', subjects_dir=subjects_dir)
fmd = make_field_map(evoked, trans_fname,
subject='sample', subjects_dir=subjects_dir)
assert_true(len(fmd) == 1)
assert len(fmd) == 1
assert_array_equal(fmd[0]['data'].shape, (642, 59)) # maps data onto surf
assert_true(len(fmd[0]['ch_names']), 59)
assert len(fmd[0]['ch_names']) == 59
@testing.requires_testing_data
@@ -141,22 +141,22 @@ def test_make_field_map_meg():
# let's reduce the number of channels by a bunch to speed it up
info['bads'] = info['ch_names'][:200]
# bad ch_type
assert_raises(ValueError, _make_surface_mapping, info, surf, 'foo')
pytest.raises(ValueError, _make_surface_mapping, info, surf, 'foo')
# bad mode
assert_raises(ValueError, _make_surface_mapping, info, surf, 'meg',
pytest.raises(ValueError, _make_surface_mapping, info, surf, 'meg',
mode='foo')
# no picks
evoked_eeg = evoked.copy().pick_types(meg=False, eeg=True)
assert_raises(RuntimeError, _make_surface_mapping, evoked_eeg.info,
pytest.raises(RuntimeError, _make_surface_mapping, evoked_eeg.info,
surf, 'meg')
# bad surface def
nn = surf['nn']
del surf['nn']
assert_raises(KeyError, _make_surface_mapping, info, surf, 'meg')
pytest.raises(KeyError, _make_surface_mapping, info, surf, 'meg')
surf['nn'] = nn
cf = surf['coord_frame']
del surf['coord_frame']
assert_raises(KeyError, _make_surface_mapping, info, surf, 'meg')
pytest.raises(KeyError, _make_surface_mapping, info, surf, 'meg')
surf['coord_frame'] = cf
# now do it with make_field_map
@@ -164,22 +164,22 @@ def test_make_field_map_meg():
evoked.info.normalize_proj() # avoid projection warnings
fmd = make_field_map(evoked, None,
subject='sample', subjects_dir=subjects_dir)
assert_true(len(fmd) == 1)
assert (len(fmd) == 1)
assert_array_equal(fmd[0]['data'].shape, (304, 106)) # maps data onto surf
assert_true(len(fmd[0]['ch_names']), 106)
assert len(fmd[0]['ch_names']) == 106
assert_raises(ValueError, make_field_map, evoked, ch_type='foobar')
pytest.raises(ValueError, make_field_map, evoked, ch_type='foobar')
# now test the make_field_map on head surf for MEG
evoked.pick_types(meg=True, eeg=False)
evoked.info.normalize_proj()
fmd = make_field_map(evoked, trans_fname, meg_surf='head',
subject='sample', subjects_dir=subjects_dir)
assert_true(len(fmd) == 1)
assert len(fmd) == 1
assert_array_equal(fmd[0]['data'].shape, (642, 106)) # maps data onto surf
assert_true(len(fmd[0]['ch_names']), 106)
assert len(fmd[0]['ch_names']) == 106
assert_raises(ValueError, make_field_map, evoked, meg_surf='foobar',
pytest.raises(ValueError, make_field_map, evoked, meg_surf='foobar',
subjects_dir=subjects_dir, trans=trans_fname)
@@ -210,7 +210,7 @@ def test_make_field_map_meeg():
def _setup_args(info):
"""Helper to test_as_meg_type_evoked."""
"""Configure args for test_as_meg_type_evoked."""
coils = _create_meg_coils(info['chs'], 'normal', info['dev_head_t'])
int_rad, noise, lut_fun, n_fact = _setup_dots('fast', coils, 'meg')
my_origin = np.array([0., 0., 0.04])
@@ -224,8 +224,8 @@ def test_as_meg_type_evoked():
"""Test interpolation of data on to virtual channels."""
# validation tests
evoked = read_evokeds(evoked_fname, condition='Left Auditory')
assert_raises(ValueError, evoked.as_type, 'meg')
assert_raises(ValueError, evoked.copy().pick_types(meg='grad').as_type,
pytest.raises(ValueError, evoked.as_type, 'meg')
pytest.raises(ValueError, evoked.copy().pick_types(meg='grad').as_type,
'meg')
# channel names
@@ -233,7 +233,7 @@ def test_as_meg_type_evoked():
virt_evoked = evoked.copy().pick_channels(ch_names=ch_names[:10:1])
virt_evoked.info.normalize_proj()
virt_evoked = virt_evoked.as_type('mag')
assert_true(all(ch.endswith('_v') for ch in virt_evoked.info['ch_names']))
assert (all(ch.endswith('_v') for ch in virt_evoked.info['ch_names']))
# pick from and to channels
evoked_from = evoked.copy().pick_channels(ch_names=ch_names[2:10:3])
@@ -256,7 +256,7 @@ def test_as_meg_type_evoked():
evoked = evoked.pick_channels(ch_names=ch_names[:10:]).copy()
data1 = evoked.pick_types(meg='grad').data.ravel()
data2 = evoked.as_type('grad').data.ravel()
assert_true(np.corrcoef(data1, data2)[0, 1] > 0.95)
assert (np.corrcoef(data1, data2)[0, 1] > 0.95)
run_tests_if_main()
+48 -54
View File
@@ -3,7 +3,6 @@ import os.path as op
import warnings
import gc
from nose.tools import assert_true, assert_raises
import pytest
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_equal,
@@ -39,38 +38,37 @@ fname_src = op.join(subjects_dir, 'sample', 'bem', 'sample-oct-4-src.fif')
def compare_forwards(f1, f2):
"""Helper to compare two potentially converted forward solutions"""
"""Compare two potentially converted forward solutions."""
assert_allclose(f1['sol']['data'], f2['sol']['data'])
assert_equal(f1['sol']['ncol'], f2['sol']['ncol'])
assert_equal(f1['sol']['ncol'], f1['sol']['data'].shape[1])
assert_allclose(f1['source_nn'], f2['source_nn'])
if f1['sol_grad'] is not None:
assert_true(f2['sol_grad'] is not None)
assert (f2['sol_grad'] is not None)
assert_allclose(f1['sol_grad']['data'], f2['sol_grad']['data'])
assert_equal(f1['sol_grad']['ncol'], f2['sol_grad']['ncol'])
assert_equal(f1['sol_grad']['ncol'], f1['sol_grad']['data'].shape[1])
else:
assert_true(f2['sol_grad'] is None)
assert (f2['sol_grad'] is None)
assert_equal(f1['source_ori'], f2['source_ori'])
assert_equal(f1['surf_ori'], f2['surf_ori'])
@testing.requires_testing_data
def test_convert_forward():
"""Test converting forward solution between different representations
"""
"""Test converting forward solution between different representations."""
fwd = read_forward_solution(fname_meeg_grad)
fwd_repr = repr(fwd)
assert_true('306' in fwd_repr)
assert_true('60' in fwd_repr)
assert_true(fwd_repr)
assert_true(isinstance(fwd, Forward))
assert ('306' in fwd_repr)
assert ('60' in fwd_repr)
assert (fwd_repr)
assert (isinstance(fwd, Forward))
# look at surface orientation
fwd_surf = convert_forward_solution(fwd, surf_ori=True)
# go back
fwd_new = convert_forward_solution(fwd_surf, surf_ori=False)
assert_true(repr(fwd_new))
assert_true(isinstance(fwd_new, Forward))
assert (repr(fwd_new))
assert (isinstance(fwd_new, Forward))
compare_forwards(fwd, fwd_new)
del fwd_new
gc.collect()
@@ -80,14 +78,14 @@ def test_convert_forward():
force_fixed=True, use_cps=False)
del fwd_surf
gc.collect()
assert_true(repr(fwd_fixed))
assert_true(isinstance(fwd_fixed, Forward))
assert_true(is_fixed_orient(fwd_fixed))
assert (repr(fwd_fixed))
assert (isinstance(fwd_fixed, Forward))
assert (is_fixed_orient(fwd_fixed))
# now go back to cartesian (original condition)
fwd_new = convert_forward_solution(fwd_fixed, surf_ori=False,
force_fixed=False)
assert_true(repr(fwd_new))
assert_true(isinstance(fwd_new, Forward))
assert (repr(fwd_new))
assert (isinstance(fwd_new, Forward))
compare_forwards(fwd, fwd_new)
del fwd, fwd_new, fwd_fixed
gc.collect()
@@ -96,13 +94,12 @@ def test_convert_forward():
@pytest.mark.slowtest
@testing.requires_testing_data
def test_io_forward():
"""Test IO for forward solutions
"""
"""Test IO for forward solutions."""
temp_dir = _TempDir()
# do extensive tests with MEEG + grad
n_channels, n_src = 366, 108
fwd = read_forward_solution(fname_meeg_grad)
assert_true(isinstance(fwd, Forward))
assert (isinstance(fwd, Forward))
fwd = read_forward_solution(fname_meeg_grad)
fwd = convert_forward_solution(fwd, surf_ori=True)
leadfield = fwd['sol']['data']
@@ -121,8 +118,8 @@ def test_io_forward():
assert_equal(leadfield.shape, (n_channels, n_src))
assert_equal(len(fwd_read['sol']['row_names']), n_channels)
assert_equal(len(fwd_read['info']['chs']), n_channels)
assert_true('dev_head_t' in fwd_read['info'])
assert_true('mri_head_t' in fwd_read)
assert ('dev_head_t' in fwd_read['info'])
assert ('mri_head_t' in fwd_read)
assert_array_almost_equal(fwd['sol']['data'], fwd_read['sol']['data'])
fwd = read_forward_solution(fname_meeg)
@@ -134,9 +131,9 @@ def test_io_forward():
fwd_read = read_forward_solution(fname_temp)
fwd_read = convert_forward_solution(fwd_read, surf_ori=True,
force_fixed=True, use_cps=False)
assert_true(repr(fwd_read))
assert_true(isinstance(fwd_read, Forward))
assert_true(is_fixed_orient(fwd_read))
assert (repr(fwd_read))
assert (isinstance(fwd_read, Forward))
assert (is_fixed_orient(fwd_read))
compare_forwards(fwd, fwd_read)
fwd = convert_forward_solution(fwd, surf_ori=True, force_fixed=True,
@@ -145,18 +142,18 @@ def test_io_forward():
assert_equal(leadfield.shape, (n_channels, 1494 / 3))
assert_equal(len(fwd['sol']['row_names']), n_channels)
assert_equal(len(fwd['info']['chs']), n_channels)
assert_true('dev_head_t' in fwd['info'])
assert_true('mri_head_t' in fwd)
assert_true(fwd['surf_ori'])
assert ('dev_head_t' in fwd['info'])
assert ('mri_head_t' in fwd)
assert (fwd['surf_ori'])
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
write_forward_solution(fname_temp, fwd, overwrite=True)
fwd_read = read_forward_solution(fname_temp)
fwd_read = convert_forward_solution(fwd_read, surf_ori=True,
force_fixed=True, use_cps=True)
assert_true(repr(fwd_read))
assert_true(isinstance(fwd_read, Forward))
assert_true(is_fixed_orient(fwd_read))
assert (repr(fwd_read))
assert (isinstance(fwd_read, Forward))
assert (is_fixed_orient(fwd_read))
compare_forwards(fwd, fwd_read)
fwd = read_forward_solution(fname_meeg_grad)
@@ -166,18 +163,18 @@ def test_io_forward():
assert_equal(leadfield.shape, (n_channels, n_src / 3))
assert_equal(len(fwd['sol']['row_names']), n_channels)
assert_equal(len(fwd['info']['chs']), n_channels)
assert_true('dev_head_t' in fwd['info'])
assert_true('mri_head_t' in fwd)
assert_true(fwd['surf_ori'])
assert ('dev_head_t' in fwd['info'])
assert ('mri_head_t' in fwd)
assert (fwd['surf_ori'])
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
write_forward_solution(fname_temp, fwd, overwrite=True)
fwd_read = read_forward_solution(fname_temp)
fwd_read = convert_forward_solution(fwd_read, surf_ori=True,
force_fixed=True, use_cps=True)
assert_true(repr(fwd_read))
assert_true(isinstance(fwd_read, Forward))
assert_true(is_fixed_orient(fwd_read))
assert (repr(fwd_read))
assert (isinstance(fwd_read, Forward))
assert (is_fixed_orient(fwd_read))
compare_forwards(fwd, fwd_read)
# test warnings on bad filenames
@@ -197,8 +194,7 @@ def test_io_forward():
@testing.requires_testing_data
def test_apply_forward():
"""Test projection of source space data to sensor space
"""
"""Test projection of source space data to sensor space."""
start = 0
stop = 5
n_times = stop - start - 1
@@ -209,7 +205,7 @@ def test_apply_forward():
fwd = convert_forward_solution(fwd, surf_ori=True, force_fixed=True,
use_cps=True)
fwd = pick_types_forward(fwd, meg=True)
assert_true(isinstance(fwd, Forward))
assert isinstance(fwd, Forward)
vertno = [fwd['src'][0]['vertno'], fwd['src'][1]['vertno']]
stc_data = np.ones((len(vertno[0]) + len(vertno[1]), n_times))
@@ -248,8 +244,7 @@ def test_apply_forward():
@testing.requires_testing_data
def test_restrict_forward_to_stc():
"""Test restriction of source space to source SourceEstimate
"""
"""Test restriction of source space to source SourceEstimate."""
start = 0
stop = 5
n_times = stop - start - 1
@@ -266,7 +261,7 @@ def test_restrict_forward_to_stc():
stc = SourceEstimate(stc_data, vertno, tmin=t_start, tstep=1.0 / sfreq)
fwd_out = restrict_forward_to_stc(fwd, stc)
assert_true(isinstance(fwd_out, Forward))
assert (isinstance(fwd_out, Forward))
assert_equal(fwd_out['sol']['ncol'], 20)
assert_equal(fwd_out['src'][0]['nuse'], 15)
@@ -305,8 +300,7 @@ def test_restrict_forward_to_stc():
@testing.requires_testing_data
def test_restrict_forward_to_label():
"""Test restriction of source space to label
"""
"""Test restriction of source space to label."""
fwd = read_forward_solution(fname_meeg)
fwd = convert_forward_solution(fwd, surf_ori=True, force_fixed=True,
use_cps=True)
@@ -374,26 +368,25 @@ def test_restrict_forward_to_label():
@testing.requires_testing_data
@requires_mne
def test_average_forward_solution():
"""Test averaging forward solutions
"""
"""Test averaging forward solutions."""
temp_dir = _TempDir()
fwd = read_forward_solution(fname_meeg)
# input not a list
assert_raises(TypeError, average_forward_solutions, 1)
pytest.raises(TypeError, average_forward_solutions, 1)
# list is too short
assert_raises(ValueError, average_forward_solutions, [])
pytest.raises(ValueError, average_forward_solutions, [])
# negative weights
assert_raises(ValueError, average_forward_solutions, [fwd, fwd], [-1, 0])
pytest.raises(ValueError, average_forward_solutions, [fwd, fwd], [-1, 0])
# all zero weights
assert_raises(ValueError, average_forward_solutions, [fwd, fwd], [0, 0])
pytest.raises(ValueError, average_forward_solutions, [fwd, fwd], [0, 0])
# weights not same length
assert_raises(ValueError, average_forward_solutions, [fwd, fwd], [0, 0, 0])
pytest.raises(ValueError, average_forward_solutions, [fwd, fwd], [0, 0, 0])
# list does not only have all dict()
assert_raises(TypeError, average_forward_solutions, [1, fwd])
pytest.raises(TypeError, average_forward_solutions, [1, fwd])
# try an easy case
fwd_copy = average_forward_solutions([fwd])
assert_true(isinstance(fwd_copy, Forward))
assert (isinstance(fwd_copy, Forward))
assert_array_equal(fwd['sol']['data'], fwd_copy['sol']['data'])
# modify a fwd solution, save it, use MNE to average with old one
@@ -415,4 +408,5 @@ def test_average_forward_solution():
fwd_ave = average_forward_solutions([fwd, fwd])
compare_forwards(fwd, fwd_ave)
run_tests_if_main()
+17 -19
View File
@@ -1,11 +1,8 @@
from __future__ import print_function
from itertools import product
import os
import os.path as op
import warnings
from nose.tools import assert_raises, assert_true
import pytest
import numpy as np
from numpy.testing import assert_equal, assert_allclose, assert_array_equal
@@ -146,18 +143,18 @@ def test_make_forward_solution_kit():
fwd = _do_forward_solution('sample', fname_kit_raw, src=fname_src_small,
bem=fname_bem_meg, mri=trans_path,
eeg=False, meg=True, subjects_dir=subjects_dir)
assert_true(isinstance(fwd, Forward))
assert (isinstance(fwd, Forward))
# now let's use python with the same raw file
fwd_py = make_forward_solution(fname_kit_raw, trans_path, src,
fname_bem_meg, eeg=False, meg=True)
_compare_forwards(fwd, fwd_py, 157, n_src)
assert_true(isinstance(fwd_py, Forward))
assert (isinstance(fwd_py, Forward))
# now let's use mne-python all the way
raw_py = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path)
# without ignore_ref=True, this should throw an error:
assert_raises(NotImplementedError, make_forward_solution, raw_py.info,
pytest.raises(NotImplementedError, make_forward_solution, raw_py.info,
src=src, eeg=False, meg=True,
bem=fname_bem_meg, trans=trans_path)
@@ -218,9 +215,9 @@ def test_make_forward_solution():
fwd_py = make_forward_solution(fname_raw, fname_trans, fname_src,
fname_bem, mindist=5.0, eeg=True, meg=True,
n_jobs=-1)
assert_true(isinstance(fwd_py, Forward))
assert (isinstance(fwd_py, Forward))
fwd = read_forward_solution(fname_meeg)
assert_true(isinstance(fwd, Forward))
assert (isinstance(fwd, Forward))
_compare_forwards(fwd, fwd_py, 366, 1494, meg_rtol=1e-3)
@@ -289,7 +286,7 @@ def test_forward_mixed_source_space():
# calculate forward solution
fwd = make_forward_solution(fname_raw, fname_trans, src, fname_bem, None)
assert_true(repr(fwd))
assert (repr(fwd))
# extract source spaces
src_from_fwd = fwd['src']
@@ -298,18 +295,18 @@ def test_forward_mixed_source_space():
coord_frames = np.array([s['coord_frame'] for s in src_from_fwd])
# assert that all source spaces are in head coordinates
assert_true((coord_frames == FIFF.FIFFV_COORD_HEAD).all())
assert ((coord_frames == FIFF.FIFFV_COORD_HEAD).all())
# run tests for SourceSpaces.export_volume
fname_img = op.join(temp_dir, 'temp-image.mgz')
# head coordinates and mri_resolution, but trans file
assert_raises(ValueError, src_from_fwd.export_volume, fname_img,
pytest.raises(ValueError, src_from_fwd.export_volume, fname_img,
mri_resolution=True, trans=None)
# head coordinates and mri_resolution, but wrong trans file
vox_mri_t = vol1[0]['vox_mri_t']
assert_raises(ValueError, src_from_fwd.export_volume, fname_img,
pytest.raises(ValueError, src_from_fwd.export_volume, fname_img,
mri_resolution=True, trans=vox_mri_t)
@@ -344,7 +341,7 @@ def test_make_forward_dipole():
with warnings.catch_warnings(record=True) as w:
fwd, stc = make_forward_dipole(dip_test, sphere, info,
trans=fname_trans)
assert_true(issubclass(w[-1].category, RuntimeWarning))
assert (issubclass(w[-1].category, RuntimeWarning))
# stc is list of VolSourceEstimate's
assert isinstance(stc, list)
@@ -382,10 +379,10 @@ def test_make_forward_dipole():
# NB tolerance should be set relative to snr of simulated evoked!
assert_allclose(dip_fit.pos, dip_test.pos, rtol=0, atol=1e-2,
err_msg='position mismatch')
assert_true(dist < 1e-2, 'dist: %s' % dist) # within 1 cm
assert_true(corr > 1 - 1e-2, 'corr: %s' % corr)
assert_true(gc_dist < 20, 'gc_dist: %s' % gc_dist) # less than 20 degrees
assert_true(amp_err < 10e-9, 'amp_err: %s' % amp_err) # within 10 nAm
assert dist < 1e-2 # within 1 cm
assert corr > 1 - 1e-2
assert gc_dist < 20 # less than 20 degrees
assert amp_err < 10e-9 # within 10 nAm
# Make sure rejection works with BEM: one dipole at z=1m
# NB _make_forward.py:_prepare_for_forward will raise a RuntimeError
@@ -394,7 +391,7 @@ def test_make_forward_dipole():
pos=[[0., 0., 1.0], [0., 0., 0.040]],
amplitude=[100e-9, 100e-9],
ori=[[1., 0., 0.], [1., 0., 0.]], gof=1)
assert_raises(ValueError, make_forward_dipole, dip_outside, fname_bem,
pytest.raises(ValueError, make_forward_dipole, dip_outside, fname_bem,
info, fname_trans)
# if we get this far, can safely assume the code works with BEMs too
# -> use sphere again below for speed
@@ -412,7 +409,8 @@ def test_make_forward_dipole():
fwd, stc = make_forward_dipole(dip_even_samp, sphere, info,
trans=fname_trans)
assert_true(isinstance, VolSourceEstimate)
assert isinstance(stc, VolSourceEstimate)
assert_allclose(stc.times, np.arange(0., 0.003, 0.001))
run_tests_if_main()
+2 -1
View File
@@ -294,7 +294,8 @@ class MarkerPointDest(MarkerPoints): # noqa: D401
return pts
# Transform method
idx = np.intersect1d(self.src1.use, self.src2.use, assume_unique=True)
idx = np.intersect1d(np.array(self.src1.use),
np.array(self.src2.use), assume_unique=True)
if len(idx) < 3:
error(None, "Need at least three shared points for trans"
"formation.", "Marker Interpolation Error")
+26 -26
View File
@@ -11,9 +11,9 @@ from unittest import SkipTest
import warnings
import numpy as np
from numpy.testing import assert_allclose
from nose.tools import (assert_equal, assert_almost_equal, assert_false,
assert_raises, assert_true)
from numpy.testing import (assert_allclose, assert_equal,
assert_array_almost_equal)
import pytest
import mne
from mne.datasets import testing
@@ -75,16 +75,16 @@ def test_coreg_model():
trans_dst = op.join(tempdir, 'test-trans.fif')
model = CoregModel()
assert_raises(RuntimeError, model.save_trans, 'blah.fif')
pytest.raises(RuntimeError, model.save_trans, 'blah.fif')
model.mri.subjects_dir = subjects_dir
model.mri.subject = 'sample'
assert_false(model.mri.fid_ok)
assert not model.mri.fid_ok
model.mri.lpa = [[-0.06, 0, 0]]
model.mri.nasion = [[0, 0.05, 0]]
model.mri.rpa = [[0.08, 0, 0]]
assert_true(model.mri.fid_ok)
assert (model.mri.fid_ok)
model.hsp.file = raw_path
assert_allclose(model.hsp.lpa, [[-7.137e-2, 0, 5.122e-9]], 1e-4)
@@ -132,21 +132,21 @@ def test_coreg_model():
"rot_z"])
assert_equal(model.trans_x, 0)
model.set_trans(trans)
assert_almost_equal(model.trans_x, x)
assert_almost_equal(model.trans_y, y)
assert_almost_equal(model.trans_z, z)
assert_almost_equal(model.rot_x, rot_x)
assert_almost_equal(model.rot_y, rot_y)
assert_almost_equal(model.rot_z, rot_z)
assert_array_almost_equal(model.trans_x, x)
assert_array_almost_equal(model.trans_y, y)
assert_array_almost_equal(model.trans_z, z)
assert_array_almost_equal(model.rot_x, rot_x)
assert_array_almost_equal(model.rot_y, rot_y)
assert_array_almost_equal(model.rot_z, rot_z)
# info
assert_true(isinstance(model.fid_eval_str, string_types))
assert_true(isinstance(model.points_eval_str, string_types))
assert (isinstance(model.fid_eval_str, string_types))
assert (isinstance(model.points_eval_str, string_types))
# scaling job
assert_false(model.can_prepare_bem_model)
assert not model.can_prepare_bem_model
model.n_scale_params = 1
assert_true(model.can_prepare_bem_model)
assert (model.can_prepare_bem_model)
model.prepare_bem_model = True
sdir, sfrom, sto, scale, skip_fiducials, labels, annot, bemsol = \
model.get_scaling_job('sample2', False)
@@ -166,7 +166,7 @@ def test_coreg_model():
sdir, sfrom, sto, scale, skip_fiducials, labels, annot, bemsol = \
model.get_scaling_job('sample2', True)
assert_equal(bemsol, [])
assert_true(skip_fiducials)
assert (skip_fiducials)
model.load_trans(fname_trans)
model.save_trans(trans_dst)
@@ -192,7 +192,7 @@ def test_coreg_gui():
os.environ['_MNE_GUI_TESTING_MODE'] = 'true'
os.environ['_MNE_FAKE_HOME_DIR'] = home_dir
try:
assert_raises(ValueError, mne.gui.coregistration, subject='Elvis',
pytest.raises(ValueError, mne.gui.coregistration, subject='Elvis',
subjects_dir=subjects_dir)
from pyface.api import GUI
@@ -206,11 +206,11 @@ def test_coreg_gui():
frame.model.mri.subjects_dir = subjects_dir
frame.model.mri.subject = 'sample'
assert_false(frame.model.mri.fid_ok)
assert not frame.model.mri.fid_ok
frame.model.mri.lpa = [[-0.06, 0, 0]]
frame.model.mri.nasion = [[0, 0.05, 0]]
frame.model.mri.rpa = [[0.08, 0, 0]]
assert_true(frame.model.mri.fid_ok)
assert (frame.model.mri.fid_ok)
frame.data_panel.raw_src.file = raw_path
assert isinstance(frame.eeg_obj.glyph.glyph.glyph_source.glyph_source,
tvtk.SphereSource)
@@ -236,14 +236,14 @@ def test_coreg_gui():
assert not frame.data_panel.view_options_panel.head_high_res
# configuration persistence
assert_true(frame.model.prepare_bem_model)
assert (frame.model.prepare_bem_model)
frame.model.prepare_bem_model = False
frame.save_config(home_dir)
ui.dispose()
gui.process_events()
ui, frame = mne.gui.coregistration(subjects_dir=subjects_dir)
assert_false(frame.model.prepare_bem_model)
assert not frame.model.prepare_bem_model
assert not frame.data_panel.view_options_panel.head_high_res
ui.dispose()
gui.process_events()
@@ -266,7 +266,7 @@ def test_coreg_model_with_fsaverage():
model = CoregModel()
model.mri.subjects_dir = tempdir
model.mri.subject = 'fsaverage'
assert_true(model.mri.fid_ok)
assert (model.mri.fid_ok)
model.hsp.file = raw_path
lpa_distance = model.lpa_distance
@@ -299,11 +299,11 @@ def test_coreg_model_with_fsaverage():
old_x = lpa_distance ** 2 + rpa_distance ** 2 + nasion_distance ** 2
new_x = (model.lpa_distance ** 2 + model.rpa_distance ** 2 +
model.nasion_distance ** 2)
assert_true(new_x < old_x)
assert (new_x < old_x)
model.fit_icp(1)
avg_point_distance_1param = np.mean(model.point_distance)
assert_true(avg_point_distance_1param < avg_point_distance)
assert (avg_point_distance_1param < avg_point_distance)
# scaling job
sdir, sfrom, sto, scale, skip_fiducials, labels, annot, bemsol = \
@@ -321,7 +321,7 @@ def test_coreg_model_with_fsaverage():
# scale with 3 parameters
model.n_scale_params = 3
model.fit_icp(3)
assert_true(np.mean(model.point_distance) < avg_point_distance_1param)
assert (np.mean(model.point_distance) < avg_point_distance_1param)
# test switching raw disables point omission
assert_equal(model.hsp.n_omitted, 1)
+1 -1
View File
@@ -17,7 +17,7 @@ subjects_dir = os.path.join(sample_path, 'subjects')
@requires_mayavi
@traits_test
def test_mri_model():
"""Test MRIHeadWithFiducialsModel Traits Model"""
"""Test MRIHeadWithFiducialsModel Traits Model."""
from mne.gui._fiducials_gui import MRIHeadWithFiducialsModel
tempdir = _TempDir()
tgt_fname = os.path.join(tempdir, 'test-fiducials.fif')
+1 -1
View File
@@ -31,7 +31,7 @@ def _check_ci():
@requires_mayavi
@traits_test
def test_combine_markers_model():
"""Test CombineMarkersModel Traits Model"""
"""Test CombineMarkersModel Traits Model."""
from mne.gui._marker_gui import CombineMarkersModel, CombineMarkersPanel
tempdir = _TempDir()
tgt_fname = os.path.join(tempdir, 'test.txt')
+11 -11
View File
@@ -4,7 +4,6 @@
import os.path as op
from nose.tools import assert_true, assert_raises
import pytest
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_equal,
@@ -31,18 +30,18 @@ subjects_dir = op.join(data_path, 'subjects')
def _check_stc(stc, evoked, idx, ratio=50.):
"""Helper to check correctness"""
"""Check correctness."""
assert_array_almost_equal(stc.times, evoked.times, 5)
amps = np.sum(stc.data ** 2, axis=1)
order = np.argsort(amps)[::-1]
amps = amps[order]
verts = np.concatenate(stc.vertices)[order]
assert_equal(idx, verts[0], err_msg=str(list(verts)))
assert_true(amps[0] > ratio * amps[1], msg=str(amps[0] / amps[1]))
assert amps[0] > ratio * amps[1]
def _check_stcs(stc1, stc2):
"""Helper to check correctness"""
"""Check correctness."""
assert_allclose(stc1.times, stc2.times)
assert_allclose(stc1.data, stc2.data)
assert_allclose(stc1.vertices[0], stc2.vertices[0])
@@ -54,7 +53,7 @@ def _check_stcs(stc1, stc2):
@pytest.mark.slowtest
@testing.requires_testing_data
def test_gamma_map():
"""Test Gamma MAP inverse"""
"""Test Gamma MAP inverse."""
forward = read_forward_solution(fname_fwd)
forward = convert_forward_solution(forward, surf_ori=True)
@@ -79,7 +78,7 @@ def test_gamma_map():
dips = gamma_map(evoked, forward, cov, alpha, tol=1e-4,
xyz_same_gamma=False, update_mode=1,
return_as_dipoles=True)
assert_true(isinstance(dips[0], Dipole))
assert (isinstance(dips[0], Dipole))
stc_dip = make_stc_from_dipoles(dips, forward['src'])
_check_stcs(stc, stc_dip)
@@ -93,7 +92,7 @@ def test_gamma_map():
@pytest.mark.slowtest
@testing.requires_testing_data
def test_gamma_map_vol_sphere():
"""Gamma MAP with a sphere forward and volumic source space"""
"""Gamma MAP with a sphere forward and volumic source space."""
evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0),
proj=False)
evoked.resample(50, npad=100)
@@ -112,10 +111,10 @@ def test_gamma_map_vol_sphere():
eeg=False, meg=True)
alpha = 0.5
assert_raises(ValueError, gamma_map, evoked, fwd, cov, alpha,
pytest.raises(ValueError, gamma_map, evoked, fwd, cov, alpha,
loose=0, return_residual=False)
assert_raises(ValueError, gamma_map, evoked, fwd, cov, alpha,
pytest.raises(ValueError, gamma_map, evoked, fwd, cov, alpha,
loose=0.2, return_residual=False)
stc = gamma_map(evoked, fwd, cov, alpha, tol=1e-4,
@@ -137,9 +136,10 @@ def test_gamma_map_vol_sphere():
amp_max = [np.max(d.amplitude) for d in dip_gmap]
dip_gmap = dip_gmap[np.argmax(amp_max)]
assert_true(dip_gmap[0].pos[0] in src[0]['rr'][stc.vertices])
assert (dip_gmap[0].pos[0] in src[0]['rr'][stc.vertices])
dip_fit = mne.fit_dipole(evoked_dip, cov, sphere)[0]
assert_true(np.abs(np.dot(dip_fit.ori[0], dip_gmap.ori[0])) > 0.99)
assert (np.abs(np.dot(dip_fit.ori[0], dip_gmap.ori[0])) > 0.99)
run_tests_if_main()
@@ -10,7 +10,7 @@ from mne.inverse_sparse.mxne_debiasing import compute_bias
def test_compute_debiasing():
"""Test source amplitude debiasing"""
"""Test source amplitude debiasing."""
rng = np.random.RandomState(42)
G = rng.randn(10, 4)
X = rng.randn(4, 20)
@@ -32,7 +32,7 @@ fname_label = op.join(data_path, 'MEG', 'sample', 'labels', '%s.label' % label)
def _check_stcs(stc1, stc2):
"""Helper to check correctness"""
"""Check STC correctness."""
assert_allclose(stc1.times, stc2.times)
assert_allclose(stc1.data, stc2.data)
assert_allclose(stc1.vertices[0], stc2.vertices[0])
@@ -44,7 +44,7 @@ def _check_stcs(stc1, stc2):
@pytest.mark.slowtest
@testing.requires_testing_data
def test_mxne_inverse():
"""Test (TF-)MxNE inverse computation"""
"""Test (TF-)MxNE inverse computation."""
# Read noise covariance matrix
cov = read_cov(fname_cov)
@@ -142,7 +142,7 @@ def test_mxne_inverse():
@pytest.mark.slowtest
@testing.requires_testing_data
def test_mxne_vol_sphere():
"""(TF-)MxNE with a sphere forward and volumic source space"""
"""Test (TF-)MxNE with a sphere forward and volumic source space."""
evoked = read_evokeds(fname_data, condition=0, baseline=(None, 0))
evoked.crop(tmin=-0.05, tmax=0.2)
cov = read_cov(fname_cov)
+7 -7
View File
@@ -7,8 +7,8 @@ import warnings
import matplotlib
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_allclose
from nose.tools import assert_equal, assert_raises, assert_true
from numpy.testing import (assert_array_almost_equal, assert_allclose,
assert_equal)
import pytest
from mne import find_events, Epochs, pick_types, channels
@@ -57,10 +57,10 @@ def test_array_raw():
types.extend(['stim'] * 9)
types.extend(['eeg'] * 60)
# wrong length
assert_raises(ValueError, create_info, ch_names, sfreq, types)
pytest.raises(ValueError, create_info, ch_names, sfreq, types)
# bad entry
types.append('foo')
assert_raises(KeyError, create_info, ch_names, sfreq, types)
pytest.raises(KeyError, create_info, ch_names, sfreq, types)
types[-1] = 'eog'
# default type
info = create_info(ch_names, sfreq)
@@ -72,8 +72,8 @@ def test_array_raw():
data2, times2 = raw2[:, :]
assert_allclose(data, data2)
assert_allclose(times, times2)
assert_true('RawArray' in repr(raw2))
assert_raises(TypeError, RawArray, info, data)
assert ('RawArray' in repr(raw2))
pytest.raises(TypeError, RawArray, info, data)
# filtering
picks = pick_types(raw2.info, misc=True, exclude='bads')[:4]
@@ -106,7 +106,7 @@ def test_array_raw():
# epoching
events = find_events(raw2, stim_channel='STI 014')
events[:, 2] = 1
assert_true(len(events) > 2)
assert (len(events) > 2)
epochs = Epochs(raw2, events, 1, -0.2, 0.4, preload=True)
epochs.plot_drop_log()
epochs.plot()
+3 -4
View File
@@ -8,7 +8,6 @@ import warnings
import numpy as np
from numpy.testing import assert_allclose, assert_equal
from nose.tools import assert_true
from mne.utils import run_tests_if_main, _TempDir
from mne.io import read_raw_artemis123
@@ -38,9 +37,9 @@ def _assert_trans(actual, desired, dist_tol=0.003, angle_tol=5.):
angle = 180 * _angle_between_quats(quat_est, quat) / np.pi
dist = np.sqrt(np.sum((trans - trans_est) ** 2))
assert_true(dist <= dist_tol, '%0.3f > %0.3f mm' % (1000 * dist,
1000 * dist_tol))
assert_true(angle <= angle_tol, '%0.3f > %0.3f deg' % (angle, angle_tol))
assert dist <= dist_tol, '%0.3f > %0.3f mm' % (1000 * dist,
1000 * dist_tol)
assert angle <= angle_tol, '%0.3f > %0.3f deg' % (angle, angle_tol)
@testing.requires_testing_data
+14 -14
View File
@@ -10,10 +10,10 @@ import os.path as op
import shutil
import warnings
from nose.tools import assert_equal, assert_raises, assert_true
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_array_equal,
assert_allclose)
assert_allclose, assert_equal)
import pytest
from mne.utils import _TempDir, run_tests_if_main
from mne import pick_types, find_events
@@ -138,7 +138,7 @@ def test_brainvision_data_highpass_filters():
raw = _test_raw_reader(
read_raw_brainvision, vhdr_fname=vhdr_highpass_path,
montage=montage, eog=eog)
assert_true(all('parse triggers that' in str(ww.message) for ww in w))
assert (all('parse triggers that' in str(ww.message) for ww in w))
assert_equal(raw.info['highpass'], 1. / (2 * np.pi * 10))
assert_equal(raw.info['lowpass'], 250.)
@@ -156,7 +156,7 @@ def test_brainvision_data_highpass_filters():
expected_warnings = zip(lowpass_warning, highpass_warning)
assert_true(all(any([lp, hp]) for lp, hp in expected_warnings))
assert (all(any([lp, hp]) for lp, hp in expected_warnings))
assert_equal(raw.info['highpass'], 1. / (2 * np.pi * 10))
assert_equal(raw.info['lowpass'], 250.)
@@ -185,7 +185,7 @@ def test_brainvision_data_highpass_filters():
expected_warnings = zip(trigger_warning, lowpass_warning, highpass_warning)
assert_true(all(any([trg, lp, hp]) for trg, lp, hp in expected_warnings))
assert (all(any([trg, lp, hp]) for trg, lp, hp in expected_warnings))
assert_equal(raw.info['highpass'], 5.)
assert_equal(raw.info['lowpass'], 250.)
@@ -214,7 +214,7 @@ def test_brainvision_data_lowpass_filters():
expected_warnings = zip(lowpass_warning, highpass_warning)
assert_true(all(any([lp, hp]) for lp, hp in expected_warnings))
assert (all(any([lp, hp]) for lp, hp in expected_warnings))
assert_equal(raw.info['highpass'], 1. / (2 * np.pi * 10))
assert_equal(raw.info['lowpass'], 250.)
@@ -240,7 +240,7 @@ def test_brainvision_data_lowpass_filters():
expected_warnings = zip(lowpass_warning, highpass_warning)
assert_true(all(any([lp, hp]) for lp, hp in expected_warnings))
assert (all(any([lp, hp]) for lp, hp in expected_warnings))
assert_equal(raw.info['highpass'], 1. / (2 * np.pi * 10))
assert_equal(raw.info['lowpass'], 1. / (2 * np.pi * 0.004))
@@ -263,7 +263,7 @@ def test_brainvision_data_partially_disabled_hw_filters():
expected_warnings = zip(trigger_warning, lowpass_warning, highpass_warning)
assert_true(all(any([trg, lp, hp]) for trg, lp, hp in expected_warnings))
assert (all(any([trg, lp, hp]) for trg, lp, hp in expected_warnings))
assert_equal(raw.info['highpass'], 0.)
assert_equal(raw.info['lowpass'], 500.)
@@ -275,7 +275,7 @@ def test_brainvision_data_software_filters_latin1_global_units():
raw = _test_raw_reader(
read_raw_brainvision, vhdr_fname=vhdr_old_path,
eog=("VEOGo", "VEOGu", "HEOGli", "HEOGre"), misc=("A2",))
assert_true(all('software filter detected' in str(ww.message) for ww in w))
assert (all('software filter detected' in str(ww.message) for ww in w))
assert_equal(raw.info['highpass'], 1. / (2 * np.pi * 0.9))
assert_equal(raw.info['lowpass'], 50.)
@@ -283,15 +283,15 @@ def test_brainvision_data_software_filters_latin1_global_units():
def test_brainvision_data():
"""Test reading raw Brain Vision files."""
assert_raises(IOError, read_raw_brainvision, vmrk_path)
assert_raises(ValueError, read_raw_brainvision, vhdr_path, montage,
pytest.raises(IOError, read_raw_brainvision, vmrk_path)
pytest.raises(ValueError, read_raw_brainvision, vhdr_path, montage,
preload=True, scale="foo")
raw_py = _test_raw_reader(
read_raw_brainvision, vhdr_fname=vhdr_path, montage=montage,
eog=eog, misc='auto', event_id=event_id)
assert_true('RawBrainVision' in repr(raw_py))
assert ('RawBrainVision' in repr(raw_py))
assert_equal(raw_py.info['highpass'], 0.)
assert_equal(raw_py.info['lowpass'], 250.)
@@ -457,9 +457,9 @@ def test_events():
[6629, 1, 255],
[7629, 1, 5]])
assert_raises(TypeError, read_raw_brainvision, vhdr_path, eog=eog,
pytest.raises(TypeError, read_raw_brainvision, vhdr_path, eog=eog,
preload=True, response_trig_shift=0.1)
assert_raises(TypeError, read_raw_brainvision, vhdr_path, eog=eog,
pytest.raises(TypeError, read_raw_brainvision, vhdr_path, eog=eog,
preload=True, response_trig_shift=np.nan)
# to handle the min duration = 1 of stim trig (re)construction ...
+19 -19
View File
@@ -10,8 +10,7 @@ import warnings
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_array_equal,
assert_allclose)
from nose.tools import assert_true, assert_raises, assert_equal
assert_allclose, assert_equal)
import pytest
from mne.datasets import testing
@@ -58,8 +57,8 @@ def test_read_config():
# for config in config_fname, config_solaris_fname:
for config in config_fnames:
cfg = _read_config(config)
assert_true(all('unknown' not in block.lower() and block != ''
for block in cfg['user_blocks']))
assert all('unknown' not in block.lower() and block != ''
for block in cfg['user_blocks'])
def test_crop_append():
@@ -72,8 +71,8 @@ def test_crop_append():
mask = (t0 <= t) * (t <= t1)
raw_ = raw.copy().crop(t0, t1)
y_, _ = raw_[:]
assert_true(y_.shape[1] == mask.sum())
assert_true(y_.shape[0] == y.shape[0])
assert (y_.shape[1] == mask.sum())
assert (y_.shape[0] == y.shape[0])
def test_transforms():
@@ -104,14 +103,14 @@ def test_raw():
for pdf, config, hs, exported in zip(pdf_fnames, config_fnames, hs_fnames,
exported_fnames):
# rx = 2 if 'linux' in pdf else 0
assert_raises(ValueError, read_raw_bti, pdf, 'eggs', preload=False)
assert_raises(ValueError, read_raw_bti, pdf, config, 'spam',
pytest.raises(ValueError, read_raw_bti, pdf, 'eggs', preload=False)
pytest.raises(ValueError, read_raw_bti, pdf, config, 'spam',
preload=False)
if op.exists(tmp_raw_fname):
os.remove(tmp_raw_fname)
ex = read_raw_fif(exported, preload=True)
ra = read_raw_bti(pdf, config, hs, preload=False)
assert_true('RawBTi' in repr(ra))
assert ('RawBTi' in repr(ra))
assert_equal(ex.ch_names[:NCH], ra.ch_names[:NCH])
assert_array_almost_equal(ex.info['dev_head_t']['trans'],
ra.info['dev_head_t']['trans'], 7)
@@ -138,7 +137,7 @@ def test_raw():
if ex.info[key] is None:
pass
else:
assert_true(ra.info[key] is not None)
assert (ra.info[key] is not None)
for ent in ('to', 'from', 'trans'):
assert_allclose(ex.info[key][ent],
ra.info[key][ent])
@@ -147,11 +146,11 @@ def test_raw():
re = read_raw_fif(tmp_raw_fname)
print(re)
for key in ('dev_head_t', 'dev_ctf_t', 'ctf_head_t'):
assert_true(isinstance(re.info[key], dict))
assert (isinstance(re.info[key], dict))
this_t = re.info[key]['trans']
assert_equal(this_t.shape, (4, 4))
# check that matrix by is not identity
assert_true(not np.allclose(this_t, np.eye(4)))
assert (not np.allclose(this_t, np.eye(4)))
os.remove(tmp_raw_fname)
@@ -181,10 +180,10 @@ def test_info_no_rename_no_reorder_no_pdf():
info2 = pick_info(info2, pick_types(info2, meg=True, stim=True,
resp=True))
assert_true(info['sfreq'] is not None)
assert_true(info['lowpass'] is not None)
assert_true(info['highpass'] is not None)
assert_true(info['meas_date'] is not None)
assert (info['sfreq'] is not None)
assert (info['lowpass'] is not None)
assert (info['highpass'] is not None)
assert (info['meas_date'] is not None)
assert_equal(info2['sfreq'], None)
assert_equal(info2['lowpass'], None)
@@ -247,7 +246,7 @@ def test_no_conversion():
dig, raw_info['dig'], raw_info_con['dig'])):
assert_equal(old['ident'], new['ident'])
assert_array_equal(old['r'], new['r'])
assert_true(not np.allclose(old['r'], con['r']))
assert (not np.allclose(old['r'], con['r']))
if ii > 10:
break
@@ -262,7 +261,7 @@ def test_no_conversion():
t2 = raw_info['chs'][ii]['loc']
t3 = raw_info_con['chs'][ii]['loc']
assert_allclose(t1, t2, atol=1e-15)
assert_true(not np.allclose(t1, t3))
assert (not np.allclose(t1, t3))
idx_a = raw_info_con['ch_names'].index('MEG 001')
idx_b = raw_info['ch_names'].index('A22')
assert_equal(
@@ -297,6 +296,7 @@ def test_setup_headshape():
expected = set(['kind', 'ident', 'r'])
found = set(reduce(lambda x, y: list(x) + list(y),
[d.keys() for d in dig]))
assert_true(not expected - found)
assert (not expected - found)
run_tests_if_main()
+5 -6
View File
@@ -6,8 +6,6 @@
import os.path as op
import warnings
from nose.tools import assert_equal, assert_true
from mne import pick_types
from mne.utils import run_tests_if_main
from mne.datasets import testing
@@ -26,10 +24,11 @@ def test_data():
with warnings.catch_warnings(record=True) as w:
raw = _test_raw_reader(read_raw_cnt, montage=None, input_fname=fname,
eog='auto', misc=['NA1', 'LEFT_EAR'])
assert_true(all('meas date' in str(ww.message) or
'number of bytes' in str(ww.message) for ww in w))
assert all('meas date' in str(ww.message) or
'number of bytes' in str(ww.message) for ww in w)
eog_chs = pick_types(raw.info, eog=True, exclude=[])
assert_equal(len(eog_chs), 2) # test eog='auto'
assert_equal(raw.info['bads'], ['LEFT_EAR', 'VEOGR']) # test bads
assert len(eog_chs) == 2 # test eog='auto'
assert raw.info['bads'] == ['LEFT_EAR', 'VEOGR'] # test bads
run_tests_if_main()
+1 -1
View File
@@ -50,7 +50,7 @@ ctf_fnames = tuple(sorted(block_sizes.keys()))
@pytest.mark.slowtest
@testing.requires_testing_data
def test_read_ctf():
"""Test CTF reader"""
"""Test CTF reader."""
temp_dir = _TempDir()
out_fname = op.join(temp_dir, 'test_py_raw.fif')
+16 -18
View File
@@ -1,6 +1,3 @@
"""Data Equivalence Tests"""
from __future__ import print_function
# Authors: Teon Brooks <teon.brooks@gmail.com>
# Martin Billinger <martin.billinger@tugraz.at>
# Alan Leggitt <alan.leggitt@ucsf.edu>
@@ -12,9 +9,10 @@ import os.path as op
import inspect
import warnings
from nose.tools import assert_equal, assert_true
from numpy.testing import (assert_array_almost_equal, assert_array_equal,
assert_raises)
assert_equal)
import pytest
from scipy import io
import numpy as np
@@ -59,7 +57,7 @@ def test_bdf_data():
raw_py = _test_raw_reader(read_raw_edf, input_fname=bdf_path,
montage=montage_path, eog=eog, misc=misc,
exclude=['M2', 'IEOG'], stim_channel=-1)
assert_true('RawEDF' in repr(raw_py))
assert ('RawEDF' in repr(raw_py))
picks = pick_types(raw_py.info, meg=False, eeg=True, exclude='bads')
data_py, _ = raw_py[picks]
@@ -71,9 +69,9 @@ def test_bdf_data():
assert_array_almost_equal(data_py, data_eeglab, 8)
# Manually checking that float coordinates are imported
assert_true((raw_py.info['chs'][0]['loc']).any())
assert_true((raw_py.info['chs'][25]['loc']).any())
assert_true((raw_py.info['chs'][63]['loc']).any())
assert ((raw_py.info['chs'][0]['loc']).any())
assert ((raw_py.info['chs'][25]['loc']).any())
assert ((raw_py.info['chs'][63]['loc']).any())
@testing.requires_testing_data
@@ -81,7 +79,7 @@ def test_bdf_stim_channel():
"""Test BDF stim channel."""
# test if last channel is detected as STIM by default
raw_py = _test_raw_reader(read_raw_edf, input_fname=bdf_path)
assert_true(channel_type(raw_py.info, raw_py.info["nchan"] - 1) == 'stim')
assert (channel_type(raw_py.info, raw_py.info["nchan"] - 1) == 'stim')
# test BDF file with wrong scaling info in header - this should be ignored
# for BDF stim channels
@@ -190,7 +188,7 @@ def test_stim_channel():
assert_array_almost_equal(data_py, data_eeglab, 10)
events = find_edf_events(raw_py)
assert_true(len(events) - 1 == len(find_events(raw_py))) # start not found
assert (len(events) - 1 == len(find_events(raw_py))) # start not found
# Test uneven sampling
raw_py = read_raw_edf(edf_uneven_path, stim_channel=None)
@@ -205,22 +203,22 @@ def test_stim_channel():
data_py = np.repeat(data_py, repeats=upsample)
assert_array_equal(data_py, data_eeglab)
assert_raises(RuntimeError, read_raw_edf, edf_path, preload=False,
pytest.raises(RuntimeError, read_raw_edf, edf_path, preload=False,
stim_channel=-1)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
raw = read_raw_edf(edf_stim_resamp_path, verbose=True, stim_channel=-1)
assert_equal(len(w), 2)
assert_true(any('Events may jitter' in str(ww.message) for ww in w))
assert_true(any('truncated' in str(ww.message) for ww in w))
assert (any('Events may jitter' in str(ww.message) for ww in w))
assert (any('truncated' in str(ww.message) for ww in w))
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
raw[:]
assert_equal(len(w), 0)
events = raw_py.find_edf_events()
assert_true(len(events) == 0)
assert (len(events) == 0)
def test_parse_annotation():
@@ -274,7 +272,7 @@ def test_edf_stim_channel():
"""Test stim channel for edf file."""
# test if stim channel is automatically detected
raw = read_raw_edf(edf_path, preload=True)
assert_true(channel_type(raw.info, raw.info["nchan"] - 1) == 'stim')
assert (channel_type(raw.info, raw.info["nchan"] - 1) == 'stim')
raw = read_raw_edf(edf_stim_channel_path, preload=True,
stim_channel=-1)
@@ -299,10 +297,10 @@ def test_to_data_frame():
verbose='error')
_, times = raw[0, :10]
df = raw.to_data_frame()
assert_true((df.columns == raw.ch_names).all())
assert ((df.columns == raw.ch_names).all())
assert_array_equal(np.round(times * 1e3), df.index.values[:10])
df = raw.to_data_frame(index=None, scalings={'eeg': 1e13})
assert_true('time' in df.index.names)
assert ('time' in df.index.names)
assert_array_equal(df.values[:, 0], raw._data[0] * 1e13)
+2 -6
View File
@@ -1,6 +1,3 @@
"""Data Equivalence Tests"""
from __future__ import print_function
# Authors: Alexandre Barachant <alexandre.barachant@gmail.com>
# Nicolas Barascud <nicolas.barascud@ens.fr>
#
@@ -9,7 +6,6 @@ from __future__ import print_function
import os.path as op
import warnings
from nose.tools import assert_true
from numpy.testing import (assert_array_almost_equal, assert_array_equal,
assert_equal)
import numpy as np
@@ -52,7 +48,7 @@ def test_gdf_data():
# Test events are encoded to stim channel.
events = find_events(raw)
evs = raw.find_edf_events()
assert_true(all([event in evs[1] for event in events[:, 0]]))
assert (all([event in evs[1] for event in events[:, 0]]))
@testing.requires_testing_data
@@ -84,7 +80,7 @@ def test_gdf2_data():
# header contains no events
raw = read_raw_edf(gdf2_path + '.gdf', stim_channel='auto')
assert_equal(len(w), 1)
assert_true(str(w[0].message).startswith('No events found.'))
assert (str(w[0].message).startswith('No events found.'))
assert_equal(nchan, raw.info['nchan']) # stim channel not constructed
assert_array_equal(ch_names[1:], raw.ch_names[1:])
+14 -12
View File
@@ -10,9 +10,10 @@ import shutil
from unittest import SkipTest
import warnings
from nose.tools import assert_raises, assert_equal, assert_true
import numpy as np
from numpy.testing import assert_array_equal, assert_array_almost_equal
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
assert_equal)
import pytest
from scipy import io
from mne import write_events, read_epochs_eeglab, Epochs, find_events
@@ -46,7 +47,7 @@ def test_io_set():
montage=montage)
for want in ('Events like', 'consist entirely', 'could not be mapped',
'string preload is not supported'):
assert_true(any(want in str(ww.message) for ww in w))
assert (any(want in str(ww.message) for ww in w))
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
# test finding events in continuous data
@@ -102,12 +103,12 @@ def test_io_set():
epochs = read_epochs_eeglab(epochs_fname, epochs.events, event_id)
assert_equal(len(epochs.events), 4)
assert_true(epochs.preload)
assert_true(epochs._bad_dropped)
assert (epochs.preload)
assert (epochs._bad_dropped)
epochs = read_epochs_eeglab(epochs_fname, out_fname, event_id)
assert_raises(ValueError, read_epochs_eeglab, epochs_fname,
pytest.raises(ValueError, read_epochs_eeglab, epochs_fname,
None, event_id)
assert_raises(ValueError, read_epochs_eeglab, epochs_fname,
pytest.raises(ValueError, read_epochs_eeglab, epochs_fname,
epochs.events, None)
# test reading file with one event
@@ -140,7 +141,7 @@ def test_io_set():
shutil.copyfile(op.join(base_dir, 'test_raw.fdt'),
negative_latency_fname.replace('.set', '.fdt'))
event_id = {eeg.event[0].type: 1}
assert_raises(ValueError, read_raw_eeglab, montage=montage, preload=True,
pytest.raises(ValueError, read_raw_eeglab, montage=montage, preload=True,
event_id=event_id, input_fname=negative_latency_fname)
# test overlapping events
@@ -161,8 +162,8 @@ def test_io_set():
assert_equal(len(w), 1) # one warning for the dropped event
events_stimchan = find_events(raw)
events_read_events_eeglab = read_events_eeglab(overlap_fname, event_id)
assert_true(len(events_stimchan) == 1)
assert_true(len(events_read_events_eeglab) == 2)
assert (len(events_stimchan) == 1)
assert (len(events_read_events_eeglab) == 2)
# test reading file with one channel
one_chan_fname = op.join(temp_dir, 'test_one_channel.set')
@@ -269,18 +270,19 @@ def test_degenerate():
op.join(temp_dir, 'test_epochs.dat'))
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
assert_raises(NotImplementedError, read_epochs_eeglab,
pytest.raises(NotImplementedError, read_epochs_eeglab,
bad_epochs_fname)
assert_equal(len(w), 1)
@testing.requires_testing_data
def test_eeglab_annotations():
"""Test reading annotations in EEGLAB files"""
"""Test reading annotations in EEGLAB files."""
for fname in [raw_fname_onefile, raw_fname]:
annotations = read_annotations_eeglab(fname)
assert len(annotations) == 154
assert set(annotations.description) == set(['rt', 'square'])
assert np.all(annotations.duration == 0.)
run_tests_if_main()
+23 -22
View File
@@ -8,8 +8,8 @@ import warnings
import inspect
import numpy as np
from numpy.testing import assert_array_equal, assert_allclose
from nose.tools import assert_true, assert_raises, assert_equal
from numpy.testing import assert_array_equal, assert_allclose, assert_equal
import pytest
from scipy import io as sio
@@ -30,10 +30,10 @@ egi_txt_fname = op.join(base_dir, 'test_egi.txt')
@requires_testing_data
def test_io_egi_mff():
"""Test importing EGI MFF simple binary files"""
"""Test importing EGI MFF simple binary files."""
egi_fname_mff = op.join(data_path(), 'EGI', 'test_egi.mff')
raw = read_raw_egi(egi_fname_mff, include=None)
assert_true('RawMff' in repr(raw))
assert ('RawMff' in repr(raw))
include = ['DIN1', 'DIN2', 'DIN3', 'DIN4', 'DIN5', 'DIN7']
raw = _test_raw_reader(read_raw_egi, input_fname=egi_fname_mff,
include=include, channel_naming='EEG %03d')
@@ -48,16 +48,16 @@ def test_io_egi_mff():
events = find_events(raw, stim_channel='STI 014')
assert_equal(len(events), 8)
assert_equal(np.unique(events[:, 1])[0], 0)
assert_true(np.unique(events[:, 0])[0] != 0)
assert_true(np.unique(events[:, 2])[0] != 0)
assert (np.unique(events[:, 0])[0] != 0)
assert (np.unique(events[:, 2])[0] != 0)
assert_raises(ValueError, read_raw_egi, egi_fname_mff, include=['Foo'],
pytest.raises(ValueError, read_raw_egi, egi_fname_mff, include=['Foo'],
preload=False)
assert_raises(ValueError, read_raw_egi, egi_fname_mff, exclude=['Bar'],
pytest.raises(ValueError, read_raw_egi, egi_fname_mff, exclude=['Bar'],
preload=False)
for ii, k in enumerate(include, 1):
assert_true(k in raw.event_id)
assert_true(raw.event_id[k] == ii)
assert (k in raw.event_id)
assert (raw.event_id[k] == ii)
def test_io_egi():
@@ -72,11 +72,11 @@ def test_io_egi():
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
raw = read_raw_egi(egi_fname, include=None)
assert_true('RawEGI' in repr(raw))
assert ('RawEGI' in repr(raw))
assert_equal(len(w), 1)
assert_true(w[0].category == RuntimeWarning)
assert (w[0].category == RuntimeWarning)
msg = 'Did not find any event code with more than one event.'
assert_true(msg in '%s' % w[0].message)
assert (msg in '%s' % w[0].message)
data_read, t_read = raw[:256]
assert_allclose(t_read, t)
assert_allclose(data_read, data, atol=1e-10)
@@ -97,8 +97,8 @@ def test_io_egi():
events = find_events(raw, stim_channel='STI 014')
assert_equal(len(events), 2) # ground truth
assert_equal(np.unique(events[:, 1])[0], 0)
assert_true(np.unique(events[:, 0])[0] != 0)
assert_true(np.unique(events[:, 2])[0] != 0)
assert (np.unique(events[:, 0])[0] != 0)
assert (np.unique(events[:, 2])[0] != 0)
triggers = np.array([[0, 1, 1, 0], [0, 0, 1, 0]])
# test trigger functionality
@@ -107,22 +107,22 @@ def test_io_egi():
new_trigger = _combine_triggers(triggers, events_ids)
assert_array_equal(np.unique(new_trigger), np.unique([0, 12, 24]))
assert_raises(ValueError, read_raw_egi, egi_fname, include=['Foo'],
pytest.raises(ValueError, read_raw_egi, egi_fname, include=['Foo'],
preload=False)
assert_raises(ValueError, read_raw_egi, egi_fname, exclude=['Bar'],
pytest.raises(ValueError, read_raw_egi, egi_fname, exclude=['Bar'],
preload=False)
for ii, k in enumerate(include, 1):
assert_true(k in raw.event_id)
assert_true(raw.event_id[k] == ii)
assert (k in raw.event_id)
assert (raw.event_id[k] == ii)
@requires_testing_data
def test_io_egi_pns_mff():
"""Test importing EGI MFF with PNS data"""
"""Test importing EGI MFF with PNS data."""
egi_fname_mff = op.join(data_path(), 'EGI', 'test_egi_pns.mff')
raw = read_raw_egi(egi_fname_mff, include=None, preload=True,
verbose='error')
assert_true('RawMff' in repr(raw))
assert ('RawMff' in repr(raw))
pns_chans = pick_types(raw.info, ecg=True, bio=True, emg=True)
assert_equal(len(pns_chans), 7)
names = [raw.ch_names[x] for x in pns_chans]
@@ -159,7 +159,7 @@ def test_io_egi_pns_mff():
@requires_testing_data
def test_io_egi_pns_mff_bug():
"""Test importing EGI MFF with PNS data (BUG)"""
"""Test importing EGI MFF with PNS data (BUG)."""
egi_fname_mff = op.join(data_path(), 'EGI', 'test_egi_pns_bug.mff')
with warnings.catch_warnings(record=True) as w:
raw = read_raw_egi(egi_fname_mff, include=None, preload=True,
@@ -194,4 +194,5 @@ def test_io_egi_pns_mff_bug():
raw_data = raw[ch_idx][0]
assert_array_equal(mat_data, raw_data)
run_tests_if_main()
+7 -7
View File
@@ -4,7 +4,6 @@
import os.path as op
from numpy.testing import assert_array_equal
from nose.tools import assert_equal, assert_true
from scipy import io as sio
from mne.io import read_raw_eximia
@@ -15,22 +14,22 @@ from mne.datasets.testing import data_path, requires_testing_data
@requires_testing_data
def test_eximia_nxe():
"""Test reading Eximia NXE files"""
"""Test reading Eximia NXE files."""
fname = op.join(data_path(), 'eximia', 'test_eximia.nxe')
raw = read_raw_eximia(fname, preload=True)
assert_true('RawEximia' in repr(raw))
assert 'RawEximia' in repr(raw)
_test_raw_reader(read_raw_eximia, fname=fname)
fname_mat = op.join(data_path(), 'eximia', 'test_eximia.mat')
mc = sio.loadmat(fname_mat)
m_data = mc['data']
m_header = mc['header']
assert_equal(raw._data.shape, m_data.shape)
assert_equal(m_header['Fs'][0, 0][0, 0], raw.info['sfreq'])
assert raw._data.shape == m_data.shape
assert m_header['Fs'][0, 0][0, 0] == raw.info['sfreq']
m_names = [x[0][0] for x in m_header['label'][0, 0]]
m_names = list(
map(lambda x: x.replace('GATE', 'GateIn').replace('TRIG', 'Trig'),
m_names))
assert_equal(raw.ch_names, m_names)
assert raw.ch_names == m_names
m_ch_types = [x[0][0] for x in m_header['chantype'][0, 0]]
m_ch_types = list(
map(lambda x: x.replace('unknown', 'stim').replace('trigger', 'stim'),
@@ -38,8 +37,9 @@ def test_eximia_nxe():
types_dict = {2: 'eeg', 3: 'stim', 202: 'eog'}
ch_types = [types_dict[raw.info['chs'][x]['kind']]
for x in range(len(raw.ch_names))]
assert_equal(ch_types, m_ch_types)
assert ch_types == m_ch_types
assert_array_equal(m_data, raw._data)
run_tests_if_main()
+64 -67
View File
@@ -12,7 +12,6 @@ import warnings
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_array_equal,
assert_allclose, assert_equal)
from nose.tools import assert_true, assert_raises, assert_not_equal
import pytest
from mne.datasets import testing
@@ -122,9 +121,9 @@ def test_fix_types():
assert_array_equal(orig_types, new_types)
else:
assert_array_equal(orig_types[other_picks], new_types[other_picks])
assert_true((orig_types[mag_picks] != new_types[mag_picks]).all())
assert_true((new_types[mag_picks] ==
FIFF.FIFFV_COIL_VV_MAG_T3).all())
assert ((orig_types[mag_picks] != new_types[mag_picks]).all())
assert ((new_types[mag_picks] ==
FIFF.FIFFV_COIL_VV_MAG_T3).all())
def test_concat():
@@ -143,12 +142,12 @@ def test_concat():
def test_hash_raw():
"""Test hashing raw objects."""
raw = read_raw_fif(fif_fname)
assert_raises(RuntimeError, raw.__hash__)
pytest.raises(RuntimeError, raw.__hash__)
raw = read_raw_fif(fif_fname).crop(0, 0.5)
raw_size = raw._size
raw.load_data()
raw_load_size = raw._size
assert_true(raw_size < raw_load_size)
assert (raw_size < raw_load_size)
raw_2 = read_raw_fif(fif_fname).crop(0, 0.5)
raw_2.load_data()
assert_equal(hash(raw), hash(raw_2))
@@ -156,7 +155,7 @@ def test_hash_raw():
assert_equal(pickle.dumps(raw), pickle.dumps(raw_2))
raw_2._data[0, 0] -= 1
assert_not_equal(hash(raw), hash(raw_2))
assert hash(raw) != hash(raw_2)
@testing.requires_testing_data
@@ -166,7 +165,7 @@ def test_maxshield():
warnings.simplefilter('always')
read_raw_fif(ms_fname, allow_maxshield=True)
assert_equal(len(w), 1)
assert_true('test_raw_fiff.py' in w[0].filename)
assert ('test_raw_fiff.py' in w[0].filename)
@testing.requires_testing_data
@@ -174,7 +173,7 @@ def test_subject_info():
"""Test reading subject information."""
tempdir = _TempDir()
raw = read_raw_fif(fif_fname).crop(0, 1)
assert_true(raw.info['subject_info'] is None)
assert (raw.info['subject_info'] is None)
# fake some subject data
keys = ['id', 'his_id', 'last_name', 'first_name', 'birthday', 'sex',
'hand']
@@ -246,7 +245,7 @@ def test_output_formats():
for ii, (fmt, tol) in enumerate(zip(formats, tols)):
# Let's test the overwriting error throwing while we're at it
if ii > 0:
assert_raises(IOError, raw.save, temp_file, fmt=fmt)
pytest.raises(IOError, raw.save, temp_file, fmt=fmt)
raw.save(temp_file, fmt=fmt, overwrite=True)
raw2 = read_raw_fif(temp_file)
raw2_data = raw2[:, :][0]
@@ -294,7 +293,7 @@ def test_multiple_files():
first_samps = [r.first_samp for r in raws]
# test concatenation of split file
assert_raises(ValueError, concatenate_raws, raws, True, events[1:])
pytest.raises(ValueError, concatenate_raws, raws, True, events[1:])
all_raw_1, events1 = concatenate_raws(raws, preload=False,
events_list=events)
assert_allclose(all_raw_1.times, raw.times)
@@ -337,14 +336,14 @@ def test_multiple_files():
# with all data preloaded, result should be preloaded
raw_combo = read_raw_fif(fif_fname, preload=True)
raw_combo.append(read_raw_fif(fif_fname, preload=True))
assert_true(raw_combo.preload is True)
assert (raw_combo.preload is True)
assert_equal(raw_combo.n_times, raw_combo._data.shape[1])
_compare_combo(raw, raw_combo, times, n_times)
# with any data not preloaded, don't set result as preloaded
raw_combo = concatenate_raws([read_raw_fif(fif_fname, preload=True),
read_raw_fif(fif_fname, preload=False)])
assert_true(raw_combo.preload is False)
assert (raw_combo.preload is False)
assert_array_equal(find_events(raw_combo, stim_channel='STI 014'),
find_events(raw_combo0, stim_channel='STI 014'))
_compare_combo(raw, raw_combo, times, n_times)
@@ -353,7 +352,7 @@ def test_multiple_files():
raw_combo = concatenate_raws([read_raw_fif(fif_fname, preload=False),
read_raw_fif(fif_fname, preload=True)],
preload=True)
assert_true(raw_combo.preload is True)
assert (raw_combo.preload is True)
_compare_combo(raw, raw_combo, times, n_times)
raw_combo = concatenate_raws([read_raw_fif(fif_fname, preload=False),
@@ -373,7 +372,7 @@ def test_multiple_files():
# verify that combining raws with different projectors throws an exception
raw.add_proj([], remove_existing=True)
assert_raises(ValueError, raw.append,
pytest.raises(ValueError, raw.append,
read_raw_fif(fif_fname, preload=True))
# now test event treatment for concatenated raw files
@@ -420,17 +419,15 @@ def test_split_files():
# somehow, the numbers below for e.g. split_size might need to be
# adjusted.
raw_crop = raw_1.copy().crop(0, 5)
try:
with pytest.raises(ValueError,
match='after writing measurement information'):
raw_crop.save(split_fname, split_size='1MB', # too small a size
buffer_size_sec=1., overwrite=True)
except ValueError as exp:
assert_true('after writing measurement information' in str(exp), exp)
try:
with pytest.raises(ValueError,
match='too large for the given split size'):
raw_crop.save(split_fname,
split_size=3002276, # still too small, now after Info
buffer_size_sec=1., overwrite=True)
except ValueError as exp:
assert_true('too large for the given split size' in str(exp), exp)
# just barely big enough here; the right size to write exactly one buffer
# at a time so we hit GH#3210 if we aren't careful
raw_crop.save(split_fname, split_size='4.5MB',
@@ -493,7 +490,7 @@ def test_load_bad_channels():
raw.info['bads'] = []
# Test bad case
assert_raises(ValueError, raw.load_bad_channels, bad_file_wrong)
pytest.raises(ValueError, raw.load_bad_channels, bad_file_wrong)
# Test forcing the bad case
with warnings.catch_warnings(record=True) as w:
@@ -522,8 +519,8 @@ def test_io_raw():
# test unicode io
for chars in [b'\xc3\xa4\xc3\xb6\xc3\xa9', b'a']:
with read_raw_fif(fif_fname) as r:
assert_true('Raw' in repr(r))
assert_true(op.basename(fif_fname) in repr(r))
assert ('Raw' in repr(r))
assert (op.basename(fif_fname) in repr(r))
desc1 = r.info['description'] = chars.decode('utf-8')
temp_file = op.join(tempdir, 'raw.fif')
r.save(temp_file, overwrite=True)
@@ -579,7 +576,7 @@ def test_io_raw():
sel = pick_channels(raw2.ch_names, meg_ch_names)
data2, times2 = raw2[sel, :]
assert_true(times2.max() <= 3)
assert (times2.max() <= 3)
# Writing
raw.save(fname_out, picks, tmin=0, tmax=5, overwrite=True)
@@ -599,7 +596,7 @@ def test_io_raw():
# check transformations
for trans in ['dev_head_t', 'dev_ctf_t', 'ctf_head_t']:
if raw.info[trans] is None:
assert_true(raw2.info[trans] is None)
assert (raw2.info[trans] is None)
else:
assert_array_equal(raw.info[trans]['trans'],
raw2.info[trans]['trans'])
@@ -688,7 +685,7 @@ def test_getitem():
assert_array_equal(
raw[-10:-1, :][0],
raw[len(raw.ch_names) - 10:len(raw.ch_names) - 1, :][0])
assert_raises(ValueError, raw.__getitem__,
pytest.raises(ValueError, raw.__getitem__,
(slice(-len(raw.ch_names) - 1), slice(None)))
with pytest.raises(ValueError, match='start must be'):
raw[-1000:]
@@ -704,7 +701,7 @@ def test_proj():
raw = read_raw_fif(fif_fname, preload=False)
if proj:
raw.apply_proj()
assert_true(all(p['active'] == proj for p in raw.info['projs']))
assert (all(p['active'] == proj for p in raw.info['projs']))
data, times = raw[0:2, :]
data1, times1 = raw[0:2]
@@ -713,9 +710,9 @@ def test_proj():
# test adding / deleting proj
if proj:
assert_raises(ValueError, raw.add_proj, [],
pytest.raises(ValueError, raw.add_proj, [],
{'remove_existing': True})
assert_raises(ValueError, raw.del_proj, 0)
pytest.raises(ValueError, raw.del_proj, 0)
else:
projs = deepcopy(raw.info['projs'])
n_proj = len(raw.info['projs'])
@@ -742,14 +739,14 @@ def test_proj():
raw2 = read_raw_fif(op.join(tempdir, 'raw.fif'))
data_proj_2, _ = raw2[:, 0:2]
assert_allclose(data_proj_1, data_proj_2)
assert_true(all(p['active'] for p in raw2.info['projs']))
assert (all(p['active'] for p in raw2.info['projs']))
# read orig file with proj. active
raw2 = read_raw_fif(fif_fname, preload=preload)
raw2.apply_proj()
data_proj_2, _ = raw2[:, 0:2]
assert_allclose(data_proj_1, data_proj_2)
assert_true(all(p['active'] for p in raw2.info['projs']))
assert (all(p['active'] for p in raw2.info['projs']))
# test that apply_proj works
raw.apply_proj()
@@ -893,14 +890,14 @@ def test_filter():
l_freq = 30
if kind == 'bandstop':
l_freq, h_freq = 70, 30
assert_true(raw.info['lowpass'] is None)
assert_true(raw.info['highpass'] is None)
assert (raw.info['lowpass'] is None)
assert (raw.info['highpass'] is None)
kwargs = dict(l_trans_bandwidth=20, h_trans_bandwidth=20,
filter_length='auto', phase='zero', fir_design='firwin')
raw_filt = raw.copy().filter(l_freq, h_freq, picks=np.arange(1),
**kwargs)
assert_true(raw.info['lowpass'] is None)
assert_true(raw.info['highpass'] is None)
assert (raw.info['lowpass'] is None)
assert (raw.info['highpass'] is None)
raw_filt = raw.copy().filter(l_freq, h_freq, **kwargs)
wanted_h = h_freq if kind != 'bandstop' else None
wanted_l = l_freq if kind != 'bandstop' else None
@@ -935,7 +932,7 @@ def test_filter_picks():
for ch_type in ('misc', 'stim'):
picks = dict((ch, ch == ch_type) for ch in ch_types)
raw_ = raw.copy().pick_types(**picks)
assert_raises(RuntimeError, raw_.filter, 10, 30)
pytest.raises(RuntimeError, raw_.filter, 10, 30)
@testing.requires_testing_data
@@ -1070,7 +1067,7 @@ def test_resample():
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
raw.resample(8., npad='auto')
assert_true(len(w) == 1)
assert (len(w) == 1)
# events are dropped in this case (warning)
stim = [0, 1, 1, 0, 0, 1, 1, 0]
@@ -1078,7 +1075,7 @@ def test_resample():
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
raw.resample(4., npad='auto')
assert_true(len(w) == 1)
assert (len(w) == 1)
# test resampling events: this should no longer give a warning
# we often have first_samp != 0, include it here too
@@ -1102,9 +1099,9 @@ def test_resample():
stim = [1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0]
raw = RawArray([stim], create_info(1, len(stim), ['stim']))
raw_resampled = raw.copy().resample(4., npad='auto')
assert_true(raw_resampled is not raw)
assert (raw_resampled is not raw)
raw_resampled = raw.resample(4., npad='auto')
assert_true(raw_resampled is raw)
assert (raw_resampled is raw)
# resample should still work even when no stim channel is present
raw = RawArray(np.random.randn(1, 100), create_info(1, 100, ['eeg']))
@@ -1139,7 +1136,7 @@ def test_hilbert():
assert_equal(raw_filt._data.shape, raw_filt_2._data.shape)
assert_allclose(raw_filt._data[:, 50:-50], raw_filt_2._data[:, 50:-50],
atol=1e-13, rtol=1e-2)
assert_raises(ValueError, raw3.apply_hilbert, picks,
pytest.raises(ValueError, raw3.apply_hilbert, picks,
n_fft=raw3.n_times - 100)
env = np.abs(raw._data[picks, :])
@@ -1172,10 +1169,10 @@ def test_to_data_frame():
raw = read_raw_fif(test_fif_fname, preload=True)
_, times = raw[0, :10]
df = raw.to_data_frame()
assert_true((df.columns == raw.ch_names).all())
assert ((df.columns == raw.ch_names).all())
assert_array_equal(np.round(times * 1e3), df.index.values[:10])
df = raw.to_data_frame(index=None)
assert_true('time' in df.index.names)
assert ('time' in df.index.names)
assert_array_equal(df.values[:, 0], raw._data[0] * 1e13)
assert_array_equal(df.values[:, 2], raw._data[2] * 1e15)
@@ -1190,16 +1187,16 @@ def test_add_channels():
raw_meg = raw.copy().pick_types(meg=True, eeg=False)
raw_stim = raw.copy().pick_types(meg=False, eeg=False, stim=True)
raw_new = raw_meg.copy().add_channels([raw_eeg, raw_stim])
assert_true(
assert (
all(ch in raw_new.ch_names
for ch in list(raw_stim.ch_names) + list(raw_meg.ch_names))
)
raw_new = raw_meg.copy().add_channels([raw_eeg])
assert_true(ch in raw_new.ch_names for ch in raw.ch_names)
assert (ch in raw_new.ch_names for ch in raw.ch_names)
assert_array_equal(raw_new[:, :][0], raw_eeg_meg[:, :][0])
assert_array_equal(raw_new[:, :][1], raw[:, :][1])
assert_true(all(ch not in raw_new.ch_names for ch in raw_stim.ch_names))
assert (all(ch not in raw_new.ch_names for ch in raw_stim.ch_names))
# Testing force updates
raw_arr_info = create_info(['1', '2'], raw_meg.info['sfreq'], 'eeg')
@@ -1207,7 +1204,7 @@ def test_add_channels():
raw_arr = rng.randn(2, raw_eeg.n_times)
raw_arr = RawArray(raw_arr, raw_arr_info)
# This should error because of conflicts in Info
assert_raises(ValueError, raw_meg.copy().add_channels, [raw_arr])
pytest.raises(ValueError, raw_meg.copy().add_channels, [raw_arr])
raw_meg.copy().add_channels([raw_arr], force_update_info=True)
# Make sure that values didn't get overwritten
assert_equal(object_diff(raw_arr.info['dev_head_t'], orig_head_t), '')
@@ -1217,11 +1214,11 @@ def test_add_channels():
raw_badsf.info['sfreq'] = 3.1415927
raw_eeg.crop(.5)
assert_raises(RuntimeError, raw_meg.add_channels, [raw_nopre])
assert_raises(RuntimeError, raw_meg.add_channels, [raw_badsf])
assert_raises(AssertionError, raw_meg.add_channels, [raw_eeg])
assert_raises(ValueError, raw_meg.add_channels, [raw_meg])
assert_raises(TypeError, raw_meg.add_channels, raw_badsf)
pytest.raises(RuntimeError, raw_meg.add_channels, [raw_nopre])
pytest.raises(RuntimeError, raw_meg.add_channels, [raw_badsf])
pytest.raises(AssertionError, raw_meg.add_channels, [raw_eeg])
pytest.raises(ValueError, raw_meg.add_channels, [raw_meg])
pytest.raises(TypeError, raw_meg.add_channels, raw_badsf)
@testing.requires_testing_data
@@ -1230,10 +1227,10 @@ def test_save():
tempdir = _TempDir()
raw = read_raw_fif(fif_fname, preload=False)
# can't write over file being read
assert_raises(ValueError, raw.save, fif_fname)
pytest.raises(ValueError, raw.save, fif_fname)
raw = read_raw_fif(fif_fname, preload=True)
# can't overwrite file without overwrite=True
assert_raises(IOError, raw.save, fif_fname)
pytest.raises(IOError, raw.save, fif_fname)
# test abspath support and annotations
annot = Annotations([10], [5], ['test'],
@@ -1243,7 +1240,7 @@ def test_save():
new_fname = op.join(op.abspath(op.curdir), 'break_raw.fif')
raw.save(op.join(tempdir, new_fname), overwrite=True)
new_raw = read_raw_fif(op.join(tempdir, new_fname), preload=False)
assert_raises(ValueError, new_raw.save, new_fname)
pytest.raises(ValueError, new_raw.save, new_fname)
assert_array_equal(annot.onset, new_raw.annotations.onset)
assert_array_equal(annot.duration, new_raw.annotations.duration)
assert_array_equal(annot.description, new_raw.annotations.description)
@@ -1262,7 +1259,7 @@ def test_annotation_crop():
r1 = raw.copy().crop(2.5, 7.5)
r2 = raw.copy().crop(12.5, 17.5)
r3 = raw.copy().crop(10., 12.)
assert_true(all('data range' in str(ww.message) for ww in w))
assert (all('data range' in str(ww.message) for ww in w))
raw = concatenate_raws([r1, r2, r3]) # segments reordered
onsets = raw.annotations.onset
durations = raw.annotations.duration
@@ -1276,7 +1273,7 @@ def test_annotation_crop():
raw.info['meas_date'] + raw.first_samp / sfreq - 1.)
with warnings.catch_warnings(record=True) as w: # outside range
raw.annotations = annot
assert_true(all('data range' in str(ww.message) for ww in w))
assert (all('data range' in str(ww.message) for ww in w))
assert_allclose(raw.annotations.duration,
[1., 1. + 1. / raw.info['sfreq']], atol=1e-3)
@@ -1316,25 +1313,25 @@ def test_compensation_raw():
assert_equal(raw_0.compensation_grade, 0)
data_0, times_new = raw_0[:, :]
assert_array_equal(times, times_new)
assert_true(np.mean(np.abs(data_0 - data_3)) > 1e-12)
assert (np.mean(np.abs(data_0 - data_3)) > 1e-12)
# change to grade 1
raw_1 = raw_0.copy().apply_gradient_compensation(1)
assert_equal(raw_1.compensation_grade, 1)
data_1, times_new = raw_1[:, :]
assert_array_equal(times, times_new)
assert_true(np.mean(np.abs(data_1 - data_3)) > 1e-12)
assert_raises(ValueError, raw_1.apply_gradient_compensation, 33)
assert (np.mean(np.abs(data_1 - data_3)) > 1e-12)
pytest.raises(ValueError, raw_1.apply_gradient_compensation, 33)
raw_bad = raw_0.copy()
raw_bad.add_proj(compute_proj_raw(raw_0, duration=0.5, verbose='error'))
raw_bad.apply_proj()
assert_raises(RuntimeError, raw_bad.apply_gradient_compensation, 1)
pytest.raises(RuntimeError, raw_bad.apply_gradient_compensation, 1)
# with preload
tols = dict(rtol=1e-12, atol=1e-25)
raw_1_new = raw_3.copy().load_data().apply_gradient_compensation(1)
assert_equal(raw_1_new.compensation_grade, 1)
data_1_new, times_new = raw_1_new[:, :]
assert_array_equal(times, times_new)
assert_true(np.mean(np.abs(data_1_new - data_3)) > 1e-12)
assert (np.mean(np.abs(data_1_new - data_3)) > 1e-12)
assert_allclose(data_1, data_1_new, **tols)
# change back
raw_3_new = raw_1.copy().apply_gradient_compensation(3)
@@ -1353,7 +1350,7 @@ def test_compensation_raw():
assert_equal(raw_3_new.compensation_grade, 3)
data_3_new, times_new = raw_3_new[:, :]
assert_array_equal(times, times_new)
assert_true(np.mean(np.abs(data_3_new - data_1)) > 1e-12)
assert (np.mean(np.abs(data_3_new - data_1)) > 1e-12)
assert_allclose(data_3, data_3_new, **tols)
# Try IO with compensation
@@ -1455,11 +1452,11 @@ def test_pick_channels_mixin():
assert_equal(ch_names, raw.ch_names)
assert_equal(len(ch_names), len(raw._cals))
assert_equal(len(ch_names), raw._data.shape[0])
assert_raises(ValueError, raw.pick_channels, ch_names[0])
pytest.raises(ValueError, raw.pick_channels, ch_names[0])
raw = read_raw_fif(fif_fname, preload=False)
assert_raises(RuntimeError, raw.pick_channels, ch_names)
assert_raises(RuntimeError, raw.drop_channels, ch_names)
pytest.raises(RuntimeError, raw.pick_channels, ch_names)
pytest.raises(RuntimeError, raw.drop_channels, ch_names)
@testing.requires_testing_data
+5 -5
View File
@@ -4,9 +4,9 @@
import inspect
import os
from ....externals.six.moves import cPickle as pickle
from mne.externals.six.moves import cPickle as pickle
from nose.tools import assert_raises
import pytest
from numpy.testing import assert_array_equal
from mne.io.kit import read_mrk
@@ -21,7 +21,7 @@ mrk_fname = os.path.join(data_dir, 'test_mrk.sqd')
def test_io_mrk():
"""Test IO for mrk files"""
"""Test IO for mrk files."""
tempdir = _TempDir()
pts = read_mrk(mrk_fname)
@@ -39,7 +39,7 @@ def test_io_mrk():
assert_array_equal(pts_2, pts, "pickle mrk")
with open(fname, 'wb') as fid:
pickle.dump(dict(), fid)
assert_raises(ValueError, read_mrk, fname)
pytest.raises(ValueError, read_mrk, fname)
# unsupported extension
assert_raises(ValueError, read_mrk, "file.ext")
pytest.raises(ValueError, read_mrk, "file.ext")
+13 -15
View File
@@ -1,6 +1,3 @@
"""Data and Channel Location Equivalence Tests"""
from __future__ import print_function
# Author: Teon Brooks <teon.brooks@gmail.com>
#
# License: BSD (3-clause)
@@ -10,9 +7,9 @@ import os.path as op
import warnings
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_array_equal
from nose.tools import (assert_equal, assert_almost_equal, assert_raises,
assert_true)
from numpy.testing import (assert_array_almost_equal, assert_array_equal,
assert_equal)
import pytest
from scipy import linalg
import scipy.io
@@ -51,12 +48,12 @@ sqd_as_path = op.join(data_path, 'KIT', 'test_as-raw.con')
@requires_testing_data
def test_data():
"""Test reading raw kit files."""
assert_raises(TypeError, read_raw_kit, epochs_path)
assert_raises(TypeError, read_epochs_kit, sqd_path)
assert_raises(ValueError, read_raw_kit, sqd_path, mrk_path, elp_txt_path)
assert_raises(ValueError, read_raw_kit, sqd_path, None, None, None,
pytest.raises(TypeError, read_raw_kit, epochs_path)
pytest.raises(TypeError, read_epochs_kit, sqd_path)
pytest.raises(ValueError, read_raw_kit, sqd_path, mrk_path, elp_txt_path)
pytest.raises(ValueError, read_raw_kit, sqd_path, None, None, None,
list(range(200, 190, -1)))
assert_raises(ValueError, read_raw_kit, sqd_path, None, None, None,
pytest.raises(ValueError, read_raw_kit, sqd_path, None, None, None,
list(range(167, 159, -1)), '*', 1, True)
# check functionality
raw_mrk = read_raw_kit(sqd_path, [mrk2_path, mrk3_path], elp_txt_path,
@@ -65,7 +62,7 @@ def test_data():
elp=elp_txt_path, hsp=hsp_txt_path,
stim=list(range(167, 159, -1)), slope='+',
stimthresh=1)
assert_true('RawKIT' in repr(raw_py))
assert 'RawKIT' in repr(raw_py)
assert_equal(raw_mrk.info['kit_system_id'], KIT.SYSTEM_NYU_2010)
# check number/kind of channels
@@ -242,20 +239,21 @@ def test_decimate():
# read in raw data using spherical hsp, and extract new hsp
with warnings.catch_warnings(record=True) as w:
raw = read_raw_kit(sqd_path, mrk_path, elp_txt_path, sphere_hsp_path)
assert_true(any('more than' in str(ww.message) for ww in w))
assert any('more than' in str(ww.message) for ww in w)
# collect headshape from raw (should now be in m)
hsp_dec = np.array([dig['r'] for dig in raw.info['dig']])[8:]
# with 10242 points and _decimate_points set to resolution of 5 mm, hsp_dec
# should be a bit over 5000 points. If not, something is wrong or
# decimation resolution has been purposefully changed
assert_true(len(hsp_dec) > 5000)
assert len(hsp_dec) > 5000
# should have similar size, distance from center
dist = np.sqrt(np.sum((hsp_m - np.mean(hsp_m, axis=0))**2, axis=1))
dist_dec = np.sqrt(np.sum((hsp_dec - np.mean(hsp_dec, axis=0))**2, axis=1))
hsp_rad = np.mean(dist)
hsp_dec_rad = np.mean(dist_dec)
assert_almost_equal(hsp_rad, hsp_dec_rad, places=3)
assert_array_almost_equal(hsp_rad, hsp_dec_rad, decimal=3)
run_tests_if_main()
+11 -10
View File
@@ -3,7 +3,6 @@
# License: BSD (3-clause)
import numpy as np
from nose.tools import assert_equal, assert_raises, assert_true
import pytest
from mne import create_info
@@ -12,40 +11,42 @@ from mne.utils import logger, catch_logging, run_tests_if_main
def bad_1(x):
"""Fail."""
return # bad return type
def bad_2(x):
"""Fail."""
return x[:-1] # bad shape
def printer(x):
"""Print."""
logger.info('exec')
return x
@pytest.mark.slowtest
def test_apply_function_verbose():
"""Test apply function verbosity
"""
"""Test apply function verbosity."""
n_chan = 2
n_times = 3
ch_names = [str(ii) for ii in range(n_chan)]
raw = RawArray(np.zeros((n_chan, n_times)),
create_info(ch_names, 1., 'mag'))
# test return types in both code paths (parallel / 1 job)
assert_raises(TypeError, raw.apply_function, bad_1)
assert_raises(ValueError, raw.apply_function, bad_2)
assert_raises(TypeError, raw.apply_function, bad_1, n_jobs=2)
assert_raises(ValueError, raw.apply_function, bad_2, n_jobs=2)
pytest.raises(TypeError, raw.apply_function, bad_1)
pytest.raises(ValueError, raw.apply_function, bad_2)
pytest.raises(TypeError, raw.apply_function, bad_1, n_jobs=2)
pytest.raises(ValueError, raw.apply_function, bad_2, n_jobs=2)
# check our arguments
with catch_logging() as sio:
out = raw.apply_function(printer, verbose=False)
assert_equal(len(sio.getvalue()), 0)
assert_true(out is raw)
assert len(sio.getvalue()) == 0
assert out is raw
raw.apply_function(printer, verbose=True)
assert_equal(sio.getvalue().count('\n'), n_chan)
assert sio.getvalue().count('\n') == n_chan
run_tests_if_main()
+4 -4
View File
@@ -3,7 +3,6 @@
# License: BSD (3-clause)
import os.path as op
from nose.tools import assert_true
import numpy as np
from numpy.testing import assert_allclose, assert_equal
@@ -22,9 +21,9 @@ def test_compensation():
raw = read_raw_fif(ctf_comp_fname)
assert_equal(get_current_comp(raw.info), 3)
comp1 = make_compensator(raw.info, 3, 1, exclude_comp_chs=False)
assert_true(comp1.shape == (340, 340))
assert comp1.shape == (340, 340)
comp2 = make_compensator(raw.info, 3, 1, exclude_comp_chs=True)
assert_true(comp2.shape == (311, 340))
assert comp2.shape == (311, 340)
# round-trip
desired = np.eye(340)
@@ -54,7 +53,7 @@ def test_compensation():
# channels have norm ~1e-12
assert_allclose(data, data2, rtol=1e-9, atol=1e-18)
for ch1, ch2 in zip(raw.info['chs'], raw2.info['chs']):
assert_true(ch1['coil_type'] == ch2['coil_type'])
assert ch1['coil_type'] == ch2['coil_type']
@requires_mne
@@ -96,4 +95,5 @@ def test_compensation_mne():
for ch_py, ch_c in zip(chs_py, chs_c):
assert_equal(ch_py['coil_type'], ch_c['coil_type'])
run_tests_if_main()
+15 -15
View File
@@ -2,8 +2,8 @@ import inspect
import os.path as op
import warnings
from nose.tools import assert_equal, assert_raises, assert_true
from numpy.testing import assert_array_equal
from numpy.testing import assert_array_equal, assert_equal
import pytest
import numpy as np
from mne import (pick_channels_regexp, pick_types, Epochs,
@@ -50,8 +50,8 @@ def test_pick_refs():
raw_ctf.apply_gradient_compensation(2)
for info in infos:
info['bads'] = []
assert_raises(ValueError, pick_types, info, meg='foo')
assert_raises(ValueError, pick_types, info, ref_meg='foo')
pytest.raises(ValueError, pick_types, info, meg='foo')
pytest.raises(ValueError, pick_types, info, ref_meg='foo')
picks_meg_ref = pick_types(info, meg=True, ref_meg=True)
picks_meg = pick_types(info, meg=True, ref_meg=False)
picks_ref = pick_types(info, meg=False, ref_meg=True)
@@ -98,7 +98,7 @@ def test_pick_refs():
for pick in (picks_meg, picks_mag):
if len(pick) > 0:
assert_raises(RuntimeError, pick_info, info, pick)
pytest.raises(RuntimeError, pick_info, info, pick)
def test_pick_channels_regexp():
@@ -141,9 +141,9 @@ def test_pick_chpi():
info = read_info(op.join(io_dir, 'tests', 'data', 'test_chpi_raw_sss.fif'))
channel_types = set([channel_type(info, idx)
for idx in range(info['nchan'])])
assert_true('chpi' in channel_types)
assert_true('seeg' not in channel_types)
assert_true('ecog' not in channel_types)
assert 'chpi' in channel_types
assert 'seeg' not in channel_types
assert 'ecog' not in channel_types
def test_pick_bio():
@@ -189,8 +189,8 @@ def test_pick_forward_seeg_ecog():
fwd_ = pick_types_forward(fwd, meg=False, eeg=True)
_check_fwd_n_chan_consistent(fwd_, counts['eeg'])
# should raise exception related to emptiness
assert_raises(ValueError, pick_types_forward, fwd, meg=False, seeg=True)
assert_raises(ValueError, pick_types_forward, fwd, meg=False, ecog=True)
pytest.raises(ValueError, pick_types_forward, fwd, meg=False, seeg=True)
pytest.raises(ValueError, pick_types_forward, fwd, meg=False, ecog=True)
# change last chan from EEG to sEEG, second-to-last to ECoG
ecog_name = 'E1'
seeg_name = 'OTp1'
@@ -256,8 +256,8 @@ def test_picks_by_channels():
[0, 1])
# Make sure checks for list input work.
assert_raises(ValueError, pick_channels, ch_names, 'MEG 001')
assert_raises(ValueError, pick_channels, ch_names, ['MEG 001'], 'hi')
pytest.raises(ValueError, pick_channels, ch_names, 'MEG 001')
pytest.raises(ValueError, pick_channels, ch_names, ['MEG 001'], 'hi')
pick_list = _picks_by_type(raw.info)
assert_equal(len(pick_list), 1)
@@ -267,7 +267,7 @@ def test_picks_by_channels():
assert_equal(pick_list2[0][0], 'mag')
# pick_types type check
assert_raises(ValueError, raw.pick_types, eeg='string')
pytest.raises(ValueError, raw.pick_types, eeg='string')
# duplicate check
names = ['MEG 002', 'MEG 002']
@@ -277,7 +277,6 @@ def test_picks_by_channels():
def test_clean_info_bads():
"""Test cleaning info['bads'] when bad_channels are excluded."""
raw_file = op.join(op.dirname(_root_init_fname), 'io', 'tests', 'data',
'test_raw.fif')
raw = read_raw_fif(raw_file)
@@ -311,6 +310,7 @@ def test_clean_info_bads():
info = pick_info(raw.info, picks_meg)
info._check_consistency()
info['bads'] += ['EEG 053']
assert_raises(RuntimeError, info._check_consistency)
pytest.raises(RuntimeError, info._check_consistency)
run_tests_if_main()
+19 -18
View File
@@ -2,12 +2,14 @@
# Eric Larson <larson.eric.d@gmail.com>
# License: Simplified BSD
import numpy as np
import os.path as op
import numpy as np
from numpy.testing import assert_array_equal
from mne.io import read_info, read_raw_fif
from mne.io.constants import FIFF
from mne.io.proc_history import _get_rank_sss
from nose.tools import assert_true, assert_equal
base_dir = op.join(op.dirname(__file__), 'data')
raw_fname = op.join(base_dir, 'test_chpi_raw_sss.fif')
@@ -18,24 +20,23 @@ def test_maxfilter_io():
info = read_info(raw_fname)
mf = info['proc_history'][1]['max_info']
assert_true(mf['sss_info']['frame'], FIFF.FIFFV_COORD_HEAD)
assert mf['sss_info']['frame'] == FIFF.FIFFV_COORD_HEAD
# based on manual 2.0, rev. 5.0 page 23
assert_true(5 <= mf['sss_info']['in_order'] <= 11)
assert_true(mf['sss_info']['out_order'] <= 5)
assert_true(mf['sss_info']['nchan'] > len(mf['sss_info']['components']))
assert 5 <= mf['sss_info']['in_order'] <= 11
assert mf['sss_info']['out_order'] <= 5
assert mf['sss_info']['nchan'] > len(mf['sss_info']['components'])
assert_equal(info['ch_names'][:mf['sss_info']['nchan']],
mf['sss_ctc']['proj_items_chs'])
assert_equal(mf['sss_ctc']['decoupler'].shape,
(mf['sss_info']['nchan'], mf['sss_info']['nchan']))
assert_equal(np.unique(np.diag(mf['sss_ctc']['decoupler'].toarray())),
np.array([1.], dtype=np.float32))
assert_equal(mf['sss_cal']['cal_corrs'].shape, (306, 14))
assert_equal(mf['sss_cal']['cal_chans'].shape, (306, 2))
assert (info['ch_names'][:mf['sss_info']['nchan']] ==
mf['sss_ctc']['proj_items_chs'])
assert (mf['sss_ctc']['decoupler'].shape ==
(mf['sss_info']['nchan'], mf['sss_info']['nchan']))
assert_array_equal(
np.unique(np.diag(mf['sss_ctc']['decoupler'].toarray())),
np.array([1.], dtype=np.float32))
assert mf['sss_cal']['cal_corrs'].shape == (306, 14)
assert mf['sss_cal']['cal_chans'].shape == (306, 2)
vv_coils = [v for k, v in FIFF.items() if 'FIFFV_COIL_VV' in k]
assert_true(all(k in vv_coils
for k in set(mf['sss_cal']['cal_chans'][:, 1])))
assert all(k in vv_coils for k in set(mf['sss_cal']['cal_chans'][:, 1]))
def test_maxfilter_get_rank():
@@ -44,4 +45,4 @@ def test_maxfilter_get_rank():
mf = raw.info['proc_history'][0]['max_info']
rank1 = mf['sss_info']['nfree']
rank2 = _get_rank_sss(raw)
assert_equal(rank1, rank2)
assert rank1 == rank2
+11 -11
View File
@@ -1,10 +1,10 @@
# Generic tests that all raw classes should run
from os import path as op
import math
import numpy as np
from numpy.testing import assert_allclose, assert_array_almost_equal
from nose.tools import assert_equal, assert_true
import numpy as np
from numpy.testing import (assert_allclose, assert_array_almost_equal,
assert_equal)
from mne import concatenate_raws
from mne.datasets import testing
@@ -58,25 +58,25 @@ def _test_raw_reader(reader, test_preloading=True, **kwargs):
raw = reader(**kwargs)
full_data = raw._data
assert_true(raw.__class__.__name__, repr(raw)) # to test repr
assert_true(raw.info.__class__.__name__, repr(raw.info))
assert raw.__class__.__name__ in repr(raw) # to test repr
assert raw.info.__class__.__name__ in repr(raw.info)
# Test saving and reading
out_fname = op.join(tempdir, 'test_raw.fif')
raw = concatenate_raws([raw])
raw.save(out_fname, tmax=raw.times[-1], overwrite=True, buffer_size_sec=1)
raw3 = read_raw_fif(out_fname)
assert_equal(set(raw.info.keys()), set(raw3.info.keys()))
assert set(raw.info.keys()) == set(raw3.info.keys())
assert_allclose(raw3[0:20][0], full_data[0:20], rtol=1e-6,
atol=1e-20) # atol is very small but > 0
assert_array_almost_equal(raw.times, raw3.times)
assert_true(not math.isnan(raw3.info['highpass']))
assert_true(not math.isnan(raw3.info['lowpass']))
assert_true(not math.isnan(raw.info['highpass']))
assert_true(not math.isnan(raw.info['lowpass']))
assert not math.isnan(raw3.info['highpass'])
assert not math.isnan(raw3.info['lowpass'])
assert not math.isnan(raw.info['highpass'])
assert not math.isnan(raw.info['lowpass'])
assert_equal(raw3.info['kit_system_id'], raw.info['kit_system_id'])
assert raw3.info['kit_system_id'] == raw.info['kit_system_id']
# Make sure concatenation works
first_samp = raw.first_samp
+44 -44
View File
@@ -8,8 +8,8 @@ import warnings
import os.path as op
import numpy as np
from nose.tools import assert_true, assert_equal, assert_raises
from numpy.testing import assert_array_equal, assert_allclose
from numpy.testing import assert_array_equal, assert_allclose, assert_equal
import pytest
from mne import (pick_channels, pick_types, Epochs, read_events,
set_eeg_reference, set_bipolar_reference,
@@ -76,15 +76,15 @@ def test_apply_reference():
# 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'])
assert (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']))
assert (not _has_eeg_average_ref_proj(reref.info['projs']))
# 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)
assert (raw is reref)
# Test that disabling the reference does not change anything
reref, ref_data = _apply_reference(raw.copy(), [])
@@ -98,19 +98,19 @@ def test_apply_reference():
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'])
assert (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'])
assert (reref.info['custom_ref_applied'])
_test_reference(evoked, reref, ref_data, ['EEG 001', 'EEG 002'])
# Referencing needs data to be preloaded
raw_np = read_raw_fif(fif_fname, preload=False)
assert_raises(RuntimeError, _apply_reference, raw_np, ['EEG 001'])
pytest.raises(RuntimeError, _apply_reference, raw_np, ['EEG 001'])
# Test having inactive SSP projections that deal with channels involved
# during re-referencing
@@ -130,7 +130,7 @@ def test_apply_reference():
)
)
# Projection concerns channels mentioned in projector
assert_raises(RuntimeError, _apply_reference, raw, ['EEG 001'])
pytest.raises(RuntimeError, _apply_reference, raw, ['EEG 001'])
# Projection does not concern channels mentioned in projector, no error
_apply_reference(raw, ['EEG 003'], ['EEG 004'])
@@ -143,11 +143,11 @@ def test_set_eeg_reference():
raw.info['projs'] = []
# Test setting an average reference projection
assert_true(not _has_eeg_average_ref_proj(raw.info['projs']))
assert (not _has_eeg_average_ref_proj(raw.info['projs']))
reref, ref_data = set_eeg_reference(raw, projection=True)
assert_true(_has_eeg_average_ref_proj(reref.info['projs']))
assert_true(not reref.info['projs'][0]['active'])
assert_true(ref_data is None)
assert (_has_eeg_average_ref_proj(reref.info['projs']))
assert (not reref.info['projs'][0]['active'])
assert (ref_data is None)
reref.apply_proj()
eeg_chans = [raw.ch_names[ch]
for ch in pick_types(raw.info, meg=False, eeg=True)]
@@ -157,29 +157,29 @@ def test_set_eeg_reference():
# Test setting an average reference when one was already present
with warnings.catch_warnings(record=True):
reref, ref_data = set_eeg_reference(raw, copy=False, projection=True)
assert_true(ref_data is None)
assert (ref_data is None)
# Test setting an average reference on non-preloaded data
raw_nopreload = read_raw_fif(fif_fname, preload=False)
raw_nopreload.info['projs'] = []
reref, ref_data = set_eeg_reference(raw_nopreload, projection=True)
assert_true(_has_eeg_average_ref_proj(reref.info['projs']))
assert_true(not reref.info['projs'][0]['active'])
assert (_has_eeg_average_ref_proj(reref.info['projs']))
assert (not reref.info['projs'][0]['active'])
# Rereference raw data by creating a copy of original data
reref, ref_data = set_eeg_reference(raw, ['EEG 001', 'EEG 002'], copy=True)
assert_true(reref.info['custom_ref_applied'])
assert (reref.info['custom_ref_applied'])
_test_reference(raw, reref, ref_data, ['EEG 001', 'EEG 002'])
# Test that data is modified in place when copy=False
reref, ref_data = set_eeg_reference(raw, ['EEG 001', 'EEG 002'],
copy=False)
assert_true(raw is reref)
assert (raw is reref)
# Test moving from custom to average reference
reref, ref_data = set_eeg_reference(raw, ['EEG 001', 'EEG 002'])
reref, _ = set_eeg_reference(reref, projection=True)
assert_true(_has_eeg_average_ref_proj(reref.info['projs']))
assert (_has_eeg_average_ref_proj(reref.info['projs']))
assert_equal(reref.info['custom_ref_applied'], False)
# When creating an average reference fails, make sure the
@@ -187,8 +187,8 @@ def test_set_eeg_reference():
reref = raw.copy()
reref.info['custom_ref_applied'] = True
reref.pick_types(eeg=False) # Cause making average ref fail
assert_raises(ValueError, set_eeg_reference, reref, projection=True)
assert_true(reref.info['custom_ref_applied'])
pytest.raises(ValueError, set_eeg_reference, reref, projection=True)
assert (reref.info['custom_ref_applied'])
# Test moving from average to custom reference
reref, ref_data = set_eeg_reference(raw, projection=True)
@@ -206,7 +206,7 @@ def test_set_eeg_reference():
# make sure ref_channels=[] removes average reference projectors
assert _has_eeg_average_ref_proj(raw.info['projs'])
reref, _ = set_eeg_reference(raw, [])
assert_true(not _has_eeg_average_ref_proj(reref.info['projs']))
assert (not _has_eeg_average_ref_proj(reref.info['projs']))
# Test that average reference gives identical results when calculated
# via SSP projection (projection=True) or directly (projection=False)
@@ -222,8 +222,8 @@ def test_set_eeg_reference():
_test_reference(raw, reref, ref_data, eeg_chans)
# projection=True only works for ref_channels='average'
assert_raises(ValueError, set_eeg_reference, raw, [], True, True)
assert_raises(ValueError, set_eeg_reference, raw, ['EEG 001'], True, True)
pytest.raises(ValueError, set_eeg_reference, raw, [], True, True)
pytest.raises(ValueError, set_eeg_reference, raw, ['EEG 001'], True, True)
@testing.requires_testing_data
@@ -235,7 +235,7 @@ def test_set_bipolar_reference():
reref = set_bipolar_reference(raw, 'EEG 001', 'EEG 002', 'bipolar',
{'kind': FIFF.FIFFV_EOG_CH,
'extra': 'some extra value'})
assert_true(reref.info['custom_ref_applied'])
assert (reref.info['custom_ref_applied'])
# Compare result to a manual calculation
a = raw.copy().pick_channels(['EEG 001', 'EEG 002'])
@@ -244,9 +244,9 @@ def test_set_bipolar_reference():
assert_allclose(a, b)
# Original channels should be replaced by a virtual one
assert_true('EEG 001' not in reref.ch_names)
assert_true('EEG 002' not in reref.ch_names)
assert_true('bipolar' in reref.ch_names)
assert ('EEG 001' not in reref.ch_names)
assert ('EEG 002' not in reref.ch_names)
assert ('bipolar' in reref.ch_names)
# Check channel information
bp_info = reref.info['chs'][reref.ch_names.index('bipolar')]
@@ -264,14 +264,14 @@ def test_set_bipolar_reference():
# Minimalist call
reref = set_bipolar_reference(raw, 'EEG 001', 'EEG 002')
assert_true('EEG 001-EEG 002' in reref.ch_names)
assert ('EEG 001-EEG 002' in reref.ch_names)
# Minimalist call with twice the same anode
reref = set_bipolar_reference(raw,
['EEG 001', 'EEG 001', 'EEG 002'],
['EEG 002', 'EEG 003', 'EEG 003'])
assert_true('EEG 001-EEG 002' in reref.ch_names)
assert_true('EEG 001-EEG 003' in reref.ch_names)
assert ('EEG 001-EEG 002' in reref.ch_names)
assert ('EEG 001-EEG 003' in reref.ch_names)
# Set multiple references at once
reref = set_bipolar_reference(
@@ -293,20 +293,20 @@ def test_set_bipolar_reference():
reref = set_bipolar_reference(raw, 'MEG 0111', 'MEG 0112',
ch_info={'kind': FIFF.FIFFV_MEG_CH},
verbose='error')
assert_true(not reref.info['custom_ref_applied'])
assert_true('MEG 0111-MEG 0112'[:15] in reref.ch_names)
assert (not reref.info['custom_ref_applied'])
assert ('MEG 0111-MEG 0112'[:15] in reref.ch_names)
# Test a battery of invalid inputs
assert_raises(ValueError, set_bipolar_reference, raw,
pytest.raises(ValueError, set_bipolar_reference, raw,
'EEG 001', ['EEG 002', 'EEG 003'], 'bipolar')
assert_raises(ValueError, set_bipolar_reference, raw,
pytest.raises(ValueError, set_bipolar_reference, raw,
['EEG 001', 'EEG 002'], 'EEG 003', 'bipolar')
assert_raises(ValueError, set_bipolar_reference, raw,
pytest.raises(ValueError, set_bipolar_reference, raw,
'EEG 001', 'EEG 002', ['bipolar1', 'bipolar2'])
assert_raises(ValueError, set_bipolar_reference, raw,
pytest.raises(ValueError, set_bipolar_reference, raw,
'EEG 001', 'EEG 002', 'bipolar',
ch_info=[{'foo': 'bar'}, {'foo': 'bar'}])
assert_raises(ValueError, set_bipolar_reference, raw,
pytest.raises(ValueError, set_bipolar_reference, raw,
'EEG 001', 'EEG 002', ch_name='EEG 003')
@@ -317,7 +317,7 @@ def _check_channel_names(inst, ref_names):
# Test that the names of the reference channels are present in `ch_names`
ref_idx = pick_channels(inst.info['ch_names'], ref_names)
assert_true(len(ref_idx), len(ref_names))
assert len(ref_idx) == len(ref_names)
# Test that the names of the reference channels are present in the `chs`
# list
@@ -330,7 +330,7 @@ def test_add_reference():
raw = read_raw_fif(fif_fname, preload=True)
picks_eeg = pick_types(raw.info, meg=False, eeg=True)
# check if channel already exists
assert_raises(ValueError, add_reference_channels,
pytest.raises(ValueError, add_reference_channels,
raw, raw.info['ch_names'][0])
# add reference channel to Raw
raw_ref = add_reference_channels(raw, 'Ref', copy=True)
@@ -371,7 +371,7 @@ def test_add_reference():
_check_channel_names(raw, 'Ref')
# Test adding an existing channel as reference channel
assert_raises(ValueError, add_reference_channels, raw,
pytest.raises(ValueError, add_reference_channels, raw,
raw.info['ch_names'][0])
# add two reference channels to Raw
@@ -395,7 +395,7 @@ def test_add_reference():
epochs = Epochs(raw, events=events, event_id=1, tmin=-0.2, tmax=0.5,
picks=picks_eeg, preload=True)
# default: proj=True, after which adding a Ref channel is prohibited
assert_raises(RuntimeError, add_reference_channels, epochs, 'Ref')
pytest.raises(RuntimeError, add_reference_channels, epochs, 'Ref')
# create epochs in delayed mode, allowing removal of CAR when re-reffing
epochs = Epochs(raw, events=events, event_id=1, tmin=-0.2, tmax=0.5,
@@ -472,8 +472,8 @@ def test_add_reference():
# Test invalid inputs
raw_np = read_raw_fif(fif_fname, preload=False)
assert_raises(RuntimeError, add_reference_channels, raw_np, ['Ref'])
assert_raises(ValueError, add_reference_channels, raw, 1)
pytest.raises(RuntimeError, add_reference_channels, raw_np, ['Ref'])
pytest.raises(ValueError, add_reference_channels, raw, 1)
run_tests_if_main()
+46 -49
View File
@@ -4,7 +4,7 @@ import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_equal,
assert_allclose, assert_array_equal)
from scipy import sparse
from nose.tools import assert_true, assert_raises
import pytest
import copy
import warnings
@@ -96,7 +96,7 @@ def _compare(a, b):
'command_line', 'working_dir', 'mri_file', 'mri_id']
try:
if isinstance(a, (dict, Info)):
assert_true(isinstance(b, (dict, Info)))
assert (isinstance(b, (dict, Info)))
for k, v in six.iteritems(a):
if k not in b and k not in skip_types:
raise ValueError('First one had one second one didn\'t:\n'
@@ -110,7 +110,7 @@ def _compare(a, b):
raise ValueError('Second one had one first one didn\'t:\n'
'%s not in %s' % (k, a.keys()))
elif isinstance(a, list):
assert_true(len(a) == len(b))
assert (len(a) == len(b))
for i, j in zip(a, b):
_compare(i, j)
elif isinstance(a, sparse.csr.csr_matrix):
@@ -135,13 +135,13 @@ def _compare_inverses_approx(inv_1, inv_2, evoked, rtol, atol,
assert_allclose(inv_1['depth_prior']['data'],
inv_2['depth_prior']['data'], atol=depth_atol)
else:
assert_true(inv_2['depth_prior'] is None)
assert (inv_2['depth_prior'] is None)
# orient prior
if inv_1['orient_prior'] is not None:
assert_allclose(inv_1['orient_prior']['data'],
inv_2['orient_prior']['data'], atol=1e-7)
else:
assert_true(inv_2['orient_prior'] is None)
assert (inv_2['orient_prior'] is None)
# source cov
assert_allclose(inv_1['source_cov']['data'], inv_2['source_cov']['data'],
atol=1e-7)
@@ -179,7 +179,7 @@ def _compare_inverses_approx(inv_1, inv_2, evoked, rtol, atol,
stc_1 /= norms
stc_2 /= norms
corr = np.corrcoef(stc_1.ravel(), stc_2.ravel())[0, 1]
assert_true(corr > ctol, msg='%s < %s' % (corr, ctol))
assert corr > ctol
assert_allclose(stc_1, stc_2, rtol=rtol, atol=atol,
err_msg='%s: %s' % (method, corr))
@@ -238,8 +238,8 @@ def test_make_inverse_operator():
_compare_io(my_inv_op)
_compare_inverses_approx(my_inv_op, inverse_operator, evoked,
rtol=1e-3, atol=1e-5)
assert_true('dev_head_t' in my_inv_op['info'])
assert_true('mri_head_t' in my_inv_op)
assert ('dev_head_t' in my_inv_op['info'])
assert ('mri_head_t' in my_inv_op)
@pytest.mark.slowtest
@@ -288,7 +288,7 @@ def test_inverse_operator_channel_ordering():
assert_equal(stc_1.subject, stc_2.subject)
assert_array_equal(stc_1.times, stc_2.times)
assert_allclose(stc_1.data, stc_2.data, rtol=1e-5, atol=1e-5)
assert_true(inv_orig['units'] == inv_reorder['units'])
assert (inv_orig['units'] == inv_reorder['units'])
# Reload with original ordering & apply reordered inverse
evoked = _get_evoked()
@@ -419,10 +419,10 @@ def test_apply_inverse_operator():
evoked = _get_evoked()
# Inverse has 306 channels - 4 proj = 302
assert_true(compute_rank_inverse(inverse_operator) == 302)
assert (compute_rank_inverse(inverse_operator) == 302)
# Inverse has 306 channels - 4 proj = 302
assert_true(compute_rank_inverse(inverse_operator) == 302)
assert (compute_rank_inverse(inverse_operator) == 302)
stc = apply_inverse(evoked, inverse_operator, lambda2, "MNE")
assert stc.subject == 'sample'
@@ -477,10 +477,10 @@ def test_apply_inverse_operator():
# Test we get errors when using custom ref or no average proj is present
evoked.info['custom_ref_applied'] = True
assert_raises(ValueError, apply_inverse, evoked, inv_op, lambda2, "MNE")
pytest.raises(ValueError, apply_inverse, evoked, inv_op, lambda2, "MNE")
evoked.info['custom_ref_applied'] = False
evoked.info['projs'] = [] # remove EEG proj
assert_raises(ValueError, apply_inverse, evoked, inv_op, lambda2, "MNE")
pytest.raises(ValueError, apply_inverse, evoked, inv_op, lambda2, "MNE")
@testing.requires_testing_data
@@ -493,7 +493,7 @@ def test_make_inverse_operator_fixed():
# can't make fixed inv with depth weighting without free ori fwd
fwd_fixed = convert_forward_solution(fwd, force_fixed=True,
use_cps=True)
assert_raises(ValueError, make_inverse_operator, evoked.info, fwd_fixed,
pytest.raises(ValueError, make_inverse_operator, evoked.info, fwd_fixed,
noise_cov, depth=0.8, fixed=True)
# now compare to C solution
@@ -511,7 +511,7 @@ def test_make_inverse_operator_fixed():
_compare_inverses_approx(inverse_operator_nodepth, inv_op, evoked,
rtol=1e-5, atol=1e-4)
# Inverse has 306 channels - 6 proj = 302
assert_true(compute_rank_inverse(inverse_operator_nodepth) == 302)
assert (compute_rank_inverse(inverse_operator_nodepth) == 302)
# Now with depth
fwd_surf = convert_forward_solution(fwd, surf_ori=True) # not fixed
for kwargs, use_fwd in zip([dict(fixed=True), dict(loose=0.)],
@@ -538,7 +538,7 @@ def test_make_inverse_operator_free():
noise_cov = read_cov(fname_cov)
# can't make free inv with fixed fwd
assert_raises(ValueError, make_inverse_operator, evoked.info, fwd_fixed,
pytest.raises(ValueError, make_inverse_operator, evoked.info, fwd_fixed,
noise_cov, depth=None)
# for depth=None, surf_ori of the fwd should not matter
@@ -578,7 +578,7 @@ def test_make_inverse_operator_vector():
assert_allclose(stc.data, stc_vec.magnitude().data)
# Vector estimates don't work when using fixed orientations
assert_raises(RuntimeError, apply_inverse, evoked, inv_3,
pytest.raises(RuntimeError, apply_inverse, evoked, inv_3,
pick_ori='vector')
# When computing with vector fields, computing the difference between two
@@ -614,59 +614,56 @@ def test_make_inverse_operator_diag():
_compare_inverses_approx(inverse_operator_diag, inv_op, evoked,
rtol=1e-1, atol=1e-1, ctol=0.99, check_K=False)
# Inverse has 366 channels - 6 proj = 360
assert_true(compute_rank_inverse(inverse_operator_diag) == 360)
assert (compute_rank_inverse(inverse_operator_diag) == 360)
@testing.requires_testing_data
def test_inverse_operator_noise_cov_rank():
"""Test MNE inverse operator with a specified noise cov rank
"""
"""Test MNE inverse operator with a specified noise cov rank."""
fwd_op = read_forward_solution_meg(fname_fwd, surf_ori=True)
evoked = _get_evoked()
noise_cov = read_cov(fname_cov)
inv = make_inverse_operator(evoked.info, fwd_op, noise_cov, rank=64)
assert_true(compute_rank_inverse(inv) == 64)
assert (compute_rank_inverse(inv) == 64)
fwd_op = read_forward_solution_eeg(fname_fwd, surf_ori=True)
inv = make_inverse_operator(evoked.info, fwd_op, noise_cov,
rank=dict(eeg=20))
assert_true(compute_rank_inverse(inv) == 20)
assert (compute_rank_inverse(inv) == 20)
@testing.requires_testing_data
def test_inverse_operator_volume():
"""Test MNE inverse computation on volume source space
"""
"""Test MNE inverse computation on volume source space."""
tempdir = _TempDir()
evoked = _get_evoked()
inv_vol = read_inverse_operator(fname_vol_inv)
assert_true(repr(inv_vol))
assert (repr(inv_vol))
stc = apply_inverse(evoked, inv_vol, lambda2, 'dSPM')
assert_true(isinstance(stc, VolSourceEstimate))
assert (isinstance(stc, VolSourceEstimate))
# volume inverses don't have associated subject IDs
assert_true(stc.subject is None)
assert (stc.subject is None)
stc.save(op.join(tempdir, 'tmp-vl.stc'))
stc2 = read_source_estimate(op.join(tempdir, 'tmp-vl.stc'))
assert_true(np.all(stc.data > 0))
assert_true(np.all(stc.data < 35))
assert (np.all(stc.data > 0))
assert (np.all(stc.data < 35))
assert_array_almost_equal(stc.data, stc2.data)
assert_array_almost_equal(stc.times, stc2.times)
# vector source estimate
stc_vec = apply_inverse(evoked, inv_vol, lambda2, 'dSPM', 'vector')
assert_true(repr(stc_vec))
assert (repr(stc_vec))
assert_allclose(np.linalg.norm(stc_vec.data, axis=1), stc.data)
@pytest.mark.slowtest
@testing.requires_testing_data
def test_io_inverse_operator():
"""Test IO of inverse_operator
"""
"""Test IO of inverse_operator."""
tempdir = _TempDir()
inverse_operator = read_inverse_operator(fname_inv)
x = repr(inverse_operator)
assert_true(x)
assert_true(isinstance(inverse_operator['noise_cov'], Covariance))
assert (x)
assert (isinstance(inverse_operator['noise_cov'], Covariance))
# just do one example for .gz, as it should generalize
_compare_io(inverse_operator, '.gz')
@@ -714,11 +711,11 @@ def test_apply_mne_inverse_raw():
buffer_size=3, prepared=True)
if pick_ori is None:
assert_true(np.all(stc.data > 0))
assert_true(np.all(stc2.data > 0))
assert (np.all(stc.data > 0))
assert (np.all(stc2.data > 0))
assert_true(stc.subject == 'sample')
assert_true(stc2.subject == 'sample')
assert (stc.subject == 'sample')
assert (stc2.subject == 'sample')
assert_array_almost_equal(stc.times, times)
assert_array_almost_equal(stc2.times, times)
assert_array_almost_equal(stc.data, stc2.data)
@@ -737,7 +734,7 @@ def test_apply_mne_inverse_fixed_raw():
fwd = read_forward_solution_meg(fname_fwd, force_fixed=False,
surf_ori=True)
noise_cov = read_cov(fname_cov)
assert_raises(ValueError, make_inverse_operator,
pytest.raises(ValueError, make_inverse_operator,
raw.info, fwd, noise_cov, loose=1., fixed=True)
inv_op = make_inverse_operator(raw.info, fwd, noise_cov,
fixed=True, use_cps=True)
@@ -756,8 +753,8 @@ def test_apply_mne_inverse_fixed_raw():
label=label_lh, start=start, stop=stop, nave=1,
pick_ori=None, buffer_size=None)
assert_true(stc.subject == 'sample')
assert_true(stc2.subject == 'sample')
assert (stc.subject == 'sample')
assert (stc2.subject == 'sample')
assert_array_almost_equal(stc.times, times)
assert_array_almost_equal(stc2.times, times)
assert_array_almost_equal(stc3.times, times)
@@ -797,9 +794,9 @@ def test_apply_mne_inverse_epochs():
assert_array_almost_equal(stcs[0].data, stcs2[0].data)
assert_array_almost_equal(stcs[0].times, stcs2[0].times)
assert_true(len(stcs) == 2)
assert_true(3 < stcs[0].data.max() < 10)
assert_true(stcs[0].subject == 'sample')
assert (len(stcs) == 2)
assert (3 < stcs[0].data.max() < 10)
assert (stcs[0].subject == 'sample')
inverse_operator = read_inverse_operator(fname_full)
stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM",
@@ -810,7 +807,7 @@ def test_apply_mne_inverse_epochs():
label_mean = np.mean(data, axis=0)
label_mean_flip = np.mean(flip[:, np.newaxis] * data, axis=0)
assert_true(label_mean.max() < label_mean_flip.max())
assert (label_mean.max() < label_mean_flip.max())
# test extracting a BiHemiLabel
inverse_operator = prepare_inverse_operator(inverse_operator, nave=1,
@@ -831,9 +828,9 @@ def test_apply_mne_inverse_epochs():
# test without using a label (so delayed computation is used)
stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM",
pick_ori="normal", prepared=True)
assert_true(stcs[0].subject == 'sample')
assert (stcs[0].subject == 'sample')
label_stc = stcs[0].in_label(label_rh)
assert_true(label_stc.subject == 'sample')
assert (label_stc.subject == 'sample')
assert_array_almost_equal(stcs_rh[0].data, label_stc.data)
@@ -851,8 +848,8 @@ def test_make_inverse_operator_bads():
union_bads = set(noise_cov['bads']) & set(evoked.info['bads'])
evoked.info['bads'].append(bad)
assert_true(len(set(inv_['info']['ch_names']) - union_good) == 0)
assert_true(len(set(inv_['info']['bads']) - union_bads) == 0)
assert (len(set(inv_['info']['ch_names']) - union_good) == 0)
assert (len(set(inv_['info']['bads']) - union_bads) == 0)
run_tests_if_main()
+6 -9
View File
@@ -8,8 +8,6 @@ from mne.minimum_norm import (read_inverse_operator,
point_spread_function, cross_talk_function)
from mne.utils import run_tests_if_main
from nose.tools import assert_true
data_path = op.join(testing.data_path(download=False), 'MEG', 'sample')
fname_inv_meg = op.join(data_path,
@@ -28,8 +26,7 @@ lambda2 = 1.0 / snr ** 2
@pytest.mark.slowtest
@testing.requires_testing_data
def test_psf_ctf():
"""Test computation of PSFs and CTFs for linear estimators
"""
"""Test computation of PSFs and CTFs for linear estimators."""
forward = read_forward_solution(fname_fwd)
labels = [mne.read_label(ss) for ss in fname_label]
@@ -54,11 +51,11 @@ def test_psf_ctf():
else:
should_n_samples = len(labels) + 1
assert_true(n_vert == should_n_vert)
assert_true(n_samples == should_n_samples)
assert (n_vert == should_n_vert)
assert (n_samples == should_n_samples)
n_chan, n_samples = psf_ev.data.shape
assert_true(n_chan == forward['nchan'])
assert (n_chan == forward['nchan'])
# Test CTFs
for mode in ('sum', 'svd'):
@@ -75,8 +72,8 @@ def test_psf_ctf():
else:
should_n_samples = len(labels) + 1
assert_true(n_vert == should_n_vert)
assert_true(n_samples == should_n_samples)
assert (n_vert == should_n_vert)
assert (n_samples == should_n_samples)
run_tests_if_main()
+1 -1
View File
@@ -23,7 +23,7 @@ fname_evoked = op.join(s_path, 'sample_audvis-ave.fif')
@testing.requires_testing_data
@requires_mne
def test_snr():
"""Test SNR calculation"""
"""Test SNR calculation."""
tempdir = _TempDir()
inv = read_inverse_operator(fname_inv)
evoked = read_evokeds(fname_evoked, baseline=(None, 0))[0]
+19 -20
View File
@@ -3,9 +3,9 @@
# License: BSD 3 clause
import warnings
from nose.tools import assert_true, assert_raises
import numpy as np
from numpy.testing import assert_array_equal
import pytest
from mne.time_frequency import morlet
from mne.preprocessing.ctps_ import (ctps, _prob_kuiper,
@@ -31,7 +31,7 @@ rng = np.random.RandomState(42)
def get_data(n_trials, j_extent):
"""Generate ground truth and testing data"""
"""Generate ground truth and testing data."""
ground_truth = np.tile(single_trial, n_trials)
my_shape = n_trials, 1, 600
random_data = rng.random_sample(my_shape)
@@ -42,17 +42,17 @@ def get_data(n_trials, j_extent):
jittered_data.reshape(my_shape),
random_data.reshape(my_shape)], 1)
assert_true(data.shape == (n_trials, 3, 600))
assert data.shape == (n_trials, 3, 600)
return data
# vary extent of jittering --> creates phaselocks at the borders if
# 2 * extent != n_samples
iter_test_ctps = enumerate(zip([400, 400], [150, 300], [0.6, 0.2]))
def test_ctps():
""" Test basic ctps functionality
"""
"""Test basic ctps functionality."""
for ii, (n_trials, j_extent, pk_max) in iter_test_ctps:
data = get_data(n_trials, j_extent)
ks_dyn, pk_dyn, phase_trial = ctps(data)
@@ -61,27 +61,26 @@ def test_ctps():
for a, b in zip([ks_dyn, pk_dyn, phase_trial],
[ks_dyn2, pk_dyn2, data2]):
assert_array_equal(a, b)
assert_true(a.min() >= 0)
assert_true(a.max() <= 1)
assert_true(b.min() >= 0)
assert_true(b.max() <= 1)
assert (a.min() >= 0)
assert (a.max() <= 1)
assert (b.min() >= 0)
assert (b.max() <= 1)
# test for normalization
assert_true((pk_dyn.min() > 0.0) or (pk_dyn.max() < 1.0))
assert ((pk_dyn.min() > 0.0) or (pk_dyn.max() < 1.0))
# test shapes
assert_true(phase_trial.shape == data.shape)
assert_true(pk_dyn.shape == data.shape[1:])
assert (phase_trial.shape == data.shape)
assert (pk_dyn.shape == data.shape[1:])
# tets ground_truth + random + jittered case
assert_true(pk_dyn[0].max() == 1.0)
assert_true(len(np.unique(pk_dyn[0])) == 1.0)
assert_true(pk_dyn[1].max() < pk_max)
assert_true(pk_dyn[2].max() > 0.3)
assert (pk_dyn[0].max() == 1.0)
assert (len(np.unique(pk_dyn[0])) == 1.0)
assert (pk_dyn[1].max() < pk_max)
assert (pk_dyn[2].max() > 0.3)
if ii < 1:
assert_raises(ValueError, ctps,
data[:, :, :, None])
pytest.raises(ValueError, ctps, data[:, :, :, None])
assert_true(_prob_kuiper(1.0, 400) == 1.0)
assert (_prob_kuiper(1.0, 400) == 1.0)
# test vecrosization
assert_array_equal(_prob_kuiper(np.array([1.0, 1.0]), 400),
_prob_kuiper(np.array([1.0, 1.0]), 400))
assert_true(_prob_kuiper(0.1, 400) < 0.1)
assert (_prob_kuiper(0.1, 400) < 0.1)
@@ -18,7 +18,6 @@ base_dir = op.join(op.dirname(__file__), 'data')
def generate_data_for_comparing_against_eeglab_infomax(ch_type, random_state):
"""Generate data."""
data_dir = op.join(testing.data_path(download=False), 'MEG', 'sample')
raw_fname = op.join(data_dir, 'sample_audvis_trunc_raw.fif')
@@ -62,7 +61,7 @@ def generate_data_for_comparing_against_eeglab_infomax(ch_type, random_state):
@pytest.mark.slowtest
@testing.requires_testing_data
def test_mne_python_vs_eeglab():
""" Test eeglab vs mne_python infomax code."""
"""Test eeglab vs mne_python infomax code."""
random_state = 42
methods = ['infomax', 'extended_infomax']
@@ -177,4 +176,5 @@ def test_mne_python_vs_eeglab():
assert_almost_equal(maximum_difference, 1e-12, decimal=10)
run_tests_if_main()
+3 -4
View File
@@ -1,5 +1,4 @@
import os.path as op
from nose.tools import assert_true
from mne import Annotations
from mne.io import read_raw_fif
@@ -16,8 +15,8 @@ def test_find_eog():
raw = read_raw_fif(raw_fname)
raw.annotations = Annotations([14, 21], [1, 1], 'BAD_blink')
events = find_eog_events(raw)
assert_true(len(events) == 4)
assert_true(not all(events[:, 0] < 29000))
assert len(events) == 4
assert not all(events[:, 0] < 29000)
events = find_eog_events(raw, reject_by_annotation=True)
assert_true(all(events[:, 0] < 29000))
assert all(events[:, 0] < 29000)
+4 -4
View File
@@ -9,7 +9,6 @@ from mne.datasets import testing
from mne.preprocessing._fine_cal import (read_fine_calibration,
write_fine_calibration)
from mne.utils import _TempDir, object_hash, run_tests_if_main
from nose.tools import assert_equal
warnings.simplefilter('always') # Always throw warnings
@@ -21,7 +20,7 @@ fine_cal_fname_3d = op.join(data_path, 'SSS', 'sss_cal_3053_3d.dat')
@testing.requires_testing_data
def test_read_write_fine_cal():
"""Test round trip reading/writing of fine calibration .dat file"""
"""Test round trip reading/writing of fine calibration .dat file."""
temp_dir = _TempDir()
temp_fname = op.join(temp_dir, 'fine_cal_temp.dat')
@@ -34,7 +33,8 @@ def test_read_write_fine_cal():
fine_cal_dict_reload = read_fine_calibration(temp_fname)
# Load temp version of fine calibration file and compare hashes
assert_equal(object_hash(fine_cal_dict),
object_hash(fine_cal_dict_reload))
assert (object_hash(fine_cal_dict) ==
object_hash(fine_cal_dict_reload))
run_tests_if_main()
+83 -84
View File
@@ -10,12 +10,10 @@ import os.path as op
import warnings
from unittest import SkipTest
from nose.tools import (assert_true, assert_raises, assert_equal, assert_false,
assert_not_equal, assert_is_none)
import pytest
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_array_equal,
assert_allclose)
assert_allclose, assert_equal)
from scipy import stats
from itertools import product
@@ -70,7 +68,7 @@ except Exception:
def _skip_check_picard(method):
if method == 'picard':
try:
import picard # noqa
import picard # noqa, analysis:ignore
except Exception:
raise SkipTest("Picard is not installed.")
@@ -110,7 +108,7 @@ def test_ica_full_data_recovery(method):
rtol=1e-10, atol=1e-15)
else:
diff = np.abs(data[:n_channels] - raw2._data[:n_channels])
assert_true(np.max(diff) > 1e-14)
assert (np.max(diff) > 1e-14)
ica = ICA(n_components=n_components, method=method,
max_pca_components=n_pca_components,
@@ -124,7 +122,7 @@ def test_ica_full_data_recovery(method):
rtol=1e-10, atol=1e-15)
else:
diff = np.abs(data_epochs[:, :n_channels] - data2)
assert_true(np.max(diff) > 1e-14)
assert (np.max(diff) > 1e-14)
evoked2 = ica.apply(evoked.copy(), exclude=[])
data2 = evoked2.data[:n_channels]
@@ -133,14 +131,14 @@ def test_ica_full_data_recovery(method):
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')
assert (np.max(diff) > 1e-14)
pytest.raises(ValueError, ICA, method='pizza-decomposision')
@requires_sklearn
@pytest.mark.parametrize("method", ["fastica", "picard"])
def test_ica_simple(method):
"""Test that ICA recovers the unmixing matrix in a simple case"""
"""Test that ICA recovers the unmixing matrix in a simple case."""
_skip_check_picard(method)
n_components = 3
n_samples = 1000
@@ -182,8 +180,8 @@ def test_ica_rank_reduction(method):
# interaction between ICA rejection and PCA components difficult
# to preduct. Rank_after often seems to be 1 higher then
# n_pca_components
assert_true(n_components < n_pca_components <= rank_after <=
rank_before)
assert (n_components < n_pca_components <= rank_after <=
rank_before)
@requires_sklearn
@@ -210,11 +208,11 @@ def test_ica_reset(method):
n_components=3, max_pca_components=3, n_pca_components=3,
method=method, max_iter=1).fit(raw, picks=picks)
assert_true(all(hasattr(ica, attr) for attr in run_time_attrs))
assert_not_equal(ica.labels_, None)
assert (all(hasattr(ica, attr) for attr in run_time_attrs))
assert ica.labels_ is not None
ica._reset()
assert_true(not any(hasattr(ica, attr) for attr in run_time_attrs))
assert_not_equal(ica.labels_, None)
assert (not any(hasattr(ica, attr) for attr in run_time_attrs))
assert ica.labels_ is not None
@requires_sklearn
@@ -241,8 +239,8 @@ def test_ica_core(method):
picks_, methods)
# # test init catchers
assert_raises(ValueError, ICA, n_components=3, max_pca_components=2)
assert_raises(ValueError, ICA, n_components=2.3, max_pca_components=2)
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:
@@ -250,19 +248,19 @@ def test_ica_core(method):
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)
assert_raises(ValueError, ica.__contains__, 'mag')
pytest.raises(ValueError, ica.__contains__, 'mag')
print(ica) # to test repr
# test fit checker
assert_raises(RuntimeError, ica.get_sources, raw)
assert_raises(RuntimeError, ica.get_sources, epochs)
pytest.raises(RuntimeError, ica.get_sources, raw)
pytest.raises(RuntimeError, ica.get_sources, epochs)
# test decomposition
with warnings.catch_warnings(record=True): # convergence
ica.fit(raw, picks=pcks, start=start, stop=stop)
repr(ica) # to test repr
assert_true('mag' in ica) # should now work without error
assert ('mag' in ica) # should now work without error
# test re-fit
unmixing1 = ica.unmixing_matrix_
@@ -276,12 +274,12 @@ def test_ica_core(method):
print(raw_sources)
sources = raw_sources[:, :][0]
assert_true(sources.shape[0] == ica.n_components_)
assert (sources.shape[0] == ica.n_components_)
# test preload filter
raw3 = raw.copy()
raw3.preload = False
assert_raises(RuntimeError, ica.apply, raw3,
pytest.raises(RuntimeError, ica.apply, raw3,
include=[1, 2])
#######################################################################
@@ -297,15 +295,15 @@ def test_ica_core(method):
print(ica) # to test repr
sources = ica.get_sources(epochs).get_data()
assert_true(sources.shape[1] == ica.n_components_)
assert (sources.shape[1] == ica.n_components_)
assert_raises(ValueError, ica.score_sources, epochs,
pytest.raises(ValueError, ica.score_sources, epochs,
target=np.arange(1))
# test preload filter
epochs3 = epochs.copy()
epochs3.preload = False
assert_raises(RuntimeError, ica.apply, epochs3,
pytest.raises(RuntimeError, ica.apply, epochs3,
include=[1, 2])
# test for bug with whitener updating
@@ -316,12 +314,12 @@ def test_ica_core(method):
# test expl. var threshold leading to empty sel
ica.n_components = 0.1
assert_raises(RuntimeError, ica.fit, epochs)
pytest.raises(RuntimeError, ica.fit, epochs)
offender = 1, 2, 3,
assert_raises(ValueError, ica.get_sources, offender)
assert_raises(ValueError, ica.fit, offender)
assert_raises(ValueError, ica.apply, offender)
pytest.raises(ValueError, ica.get_sources, offender)
pytest.raises(ValueError, ica.fit, offender)
pytest.raises(ValueError, ica.apply, offender)
@requires_sklearn
@@ -361,15 +359,15 @@ def test_ica_additional(method):
test_cov2 = test_cov.copy()
ica = ICA(noise_cov=test_cov2, n_components=3, max_pca_components=4,
n_pca_components=4, method=method)
assert_true(ica.info is None)
assert (ica.info is None)
with warnings.catch_warnings(record=True):
ica.fit(raw, picks[:5])
assert_true(isinstance(ica.info, Info))
assert_true(ica.n_components_ < 5)
assert (isinstance(ica.info, Info))
assert (ica.n_components_ < 5)
ica = ICA(n_components=3, max_pca_components=4, method=method,
n_pca_components=4, random_state=0)
assert_raises(RuntimeError, ica.save, '')
pytest.raises(RuntimeError, ica.save, '')
with warnings.catch_warnings(record=True):
ica.fit(raw, picks=[1, 2, 3, 4, 5], start=start, stop=stop2)
@@ -378,7 +376,7 @@ def test_ica_additional(method):
with warnings.catch_warnings(record=True): # filter length
_, scores_1 = ica.find_bads_ecg(raw)
_, scores_2 = ica.find_bads_ecg(raw, raw.ch_names[1])
assert_false(scores_1[0] == scores_2[0])
assert scores_1[0] != scores_2[0]
# test corrmap
ica2 = ica.copy()
@@ -386,8 +384,8 @@ def test_ica_additional(method):
corrmap([ica, ica2], (0, 0), threshold='auto', label='blinks', plot=True,
ch_type="mag")
corrmap([ica, ica2], (0, 0), threshold=2, plot=False, show=False)
assert_true(ica.labels_["blinks"] == ica2.labels_["blinks"])
assert_true(0 in ica.labels_["blinks"])
assert (ica.labels_["blinks"] == ica2.labels_["blinks"])
assert (0 in ica.labels_["blinks"])
# test retrieval of component maps as arrays
components = ica.get_components()
template = components[:, 0]
@@ -395,7 +393,7 @@ def test_ica_additional(method):
corrmap([ica, ica3], template, threshold='auto', label='blinks', plot=True,
ch_type="mag")
assert_true(ica2.labels_["blinks"] == ica3.labels_["blinks"])
assert (ica2.labels_["blinks"] == ica3.labels_["blinks"])
plt.close('all')
@@ -416,16 +414,16 @@ def test_ica_additional(method):
n_samples = raw_._data.shape[1]
with warnings.catch_warnings(record=True):
ica.fit(raw, picks=None, decim=3)
assert_true(raw_._data.shape[1], n_samples)
assert raw_._data.shape[1] == n_samples
# test expl var
ica = ICA(n_components=1.0, max_pca_components=4,
n_pca_components=4, method=method, max_iter=1)
with warnings.catch_warnings(record=True):
ica.fit(raw, picks=None, decim=3)
assert_true(ica.n_components_ == 4)
assert (ica.n_components_ == 4)
ica_var = _ica_explained_variance(ica, raw, normalize=True)
assert_true(np.all(ica_var[:-1] >= ica_var[1:]))
assert (np.all(ica_var[:-1] >= ica_var[1:]))
# test ica sorting
ica.exclude = [0]
@@ -435,7 +433,7 @@ def test_ica_additional(method):
assert_equal(ica_sorted.labels_, dict(blink=[3], think=[2]))
# epochs extraction from raw fit
assert_raises(RuntimeError, ica.get_sources, epochs)
pytest.raises(RuntimeError, ica.get_sources, epochs)
# test reading and writing
test_ica_fname = op.join(op.dirname(tempdir), 'test-ica.fif')
for cov in (None, test_cov):
@@ -444,46 +442,46 @@ def test_ica_additional(method):
with warnings.catch_warnings(record=True): # ICA does not converge
ica.fit(raw, picks=picks, start=start, stop=stop2)
sources = ica.get_sources(epochs).get_data()
assert_true(ica.mixing_matrix_.shape == (2, 2))
assert_true(ica.unmixing_matrix_.shape == (2, 2))
assert_true(ica.pca_components_.shape == (4, len(picks)))
assert_true(sources.shape[1] == ica.n_components_)
assert (ica.mixing_matrix_.shape == (2, 2))
assert (ica.unmixing_matrix_.shape == (2, 2))
assert (ica.pca_components_.shape == (4, len(picks)))
assert (sources.shape[1] == ica.n_components_)
for exclude in [[], [0], np.array([1, 2, 3])]:
ica.exclude = exclude
ica.labels_ = {'foo': [0]}
ica.save(test_ica_fname)
ica_read = read_ica(test_ica_fname)
assert_true(list(ica.exclude) == ica_read.exclude)
assert (list(ica.exclude) == ica_read.exclude)
assert_equal(ica.labels_, ica_read.labels_)
ica.apply(raw)
ica.exclude = []
ica.apply(raw, exclude=[1])
assert_true(ica.exclude == [])
assert (ica.exclude == [])
ica.exclude = [0, 1]
ica.apply(raw, exclude=[1])
assert_true(ica.exclude == [0, 1])
assert (ica.exclude == [0, 1])
ica_raw = ica.get_sources(raw)
assert_true(ica.exclude == [ica_raw.ch_names.index(e) for e in
ica_raw.info['bads']])
assert (ica.exclude == [ica_raw.ch_names.index(e) for e in
ica_raw.info['bads']])
# test filtering
d1 = ica_raw._data[0].copy()
ica_raw.filter(4, 20, fir_design='firwin2')
assert_equal(ica_raw.info['lowpass'], 20.)
assert_equal(ica_raw.info['highpass'], 4.)
assert_true((d1 != ica_raw._data[0]).any())
assert ((d1 != ica_raw._data[0]).any())
d1 = ica_raw._data[0].copy()
ica_raw.notch_filter([10], trans_bandwidth=10, fir_design='firwin')
assert_true((d1 != ica_raw._data[0]).any())
assert ((d1 != ica_raw._data[0]).any())
ica.n_pca_components = 2
ica.method = 'fake'
ica.save(test_ica_fname)
ica_read = read_ica(test_ica_fname)
assert_true(ica.n_pca_components == ica_read.n_pca_components)
assert (ica.n_pca_components == ica_read.n_pca_components)
assert_equal(ica.method, ica_read.method)
assert_equal(ica.labels_, ica_read.labels_)
@@ -509,8 +507,8 @@ def test_ica_additional(method):
assert_array_almost_equal(getattr(ica, attr),
getattr(ica_read, attr))
assert_true(ica.ch_names == ica_read.ch_names)
assert_true(isinstance(ica_read.info, Info))
assert (ica.ch_names == ica_read.ch_names)
assert (isinstance(ica_read.info, Info))
sources = ica.get_sources(raw)[:, :][0]
sources2 = ica_read.get_sources(raw)[:, :][0]
@@ -527,12 +525,12 @@ def test_ica_additional(method):
continue
scores = ica.score_sources(raw, target='EOG 061', score_func=func,
start=0, stop=10)
assert_true(ica.n_components_ == len(scores))
assert (ica.n_components_ == len(scores))
# check univariate stats
scores = ica.score_sources(raw, score_func=stats.skew)
# check exception handling
assert_raises(ValueError, ica.score_sources, raw,
pytest.raises(ValueError, ica.score_sources, raw,
target=np.arange(1))
params = []
@@ -559,9 +557,9 @@ def test_ica_additional(method):
idx, scores = ica.find_bads_ecg(epochs, method='ctps')
assert_equal(len(scores), ica.n_components_)
assert_raises(ValueError, ica.find_bads_ecg, epochs.average(),
pytest.raises(ValueError, ica.find_bads_ecg, epochs.average(),
method='ctps')
assert_raises(ValueError, ica.find_bads_ecg, raw,
pytest.raises(ValueError, ica.find_bads_ecg, raw,
method='crazy-coupling')
idx, scores = ica.find_bads_eog(raw)
@@ -569,7 +567,7 @@ def test_ica_additional(method):
raw.info['chs'][raw.ch_names.index('EOG 061') - 1]['kind'] = 202
idx, scores = ica.find_bads_eog(raw)
assert_true(isinstance(scores, list))
assert (isinstance(scores, list))
assert_equal(len(scores[0]), ica.n_components_)
idx, scores = ica.find_bads_eog(evoked, ch_name='MEG 1441')
@@ -588,13 +586,13 @@ def test_ica_additional(method):
continue
scores = ica.score_sources(epochs_eog, target='EOG 061',
score_func=func)
assert_true(ica.n_components_ == len(scores))
assert (ica.n_components_ == len(scores))
# check univariate stats
scores = ica.score_sources(epochs, score_func=stats.skew)
# check exception handling
assert_raises(ValueError, ica.score_sources, epochs,
pytest.raises(ValueError, ica.score_sources, epochs,
target=np.arange(1))
# ecg functionality
@@ -604,7 +602,7 @@ def test_ica_additional(method):
with warnings.catch_warnings(record=True): # filter attenuation warning
ecg_events = ica_find_ecg_events(raw,
sources[np.abs(ecg_scores).argmax()])
assert_true(ecg_events.ndim == 2)
assert (ecg_events.ndim == 2)
# eog functionality
eog_scores = ica.score_sources(raw, target='EOG 061',
@@ -612,14 +610,14 @@ def test_ica_additional(method):
with warnings.catch_warnings(record=True): # filter attenuation warning
eog_events = ica_find_eog_events(raw,
sources[np.abs(eog_scores).argmax()])
assert_true(eog_events.ndim == 2)
assert (eog_events.ndim == 2)
# Test ica fiff export
ica_raw = ica.get_sources(raw, start=0, stop=100)
assert_true(ica_raw.last_samp - ica_raw.first_samp == 100)
assert (ica_raw.last_samp - ica_raw.first_samp == 100)
assert_equal(len(ica_raw._filenames), 1) # API consistency
ica_chans = [ch for ch in ica_raw.ch_names if 'ICA' in ch]
assert_true(ica.n_components_ == len(ica_chans))
assert (ica.n_components_ == len(ica_chans))
test_ica_fname = op.join(op.abspath(op.curdir), 'test-ica_raw.fif')
ica.n_components = np.int32(ica.n_components)
ica_raw.save(test_ica_fname, overwrite=True)
@@ -630,19 +628,19 @@ def test_ica_additional(method):
# Test ica epochs export
ica_epochs = ica.get_sources(epochs)
assert_true(ica_epochs.events.shape == epochs.events.shape)
assert (ica_epochs.events.shape == epochs.events.shape)
ica_chans = [ch for ch in ica_epochs.ch_names if 'ICA' in ch]
assert_true(ica.n_components_ == len(ica_chans))
assert_true(ica.n_components_ == ica_epochs.get_data().shape[1])
assert_true(ica_epochs._raw is None)
assert_true(ica_epochs.preload is True)
assert (ica.n_components_ == len(ica_chans))
assert (ica.n_components_ == ica_epochs.get_data().shape[1])
assert (ica_epochs._raw is None)
assert (ica_epochs.preload is True)
# test float n pca components
ica.pca_explained_variance_ = np.array([0.2] * 5)
ica.n_components_ = 0
for ncomps, expected in [[0.3, 1], [0.9, 4], [1, 1]]:
ncomps_ = ica._check_n_pca_components(ncomps)
assert_true(ncomps_ == expected)
assert (ncomps_ == expected)
ica = ICA(method=method)
with warnings.catch_warnings(record=True) as w: # convergence and filter
@@ -653,8 +651,8 @@ def test_ica_additional(method):
raw.drop_channels(['MEG 0122'])
with warnings.catch_warnings(record=True): # filter length
assert_raises(RuntimeError, ica.find_bads_eog, raw)
assert_raises(RuntimeError, ica.find_bads_ecg, raw)
pytest.raises(RuntimeError, ica.find_bads_eog, raw)
pytest.raises(RuntimeError, ica.find_bads_ecg, raw)
@requires_sklearn
@@ -687,7 +685,7 @@ def test_ica_reject_buffer(method):
with warnings.catch_warnings(record=True):
ica.fit(raw, picks[:5], reject=dict(mag=2.5e-12), decim=2,
tstep=0.01, verbose=True, reject_by_annotation=False)
assert_true(raw._data[:5, ::2].shape[1] - 4 == ica.n_samples_)
assert (raw._data[:5, ::2].shape[1] - 4 == ica.n_samples_)
log = [l for l in drop_log.getvalue().split('\n') if 'detected' in l]
assert_equal(len(log), 1)
@@ -721,7 +719,7 @@ def test_ica_twice(method):
def test_fit_params(method):
"""Test fit_params for ICA."""
_skip_check_picard(method)
assert_raises(ValueError, ICA, fit_params=dict(extended=True))
pytest.raises(ValueError, ICA, fit_params=dict(extended=True))
fit_params = {}
ICA(fit_params=fit_params, method=method) # test no side effects
assert_equal(fit_params, {})
@@ -751,9 +749,9 @@ def test_bad_channels(method):
# Test case for good and bad channels
picks_bad2 = pick_types(inst.info, meg=True,
**{str(ch): True})
assert_raises(ValueError, ica.fit, inst, picks=picks_bad1)
assert_raises(ValueError, ica.fit, inst, picks=picks_bad2)
assert_raises(ValueError, ica.fit, inst, picks=[])
pytest.raises(ValueError, ica.fit, inst, picks=picks_bad1)
pytest.raises(ValueError, ica.fit, inst, picks=picks_bad2)
pytest.raises(ValueError, ica.fit, inst, picks=[])
@requires_sklearn
@@ -777,13 +775,13 @@ def test_eog_channel(method):
eog=True, exclude='bads')
picks1 = np.append(picks1a, picks1b)
ica.fit(inst, picks=picks1)
assert_true(any('EOG' in ch for ch in ica.ch_names))
assert (any('EOG' in ch for ch in ica.ch_names))
# Test case for MEG data. Should have no EOG channel
for inst in [raw, epochs]:
picks1 = pick_types(inst.info, meg=True, stim=False, ecg=False,
eog=False, exclude='bads')[:5]
ica.fit(inst, picks=picks1)
assert_false(any('EOG' in ch for ch in ica.ch_names))
assert not any('EOG' in ch for ch in ica.ch_names)
@requires_sklearn
@@ -845,7 +843,7 @@ def test_n_components_none(method):
# ICA.fit() replaced max_pca_components, which was previously None,
# with the appropriate integer value.
assert_equal(ica.max_pca_components, 10)
assert_is_none(ica.n_components)
assert ica.n_components is None
@requires_sklearn
@@ -876,7 +874,7 @@ def test_n_components_and_max_pca_components_none(method):
# ICA.fit() replaced max_pca_components, which was previously None,
# with the appropriate integer value.
assert_equal(ica.max_pca_components, epochs.info['nchan'])
assert_is_none(ica.n_components)
assert ica.n_components is None
@requires_sklearn
@@ -921,6 +919,7 @@ def test_ica_ctf():
@requires_sklearn
@testing.requires_testing_data
def test_ica_eeg():
"""Test ICA on EEG."""
method = 'fastica'
raw_fif = read_raw_fif(fif_fname, preload=True)
with warnings.catch_warnings(record=True): # events etc.
+3 -7
View File
@@ -2,10 +2,7 @@
#
# License: BSD (3-clause)
"""
Test the infomax algorithm.
Parts of this code are taken from scikit-learn
"""
# Parts of this code are taken from scikit-learn
import numpy as np
from numpy.testing import assert_almost_equal
@@ -18,10 +15,10 @@ from mne.utils import requires_sklearn, run_tests_if_main, check_version
def center_and_norm(x, axis=-1):
"""Centers and norms x **in place**.
"""Center and norm x in place.
Parameters
-----------
----------
x: ndarray
Array with an axis of observations (statistical units) measured on
random variables.
@@ -36,7 +33,6 @@ def center_and_norm(x, axis=-1):
@requires_sklearn
def test_infomax_blowup():
"""Test the infomax algorithm blowup condition."""
# scipy.stats uses the global RNG:
np.random.seed(0)
n_samples = 100
+48 -49
View File
@@ -8,7 +8,6 @@ import numpy as np
from numpy.testing import assert_equal, assert_allclose, assert_array_equal
import pytest
from nose.tools import assert_true, assert_raises
from scipy import sparse
from mne import compute_raw_covariance, pick_types
@@ -112,8 +111,8 @@ def _assert_n_free(raw_sss, lower, upper=None):
"""Check the DOF."""
upper = lower if upper is None else upper
n_free = raw_sss.info['proc_history'][0]['max_info']['sss_info']['nfree']
assert_true(lower <= n_free <= upper,
'nfree fail: %s <= %s <= %s' % (lower, n_free, upper))
assert lower <= n_free <= upper, \
'nfree fail: %s <= %s <= %s' % (lower, n_free, upper)
def read_crop(fname, lims=(0, None)):
@@ -160,7 +159,7 @@ def test_movement_compensation():
st_duration=4., origin=mf_head_origin,
st_fixed=False)
assert_equal(len(w), 1)
assert_true('is untested' in str(w[0].message))
assert ('is untested' in str(w[0].message))
# Neither match is particularly good because our algorithm actually differs
assert_meg_snr(raw_sss_mv, read_crop(sss_movecomp_reg_in_st4s_fname, lims),
0.6, 1.3)
@@ -181,22 +180,22 @@ def test_movement_compensation():
# some degenerate cases
raw_erm = read_crop(erm_fname)
assert_raises(ValueError, maxwell_filter, raw_erm, coord_frame='meg',
pytest.raises(ValueError, maxwell_filter, raw_erm, coord_frame='meg',
head_pos=head_pos) # can't do ERM file
assert_raises(ValueError, maxwell_filter, raw,
pytest.raises(ValueError, maxwell_filter, raw,
head_pos=head_pos[:, :9]) # bad shape
assert_raises(TypeError, maxwell_filter, raw, head_pos='foo') # bad type
assert_raises(ValueError, maxwell_filter, raw, head_pos=head_pos[::-1])
pytest.raises(TypeError, maxwell_filter, raw, head_pos='foo') # bad type
pytest.raises(ValueError, maxwell_filter, raw, head_pos=head_pos[::-1])
head_pos_bad = head_pos.copy()
head_pos_bad[0, 0] = raw.first_samp / raw.info['sfreq'] - 1e-2
assert_raises(ValueError, maxwell_filter, raw, head_pos=head_pos_bad)
pytest.raises(ValueError, maxwell_filter, raw, head_pos=head_pos_bad)
head_pos_bad = head_pos.copy()
head_pos_bad[0, 4] = 1. # off by more than 1 m
with warnings.catch_warnings(record=True) as w:
maxwell_filter(raw.copy().crop(0, 0.1), head_pos=head_pos_bad,
bad_condition='ignore')
assert_true(any('greater than 1 m' in str(ww.message) for ww in w))
assert (any('greater than 1 m' in str(ww.message) for ww in w))
# make sure numerical error doesn't screw it up, though
head_pos_bad = head_pos.copy()
@@ -218,7 +217,7 @@ def test_other_systems():
hsp_path = op.join(kit_dir, 'test_hsp.txt')
raw_kit = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path)
with warnings.catch_warnings(record=True): # head fit
assert_raises(RuntimeError, maxwell_filter, raw_kit)
pytest.raises(RuntimeError, maxwell_filter, raw_kit)
with catch_logging() as log:
raw_sss = maxwell_filter(raw_kit, origin=(0., 0., 0.04),
ignore_ref=True, verbose=True)
@@ -231,7 +230,7 @@ def test_other_systems():
# corrected HSP file with proper coverage
with warnings.catch_warnings(record=True):
with catch_logging() as log:
assert_raises(RuntimeError, maxwell_filter, raw_kit,
pytest.raises(RuntimeError, maxwell_filter, raw_kit,
ignore_ref=True, regularize=None) # bad condition
raw_sss = maxwell_filter(raw_kit, origin='auto',
ignore_ref=True, bad_condition='warning',
@@ -279,9 +278,9 @@ def test_other_systems():
# CTF
raw_ctf = read_crop(fname_ctf_raw)
assert_equal(raw_ctf.compensation_grade, 3)
assert_raises(RuntimeError, maxwell_filter, raw_ctf) # compensated
pytest.raises(RuntimeError, maxwell_filter, raw_ctf) # compensated
raw_ctf.apply_gradient_compensation(0)
assert_raises(ValueError, maxwell_filter, raw_ctf) # cannot fit headshape
pytest.raises(ValueError, maxwell_filter, raw_ctf) # cannot fit headshape
raw_sss = maxwell_filter(raw_ctf, origin=(0., 0., 0.04))
_assert_n_free(raw_sss, 68)
_assert_shielding(raw_sss, raw_ctf, 1.8)
@@ -385,9 +384,9 @@ def test_basic():
raw = read_crop(raw_fname, (0., 1.))
raw_err = read_crop(raw_fname).apply_proj()
raw_erm = read_crop(erm_fname)
assert_raises(RuntimeError, maxwell_filter, raw_err)
assert_raises(TypeError, maxwell_filter, 1.) # not a raw
assert_raises(ValueError, maxwell_filter, raw, int_order=20) # too many
pytest.raises(RuntimeError, maxwell_filter, raw_err)
pytest.raises(TypeError, maxwell_filter, 1.) # not a raw
pytest.raises(ValueError, maxwell_filter, raw, int_order=20) # too many
n_int_bases = int_order ** 2 + 2 * int_order
n_ext_bases = ext_order ** 2 + 2 * ext_order
@@ -409,7 +408,7 @@ def test_basic():
assert_equal(len(py_ctc), 0)
py_st = raw_sss.info['proc_history'][0]['max_info']['max_st']
assert_equal(len(py_st), 0)
assert_raises(RuntimeError, maxwell_filter, raw_sss)
pytest.raises(RuntimeError, maxwell_filter, raw_sss)
# Test SSS computation at non-standard head origin
raw_sss = maxwell_filter(raw, origin=[0., 0.02, 0.02], regularize=None,
@@ -441,10 +440,10 @@ def test_basic():
proc_history._get_sss_rank(sss_info))
# Degenerate cases
assert_raises(ValueError, maxwell_filter, raw, coord_frame='foo')
assert_raises(ValueError, maxwell_filter, raw, origin='foo')
assert_raises(ValueError, maxwell_filter, raw, origin=[0] * 4)
assert_raises(ValueError, maxwell_filter, raw, mag_scale='foo')
pytest.raises(ValueError, maxwell_filter, raw, coord_frame='foo')
pytest.raises(ValueError, maxwell_filter, raw, origin='foo')
pytest.raises(ValueError, maxwell_filter, raw, origin=[0] * 4)
pytest.raises(ValueError, maxwell_filter, raw, mag_scale='foo')
raw_missing = raw.copy().load_data()
raw_missing.info['bads'] = ['MEG0111']
raw_missing.pick_types(meg=True) # will be missing the bad
@@ -452,13 +451,12 @@ def test_basic():
with warnings.catch_warnings(record=True) as w:
maxwell_filter(raw_missing, calibration=fine_cal_fname)
assert_equal(len(w), 1)
assert_true('not in data' in str(w[0].message))
assert ('not in data' in str(w[0].message))
@testing.requires_testing_data
def test_maxwell_filter_additional():
"""Test processing of Maxwell filtered data."""
# TODO: Future tests integrate with mne/io/tests/test_proc_history
# Load testing data (raw, SSS std origin, SSS non-standard origin)
@@ -521,7 +519,7 @@ def test_spatiotemporal():
raw = read_crop(raw_fname)
# Test that window is less than length of data
assert_raises(ValueError, maxwell_filter, raw, st_duration=1000.)
pytest.raises(ValueError, maxwell_filter, raw, st_duration=1000.)
# We could check both 4 and 10 seconds because Elekta handles them
# differently (to ensure that std/non-std tSSS windows are correctly
@@ -549,12 +547,12 @@ def test_spatiotemporal():
assert_equal(raw_tsss.estimate_rank(), 140)
assert_meg_snr(raw_tsss, tsss_bench, tol)
py_st = raw_tsss.info['proc_history'][0]['max_info']['max_st']
assert_true(len(py_st) > 0)
assert (len(py_st) > 0)
assert_equal(py_st['buflen'], st_duration)
assert_equal(py_st['subspcorr'], 0.98)
# Degenerate cases
assert_raises(ValueError, maxwell_filter, raw, st_duration=10.,
pytest.raises(ValueError, maxwell_filter, raw, st_duration=10.,
st_correlation=0.)
@@ -591,7 +589,7 @@ def test_spatiotemporal_only():
st_only=True)
assert_allclose(raw[:][0], raw_tsss[:][0])
# degenerate
assert_raises(ValueError, maxwell_filter, raw, st_only=True) # no ST
pytest.raises(ValueError, maxwell_filter, raw, st_only=True) # no ST
# two-step process equivalent to single-step process
raw_tsss = maxwell_filter(raw, st_duration=tmax, st_only=True)
raw_tsss = maxwell_filter(raw_tsss)
@@ -615,7 +613,6 @@ def test_spatiotemporal_only():
@testing.requires_testing_data
def test_fine_calibration():
"""Test Maxwell filter fine calibration."""
# Load testing data (raw, SSS std origin, SSS non-standard origin)
raw = read_crop(raw_fname, (0., 1.))
sss_fine_cal = read_crop(sss_fine_cal_fname)
@@ -626,8 +623,8 @@ def test_fine_calibration():
bad_condition='ignore')
assert_meg_snr(raw_sss, sss_fine_cal, 82, 611)
py_cal = raw_sss.info['proc_history'][0]['max_info']['sss_cal']
assert_true(py_cal is not None)
assert_true(len(py_cal) > 0)
assert (py_cal is not None)
assert (len(py_cal) > 0)
mf_cal = sss_fine_cal.info['proc_history'][0]['max_info']['sss_cal']
# we identify these differently
mf_cal['cal_chans'][mf_cal['cal_chans'][:, 1] == 3022, 1] = 3024
@@ -656,7 +653,7 @@ def test_fine_calibration():
bad_condition='ignore')
assert_meg_snr(raw_sss_3D, sss_fine_cal, 1.0, 6.)
raw_ctf = read_crop(fname_ctf_raw).apply_gradient_compensation(0)
assert_raises(RuntimeError, maxwell_filter, raw_ctf, origin=(0., 0., 0.04),
pytest.raises(RuntimeError, maxwell_filter, raw_ctf, origin=(0., 0., 0.04),
calibration=fine_cal_fname)
@@ -687,10 +684,10 @@ def test_regularization():
def _check_reg_match(sss_py, sss_mf, comp_tol):
"""Helper to check regularization."""
"""Check regularization."""
info_py = sss_py.info['proc_history'][0]['max_info']['sss_info']
assert_true(info_py is not None)
assert_true(len(info_py) > 0)
assert (info_py is not None)
assert (len(info_py) > 0)
info_mf = sss_mf.info['proc_history'][0]['max_info']['sss_info']
n_in = None
for inf in (info_py, info_mf):
@@ -714,9 +711,9 @@ def test_cross_talk():
bad_condition='ignore')
assert_meg_snr(raw_sss, sss_ctc, 275.)
py_ctc = raw_sss.info['proc_history'][0]['max_info']['sss_ctc']
assert_true(len(py_ctc) > 0)
assert_raises(ValueError, maxwell_filter, raw, cross_talk=raw)
assert_raises(ValueError, maxwell_filter, raw, cross_talk=raw_fname)
assert (len(py_ctc) > 0)
pytest.raises(ValueError, maxwell_filter, raw, cross_talk=raw)
pytest.raises(ValueError, maxwell_filter, raw, cross_talk=raw_fname)
mf_ctc = sss_ctc.info['proc_history'][0]['max_info']['sss_ctc']
del mf_ctc['block_id'] # we don't write this
assert isinstance(py_ctc['decoupler'], sparse.csc_matrix)
@@ -734,7 +731,7 @@ def test_cross_talk():
mf_ctc['decoupler'].toarray())
assert_equal(object_diff(py_ctc, mf_ctc), '')
raw_ctf = read_crop(fname_ctf_raw).apply_gradient_compensation(0)
assert_raises(ValueError, maxwell_filter, raw_ctf) # cannot fit headshape
pytest.raises(ValueError, maxwell_filter, raw_ctf) # cannot fit headshape
raw_sss = maxwell_filter(raw_ctf, origin=(0., 0., 0.04))
_assert_n_free(raw_sss, 68)
raw_sss = maxwell_filter(raw_ctf, origin=(0., 0., 0.04), ignore_ref=True)
@@ -745,9 +742,9 @@ def test_cross_talk():
with warnings.catch_warnings(record=True) as w:
maxwell_filter(raw_missing, cross_talk=ctc_fname)
assert_equal(len(w), 1)
assert_true('Not all cross-talk channels in raw' in str(w[0].message))
assert ('Not all cross-talk channels in raw' in str(w[0].message))
# MEG channels not in cross-talk
assert_raises(RuntimeError, maxwell_filter, raw_ctf, origin=(0., 0., 0.04),
pytest.raises(RuntimeError, maxwell_filter, raw_ctf, origin=(0., 0., 0.04),
cross_talk=ctc_fname)
@@ -766,7 +763,7 @@ def test_head_translation():
raw_sss = maxwell_filter(raw, destination=mf_head_origin,
origin=mf_head_origin, regularize=None,
bad_condition='ignore', verbose='warning')
assert_true('over 25 mm' in log.getvalue())
assert ('over 25 mm' in log.getvalue())
assert_meg_snr(raw_sss, read_crop(sss_trans_default_fname), 125.)
destination = np.eye(4)
destination[2, 3] = 0.04
@@ -777,14 +774,14 @@ def test_head_translation():
raw_sss = maxwell_filter(raw, destination=sample_fname,
origin=mf_head_origin, regularize=None,
bad_condition='ignore', verbose='warning')
assert_true('= 25.6 mm' in log.getvalue())
assert ('= 25.6 mm' in log.getvalue())
assert_meg_snr(raw_sss, read_crop(sss_trans_sample_fname), 350.)
assert_allclose(raw_sss.info['dev_head_t']['trans'],
read_info(sample_fname)['dev_head_t']['trans'])
# Degenerate cases
assert_raises(RuntimeError, maxwell_filter, raw,
pytest.raises(RuntimeError, maxwell_filter, raw,
destination=mf_head_origin, coord_frame='meg')
assert_raises(ValueError, maxwell_filter, raw, destination=[0.] * 4)
pytest.raises(ValueError, maxwell_filter, raw, destination=[0.] * 4)
# TODO: Eventually add simulation tests mirroring Taulu's original paper
@@ -792,7 +789,7 @@ def test_head_translation():
# http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=1495874
def _assert_shielding(raw_sss, erm_power, shielding_factor, meg='mag'):
"""Helper to assert a minimum shielding factor using empty-room power."""
"""Assert a minimum shielding factor using empty-room power."""
picks = pick_types(raw_sss.info, meg=meg, ref_meg=False)
if isinstance(erm_power, BaseRaw):
picks_erm = pick_types(raw_sss.info, meg=meg, ref_meg=False)
@@ -801,8 +798,8 @@ def _assert_shielding(raw_sss, erm_power, shielding_factor, meg='mag'):
sss_power = raw_sss[picks][0].ravel()
sss_power = np.sqrt(np.sum(sss_power * sss_power))
factor = erm_power / sss_power
assert_true(factor >= shielding_factor,
'Shielding factor %0.3f < %0.3f' % (factor, shielding_factor))
assert factor >= shielding_factor, \
'Shielding factor %0.3f < %0.3f' % (factor, shielding_factor)
@buggy_mkl_svd
@@ -1002,9 +999,11 @@ def test_triux():
@testing.requires_testing_data
def test_MGH_cross_talk():
"""Test cross-talk."""
raw = read_crop(raw_fname, (0., 1.))
raw_sss = maxwell_filter(raw, cross_talk=ctc_mgh_fname)
py_ctc = raw_sss.info['proc_history'][0]['max_info']['sss_ctc']
assert_true(len(py_ctc) > 0)
assert (len(py_ctc) > 0)
run_tests_if_main()
+7 -5
View File
@@ -1,12 +1,13 @@
from numpy.testing import assert_array_equal, assert_raises, assert_equal
from numpy.testing import assert_array_equal, assert_equal
import pytest
import numpy as np
from mne.utils import run_tests_if_main
from mne.preprocessing.peak_finder import peak_finder
def test_peak_finder():
"""Test the peak detection method"""
"""Test the peak detection method."""
# check for random data
rng = np.random.RandomState(42)
peak_inds, peak_mags = peak_finder(rng.randn(20))
@@ -15,11 +16,11 @@ def test_peak_finder():
assert_equal(peak_mags.dtype, np.dtype('float64'))
# check for empty array as created in the #5025
with assert_raises(ValueError):
with pytest.raises(ValueError):
peak_finder(np.arange(2, 1, 0.05))
# check for empty array
with assert_raises(ValueError):
with pytest.raises(ValueError):
peak_finder([])
# check for monotonic function
@@ -38,4 +39,5 @@ def test_peak_finder():
peak_inds, peak_mags = peak_finder([0, 2, 5, 0, 6, -1])
assert_array_equal(peak_inds, [2, 4])
run_tests_if_main()
+10 -11
View File
@@ -1,8 +1,7 @@
import os.path as op
import warnings
from nose.tools import assert_true, assert_equal
from numpy.testing import assert_array_almost_equal
from numpy.testing import assert_array_almost_equal, assert_equal
import numpy as np
from mne.io import read_raw_fif, read_raw_ctf
@@ -36,8 +35,8 @@ def test_compute_proj_ecg():
qrs_threshold=0.5, filter_length=6000)
assert len(projs) == 7
# heart rate at least 0.5 Hz, but less than 3 Hz
assert_true(events.shape[0] > 0.5 * dur_use and
events.shape[0] < 3 * dur_use)
assert (events.shape[0] > 0.5 * dur_use and
events.shape[0] < 3 * dur_use)
ssp_ecg = [proj for proj in projs if proj['desc'].startswith('ECG')]
# check that the first principal component have a certain minimum
ssp_ecg = [proj for proj in ssp_ecg if 'PCA-01' in proj['desc']]
@@ -75,20 +74,20 @@ def test_compute_proj_eog():
l_freq=None, h_freq=None,
reject=None, tmax=dur_use,
filter_length=6000)
assert_true(len(projs) == (7 + n_projs_init))
assert_true(np.abs(events.shape[0] -
np.sum(np.less(eog_times, dur_use))) <= 1)
assert (len(projs) == (7 + n_projs_init))
assert (np.abs(events.shape[0] -
np.sum(np.less(eog_times, dur_use))) <= 1)
ssp_eog = [proj for proj in projs if proj['desc'].startswith('EOG')]
# check that the first principal component have a certain minimum
ssp_eog = [proj for proj in ssp_eog if 'PCA-01' in proj['desc']]
thresh_eeg, thresh_axial, thresh_planar = .9, .3, .1
for proj in ssp_eog:
if 'planar' in proj['desc']:
assert_true(proj['explained_var'] > thresh_planar)
assert (proj['explained_var'] > thresh_planar)
elif 'axial' in proj['desc']:
assert_true(proj['explained_var'] > thresh_axial)
assert (proj['explained_var'] > thresh_axial)
elif 'eeg' in proj['desc']:
assert_true(proj['explained_var'] > thresh_eeg)
assert (proj['explained_var'] > thresh_eeg)
# XXX: better tests
# This will throw a warning b/c simplefilter('always')
@@ -99,7 +98,7 @@ def test_compute_proj_eog():
avg_ref=True, no_proj=False,
l_freq=None, h_freq=None,
tmax=dur_use)
assert_true(len(w) >= 1)
assert (len(w) >= 1)
assert_equal(projs, None)
+8 -7
View File
@@ -6,7 +6,7 @@ import os.path as op
import numpy as np
from numpy.testing import assert_array_almost_equal
from nose.tools import assert_true, assert_raises
import pytest
from mne.io import read_raw_fif
from mne.io.pick import pick_types
@@ -24,7 +24,7 @@ def test_fix_stim_artifact():
events = read_events(event_fname)
raw = read_raw_fif(raw_fname)
assert_raises(RuntimeError, fix_stim_artifact, raw)
pytest.raises(RuntimeError, fix_stim_artifact, raw)
raw = read_raw_fif(raw_fname, preload=True)
@@ -47,7 +47,8 @@ def test_fix_stim_artifact():
epochs = fix_stim_artifact(epochs, tmin=tmin, tmax=tmax, mode='window')
data_from_epochs_fix = epochs.get_data()[:, :, tmin_samp:tmax_samp]
assert_true(np.all(data_from_epochs_fix) == 0.)
# XXX This is a very weird check...
assert np.all(data_from_epochs_fix) == 0.
# use window before stimulus in raw
event_idx = np.where(events[:, 2] == 1)[0][0]
@@ -56,7 +57,7 @@ def test_fix_stim_artifact():
tmax_samp = int(-0.015 * raw.info['sfreq'])
tidx = int(events[event_idx, 0] - raw.first_samp)
assert_raises(ValueError, fix_stim_artifact, raw, events=np.array([]))
pytest.raises(ValueError, fix_stim_artifact, raw, events=np.array([]))
raw = fix_stim_artifact(raw, events=None, event_id=1, tmin=tmin,
tmax=tmax, mode='linear', stim_channel='STI 014')
data, times = raw[:, (tidx + tmin_samp):(tidx + tmax_samp)]
@@ -67,7 +68,7 @@ def test_fix_stim_artifact():
raw = fix_stim_artifact(raw, events, event_id=1, tmin=tmin,
tmax=tmax, mode='window')
data, times = raw[:, (tidx + tmin_samp):(tidx + tmax_samp)]
assert_true(np.all(data) == 0.)
assert np.all(data) == 0.
# get epochs from raw with fixed data
tmin, tmax, event_id = -0.2, 0.5, 1
@@ -77,7 +78,7 @@ def test_fix_stim_artifact():
tmin_samp = int(-0.035 * epochs.info['sfreq']) - e_start
tmax_samp = int(-0.015 * epochs.info['sfreq']) - e_start
data_from_raw_fix = epochs.get_data()[:, :, tmin_samp:tmax_samp]
assert_true(np.all(data_from_raw_fix) == 0.)
assert np.all(data_from_raw_fix) == 0.
# use window after stimulus
evoked = epochs.average()
@@ -93,4 +94,4 @@ def test_fix_stim_artifact():
evoked = fix_stim_artifact(evoked, tmin=tmin, tmax=tmax, mode='window')
data = evoked.data[:, tmin_samp:tmax_samp]
assert_true(np.all(data) == 0.)
assert np.all(data) == 0.
+3 -3
View File
@@ -36,7 +36,7 @@ warnings.simplefilter('always') # enable b/c these tests throw warnings
@pytest.fixture
def free_tcp_port():
"""Returns a free TCP port"""
"""Get a free TCP port."""
with contextlib.closing(socket.socket()) as free_socket:
free_socket.bind(('127.0.0.1', 0))
return free_socket.getsockname()[1]
@@ -75,6 +75,7 @@ def _start_buffer_thread(buffer_port):
@pytest.mark.slowtest
@requires_neuromag2ft
def test_fieldtrip_rtepochs(free_tcp_port, tmpdir):
"""Test FieldTrip RtEpochs."""
raw_tmax = 7
raw = read_raw_fif(raw_fname, preload=True)
raw.crop(tmin=0, tmax=raw_tmax)
@@ -130,8 +131,7 @@ def test_fieldtrip_rtepochs(free_tcp_port, tmpdir):
@requires_neuromag2ft
def test_fieldtrip_client(free_tcp_port):
"""Test fieldtrip_client"""
"""Test fieldtrip_client."""
kill_signal = _start_buffer_thread(free_tcp_port)
time.sleep(0.5)
+2 -4
View File
@@ -78,7 +78,6 @@ def _call_base_epochs_public_api(epochs, tmpdir):
def test_mockclient(tmpdir):
"""Test the RtMockClient."""
raw = read_raw_fif(raw_fname, preload=True, verbose=False)
picks = pick_types(raw.info, meg='grad', eeg=False, eog=True,
stim=True, exclude=raw.info['bads'])
@@ -125,7 +124,6 @@ def test_mockclient(tmpdir):
def test_get_event_data():
"""Test emulation of realtime data stream."""
raw = read_raw_fif(raw_fname, preload=True, verbose=False)
picks = pick_types(raw.info, meg='grad', eeg=False, eog=True,
stim=True, exclude=raw.info['bads'])
@@ -147,7 +145,6 @@ def test_get_event_data():
def test_find_events():
"""Test find_events in rt_epochs."""
raw = read_raw_fif(raw_fname, preload=True, verbose=False)
picks = pick_types(raw.info, meg='grad', eeg=False, eog=True,
stim=True, exclude=raw.info['bads'])
@@ -268,6 +265,7 @@ def test_find_events():
@pytest.mark.parametrize("buffer_size", [420, 1000, 6000])
def test_rejection(buffer_size):
"""Test rejection."""
event_id, tmin, tmax = 1, 0.0, 0.5
sfreq = 1000
ch_names = ['Fz', 'Cz', 'Pz', 'STI 014']
@@ -324,7 +322,7 @@ def test_rejection(buffer_size):
@sample.requires_sample_data
def test_events_sampledata():
""" based on examples/realtime/plot_compute_rt_decoder.py"""
"""Test events."""
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
raw = read_raw_fif(raw_fname, preload=True)
+8 -10
View File
@@ -1,7 +1,7 @@
import threading
import time
from nose.tools import assert_equal, assert_raises, assert_true
import pytest
from mne.realtime import StimServer, StimClient
from mne.externals.six.moves import queue
from mne.utils import requires_good_network, run_tests_if_main
@@ -14,8 +14,7 @@ _max_wait = 10.
@requires_good_network
def test_connection():
"""Test TCP/IP connection for StimServer <-> StimClient.
"""
"""Test TCP/IP connection for StimServer <-> StimClient."""
global _server, _have_put_in_trigger
# have to start a thread to simulate the effect of two
@@ -48,25 +47,24 @@ def test_connection():
# Hence communication between threads is necessary
trig1 = trig_queue1.get(timeout=_max_wait)
trig2 = trig_queue2.get(timeout=_max_wait)
assert_equal(trig1, 20)
assert trig1 == 20
# test if both clients receive the same trigger
assert_equal(trig1, trig2)
assert trig1 == trig2
# test timeout for stim_server
with StimServer(port=4218) as stim_server:
assert_raises(StopIteration, stim_server.start, 0.1)
pytest.raises(StopIteration, stim_server.start, 0.1)
def _connect_client(trig_queue):
"""Helper method that instantiates the StimClient.
"""
"""Instantiate the StimClient."""
# just wait till the main thread reaches stim_server.start()
t0 = time.time()
while (time.time() - t0 < _max_wait and
(_server is None or not _server._running)):
time.sleep(0.01)
assert_true(_server is not None and _server._running)
assert _server is not None and _server._running
# instantiate StimClient
stim_client = StimClient('localhost', port=4218)
@@ -75,7 +73,7 @@ def _connect_client(trig_queue):
t0 = time.time()
while (time.time() - t0 < _max_wait and not _have_put_in_trigger):
time.sleep(0.01)
assert_true(_have_put_in_trigger)
assert _have_put_in_trigger
trig_queue.put(stim_client.get_trigger())
stim_client.close()
+4 -5
View File
@@ -7,7 +7,7 @@ import os.path as op
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_array_equal,
assert_equal)
from nose.tools import assert_true, assert_raises
import pytest
import warnings
from mne import (read_cov, read_forward_solution, convert_forward_solution,
@@ -34,7 +34,6 @@ cov_fname = op.join(op.dirname(__file__), '..', '..', 'io', 'tests',
@testing.requires_testing_data
def test_simulate_evoked():
"""Test simulation of evoked data."""
raw = read_raw_fif(raw_fname)
fwd = read_forward_solution(fwd_fname)
fwd = convert_forward_solution(fwd, force_fixed=True, use_cps=False)
@@ -62,7 +61,7 @@ def test_simulate_evoked():
evoked = simulate_evoked(fwd, stc, evoked_template.info, cov,
iir_filter=iir_filter, nave=nave)
assert_array_almost_equal(evoked.times, stc.times)
assert_true(len(evoked.data) == len(fwd['sol']['data']))
assert len(evoked.data) == len(fwd['sol']['data'])
assert_equal(evoked.nave, nave)
# make a vertex that doesn't exist in fwd, should throw error
@@ -70,7 +69,7 @@ def test_simulate_evoked():
mv = np.max(fwd['src'][0]['vertno'][fwd['src'][0]['inuse']])
stc_bad.vertices[0][0] = mv + 1
assert_raises(RuntimeError, simulate_evoked, fwd, stc_bad,
pytest.raises(RuntimeError, simulate_evoked, fwd, stc_bad,
evoked_template.info, cov)
evoked_1 = simulate_evoked(fwd, stc, evoked_template.info, cov,
nave=np.inf)
@@ -79,7 +78,7 @@ def test_simulate_evoked():
assert_array_equal(evoked_1.data, evoked_2.data)
cov['names'] = cov.ch_names[:-2] # Error channels are different.
assert_raises(ValueError, simulate_evoked, fwd, stc, evoked_template.info,
pytest.raises(ValueError, simulate_evoked, fwd, stc, evoked_template.info,
cov, nave=nave, iir_filter=None)
+8 -7
View File
@@ -8,7 +8,7 @@ import os.path as op
import numpy as np
from numpy.testing import assert_almost_equal
from nose.tools import assert_true, assert_raises
import pytest
import warnings
from mne import read_source_spaces
@@ -25,7 +25,7 @@ src_fname = op.join(data_path, 'subjects', 'sample', 'bem',
@testing.requires_testing_data
def test_metrics():
"""Test simulation metrics"""
"""Test simulation metrics."""
src = read_source_spaces(src_fname)
times = np.arange(600) / 1000.
rng = np.random.RandomState(42)
@@ -37,16 +37,17 @@ def test_metrics():
E2_cos = source_estimate_quantification(stc2, stc2, metric='cosine')
# ### Tests to add
assert_true(E1_rms == 0.)
assert_true(E2_rms == 0.)
assert (E1_rms == 0.)
assert (E2_rms == 0.)
assert_almost_equal(E1_cos, 0.)
assert_almost_equal(E2_cos, 0.)
stc_bad = stc2.copy().crop(0, 0.5)
assert_raises(ValueError, source_estimate_quantification, stc1, stc_bad)
pytest.raises(ValueError, source_estimate_quantification, stc1, stc_bad)
stc_bad = stc2.copy()
stc_bad.tmin -= 0.1
assert_raises(ValueError, source_estimate_quantification, stc1, stc_bad)
assert_raises(ValueError, source_estimate_quantification, stc1, stc2,
pytest.raises(ValueError, source_estimate_quantification, stc1, stc_bad)
pytest.raises(ValueError, source_estimate_quantification, stc1, stc2,
metric='foo')
run_tests_if_main()
+2 -2
View File
@@ -47,7 +47,7 @@ pos_fname = op.join(data_path, 'SSS', 'test_move_anon_raw_subsampled.pos')
def _make_stc(raw, src):
"""Helper to make a STC."""
"""Make a STC."""
seed = 42
sfreq = raw.info['sfreq'] # Hz
tstep = 1. / sfreq
@@ -58,7 +58,7 @@ def _make_stc(raw, src):
def _get_data():
"""Helper to get some starting data."""
"""Get some starting data."""
# raw with ECG channel
raw = read_raw_fif(raw_fname).crop(0., 5.0).load_data()
data_picks = pick_types(raw.info, meg=True, eeg=True)
+23 -20
View File
@@ -1,8 +1,9 @@
import os.path as op
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_array_equal
from nose.tools import assert_true, assert_raises, assert_equal
from numpy.testing import (assert_array_almost_equal, assert_array_equal,
assert_equal)
import pytest
from mne.datasets import testing
from mne import (read_label, read_forward_solution, pick_types_forward,
@@ -22,6 +23,7 @@ subjects_dir = op.join(data_path, 'subjects')
def read_forward_solution_meg(*args, **kwargs):
"""Read forward MEG."""
fwd = read_forward_solution(*args)
fwd = convert_forward_solution(fwd, **kwargs)
fwd = pick_types_forward(fwd, meg=True, eeg=False)
@@ -30,7 +32,7 @@ def read_forward_solution_meg(*args, **kwargs):
@testing.requires_testing_data
def test_simulate_stc():
""" Test generation of source estimate """
"""Test generation of source estimate."""
fwd = read_forward_solution_meg(fname_fwd, force_fixed=True, use_cps=True)
labels = [read_label(op.join(data_path, 'MEG', 'sample', 'labels',
'%s.label' % label)) for label in label_names]
@@ -63,8 +65,8 @@ def test_simulate_stc():
if hemi_idx == 1:
idx += len(stc.vertices[0])
assert_true(np.all(stc.data[idx] == 1.0))
assert_true(stc.data[idx].shape[1] == n_times)
assert (np.all(stc.data[idx] == 1.0))
assert (stc.data[idx].shape[1] == n_times)
# test with function
def fun(x):
@@ -92,15 +94,15 @@ def test_simulate_stc():
label_subset = mylabels[:2]
data_subset = stc_data[:2]
stc = simulate_stc(fwd['src'], label_subset, data_subset, tmin, tstep, fun)
assert_raises(ValueError, simulate_stc, fwd['src'],
pytest.raises(ValueError, simulate_stc, fwd['src'],
label_subset, data_subset[:-1], tmin, tstep, fun)
assert_raises(RuntimeError, simulate_stc, fwd['src'], label_subset * 2,
pytest.raises(RuntimeError, simulate_stc, fwd['src'], label_subset * 2,
np.concatenate([data_subset] * 2, axis=0), tmin, tstep, fun)
@testing.requires_testing_data
def test_simulate_sparse_stc():
""" Test generation of sparse source estimate """
"""Test generation of sparse source estimate."""
fwd = read_forward_solution_meg(fname_fwd, force_fixed=True, use_cps=True)
labels = [read_label(op.join(data_path, 'MEG', 'sample', 'labels',
'%s.label' % label)) for label in label_names]
@@ -110,7 +112,7 @@ def test_simulate_sparse_stc():
tstep = 1e-3
times = np.arange(n_times, dtype=np.float) * tstep + tmin
assert_raises(ValueError, simulate_sparse_stc, fwd['src'], len(labels),
pytest.raises(ValueError, simulate_sparse_stc, fwd['src'], len(labels),
times, labels=labels, location='center', subject='sample',
subjects_dir=subjects_dir) # no non-zero values
for label in labels:
@@ -123,8 +125,8 @@ def test_simulate_sparse_stc():
subjects_dir=subjects_dir)
assert_equal(stc_1.subject, 'sample')
assert_true(stc_1.data.shape[0] == len(labels))
assert_true(stc_1.data.shape[1] == n_times)
assert (stc_1.data.shape[0] == len(labels))
assert (stc_1.data.shape[1] == n_times)
# make sure we get the same result when using the same seed
stc_2 = simulate_sparse_stc(fwd['src'], len(labels), times,
@@ -135,20 +137,20 @@ def test_simulate_sparse_stc():
assert_array_equal(stc_1.lh_vertno, stc_2.lh_vertno)
assert_array_equal(stc_1.rh_vertno, stc_2.rh_vertno)
# Degenerate cases
assert_raises(ValueError, simulate_sparse_stc, fwd['src'], len(labels),
pytest.raises(ValueError, simulate_sparse_stc, fwd['src'], len(labels),
times, labels=labels, location='center', subject='foo',
subjects_dir=subjects_dir) # wrong subject
del fwd['src'][0]['subject_his_id']
assert_raises(ValueError, simulate_sparse_stc, fwd['src'], len(labels),
pytest.raises(ValueError, simulate_sparse_stc, fwd['src'], len(labels),
times, labels=labels, location='center',
subjects_dir=subjects_dir) # no subject
assert_raises(ValueError, simulate_sparse_stc, fwd['src'], len(labels),
pytest.raises(ValueError, simulate_sparse_stc, fwd['src'], len(labels),
times, labels=labels, location='foo') # bad location
@testing.requires_testing_data
def test_generate_stc_single_hemi():
""" Test generation of source estimate, single hemi """
"""Test generation of source estimate, single hemi."""
fwd = read_forward_solution_meg(fname_fwd, force_fixed=True, use_cps=True)
labels_single_hemi = [read_label(op.join(data_path, 'MEG', 'sample',
'labels', '%s.label' % label))
@@ -181,8 +183,8 @@ def test_generate_stc_single_hemi():
if hemi_idx == 1:
idx += len(stc.vertices[0])
assert_true(np.all(stc.data[idx] == 1.0))
assert_true(stc.data[idx].shape[1] == n_times)
assert (np.all(stc.data[idx] == 1.0))
assert (stc.data[idx].shape[1] == n_times)
# test with function
def fun(x):
@@ -209,7 +211,7 @@ def test_generate_stc_single_hemi():
@testing.requires_testing_data
def test_simulate_sparse_stc_single_hemi():
""" Test generation of sparse source estimate """
"""Test generation of sparse source estimate."""
fwd = read_forward_solution_meg(fname_fwd, force_fixed=True, use_cps=True)
n_times = 10
tmin = 0
@@ -223,8 +225,8 @@ def test_simulate_sparse_stc_single_hemi():
stc_1 = simulate_sparse_stc(fwd['src'], len(labels_single_hemi), times,
labels=labels_single_hemi, random_state=0)
assert_true(stc_1.data.shape[0] == len(labels_single_hemi))
assert_true(stc_1.data.shape[1] == n_times)
assert (stc_1.data.shape[0] == len(labels_single_hemi))
assert (stc_1.data.shape[1] == n_times)
# make sure we get the same result when using the same seed
stc_2 = simulate_sparse_stc(fwd['src'], len(labels_single_hemi), times,
@@ -233,4 +235,5 @@ def test_simulate_sparse_stc_single_hemi():
assert_array_equal(stc_1.lh_vertno, stc_2.lh_vertno)
assert_array_equal(stc_1.rh_vertno, stc_2.rh_vertno)
run_tests_if_main()
+15 -16
View File
@@ -2723,8 +2723,8 @@ def _compare_source_spaces(src0, src1, mode='exact', nearest=True,
Note: this function is also used by forward/tests/test_make_forward.py
"""
from nose.tools import assert_equal, assert_true
from numpy.testing import assert_allclose, assert_array_equal
from numpy.testing import (assert_allclose, assert_array_equal,
assert_equal, assert_)
from scipy.spatial.distance import cdist
if mode != 'exact' and 'approx' not in mode: # 'nointerp' can be appended
raise RuntimeError('unknown mode %s' % mode)
@@ -2743,10 +2743,10 @@ def _compare_source_spaces(src0, src1, mode='exact', nearest=True,
diffs = (s0['interpolator'] - s1['interpolator']).data
if len(diffs) > 0 and 'nointerp' not in mode:
# 5%
assert_true(np.sqrt(np.mean(diffs ** 2)) < 0.10, name)
assert_(np.sqrt(np.mean(diffs ** 2)) < 0.10, name)
for name in ['nn', 'rr', 'nuse_tri', 'coord_frame', 'tris']:
if s0[name] is None:
assert_true(s1[name] is None, name)
assert_(s1[name] is None, name)
else:
if mode == 'exact':
assert_array_equal(s0[name], s1[name], name)
@@ -2761,25 +2761,25 @@ def _compare_source_spaces(src0, src1, mode='exact', nearest=True,
if nearest:
for name in ['nearest', 'nearest_dist', 'patch_inds']:
if s0[name] is None:
assert_true(s1[name] is None, name)
assert_(s1[name] is None, name)
else:
assert_array_equal(s0[name], s1[name])
for name in ['pinfo']:
if s0[name] is None:
assert_true(s1[name] is None, name)
assert_(s1[name] is None, name)
else:
assert_true(len(s0[name]) == len(s1[name]), name)
assert_(len(s0[name]) == len(s1[name]), name)
for p1, p2 in zip(s0[name], s1[name]):
assert_true(all(p1 == p2), name)
assert_(all(p1 == p2), name)
if mode == 'exact':
for name in ['inuse', 'vertno', 'use_tris']:
assert_array_equal(s0[name], s1[name], err_msg=name)
for name in ['dist_limit']:
assert_true(s0[name] == s1[name], name)
assert_(s0[name] == s1[name], name)
for name in ['dist']:
if s0[name] is not None:
assert_equal(s1[name].shape, s0[name].shape)
assert_true(len((s0['dist'] - s1['dist']).data) == 0)
assert_(len((s0['dist'] - s1['dist']).data) == 0)
else: # 'approx' in mode:
# deal with vertno, inuse, and use_tris carefully
for ii, s in enumerate((s0, s1)):
@@ -2789,7 +2789,7 @@ def _compare_source_spaces(src0, src1, mode='exact', nearest=True,
% (ii, si, ii, si))
assert_equal(len(s0['vertno']), len(s1['vertno']))
agreement = np.mean(s0['inuse'] == s1['inuse'])
assert_true(agreement >= 0.99, "%s < 0.99" % agreement)
assert_(agreement >= 0.99, "%s < 0.99" % agreement)
if agreement < 1.0:
# make sure mismatched vertno are within 1.5mm
v0 = np.setdiff1d(s0['vertno'], s1['vertno'])
@@ -2800,8 +2800,8 @@ def _compare_source_spaces(src0, src1, mode='exact', nearest=True,
if s0['use_tris'] is not None: # for "spacing"
assert_array_equal(s0['use_tris'].shape, s1['use_tris'].shape)
else:
assert_true(s1['use_tris'] is None)
assert_true(np.mean(s0['use_tris'] == s1['use_tris']) > 0.99)
assert_(s1['use_tris'] is None)
assert_(np.mean(s0['use_tris'] == s1['use_tris']) > 0.99)
# The above "if s0[name] is not None" can be removed once the sample
# dataset is updated to have a source space with distance info
for name in ['working_dir', 'command_line']:
@@ -2809,7 +2809,6 @@ def _compare_source_spaces(src0, src1, mode='exact', nearest=True,
assert_equal(src0.info[name], src1.info[name])
else: # 'approx' in mode:
if name in src0.info:
assert_true(name in src1.info, '"%s" missing' % name)
assert_(name in src1.info, '"%s" missing' % name)
else:
assert_true(name not in src1.info,
'"%s" should not exist' % name)
assert_(name not in src1.info, '"%s" should not exist' % name)
+33 -32
View File
@@ -11,7 +11,7 @@ import numpy as np
from scipy import sparse, linalg, stats
from numpy.testing import (assert_equal, assert_array_equal,
assert_array_almost_equal)
from nose.tools import assert_true, assert_raises
import pytest
from mne.parallel import _force_serial
from mne.stats.cluster_level import (permutation_cluster_test,
@@ -67,12 +67,12 @@ def test_cache_dir():
seed=0, stat_fun=ttest_1samp_no_p, verbose=False)
# ensure that non-independence yields warning
stat_fun = partial(ttest_1samp_no_p, sigma=1e-3)
assert_true('independently' not in log_file.getvalue())
assert 'independently' not in log_file.getvalue()
with warnings.catch_warnings(record=True): # independently
permutation_cluster_1samp_test(
X, buffer_size=10, n_jobs=2, n_permutations=1,
seed=0, stat_fun=stat_fun, verbose=False)
assert_true('independently' in log_file.getvalue())
assert 'independently' in log_file.getvalue()
finally:
if orig_dir is not None:
os.environ['MNE_CACHE_DIR'] = orig_dir
@@ -125,7 +125,7 @@ def test_permutation_step_down_p():
permutation_cluster_1samp_test(X, threshold=thresh,
step_down_p=0.05)
assert_equal(np.sum(p_new < 0.05), 2) # time one rescued
assert_true(np.all(p_old >= p_new))
assert np.all(p_old >= p_new)
def test_cluster_permutation_test():
@@ -241,7 +241,7 @@ def test_cluster_permutation_with_connectivity():
assert_array_equal(out[0], out_connectivity[0])
for a, b in zip(out_connectivity[1], out[1]):
assert_array_equal(out[0][a], out[0][b])
assert_true(np.all(a[b]))
assert np.all(a[b])
# test spatio-temporal w/o time connectivity (repeat spatial pattern)
connectivity_2 = sparse.coo_matrix(
@@ -261,13 +261,13 @@ def test_cluster_permutation_with_connectivity():
# make sure we really got 2x the number of original clusters
n_clust_orig = len(out[1])
assert_true(len(out_connectivity_2[1]) == 2 * n_clust_orig)
assert len(out_connectivity_2[1]) == 2 * n_clust_orig
# Make sure that we got the old ones back
data_1 = set([np.sum(out[0][b[:n_pts]]) for b in out[1]])
data_2 = set([np.sum(out_connectivity_2[0][a]) for a in
out_connectivity_2[1][:]])
assert_true(len(data_1.intersection(data_2)) == len(data_1))
assert len(data_1.intersection(data_2)) == len(data_1)
# now use the other algorithm
if isinstance(X1d, list):
@@ -285,13 +285,13 @@ def test_cluster_permutation_with_connectivity():
assert_array_equal(out[0], out_connectivity_3[0][1])
# make sure we really got 2x the number of original clusters
assert_true(len(out_connectivity_3[1]) == 2 * n_clust_orig)
assert len(out_connectivity_3[1]) == 2 * n_clust_orig
# Make sure that we got the old ones back
data_1 = set([np.sum(out[0][b[:n_pts]]) for b in out[1]])
data_2 = set([np.sum(out_connectivity_3[0][a[0], a[1]]) for a in
out_connectivity_3[1]])
assert_true(len(data_1.intersection(data_2)) == len(data_1))
assert len(data_1.intersection(data_2)) == len(data_1)
# test new versus old method
out_connectivity_4 = spatio_temporal_func(X1d_3, n_permutations=50,
@@ -311,12 +311,12 @@ def test_cluster_permutation_with_connectivity():
assert_array_almost_equal(sums_4, sums_5)
if not _force_serial:
assert_raises(ValueError, spatio_temporal_func, X1d_3,
pytest.raises(ValueError, spatio_temporal_func, X1d_3,
n_permutations=1, connectivity=connectivity,
max_step=1, threshold=1.67, n_jobs=-1000)
# not enough TFCE params
assert_raises(KeyError, spatio_temporal_func, X1d_3,
pytest.raises(KeyError, spatio_temporal_func, X1d_3,
connectivity=connectivity, threshold=dict(me='hello'))
# too extreme a start threshold
@@ -324,27 +324,27 @@ def test_cluster_permutation_with_connectivity():
spatio_temporal_func(X1d_3, connectivity=connectivity,
threshold=dict(start=10, step=1))
if not did_warn:
assert_true(len(w) == 1)
assert len(w) == 1
did_warn = True
# too extreme a start threshold
assert_raises(ValueError, spatio_temporal_func, X1d_3,
pytest.raises(ValueError, spatio_temporal_func, X1d_3,
connectivity=connectivity, tail=-1,
threshold=dict(start=1, step=-1))
assert_raises(ValueError, spatio_temporal_func, X1d_3,
pytest.raises(ValueError, spatio_temporal_func, X1d_3,
connectivity=connectivity, tail=-1,
threshold=dict(start=-1, step=1))
# Make sure connectivity has to be sparse
assert_raises(ValueError, spatio_temporal_func, X1d_3,
pytest.raises(ValueError, spatio_temporal_func, X1d_3,
n_permutations=50, connectivity=connectivity.todense(),
max_step=1, threshold=1.67)
# wrong type for threshold
assert_raises(TypeError, spatio_temporal_func, X1d_3,
pytest.raises(TypeError, spatio_temporal_func, X1d_3,
connectivity=connectivity, threshold=[])
# wrong value for tail
assert_raises(ValueError, spatio_temporal_func, X1d_3,
pytest.raises(ValueError, spatio_temporal_func, X1d_3,
connectivity=connectivity, tail=2)
# make sure it actually found a significant point
@@ -353,7 +353,7 @@ def test_cluster_permutation_with_connectivity():
max_step=1,
threshold=dict(start=1,
step=1))
assert_true(np.min(out_connectivity_6[2]) < 0.05)
assert np.min(out_connectivity_6[2]) < 0.05
def test_permutation_connectivity_equiv():
@@ -395,8 +395,8 @@ def test_permutation_connectivity_equiv():
X, threshold=thresh, connectivity=conn, n_jobs=2,
max_step=max_step, stat_fun=stat_fun)
# make sure our output datatype is correct
assert_true(isinstance(clusters[0], np.ndarray))
assert_true(clusters[0].dtype == bool)
assert isinstance(clusters[0], np.ndarray)
assert clusters[0].dtype == bool
assert_array_equal(clusters[0].shape, X.shape[1:])
# make sure all comparisons were done; for TFCE, no perm
@@ -405,7 +405,7 @@ def test_permutation_connectivity_equiv():
assert_equal(len(inds), count)
if isinstance(thresh, dict):
assert_equal(len(clusters), n_time * n_space)
assert_true(np.all(H0 != 0))
assert np.all(H0 != 0)
continue
this_cs = [clusters[ii] for ii in inds]
this_ps = p[inds]
@@ -425,7 +425,7 @@ def test_permutation_connectivity_equiv():
if stat_map is None:
stat_map = this_stat_map
assert_array_equal(ps, this_ps)
assert_true(len(cs) == len(this_cs))
assert len(cs) == len(this_cs)
for c1, c2 in zip(cs, this_cs):
assert_array_equal(c1, c2)
assert_array_equal(stat_map, this_stat_map)
@@ -474,11 +474,11 @@ def test_spatio_temporal_cluster_connectivity():
threshold=threshold, n_jobs=2,
buffer_size=None)
assert_array_equal(p_values_no_conn, p_values2)
assert_raises(ValueError, spatio_temporal_cluster_test,
pytest.raises(ValueError, spatio_temporal_cluster_test,
[data1_2d, data2_2d], tail=1, threshold=-2.)
assert_raises(ValueError, spatio_temporal_cluster_test,
pytest.raises(ValueError, spatio_temporal_cluster_test,
[data1_2d, data2_2d], tail=-1, threshold=2.)
assert_raises(ValueError, spatio_temporal_cluster_test,
pytest.raises(ValueError, spatio_temporal_cluster_test,
[data1_2d, data2_2d], tail=0, threshold=-1)
@@ -494,9 +494,9 @@ def test_summarize_clusters():
np.array([0.02, 0.1]),
np.array([12, -14, 30]))
stc_sum = summarize_clusters_stc(clu)
assert_true(stc_sum.data.shape[1] == 2)
assert stc_sum.data.shape[1] == 2
clu[2][0] = 0.3
assert_raises(RuntimeError, summarize_clusters_stc, clu)
pytest.raises(RuntimeError, summarize_clusters_stc, clu)
def test_permutation_test_H0():
@@ -507,37 +507,38 @@ def test_permutation_test_H0():
t, clust, p, h0 = spatio_temporal_cluster_1samp_test(
data, threshold=100, n_permutations=1024, seed=rng)
assert_equal(len(w), 1)
assert_true('No clusters found' in str(w[0].message))
assert 'No clusters found' in str(w[0].message)
assert_equal(len(h0), 0)
for n_permutations in (1024, 65, 64, 63):
t, clust, p, h0 = spatio_temporal_cluster_1samp_test(
data, threshold=0.1, n_permutations=n_permutations, seed=rng)
assert_equal(len(h0), min(n_permutations, 64))
assert_true(isinstance(clust[0], tuple)) # sets of indices
assert isinstance(clust[0], tuple) # sets of indices
for tail, thresh in zip((-1, 0, 1), (-0.1, 0.1, 0.1)):
with warnings.catch_warnings(record=True) as w:
t, clust, p, h0 = spatio_temporal_cluster_1samp_test(
data, threshold=thresh, seed=rng, tail=tail, out_type='mask')
assert_equal(len(w), 0)
assert_true(isinstance(clust[0], np.ndarray)) # bool mask
assert isinstance(clust[0], np.ndarray) # bool mask
# same as "128 if tail else 64"
assert_equal(len(h0), 2 ** (7 - (tail == 0))) # exact test
def test_tfce_thresholds():
"""Test TFCE thresholds."""
rng = np.random.RandomState(0)
data = rng.randn(7, 10, 1) - 0.5
# if tail==-1, step must also be negative
assert_raises(ValueError, permutation_cluster_1samp_test, data, tail=-1,
pytest.raises(ValueError, permutation_cluster_1samp_test, data, tail=-1,
threshold=dict(start=0, step=0.1))
# this works (smoke test)
permutation_cluster_1samp_test(data, tail=-1,
threshold=dict(start=0, step=-0.1))
# thresholds must be monotonically increasing
assert_raises(ValueError, permutation_cluster_1samp_test, data, tail=1,
pytest.raises(ValueError, permutation_cluster_1samp_test, data, tail=1,
threshold=dict(start=1, step=-0.5))
+14 -15
View File
@@ -1,15 +1,14 @@
import numpy as np
from numpy.testing import (
assert_almost_equal, assert_allclose, assert_raises, assert_array_equal)
from nose.tools import assert_true
from numpy.testing import (assert_almost_equal, assert_allclose,
assert_array_equal)
from scipy import stats
import pytest
from mne.stats import fdr_correction, bonferroni_correction
def test_multi_pval_correction():
"""Test pval correction for multi comparison (FDR and Bonferroni)
"""
"""Test pval correction for multi comparison (FDR and Bonferroni)."""
rng = np.random.RandomState(0)
X = rng.randn(10, 1000, 10)
X[:, :50, 0] += 4.0 # 50 significant tests
@@ -23,8 +22,8 @@ def test_multi_pval_correction():
reject_bonferroni, pval_bonferroni = bonferroni_correction(pval, alpha)
thresh_bonferroni = stats.t.ppf(1.0 - alpha / n_tests, n_samples - 1)
assert_true(pval_bonferroni.ndim == 2)
assert_true(reject_bonferroni.ndim == 2)
assert pval_bonferroni.ndim == 2
assert reject_bonferroni.ndim == 2
assert_allclose(pval_bonferroni / 10000, pval)
reject_expected = pval_bonferroni < alpha
assert_array_equal(reject_bonferroni, reject_expected)
@@ -33,15 +32,15 @@ def test_multi_pval_correction():
assert_almost_equal(fwer, alpha, 1)
reject_fdr, pval_fdr = fdr_correction(pval, alpha=alpha, method='indep')
assert_true(pval_fdr.ndim == 2)
assert_true(reject_fdr.ndim == 2)
assert pval_fdr.ndim == 2
assert reject_fdr.ndim == 2
thresh_fdr = np.min(np.abs(T)[reject_fdr])
assert_true(0 <= (reject_fdr.sum() - 50) <= 50 * 1.05)
assert_true(thresh_uncorrected <= thresh_fdr <= thresh_bonferroni)
assert_raises(ValueError, fdr_correction, pval, alpha, method='blah')
assert_true(np.all(fdr_correction(pval, alpha=0)[0] == 0))
assert 0 <= (reject_fdr.sum() - 50) <= 50 * 1.05
assert thresh_uncorrected <= thresh_fdr <= thresh_bonferroni
pytest.raises(ValueError, fdr_correction, pval, alpha, method='blah')
assert np.all(fdr_correction(pval, alpha=0)[0] == 0)
reject_fdr, pval_fdr = fdr_correction(pval, alpha=alpha, method='negcorr')
thresh_fdr = np.min(np.abs(T)[reject_fdr])
assert_true(0 <= (reject_fdr.sum() - 50) <= 50 * 1.05)
assert_true(thresh_uncorrected <= thresh_fdr <= thresh_bonferroni)
assert 0 <= (reject_fdr.sum() - 50) <= 50 * 1.05
assert thresh_uncorrected <= thresh_fdr <= thresh_bonferroni
+22 -20
View File
@@ -1,10 +1,11 @@
from itertools import product
import pytest
from numpy.testing import assert_array_almost_equal
import numpy as np
from mne.stats.parametric import (f_mway_rm, f_threshold_mway_rm,
_map_effects)
from nose.tools import assert_raises, assert_true
from numpy.testing import assert_array_almost_equal
import numpy as np
# hardcoded external test results, manually transferred
test_external = {
@@ -30,7 +31,7 @@ test_external = {
def generate_data(n_subjects, n_conditions):
"""generate testing data"""
"""Generate testing data."""
rng = np.random.RandomState(42)
data = rng.randn(n_subjects * n_conditions).reshape(
n_subjects, n_conditions)
@@ -38,26 +39,27 @@ def generate_data(n_subjects, n_conditions):
def test_map_effects():
""" Test ANOVA effects parsing"""
"""Test ANOVA effects parsing."""
selection, names = _map_effects(n_factors=2, effects='A')
assert_true(names, ['A'])
assert names == ['A']
selection, names = _map_effects(n_factors=2, effects=['A', 'A:B'])
assert_true(names, ['A', 'A:B'])
assert names == ['A', 'A:B']
selection, names = _map_effects(n_factors=3, effects='A*B')
assert_true(names, ['A', 'B', 'A:B'])
assert names == ['A', 'B', 'A:B']
# XXX this might be wrong?
selection, names = _map_effects(n_factors=3, effects='A*C')
assert_true(names, ['A', 'B', 'A:B', 'C', 'A:C', 'B:C', 'A:B:C'])
assert names == ['A', 'B', 'A:B', 'C', 'A:C']
assert_raises(ValueError, _map_effects, n_factors=2, effects='C')
pytest.raises(ValueError, _map_effects, n_factors=2, effects='C')
assert_raises(ValueError, _map_effects, n_factors=27, effects='all')
pytest.raises(ValueError, _map_effects, n_factors=27, effects='all')
def test_f_twoway_rm():
""" Test 2-way anova """
"""Test 2-way anova."""
rng = np.random.RandomState(42)
iter_params = product([4, 10], [2, 15], [4, 6, 8],
['A', 'B', 'A:B'],
@@ -72,20 +74,20 @@ def test_f_twoway_rm():
data = rng.random_sample([n_subj, n_levels, n_obs])
fvals, pvals = f_mway_rm(data, _effects[n_levels], effects,
correction=correction)
assert_true((fvals >= 0).all())
assert (fvals >= 0).all()
if pvals.any():
assert_true(((0 <= pvals) & (1 >= pvals)).all())
assert ((0 <= pvals) & (1 >= pvals)).all()
n_effects = len(_map_effects(n_subj, effects)[0])
assert_true(fvals.size == n_obs * n_effects)
assert fvals.size == n_obs * n_effects
if n_effects == 1: # test for principle of least surprise ...
assert_true(fvals.ndim == 1)
assert fvals.ndim == 1
fvals_ = f_threshold_mway_rm(n_subj, _effects[n_levels], effects)
assert_true((fvals_ >= 0).all())
assert_true(fvals_.size == n_effects)
assert (fvals_ >= 0).all()
assert fvals_.size == n_effects
data = rng.random_sample([n_subj, n_levels, 1])
assert_raises(ValueError, f_mway_rm, data, _effects[n_levels],
pytest.raises(ValueError, f_mway_rm, data, _effects[n_levels],
effects='C', correction=correction)
data = rng.random_sample([n_subj, n_levels, n_obs, 3])
# check for dimension handling
+1
View File
@@ -63,6 +63,7 @@ def test_permutation_t_test():
def test_ci():
"""Test confidence intervals."""
# isolated test of CI functions
arr = np.linspace(0, 1, 1000)[..., np.newaxis]
assert_allclose(_ci(arr, method="parametric"),
+16 -17
View File
@@ -8,12 +8,11 @@ import os.path as op
import warnings
import numpy as np
from numpy.testing import assert_array_equal, assert_allclose
from numpy.testing import assert_array_equal, assert_allclose, assert_equal
import pytest
from scipy.signal import hann
from nose.tools import assert_raises, assert_true, assert_equal
import mne
from mne import read_source_estimate
from mne.datasets import testing
@@ -51,14 +50,14 @@ def test_regression():
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
lm = linear_regression(epochs, design_matrix, ['intercept', 'aud'])
assert_true(w[0].category == RuntimeWarning)
assert_true('non-data' in '%s' % w[0].message)
assert (w[0].category == RuntimeWarning)
assert ('non-data' in '%s' % w[0].message)
for predictor, parameters in lm.items():
for value in parameters:
assert_equal(value.data.shape, evoked.data.shape)
assert_raises(ValueError, linear_regression, [epochs, epochs],
pytest.raises(ValueError, linear_regression, [epochs, epochs],
design_matrix)
stc = read_source_estimate(stc_fname).crop(0, 0.02)
@@ -72,13 +71,13 @@ def test_regression():
# all p values are 0 < p <= 1 to start, but get stored in float32
# data, so can actually be truncated to 0. Thus the mlog10_p_val
# actually maintains better precision for tiny p-values.
assert_true(np.isfinite(val.p_val.data).all())
assert_true((val.p_val.data <= 1).all())
assert_true((val.p_val.data >= 0).all())
assert (np.isfinite(val.p_val.data).all())
assert ((val.p_val.data <= 1).all())
assert ((val.p_val.data >= 0).all())
# all -log10(p) are non-negative
assert_true(np.isfinite(val.mlog10_p_val.data).all())
assert_true((val.mlog10_p_val.data >= 0).all())
assert_true((val.mlog10_p_val.data >= 0).all())
assert (np.isfinite(val.mlog10_p_val.data).all())
assert ((val.mlog10_p_val.data >= 0).all())
assert ((val.mlog10_p_val.data >= 0).all())
for k in lm1:
for v1, v2 in zip(lm1[k], lm2[k]):
@@ -118,12 +117,12 @@ def test_continuous_regression_no_overlap():
# Test events that will lead to "duplicate" errors
old_latency = events[1, 0]
events[1, 0] = events[0, 0]
assert_raises(ValueError, linear_regression_raw,
pytest.raises(ValueError, linear_regression_raw,
raw, events, event_id, tmin, tmax)
events[1, 0] = old_latency
events[:, 0] = range(len(events))
assert_raises(ValueError, linear_regression_raw, raw,
pytest.raises(ValueError, linear_regression_raw, raw,
events, event_id, tmin, tmax, decim=2)
@@ -158,9 +157,9 @@ def test_continuous_regression_with_overlap():
def solT(X, y):
return ridge_regression(X, y, alpha=0.).T
with warnings.catch_warnings(record=True): # transpose
assert_raises(ValueError, linear_regression_raw, raw, events,
pytest.raises(ValueError, linear_regression_raw, raw, events,
solver=solT)
assert_raises(ValueError, linear_regression_raw, raw, events, solver='err')
assert_raises(TypeError, linear_regression_raw, raw, events, solver=0)
pytest.raises(ValueError, linear_regression_raw, raw, events, solver='err')
pytest.raises(TypeError, linear_regression_raw, raw, events, solver=0)
run_tests_if_main()
+17 -19
View File
@@ -14,7 +14,7 @@ from ..bem import fit_sphere_to_headshape
def _get_data(x, ch_idx):
"""Helper to get the (n_ch, n_times) data array"""
"""Get the (n_ch, n_times) data array."""
if isinstance(x, BaseRaw):
return x[ch_idx][0]
elif isinstance(x, Evoked):
@@ -22,8 +22,7 @@ def _get_data(x, ch_idx):
def _check_snr(actual, desired, picks, min_tol, med_tol, msg, kind='MEG'):
"""Helper to check the SNR of a set of channels"""
from nose.tools import assert_true
"""Check the SNR of a set of channels."""
actual_data = _get_data(actual, picks)
desired_data = _get_data(desired, picks)
bench_rms = np.sqrt(np.mean(desired_data * desired_data, axis=1))
@@ -35,17 +34,18 @@ def _check_snr(actual, desired, picks, min_tol, med_tol, msg, kind='MEG'):
snr = snrs.min()
bad_count = (snrs < min_tol).sum()
msg = ' (%s)' % msg if msg != '' else msg
assert_true(bad_count == 0, 'SNR (worst %0.2f) < %0.2f for %s/%s '
'channels%s' % (snr, min_tol, bad_count, len(picks), msg))
assert bad_count == 0, ('SNR (worst %0.2f) < %0.2f for %s/%s '
'channels%s' % (snr, min_tol, bad_count,
len(picks), msg))
# median tol
snr = np.median(snrs)
assert_true(snr >= med_tol, '%s SNR median %0.2f < %0.2f%s'
% (kind, snr, med_tol, msg))
assert snr >= med_tol, ('%s SNR median %0.2f < %0.2f%s'
% (kind, snr, med_tol, msg))
def assert_meg_snr(actual, desired, min_tol, med_tol=500., chpi_med_tol=500.,
msg=None):
"""Helper to assert channel SNR of a certain level
"""Assert channel SNR of a certain level.
Mostly useful for operations like Maxwell filtering that modify
MEG channels while leaving EEG and others intact.
@@ -73,19 +73,19 @@ def assert_meg_snr(actual, desired, min_tol, med_tol=500., chpi_med_tol=500.,
def assert_snr(actual, desired, tol):
"""Assert actual and desired arrays are within some SNR tolerance"""
from nose.tools import assert_true
"""Assert actual and desired arrays are within some SNR tolerance."""
snr = (linalg.norm(desired, ord='fro') /
linalg.norm(desired - actual, ord='fro'))
assert_true(snr >= tol, msg='%f < %f' % (snr, tol))
assert snr >= tol, '%f < %f' % (snr, tol)
def _dig_sort_key(dig):
"""Helper for sorting"""
return 10000 * dig['kind'] + dig['ident']
"""Sort dig keys."""
return (dig['kind'], dig['ident'])
def assert_dig_allclose(info_py, info_bin):
"""Assert dig allclose."""
# test dig positions
dig_py = sorted(info_py['dig'], key=_dig_sort_key)
dig_bin = sorted(info_bin['dig'], key=_dig_sort_key)
@@ -107,7 +107,7 @@ def assert_dig_allclose(info_py, info_bin):
def assert_naming(warns, fname, n_warn):
"""Assert a non-standard naming scheme was used while saving or loading
"""Assert a non-standard naming scheme was used while saving or loading.
Parameters
----------
@@ -118,11 +118,9 @@ def assert_naming(warns, fname, n_warn):
n_warn : int
Number of warnings that should have naming convention errors.
"""
from nose.tools import assert_true
assert_true(sum('naming conventions' in str(ww.message)
for ww in warns) == n_warn)
assert sum('naming conventions' in str(ww.message)
for ww in warns) == n_warn
# check proper stacklevel reporting
for ww in warns:
if 'naming conventions' in str(ww.message):
assert_true(fname in ww.filename,
msg='"%s" not in "%s"' % (fname, ww.filename))
assert fname in ww.filename
+1 -1
View File
@@ -212,7 +212,7 @@ def test_crop_more():
@testing.requires_testing_data
def test_read_brainstorm_annotations():
"""Test reading for Brainstorm events file"""
"""Test reading for Brainstorm events file."""
fname = op.join(data_dir, 'events_sample_audvis_raw_bst.mat')
annot = read_brainstorm_annotations(fname)
assert len(annot) == 238
+38 -39
View File
@@ -9,7 +9,6 @@ from shutil import copy
import warnings
import numpy as np
from nose.tools import assert_raises, assert_true
import pytest
from numpy.testing import assert_equal, assert_allclose
@@ -47,7 +46,7 @@ fname_bem_sol_1 = op.join(subjects_dir, 'sample', 'bem',
def _compare_bem_surfaces(surfs_1, surfs_2):
"""Helper to compare BEM surfaces"""
"""Compare BEM surfaces."""
names = ['id', 'nn', 'rr', 'coord_frame', 'tris', 'sigma', 'ntri', 'np']
ignores = ['tri_cent', 'tri_nn', 'tri_area', 'neighbor_tri']
for s0, s1 in zip(surfs_1, surfs_2):
@@ -59,7 +58,7 @@ def _compare_bem_surfaces(surfs_1, surfs_2):
def _compare_bem_solutions(sol_a, sol_b):
"""Helper to compare BEM solutions"""
"""Compare BEM solutions."""
# compare the surfaces we used
_compare_bem_surfaces(sol_a['surfs'], sol_b['surfs'])
# compare the actual solutions
@@ -74,53 +73,53 @@ def _compare_bem_solutions(sol_a, sol_b):
@testing.requires_testing_data
def test_io_bem():
"""Test reading and writing of bem surfaces and solutions"""
"""Test reading and writing of bem surfaces and solutions."""
tempdir = _TempDir()
temp_bem = op.join(tempdir, 'temp-bem.fif')
assert_raises(ValueError, read_bem_surfaces, fname_raw)
assert_raises(ValueError, read_bem_surfaces, fname_bem_3, s_id=10)
pytest.raises(ValueError, read_bem_surfaces, fname_raw)
pytest.raises(ValueError, read_bem_surfaces, fname_bem_3, s_id=10)
surf = read_bem_surfaces(fname_bem_3, patch_stats=True)
surf = read_bem_surfaces(fname_bem_3, patch_stats=False)
write_bem_surfaces(temp_bem, surf[0])
surf_read = read_bem_surfaces(temp_bem, patch_stats=False)
_compare_bem_surfaces(surf, surf_read)
assert_raises(RuntimeError, read_bem_solution, fname_bem_3)
pytest.raises(RuntimeError, read_bem_solution, fname_bem_3)
temp_sol = op.join(tempdir, 'temp-sol.fif')
sol = read_bem_solution(fname_bem_sol_3)
assert_true('BEM' in repr(sol))
assert 'BEM' in repr(sol)
write_bem_solution(temp_sol, sol)
sol_read = read_bem_solution(temp_sol)
_compare_bem_solutions(sol, sol_read)
sol = read_bem_solution(fname_bem_sol_1)
assert_raises(RuntimeError, _bem_find_surface, sol, 3)
pytest.raises(RuntimeError, _bem_find_surface, sol, 3)
def test_make_sphere_model():
"""Test making a sphere model"""
"""Test making a sphere model."""
info = read_info(fname_raw)
assert_raises(ValueError, make_sphere_model, 'foo', 'auto', info)
assert_raises(ValueError, make_sphere_model, 'auto', 'auto', None)
assert_raises(ValueError, make_sphere_model, 'auto', 'auto', info,
pytest.raises(ValueError, make_sphere_model, 'foo', 'auto', info)
pytest.raises(ValueError, make_sphere_model, 'auto', 'auto', None)
pytest.raises(ValueError, make_sphere_model, 'auto', 'auto', info,
relative_radii=(), sigmas=())
assert_raises(ValueError, make_sphere_model, 'auto', 'auto', info,
pytest.raises(ValueError, make_sphere_model, 'auto', 'auto', info,
relative_radii=(1,)) # wrong number of radii
# here we just make sure it works -- the functionality is actually
# tested more extensively e.g. in the forward and dipole code
bem = make_sphere_model('auto', 'auto', info)
assert_true('3 layers' in repr(bem))
assert_true('Sphere ' in repr(bem))
assert_true(' mm' in repr(bem))
assert '3 layers' in repr(bem)
assert 'Sphere ' in repr(bem)
assert ' mm' in repr(bem)
bem = make_sphere_model('auto', None, info)
assert_true('no layers' in repr(bem))
assert_true('Sphere ' in repr(bem))
assert_raises(ValueError, make_sphere_model, sigmas=(0.33,),
assert 'no layers' in repr(bem)
assert 'Sphere ' in repr(bem)
pytest.raises(ValueError, make_sphere_model, sigmas=(0.33,),
relative_radii=(1.0,))
@testing.requires_testing_data
def test_bem_model():
"""Test BEM model creation from Python with I/O"""
"""Test BEM model creation from Python with I/O."""
tempdir = _TempDir()
fname_temp = op.join(tempdir, 'temp-bem.fif')
for kwargs, fname in zip((dict(), dict(conductivity=[0.3])),
@@ -133,35 +132,35 @@ def test_bem_model():
model_read = read_bem_surfaces(fname_temp)
_compare_bem_surfaces(model, model_c)
_compare_bem_surfaces(model_read, model_c)
assert_raises(ValueError, make_bem_model, 'sample', # bad conductivity
pytest.raises(ValueError, make_bem_model, 'sample', # bad conductivity
conductivity=[0.3, 0.006], subjects_dir=subjects_dir)
@pytest.mark.slowtest
@testing.requires_testing_data
def test_bem_solution():
"""Test making a BEM solution from Python with I/O"""
"""Test making a BEM solution from Python with I/O."""
# test degenerate conditions
surf = read_bem_surfaces(fname_bem_1)[0]
assert_raises(RuntimeError, _ico_downsample, surf, 10) # bad dec grade
pytest.raises(RuntimeError, _ico_downsample, surf, 10) # bad dec grade
s_bad = dict(tris=surf['tris'][1:], ntri=surf['ntri'] - 1, rr=surf['rr'])
assert_raises(RuntimeError, _ico_downsample, s_bad, 1) # not isomorphic
pytest.raises(RuntimeError, _ico_downsample, s_bad, 1) # not isomorphic
s_bad = dict(tris=surf['tris'].copy(), ntri=surf['ntri'],
rr=surf['rr']) # bad triangulation
s_bad['tris'][0] = [0, 0, 0]
assert_raises(RuntimeError, _ico_downsample, s_bad, 1)
pytest.raises(RuntimeError, _ico_downsample, s_bad, 1)
s_bad['id'] = 1
assert_raises(RuntimeError, _assert_complete_surface, s_bad)
pytest.raises(RuntimeError, _assert_complete_surface, s_bad)
s_bad = dict(tris=surf['tris'], ntri=surf['ntri'], rr=surf['rr'].copy())
s_bad['rr'][0] = 0.
assert_raises(RuntimeError, _get_ico_map, surf, s_bad)
pytest.raises(RuntimeError, _get_ico_map, surf, s_bad)
surfs = read_bem_surfaces(fname_bem_3)
assert_raises(RuntimeError, _assert_inside, surfs[0], surfs[1]) # outside
pytest.raises(RuntimeError, _assert_inside, surfs[0], surfs[1]) # outside
surfs[0]['id'] = 100 # bad surfs
assert_raises(RuntimeError, _order_surfaces, surfs)
pytest.raises(RuntimeError, _order_surfaces, surfs)
surfs[1]['rr'] /= 1000.
assert_raises(RuntimeError, _check_surface_size, surfs[1])
pytest.raises(RuntimeError, _check_surface_size, surfs[1])
# actually test functionality
tempdir = _TempDir()
@@ -186,7 +185,7 @@ def test_bem_solution():
def test_fit_sphere_to_headshape():
"""Test fitting a sphere to digitization points"""
"""Test fitting a sphere to digitization points."""
# Create points of various kinds
rad = 0.09
big_rad = 0.12
@@ -246,12 +245,12 @@ def test_fit_sphere_to_headshape():
info = Info(dig=dig, dev_head_t=dev_head_t)
# Degenerate conditions
assert_raises(ValueError, fit_sphere_to_headshape, info,
pytest.raises(ValueError, fit_sphere_to_headshape, info,
dig_kinds=(FIFF.FIFFV_POINT_HPI,))
assert_raises(ValueError, fit_sphere_to_headshape, info,
pytest.raises(ValueError, fit_sphere_to_headshape, info,
dig_kinds='foo', units='m')
info['dig'][0]['coord_frame'] = FIFF.FIFFV_COORD_DEVICE
assert_raises(RuntimeError, fit_sphere_to_headshape, info, units='m')
pytest.raises(RuntimeError, fit_sphere_to_headshape, info, units='m')
info['dig'][0]['coord_frame'] = FIFF.FIFFV_COORD_HEAD
# # Test with 4 points that match a perfect sphere
@@ -297,7 +296,7 @@ def test_fit_sphere_to_headshape():
verbose='warning', units='mm')
log_file = log_file.getvalue().strip()
assert_equal(len(log_file.split('\n')), 2)
assert_true('Estimated head size' in log_file)
assert 'Estimated head size' in log_file
assert_allclose(oh, center * 1000, atol=1e-3)
assert_allclose(r, big_rad * 1000, atol=1e-3)
del info_big
@@ -315,7 +314,7 @@ def test_fit_sphere_to_headshape():
info_shift, dig_kinds=dig_kinds, verbose='warning', units='m')
log_file = log_file.getvalue().strip()
assert_equal(len(log_file.split('\n')), 2)
assert_true('from head frame origin' in log_file)
assert 'from head frame origin' in log_file
assert_allclose(oh, shift_center, atol=1e-6)
assert_allclose(r, rad, atol=1e-6)
@@ -338,8 +337,8 @@ def test_fit_sphere_to_headshape():
r, oh, od = fit_sphere_to_headshape(info, units='m')
# this one should fail, 1 EXTRA point and 3 EEG (but the fit is terrible)
info = Info(dig=dig[:6], dev_head_t=dev_head_t)
assert_raises(ValueError, fit_sphere_to_headshape, info, units='m')
assert_raises(TypeError, fit_sphere_to_headshape, 1, units='m')
pytest.raises(ValueError, fit_sphere_to_headshape, info, units='m')
pytest.raises(TypeError, fit_sphere_to_headshape, 1, units='m')
@requires_nibabel()
+29 -32
View File
@@ -7,7 +7,7 @@ import warnings
import numpy as np
from numpy.testing import assert_allclose
from nose.tools import assert_raises, assert_equal, assert_true
from scipy.interpolate import interp1d
import pytest
from mne import (pick_types, Dipole, make_sphere_model, make_forward_dipole,
@@ -19,7 +19,6 @@ from mne.chpi import (_calculate_chpi_positions, _calculate_chpi_coil_locs,
_calculate_head_pos_ctf, head_pos_to_trans_rot_t,
read_head_pos, write_head_pos, filter_chpi,
_get_hpi_info, _get_hpi_initial_fit)
from mne.fixes import assert_raises_regex
from mne.transforms import rot_to_quat, _angle_between_quats
from mne.simulation import simulate_raw
from mne.utils import run_tests_if_main, _TempDir, catch_logging
@@ -74,7 +73,7 @@ def test_chpi_adjust():
]
log = log.getvalue().splitlines()
assert_true(set(log) == set(msg), '\n' + '\n'.join(set(msg) - set(log)))
assert set(log) == set(msg), '\n' + '\n'.join(set(msg) - set(log))
# Then took the raw file, did this:
raw.info['dig'][5]['r'][2] += 1.
@@ -87,7 +86,7 @@ def test_chpi_adjust():
_get_hpi_initial_fit(raw.info, adjust=True, verbose='debug')
_get_hpi_info(raw.info, verbose='debug')
log = log.getvalue().splitlines()
assert_true(set(log) == set(msg), '\n' + '\n'.join(set(msg) - set(log)))
assert set(log) == set(msg), '\n' + '\n'.join(set(msg) - set(log))
@testing.requires_testing_data
@@ -104,11 +103,11 @@ def test_read_write_head_pos():
head_pos = read_head_pos(temp_name)
assert_allclose(head_pos_orig, head_pos, atol=1e-3)
# Degenerate cases
assert_raises(TypeError, write_head_pos, 0, head_pos_read) # not filename
assert_raises(ValueError, write_head_pos, temp_name, 'foo') # not array
assert_raises(ValueError, write_head_pos, temp_name, head_pos_read[:, :9])
assert_raises(TypeError, read_head_pos, 0)
assert_raises(IOError, read_head_pos, temp_name + 'foo')
pytest.raises(TypeError, write_head_pos, 0, head_pos_read) # not filename
pytest.raises(ValueError, write_head_pos, temp_name, 'foo') # not array
pytest.raises(ValueError, write_head_pos, temp_name, head_pos_read[:, :9])
pytest.raises(TypeError, read_head_pos, 0)
pytest.raises(IOError, read_head_pos, temp_name + 'foo')
@testing.requires_testing_data
@@ -118,16 +117,14 @@ def test_hpi_info():
temp_name = op.join(tempdir, 'temp_raw.fif')
for fname in (chpi_fif_fname, sss_fif_fname):
raw = read_raw_fif(fname, allow_maxshield='yes').crop(0, 0.1)
assert_true(len(raw.info['hpi_subsystem']) > 0)
assert len(raw.info['hpi_subsystem']) > 0
raw.save(temp_name, overwrite=True)
info = read_info(temp_name)
assert_equal(len(info['hpi_subsystem']),
len(raw.info['hpi_subsystem']))
assert len(info['hpi_subsystem']) == len(raw.info['hpi_subsystem'])
def _assert_quats(actual, desired, dist_tol=0.003, angle_tol=5.):
"""Compare estimated cHPI positions."""
from scipy.interpolate import interp1d
trans_est, rot_est, t_est = head_pos_to_trans_rot_t(actual)
trans, rot, t = head_pos_to_trans_rot_t(desired)
quats_est = rot_to_quat(rot_est)
@@ -151,18 +148,18 @@ def _assert_quats(actual, desired, dist_tol=0.003, angle_tol=5.):
trans_est_interp = interp1d(t_est, trans_est, axis=0)(t)
distances = np.sqrt(np.sum((trans - trans_est_interp) ** 2, axis=1))
arg_worst = np.argmax(distances)
assert_true(distances[arg_worst] <= dist_tol,
'@ %0.3f seconds: %0.3f > %0.3f mm'
% (t[arg_worst], 1000 * distances[arg_worst], 1000 * dist_tol))
assert distances[arg_worst] <= dist_tol, (
'@ %0.3f seconds: %0.3f > %0.3f mm'
% (t[arg_worst], 1000 * distances[arg_worst], 1000 * dist_tol))
# limit rotation difference between MF and our estimation
# (note that the interpolation will make this slightly worse)
quats_est_interp = interp1d(t_est, quats_est, axis=0)(t)
angles = 180 * _angle_between_quats(quats_est_interp, quats) / np.pi
arg_worst = np.argmax(angles)
assert_true(angles[arg_worst] <= angle_tol,
'@ %0.3f seconds: %0.3f > %0.3f deg'
% (t[arg_worst], angles[arg_worst], angle_tol))
assert angles[arg_worst] <= angle_tol, (
'@ %0.3f seconds: %0.3f > %0.3f deg'
% (t[arg_worst], angles[arg_worst], angle_tol))
def _decimate_chpi(raw, decim=4):
@@ -193,21 +190,21 @@ def test_calculate_chpi_positions():
with catch_logging() as log:
py_quats = _calculate_chpi_positions(raw_dec, t_step_max=1.,
verbose='debug')
assert_true(log.getvalue().startswith('HPIFIT'))
assert log.getvalue().startswith('HPIFIT')
_assert_quats(py_quats, mf_quats, dist_tol=0.004, angle_tol=2.5)
# degenerate conditions
raw_no_chpi = read_raw_fif(test_fif_fname)
assert_raises(RuntimeError, _calculate_chpi_positions, raw_no_chpi)
pytest.raises(RuntimeError, _calculate_chpi_positions, raw_no_chpi)
raw_bad = raw.copy()
del raw_bad.info['hpi_meas'][0]['hpi_coils'][0]['coil_freq']
assert_raises(RuntimeError, _calculate_chpi_positions, raw_bad)
pytest.raises(RuntimeError, _calculate_chpi_positions, raw_bad)
raw_bad = raw.copy()
for d in raw_bad.info['dig']:
if d['kind'] == FIFF.FIFFV_POINT_HPI:
d['coord_frame'] = FIFF.FIFFV_COORD_UNKNOWN
break
assert_raises(RuntimeError, _calculate_chpi_positions, raw_bad)
pytest.raises(RuntimeError, _calculate_chpi_positions, raw_bad)
for d in raw_bad.info['dig']:
if d['kind'] == FIFF.FIFFV_POINT_HPI:
d['coord_frame'] = FIFF.FIFFV_COORD_HEAD
@@ -220,12 +217,12 @@ def test_calculate_chpi_positions():
with catch_logging() as log_file:
_calculate_chpi_positions(raw_bad, t_step_min=1., verbose=True)
# ignore HPI info header and [done] footer
assert_true('0/5 good' in log_file.getvalue().strip().split('\n')[-2])
assert '0/5 good' in log_file.getvalue().strip().split('\n')[-2]
# half the rate cuts off cHPI coils
raw.info['lowpass'] /= 2.
assert_raises_regex(RuntimeError, 'above the',
_calculate_chpi_positions, raw)
with pytest.raises(RuntimeError, match='above the'):
_calculate_chpi_positions(raw)
# test on 5k artemis data
raw = read_raw_artemis123(art_fname, preload=True)
@@ -386,8 +383,8 @@ def test_chpi_subtraction():
raw.del_proj()
with catch_logging() as log:
filter_chpi(raw, include_line=False, verbose=True)
assert_true('No average EEG' not in log.getvalue())
assert_true('5 cHPI' in log.getvalue())
assert 'No average EEG' not in log.getvalue()
assert '5 cHPI' in log.getvalue()
# MaxFilter doesn't do quite as well as our algorithm with the last bit
raw.crop(0, 16)
# remove cHPI status chans
@@ -398,7 +395,7 @@ def test_chpi_subtraction():
# Degenerate cases
raw_nohpi = read_raw_fif(test_fif_fname, preload=True)
assert_raises(RuntimeError, filter_chpi, raw_nohpi)
pytest.raises(RuntimeError, filter_chpi, raw_nohpi)
# When MaxFliter downsamples, like::
# $ maxfilter -nosss -ds 2 -f test_move_anon_raw.fif \
@@ -414,8 +411,8 @@ def test_chpi_subtraction():
del raw.info['hpi_subsystem']['event_channel']
with catch_logging() as log:
filter_chpi(raw, verbose=True)
assert_raises(ValueError, filter_chpi, raw, t_window=-1)
assert_true('2 cHPI' in log.getvalue())
pytest.raises(ValueError, filter_chpi, raw, t_window=-1)
assert '2 cHPI' in log.getvalue()
@testing.requires_testing_data
@@ -427,7 +424,7 @@ def test_calculate_head_pos_ctf():
_assert_quats(quats, mc_quats, dist_tol=0.004, angle_tol=2.5)
raw = read_raw_fif(ctf_fname)
assert_raises(RuntimeError, _calculate_head_pos_ctf, raw)
pytest.raises(RuntimeError, _calculate_head_pos_ctf, raw)
run_tests_if_main()
+2 -2
View File
@@ -22,7 +22,7 @@ from mne.source_space import write_source_spaces
def test_coregister_fiducials():
"""Test coreg.coregister_fiducials()"""
"""Test coreg.coregister_fiducials()."""
# prepare head and MRI fiducials
trans = Transform('head', 'mri',
rotation(.4, .1, 0).dot(translation(.1, -.1, .1)))
@@ -192,7 +192,7 @@ def test_scale_mri_xfm():
def test_fit_matched_points():
"""Test fit_matched_points: fitting two matching sets of points"""
"""Test fit_matched_points: fitting two matching sets of points."""
tgt_pts = np.random.RandomState(42).uniform(size=(6, 3))
# rotation only
+44 -50
View File
@@ -7,10 +7,8 @@ import os.path as op
import itertools as itt
import warnings
from nose.tools import assert_true
from numpy.testing import (assert_array_almost_equal, assert_array_equal,
assert_equal, assert_allclose)
from nose.tools import assert_raises
import pytest
import numpy as np
from scipy import linalg
@@ -66,14 +64,14 @@ def test_cov_mismatch():
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])
pytest.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,
pytest.raises(ValueError, compute_covariance, epochs,
on_mismatch='x')
assert_true(any('transform mismatch' in str(ww.message) for ww in w))
assert 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
@@ -136,13 +134,13 @@ def test_ad_hoc_cov():
evoked = read_evokeds(ave_fname)[0]
cov = make_ad_hoc_cov(evoked.info)
cov.save(out_fname)
assert_true('Covariance' in repr(cov))
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_true('Covariance' in repr(cov))
assert 'Covariance' in repr(cov)
cov2 = read_cov(out_fname)
assert_array_almost_equal(cov['data'], cov2['data'])
@@ -158,7 +156,7 @@ def test_io_cov():
assert_array_almost_equal(cov.data, cov2.data)
assert_equal(cov['method'], cov2['method'])
assert_equal(cov['loglik'], cov2['loglik'])
assert_true('Covariance' in repr(cov))
assert 'Covariance' in repr(cov)
cov2 = read_cov(cov_gz_fname)
assert_array_almost_equal(cov.data, cov2.data)
@@ -168,8 +166,8 @@ def test_io_cov():
cov['bads'] = ['EEG 039']
cov_sel = pick_channels_cov(cov, exclude=cov['bads'])
assert_true(cov_sel['dim'] == (len(cov['data']) - len(cov['bads'])))
assert_true(cov_sel['data'].shape == (cov_sel['dim'], cov_sel['dim']))
assert cov_sel['dim'] == (len(cov['data']) - len(cov['bads']))
assert cov_sel['data'].shape == (cov_sel['dim'], cov_sel['dim'])
cov_sel.save(op.join(tempdir, 'test-cov.fif'))
cov2 = read_cov(cov_gz_fname)
@@ -209,15 +207,15 @@ def test_cov_estimation_on_raw():
# test IO when computation done in Python
cov.save(op.join(tempdir, 'test-cov.fif')) # test saving
cov_read = read_cov(op.join(tempdir, 'test-cov.fif'))
assert_true(cov_read.ch_names == cov.ch_names)
assert_true(cov_read.nfree == cov.nfree)
assert cov_read.ch_names == cov.ch_names
assert cov_read.nfree == cov.nfree
assert_array_almost_equal(cov.data, cov_read.data)
# test with a subset of channels
raw_pick = raw.copy().pick_channels(raw.ch_names[:5])
raw_pick.info.normalize_proj()
cov = compute_raw_covariance(raw_pick, tstep=None, method=method)
assert_true(cov_mne.ch_names[:5] == cov.ch_names)
assert cov_mne.ch_names[:5] == cov.ch_names
assert_snr(cov.data, cov_mne.data[:5, :5], 1e4)
cov = compute_raw_covariance(raw_pick, method=method)
assert_snr(cov.data, cov_mne.data[:5, :5], 90) # cutoff samps
@@ -226,9 +224,9 @@ def test_cov_estimation_on_raw():
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
cov = compute_raw_covariance(raw_2, method=method)
assert_true(any('Too few samples' in str(ww.message) for ww in w))
assert any('Too few samples' in str(ww.message) for ww in w)
# no epochs found due to rejection
assert_raises(ValueError, compute_raw_covariance, raw, tstep=None,
pytest.raises(ValueError, compute_raw_covariance, raw, tstep=None,
method='empirical', reject=dict(eog=200e-6))
# but this should work
cov = compute_raw_covariance(raw.copy().crop(0, 10.),
@@ -256,7 +254,7 @@ def _assert_cov(cov, cov_desired, tol=0.005, nfree=True):
assert_equal(cov.ch_names, cov_desired.ch_names)
err = (linalg.norm(cov.data - cov_desired.data, ord='fro') /
linalg.norm(cov.data, ord='fro'))
assert_true(err < tol, msg='%s >= %s' % (err, tol))
assert err < tol, '%s >= %s' % (err, tol)
if nfree:
assert_equal(cov.nfree, cov_desired.nfree)
@@ -282,10 +280,10 @@ def test_cov_estimation_with_triggers():
# Test with tmin and tmax (different but not too much)
cov_tmin_tmax = compute_covariance(epochs, tmin=-0.19, tmax=-0.01)
assert_true(np.all(cov.data != cov_tmin_tmax.data))
assert np.all(cov.data != cov_tmin_tmax.data)
err = (linalg.norm(cov.data - cov_tmin_tmax.data, ord='fro') /
linalg.norm(cov_tmin_tmax.data, ord='fro'))
assert_true(err < 0.05, msg=err)
assert err < 0.05
# cov using a list of epochs and keep_sample_mean=True
epochs = [Epochs(raw, events, ev_id, tmin=-0.2, tmax=0,
@@ -293,16 +291,16 @@ def test_cov_estimation_with_triggers():
for ev_id in event_ids]
cov2 = compute_covariance(epochs, keep_sample_mean=True)
assert_array_almost_equal(cov.data, cov2.data)
assert_true(cov.ch_names == cov2.ch_names)
assert cov.ch_names == cov2.ch_names
# cov with keep_sample_mean=False using a list of epochs
cov = compute_covariance(epochs, keep_sample_mean=False)
_assert_cov(cov, read_cov(cov_fname), nfree=False)
method_params = {'empirical': {'assume_centered': False}}
assert_raises(ValueError, compute_covariance, epochs,
pytest.raises(ValueError, compute_covariance, epochs,
keep_sample_mean=False, method_params=method_params)
assert_raises(ValueError, compute_covariance, epochs,
pytest.raises(ValueError, compute_covariance, epochs,
keep_sample_mean=False, method='factor_analysis')
# test IO when computation done in Python
@@ -316,8 +314,8 @@ def test_cov_estimation_with_triggers():
Epochs(raw, events[:1], None, tmin=-0.2, tmax=0,
baseline=(-0.2, -0.1), proj=False)]
# these should fail
assert_raises(ValueError, compute_covariance, epochs)
assert_raises(ValueError, compute_covariance, epochs, projs=None)
pytest.raises(ValueError, compute_covariance, epochs)
pytest.raises(ValueError, compute_covariance, epochs, projs=None)
# these should work, but won't be equal to above
with warnings.catch_warnings(record=True) as w: # too few samples warning
warnings.simplefilter('always')
@@ -333,8 +331,8 @@ def test_cov_estimation_with_triggers():
# projs checking
compute_covariance(epochs, projs=[])
assert_raises(TypeError, compute_covariance, epochs, projs='foo')
assert_raises(TypeError, compute_covariance, epochs, projs=['foo'])
pytest.raises(TypeError, compute_covariance, epochs, projs='foo')
pytest.raises(TypeError, compute_covariance, epochs, projs=['foo'])
def test_arithmetic_cov():
@@ -343,12 +341,12 @@ def test_arithmetic_cov():
cov_sum = cov + cov
assert_array_almost_equal(2 * cov.nfree, cov_sum.nfree)
assert_array_almost_equal(2 * cov.data, cov_sum.data)
assert_true(cov.ch_names == cov_sum.ch_names)
assert cov.ch_names == cov_sum.ch_names
cov += cov
assert_array_almost_equal(cov_sum.nfree, cov.nfree)
assert_array_almost_equal(cov_sum.data, cov.data)
assert_true(cov_sum.ch_names == cov.ch_names)
assert cov_sum.ch_names == cov.ch_names
def test_regularize_cov():
@@ -384,12 +382,12 @@ def test_whiten_evoked():
evoked_white = whiten_evoked(evoked, noise_cov, picks, diag=True)
whiten_baseline_data = evoked_white.data[picks][:, evoked.times < 0]
mean_baseline = np.mean(np.abs(whiten_baseline_data), axis=1)
assert_true(np.all(mean_baseline < 1.))
assert_true(np.all(mean_baseline > 0.2))
assert np.all(mean_baseline < 1.)
assert np.all(mean_baseline > 0.2)
# degenerate
cov_bad = pick_channels_cov(cov, include=evoked.ch_names[:10])
assert_raises(RuntimeError, whiten_evoked, evoked, cov_bad, picks)
pytest.raises(RuntimeError, whiten_evoked, evoked, cov_bad, picks)
@pytest.mark.slowtest
@@ -403,7 +401,7 @@ def test_rank():
ch.startswith('EEG')]
cov = prepare_noise_cov(cov, evoked.info, ch_names, None)
assert_equal(cov['eig'][0], 0.) # avg projector should set this to zero
assert_true((cov['eig'][1:] > 0).all()) # all else should be > 0
assert (cov['eig'][1:] > 0).all() # all else should be > 0
# Now do some more comprehensive tests
raw_sample = read_raw_fif(raw_fname)
@@ -483,7 +481,7 @@ def test_rank():
def test_cov_scaling():
"""Test rescaling covs"""
"""Test rescaling covs."""
evoked = read_evokeds(ave_fname, condition=0, baseline=(None, 0),
proj=True)
cov = read_cov(cov_fname)['data']
@@ -499,12 +497,12 @@ def test_cov_scaling():
_apply_scaling_cov(cov2, picks_list, scalings=scalings)
_apply_scaling_cov(cov, picks_list, scalings=scalings)
assert_array_equal(cov, cov2)
assert_true(cov.max() > 1)
assert cov.max() > 1
_undo_scaling_cov(cov2, picks_list, scalings=scalings)
_undo_scaling_cov(cov, picks_list, scalings=scalings)
assert_array_equal(cov, cov2)
assert_true(cov.max() < 1)
assert cov.max() < 1
data = evoked.data.copy()
_apply_scaling_array(data, picks_list, scalings=scalings)
@@ -555,7 +553,7 @@ def test_auto_low_rank():
assert_equal(msg % (n_features + 5, n_features), '%s' % w[0].message)
method_params = {'iter_n_components': [n_features + 5]}
assert_raises(ValueError, _auto_low_rank_model, X, mode='foo',
pytest.raises(ValueError, _auto_low_rank_model, X, mode='foo',
n_jobs=n_jobs, method_params=method_params, cv=cv)
@@ -594,27 +592,23 @@ def test_compute_covariance_auto_reg():
# here we have diagnoal or no regularization.
cov_b['method'] == 'empirical'):
assert_true(not np.any(
cov_a['data'][diag_mask] ==
cov_b['data'][diag_mask]))
assert not np.any(cov_a['data'][diag_mask] ==
cov_b['data'][diag_mask])
# but the rest is the same
assert_array_equal(
cov_a['data'][off_diag_mask],
cov_b['data'][off_diag_mask])
assert_array_equal(cov_a['data'][off_diag_mask],
cov_b['data'][off_diag_mask])
else:
# and here we have shrinkage everywhere.
assert_true(not np.any(
cov_a['data'][diag_mask] ==
cov_b['data'][diag_mask]))
assert not np.any(cov_a['data'][diag_mask] ==
cov_b['data'][diag_mask])
assert_true(not np.any(
cov_a['data'][diag_mask] ==
cov_b['data'][diag_mask]))
assert not np.any(cov_a['data'][diag_mask] ==
cov_b['data'][diag_mask])
logliks = [c['loglik'] for c in covs]
assert_true(np.diff(logliks).max() <= 0) # descending order
assert np.diff(logliks).max() <= 0 # descending order
methods = ['empirical', 'factor_analysis', 'ledoit_wolf', 'oas', 'pca',
'shrunk', 'shrinkage']
@@ -639,10 +633,10 @@ def test_compute_covariance_auto_reg():
assert cov3[0]['method'] == cov4['method'] # ordering
# invalid prespecified method
assert_raises(ValueError, compute_covariance, epochs, method='pizza')
pytest.raises(ValueError, compute_covariance, epochs, method='pizza')
# invalid scalings
assert_raises(ValueError, compute_covariance, epochs, method='shrunk',
pytest.raises(ValueError, compute_covariance, epochs, method='shrunk',
scalings=dict(misc=123))
+7 -9
View File
@@ -1,22 +1,20 @@
from nose.tools import assert_equal, assert_true
from copy import deepcopy
from mne.defaults import _handle_default
def test_handle_default():
"""Test mutable default
"""
"""Test mutable default."""
x = deepcopy(_handle_default('scalings'))
y = _handle_default('scalings')
z = _handle_default('scalings', dict(mag=1, grad=2))
w = _handle_default('scalings', {})
assert_equal(set(x.keys()), set(y.keys()))
assert_equal(set(x.keys()), set(z.keys()))
assert set(x.keys()) == set(y.keys())
assert set(x.keys()) == set(z.keys())
for key in x.keys():
assert_equal(x[key], y[key])
assert_equal(x[key], w[key])
assert x[key] == y[key]
assert x[key] == w[key]
if key in ('mag', 'grad'):
assert_true(x[key] != z[key])
assert x[key] != z[key]
else:
assert_equal(x[key], z[key])
assert x[key] == z[key]
+28 -28
View File
@@ -2,8 +2,7 @@ import os.path as op
import warnings
import numpy as np
from nose.tools import assert_true, assert_equal, assert_raises
from numpy.testing import assert_allclose, assert_array_equal
from numpy.testing import assert_allclose, assert_array_equal, assert_equal
import pytest
from mne import (read_dipole, read_forward_solution,
@@ -143,8 +142,8 @@ def test_dipole_fitting():
# Sanity check: do our residuals have less power than orig data?
data_rms = np.sqrt(np.sum(evoked.data ** 2, axis=0))
resi_rms = np.sqrt(np.sum(residuals ** 2, axis=0))
assert_true((data_rms > resi_rms * 0.95).all(),
msg='%s (factor: %s)' % ((data_rms / resi_rms).min(), 0.95))
assert (data_rms > resi_rms * 0.95).all(), \
'%s (factor: %s)' % ((data_rms / resi_rms).min(), 0.95)
# Compare to original points
transform_surface_to(fwd['src'][0], 'head', fwd['mri_head_t'])
@@ -157,7 +156,7 @@ def test_dipole_fitting():
# MNE-C skips the last "time" point :(
out = dip.crop(dip_c.times[0], dip_c.times[-1])
assert_true(dip is out)
assert (dip is out)
src_rr, src_nn = src_rr[:-1], src_nn[:-1]
# check that we did about as well
@@ -172,14 +171,14 @@ def test_dipole_fitting():
amp_errs += [np.sqrt(np.mean((amp - d.amplitude) ** 2))]
gofs += [np.mean(d.gof)]
factor = 0.8
assert_true(dists[0] / factor >= dists[1], 'dists: %s' % dists)
assert_true(corrs[0] * factor <= corrs[1], 'corrs: %s' % corrs)
assert_true(gc_dists[0] / factor >= gc_dists[1] * 0.8,
'gc-dists (ori): %s' % gc_dists)
assert_true(amp_errs[0] / factor >= amp_errs[1],
'amplitude errors: %s' % amp_errs)
assert dists[0] / factor >= dists[1], 'dists: %s' % dists
assert corrs[0] * factor <= corrs[1], 'corrs: %s' % corrs
assert gc_dists[0] / factor >= gc_dists[1] * 0.8, \
'gc-dists (ori): %s' % gc_dists
assert amp_errs[0] / factor >= amp_errs[1],\
'amplitude errors: %s' % amp_errs
# This one is weird because our cov/sim/picking is weird
assert_true(gofs[0] * factor <= gofs[1] * 2, 'gof: %s' % gofs)
assert gofs[0] * factor <= gofs[1] * 2, 'gof: %s' % gofs
@testing.requires_testing_data
@@ -195,24 +194,24 @@ def test_dipole_fitting_fixed():
assert_equal(len(evoked_crop.times), 1)
cov = read_cov(fname_cov)
dip_seq, resid = fit_dipole(evoked_crop, cov, sphere)
assert_true(isinstance(dip_seq, Dipole))
assert (isinstance(dip_seq, Dipole))
assert_equal(len(dip_seq.times), 1)
pos, ori, gof = dip_seq.pos[0], dip_seq.ori[0], dip_seq.gof[0]
amp = dip_seq.amplitude[0]
# Fix position, allow orientation to change
dip_free, resid_free = fit_dipole(evoked, cov, sphere, pos=pos)
assert_true(isinstance(dip_free, Dipole))
assert (isinstance(dip_free, Dipole))
assert_allclose(dip_free.times, evoked.times)
assert_allclose(np.tile(pos[np.newaxis], (len(evoked.times), 1)),
dip_free.pos)
assert_allclose(ori, dip_free.ori[t_idx]) # should find same ori
assert_true(np.dot(dip_free.ori, ori).mean() < 0.9) # but few the same
assert (np.dot(dip_free.ori, ori).mean() < 0.9) # but few the same
assert_allclose(gof, dip_free.gof[t_idx]) # ... same gof
assert_allclose(amp, dip_free.amplitude[t_idx]) # and same amp
assert_allclose(resid, resid_free[:, [t_idx]])
# Fix position and orientation
dip_fixed, resid_fixed = fit_dipole(evoked, cov, sphere, pos=pos, ori=ori)
assert_true(isinstance(dip_fixed, DipoleFixed))
assert (isinstance(dip_fixed, DipoleFixed))
assert_allclose(dip_fixed.times, evoked.times)
assert_allclose(dip_fixed.info['chs'][0]['loc'][:3], pos)
assert_allclose(dip_fixed.info['chs'][0]['loc'][3:6], ori)
@@ -225,11 +224,11 @@ def test_dipole_fitting_fixed():
# Degenerate conditions
evoked_nan = evoked.copy().crop(0, 0)
evoked_nan.data[0, 0] = None
assert_raises(ValueError, fit_dipole, evoked_nan, cov, sphere)
assert_raises(ValueError, fit_dipole, evoked, cov, sphere, ori=[1, 0, 0])
assert_raises(ValueError, fit_dipole, evoked, cov, sphere, pos=[0, 0, 0],
pytest.raises(ValueError, fit_dipole, evoked_nan, cov, sphere)
pytest.raises(ValueError, fit_dipole, evoked, cov, sphere, ori=[1, 0, 0])
pytest.raises(ValueError, fit_dipole, evoked, cov, sphere, pos=[0, 0, 0],
ori=[2, 0, 0])
assert_raises(ValueError, fit_dipole, evoked, cov, sphere, pos=[0.1, 0, 0])
pytest.raises(ValueError, fit_dipole, evoked, cov, sphere, pos=[0.1, 0, 0])
# copying
dip_fixed_2 = dip_fixed.copy()
dip_fixed_2.data[:] = 0.
@@ -287,9 +286,9 @@ def test_min_distance_fit_dipole():
dist = _compute_depth(dip, fname_bem, fname_trans, subject, subjects_dir)
# Constraints are not exact, so bump the minimum slightly
assert_true(min_dist - 0.1 < (dist[0] * 1000.) < (min_dist + 1.))
assert (min_dist - 0.1 < (dist[0] * 1000.) < (min_dist + 1.))
assert_raises(ValueError, fit_dipole, evoked, cov, fname_bem, fname_trans,
pytest.raises(ValueError, fit_dipole, evoked, cov, fname_bem, fname_trans,
-1.)
@@ -345,7 +344,7 @@ def test_accuracy():
# 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())
assert ((np.percentile(ds, [50, 90]) < [0.0005, perc_90]).all())
@testing.requires_testing_data
@@ -358,7 +357,7 @@ def test_dipole_fixed():
_check_roundtrip_fixed(dip)
with warnings.catch_warnings(record=True) as w: # unused fields
dip_txt = read_dipole(fname_xfit_dip_txt)
assert_true(any('extra fields' in str(ww.message) for ww in w))
assert (any('extra fields' in str(ww.message) for ww in w))
assert_allclose(dip.info['chs'][0]['loc'][:3], dip_txt.pos[0])
assert_allclose(dip_txt.amplitude[0], 12.1e-9)
with warnings.catch_warnings(record=True): # unused fields
@@ -367,7 +366,7 @@ def test_dipole_fixed():
def _check_roundtrip_fixed(dip):
"""Helper to test roundtrip IO for fixed dipoles."""
"""Check roundtrip IO for fixed dipoles."""
tempdir = _TempDir()
dip.save(op.join(tempdir, 'test-dip.fif.gz'))
dip_read = read_dipole(op.join(tempdir, 'test-dip.fif.gz'))
@@ -384,8 +383,8 @@ def _check_roundtrip_fixed(dip):
def test_get_phantom_dipoles():
"""Test getting phantom dipole locations."""
assert_raises(ValueError, get_phantom_dipoles, 0)
assert_raises(ValueError, get_phantom_dipoles, 'foo')
pytest.raises(ValueError, get_phantom_dipoles, 0)
pytest.raises(ValueError, get_phantom_dipoles, 'foo')
for kind in ('vectorview', 'otaniemi'):
pos, ori = get_phantom_dipoles(kind)
assert_equal(pos.shape, (32, 3))
@@ -407,7 +406,7 @@ def test_confidence():
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))
assert ("['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%
@@ -418,4 +417,5 @@ def test_confidence():
assert_allclose(dip_check.conf[key], dip_xfit.conf[key],
rtol=1.5e-1, err_msg=key)
run_tests_if_main(False)
+7 -3
View File
@@ -47,6 +47,7 @@ public_modules = [
def get_name(func):
"""Get the name."""
parts = []
module = inspect.getmodule(func)
if module:
@@ -61,6 +62,7 @@ def get_name(func):
_docstring_ignores = [
'mne.io.Info', # Parameters
'mne.io.write', # always ignore these
'mne.datasets.sample.sample.requires_sample_data',
# Deprecations
]
@@ -69,7 +71,7 @@ _tab_ignores = [
def check_parameters_match(func, doc=None):
"""Helper to check docstring, returns list of incorrect results"""
"""Check docstring, return list of incorrect results."""
from numpydoc import docscrape
incorrect = []
name_ = get_name(func)
@@ -155,7 +157,7 @@ def test_docstring_parameters():
def test_tabs():
"""Test that there are no tabs in our source files"""
"""Test that there are no tabs in our source files."""
# avoid importing modules that require mayavi if mayavi is not installed
ignore = _tab_ignores[:]
try:
@@ -239,6 +241,7 @@ plot_source_spectrogram
prepare_inverse_operator
read_fiducials
read_tag
requires_sample_data
rescale
simulate_noise_evoked
source_estimate_quantification
@@ -254,9 +257,10 @@ def test_documented():
public_modules_ = public_modules[:]
try:
import mayavi # noqa: F401, analysis:ignore
public_modules_.append('mne.gui')
except ImportError:
pass
else:
public_modules_.append('mne.gui')
doc_file = op.abspath(op.join(op.dirname(__file__), '..', '..', 'doc',
'python_reference.rst'))
+212 -214
View File
File diff suppressed because it is too large Load Diff
+35 -35
View File
@@ -1,11 +1,11 @@
import os.path as op
import os
import warnings
from nose.tools import assert_true, assert_raises
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_array_equal,
assert_equal, assert_allclose)
import warnings
import pytest
from mne import (read_events, write_events, make_fixed_length_events,
find_events, pick_events, find_stim_steps, pick_channels,
@@ -43,8 +43,8 @@ def test_fix_stim():
raw._data[raw.ch_names.index('STI 014'), :3] = [0, -32765, 0]
with warnings.catch_warnings(record=True) as w:
events = find_events(raw, 'STI 014')
assert_true(len(w) >= 1)
assert_true(any('STI016' in str(ww.message) for ww in w))
assert (len(w) >= 1)
assert (any('STI016' in str(ww.message) for ww in w))
assert_array_equal(events[0], [raw.first_samp + 1, 0, 32765])
events = find_events(raw, 'STI 014', uint_cast=True)
assert_array_equal(events[0], [raw.first_samp + 1, 0, 32771])
@@ -55,19 +55,19 @@ def test_add_events():
# need preload
raw = read_raw_fif(raw_fname)
events = np.array([[raw.first_samp, 0, 1]])
assert_raises(RuntimeError, raw.add_events, events, 'STI 014')
pytest.raises(RuntimeError, raw.add_events, events, 'STI 014')
raw = read_raw_fif(raw_fname, preload=True)
orig_events = find_events(raw, 'STI 014')
# add some events
events = np.array([raw.first_samp, 0, 1])
assert_raises(ValueError, raw.add_events, events, 'STI 014') # bad shape
pytest.raises(ValueError, raw.add_events, events, 'STI 014') # bad shape
events[0] = raw.first_samp + raw.n_times + 1
events = events[np.newaxis, :]
assert_raises(ValueError, raw.add_events, events, 'STI 014') # bad time
pytest.raises(ValueError, raw.add_events, events, 'STI 014') # bad time
events[0, 0] = raw.first_samp - 1
assert_raises(ValueError, raw.add_events, events, 'STI 014') # bad time
pytest.raises(ValueError, raw.add_events, events, 'STI 014') # bad time
events[0, 0] = raw.first_samp + 1 # can't actually be first_samp
assert_raises(ValueError, raw.add_events, events, 'STI FOO')
pytest.raises(ValueError, raw.add_events, events, 'STI FOO')
raw.add_events(events, 'STI 014')
new_events = find_events(raw, 'STI 014')
assert_array_equal(new_events, np.concatenate((events, orig_events)))
@@ -128,7 +128,7 @@ def test_io_events():
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
events2 = read_events(fname_txt_mpr, mask=0, mask_type='not_and')
assert_true(sum('first row of' in str(ww.message) for ww in w) == 1)
assert (sum('first row of' in str(ww.message) for ww in w) == 1)
assert_array_almost_equal(events, events2)
# Test old format text file IO
@@ -193,7 +193,7 @@ def test_find_events():
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
events22 = read_events(fname, mask=3, mask_type='not_and')
assert_true(sum('events masked' in str(ww.message) for ww in w) == 1)
assert (sum('events masked' in str(ww.message) for ww in w) == 1)
assert_array_equal(events11, events22)
# Reset some data for ease of comparison
@@ -210,8 +210,8 @@ def test_find_events():
raw._data[stim_channel_idx, 5:] = 0
# 1 == '0b1', 2 == '0b10', 3 == '0b11', 4 == '0b100'
assert_raises(TypeError, find_events, raw, mask="0", mask_type='and')
assert_raises(ValueError, find_events, raw, mask=0, mask_type='blah')
pytest.raises(TypeError, find_events, raw, mask="0", mask_type='and')
pytest.raises(ValueError, find_events, raw, mask=0, mask_type='blah')
# testing mask_type. default = 'not_and'
assert_array_equal(find_events(raw, shortest_event=1, mask=1,
mask_type='not_and'),
@@ -280,7 +280,7 @@ def test_find_events():
[31, 0, 5],
[40, 0, 6],
[14399, 0, 9]])
assert_raises(ValueError, find_events, raw, output='step',
pytest.raises(ValueError, find_events, raw, output='step',
consecutive=True)
assert_array_equal(find_events(raw, output='step', consecutive=True,
shortest_event=1),
@@ -394,7 +394,7 @@ def test_make_fixed_length_events():
"""Test making events of a fixed length."""
raw = read_raw_fif(raw_fname)
events = make_fixed_length_events(raw, id=1)
assert_true(events.shape[1], 3)
assert events.shape[1] == 3
events_zero = make_fixed_length_events(raw, 1, first_samp=False)
assert_equal(events_zero[0, 0], 0)
assert_array_equal(events_zero[:, 0], events[:, 0] - raw.first_samp)
@@ -404,12 +404,12 @@ def test_make_fixed_length_events():
events = make_fixed_length_events(raw, 1, tmin, tmax, duration)
assert_equal(events.shape[0], 1)
# With bad limits (no resulting events)
assert_raises(ValueError, make_fixed_length_events, raw, 1,
pytest.raises(ValueError, make_fixed_length_events, raw, 1,
tmin, tmax - 1e-3, duration)
# not raw, bad id or duration
assert_raises(TypeError, make_fixed_length_events, raw, 2.3)
assert_raises(TypeError, make_fixed_length_events, 'not raw', 2)
assert_raises(TypeError, make_fixed_length_events, raw, 23, tmin, tmax,
pytest.raises(TypeError, make_fixed_length_events, raw, 2.3)
pytest.raises(TypeError, make_fixed_length_events, 'not raw', 2)
pytest.raises(TypeError, make_fixed_length_events, raw, 23, tmin, tmax,
'abc')
# Let's try some ugly sample rate/sample count combos
@@ -444,7 +444,7 @@ def test_define_events():
n_miss = events_[events_[:, 2] == 99].shape[0]
n_target_ = events_[events_[:, 2] == 42].shape[0]
assert_true(n_target_ == (n_target - n_miss))
assert (n_target_ == (n_target - n_miss))
events = np.array([[0, 0, 1],
[375, 0, 2],
@@ -467,39 +467,39 @@ def test_define_events():
@testing.requires_testing_data
def test_acqparser():
""" Test AcqParserFIF """
"""Test AcqParserFIF."""
# no acquisition parameters
assert_raises(ValueError, AcqParserFIF, {'acq_pars': ''})
pytest.raises(ValueError, AcqParserFIF, {'acq_pars': ''})
# invalid acquisition parameters
assert_raises(ValueError, AcqParserFIF, {'acq_pars': 'baaa'})
assert_raises(ValueError, AcqParserFIF, {'acq_pars': 'ERFVersion\n1'})
pytest.raises(ValueError, AcqParserFIF, {'acq_pars': 'baaa'})
pytest.raises(ValueError, AcqParserFIF, {'acq_pars': 'ERFVersion\n1'})
# test oldish file
raw = read_raw_fif(raw_fname, preload=False)
acqp = AcqParserFIF(raw.info)
# test __repr__()
assert_true(repr(acqp))
assert (repr(acqp))
# old file should trigger compat mode
assert_true(acqp.compat)
assert (acqp.compat)
# count events and categories
assert_equal(len(acqp.categories), 6)
assert_equal(len(acqp._categories), 17)
assert_equal(len(acqp.events), 6)
assert_equal(len(acqp._events), 17)
# get category
assert_true(acqp['Surprise visual'])
assert (acqp['Surprise visual'])
# test TRIUX file
raw = read_raw_fif(fname_raw_elekta, preload=False)
acqp = raw.acqparser
assert_true(acqp is raw.acqparser) # same one, not regenerated
assert (acqp is raw.acqparser) # same one, not regenerated
# test __repr__()
assert_true(repr(acqp))
assert (repr(acqp))
# this file should not be in compatibility mode
assert_true(not acqp.compat)
assert (not acqp.compat)
# nonexisting category
assert_raises(KeyError, acqp.__getitem__, 'does not exist')
assert_raises(KeyError, acqp.get_condition, raw, 'foo')
pytest.raises(KeyError, acqp.__getitem__, 'does not exist')
pytest.raises(KeyError, acqp.get_condition, raw, 'foo')
# category not a string
assert_raises(TypeError, acqp.__getitem__, 0)
pytest.raises(TypeError, acqp.__getitem__, 0)
# number of events / categories
assert_equal(len(acqp), 7)
assert_equal(len(acqp.categories), 7)
@@ -507,12 +507,12 @@ def test_acqparser():
assert_equal(len(acqp.events), 6)
assert_equal(len(acqp._events), 32)
# get category
assert_true(acqp['Test event 5'])
assert (acqp['Test event 5'])
@testing.requires_testing_data
def test_acqparser_averaging():
""" Test averaging with AcqParserFIF vs. Elekta software """
"""Test averaging with AcqParserFIF vs. Elekta software."""
raw = read_raw_fif(fname_raw_elekta, preload=True)
acqp = AcqParserFIF(raw.info)
for cat in acqp.categories:
+68 -70
View File
@@ -13,7 +13,6 @@ import numpy as np
from scipy import fftpack
from numpy.testing import (assert_array_almost_equal, assert_equal,
assert_array_equal, assert_allclose)
from nose.tools import assert_true, assert_raises, assert_not_equal
import pytest
from mne import (equalize_channels, pick_types, read_evokeds, write_evokeds,
@@ -84,7 +83,7 @@ def test_savgol_filter():
data = np.abs(fftpack.fft(evoked.data))
match_mask = np.logical_and(freqs >= 0, freqs <= h_freq / 2.)
mismatch_mask = np.logical_and(freqs >= h_freq * 2, freqs < 50.)
assert_raises(ValueError, evoked.savgol_filter, evoked.info['sfreq'])
pytest.raises(ValueError, evoked.savgol_filter, evoked.info['sfreq'])
evoked_sg = evoked.copy().savgol_filter(h_freq)
data_filt = np.abs(fftpack.fft(evoked_sg.data))
# decent in pass-band
@@ -92,8 +91,8 @@ def test_savgol_filter():
np.mean(data_filt[:, match_mask], 0),
rtol=1e-4, atol=1e-2)
# suppression in stop-band
assert_true(np.mean(data[:, mismatch_mask]) >
np.mean(data_filt[:, mismatch_mask]) * 5)
assert (np.mean(data[:, mismatch_mask]) >
np.mean(data_filt[:, mismatch_mask]) * 5)
# original preserved
assert_allclose(data, np.abs(fftpack.fft(evoked.data)), atol=1e-16)
@@ -104,10 +103,10 @@ def test_hash_evoked():
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))
assert (pickle.dumps(ave) == pickle.dumps(ave_2))
ave_2.data[0, 0] -= 1
assert_not_equal(hash(ave), hash(ave_2))
assert hash(ave) != hash(ave_2)
@pytest.mark.slowtest
@@ -120,23 +119,23 @@ def test_io_evoked():
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 (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))
assert (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))
assert (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,
pytest.raises(ValueError, read_evokeds, fname, condition, kind='stderr')
pytest.raises(ValueError, read_evokeds, fname, condition,
kind='standard_error')
ave3 = read_evokeds(fname, condition)
assert_array_almost_equal(ave.data, ave3.data, 19)
@@ -167,26 +166,26 @@ def test_io_evoked():
assert_naming(w, 'test_evoked.py', 2)
# constructor
assert_raises(TypeError, Evoked, fname)
pytest.raises(TypeError, Evoked, fname)
# MaxShield
fname_ms = op.join(tempdir, 'test-ave.fif')
assert_true(ave.info['maxshield'] is False)
assert (ave.info['maxshield'] is False)
ave.info['maxshield'] = True
ave.save(fname_ms)
assert_raises(ValueError, read_evokeds, fname_ms)
pytest.raises(ValueError, read_evokeds, fname_ms)
with warnings.catch_warnings(record=True) as w:
aves = read_evokeds(fname_ms, allow_maxshield=True)
assert_true(all('Elekta' in str(ww.message) for ww in w))
assert_true(all(ave.info['maxshield'] is True for ave in aves))
assert (all('Elekta' in str(ww.message) for ww in w))
assert (all(ave.info['maxshield'] is True for ave in aves))
with warnings.catch_warnings(record=True) as w:
aves = read_evokeds(fname_ms, allow_maxshield='yes')
assert_equal(len(w), 0)
assert_true(all(ave.info['maxshield'] is True for ave in aves))
assert (all(ave.info['maxshield'] is True for ave in aves))
def test_shift_time_evoked():
""" Test for shifting of time scale."""
"""Test for shifting of time scale."""
tempdir = _TempDir()
# Shift backward
ave = read_evokeds(fname, 0)
@@ -206,8 +205,7 @@ def test_shift_time_evoked():
ave_normal = read_evokeds(fname, 0)
ave_relative = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)
assert_true(np.allclose(ave_normal.data, ave_relative.data,
atol=1e-16, rtol=1e-3))
assert_allclose(ave_normal.data, ave_relative.data, atol=1e-16, rtol=1e-3)
assert_array_almost_equal(ave_normal.times, ave_relative.times, 10)
assert_equal(ave_normal.last, ave_relative.last)
@@ -220,8 +218,7 @@ def test_shift_time_evoked():
ave_absolute = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)
assert_true(np.allclose(ave_normal.data, ave_absolute.data,
atol=1e-16, rtol=1e-3))
assert_allclose(ave_normal.data, ave_absolute.data, atol=1e-16, rtol=1e-3)
assert_equal(ave_absolute.first, int(-0.3 * ave.info['sfreq']))
@@ -252,8 +249,8 @@ def test_evoked_resample():
# 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])
assert (len(ave_up.times) == 2 * len(ave_normal.times))
assert (ave_up.data.shape[1] == 2 * ave_normal.data.shape[1])
def test_evoked_filter():
@@ -274,19 +271,19 @@ def test_evoked_detrend():
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))
assert_allclose(ave.data[picks], ave_normal.data[picks],
rtol=1e-8, atol=1e-16)
@requires_pandas
def test_to_data_frame():
"""Test evoked Pandas exporter."""
ave = read_evokeds(fname, 0)
assert_raises(ValueError, ave.to_data_frame, picks=np.arange(400))
pytest.raises(ValueError, ave.to_data_frame, picks=np.arange(400))
df = ave.to_data_frame()
assert_true((df.columns == ave.ch_names).all())
assert ((df.columns == ave.ch_names).all())
df = ave.to_data_frame(index=None).reset_index()
assert_true('time' in df.columns)
assert ('time' in df.columns)
assert_array_equal(df.values[:, 1], ave.data[0] * 1e13)
assert_array_equal(df.values[:, 3], ave.data[2] * 1e15)
@@ -295,23 +292,23 @@ 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']))
assert (all(p['active'] == proj for p in ave.info['projs']))
# test adding / deleting proj
if proj:
assert_raises(ValueError, ave.add_proj, [],
pytest.raises(ValueError, ave.add_proj, [],
{'remove_existing': True})
assert_raises(ValueError, ave.del_proj, 0)
pytest.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)
assert (len(ave.info['projs']) == n_proj - 1)
# Test that already existing projections are not added.
ave.add_proj(projs, remove_existing=False)
assert_true(len(ave.info['projs']) == n_proj)
assert (len(ave.info['projs']) == n_proj)
ave.add_proj(projs[:-1], remove_existing=True)
assert_true(len(ave.info['projs']) == n_proj - 1)
assert (len(ave.info['projs']) == n_proj - 1)
ave = read_evokeds(fname, condition=0, proj=False)
data = ave.data.copy()
@@ -322,26 +319,26 @@ def test_evoked_proj():
def test_get_peak():
"""Test peak getter."""
evoked = read_evokeds(fname, condition=0, proj=True)
assert_raises(ValueError, evoked.get_peak, ch_type='mag', tmin=1)
assert_raises(ValueError, evoked.get_peak, ch_type='mag', tmax=0.9)
assert_raises(ValueError, evoked.get_peak, ch_type='mag', tmin=0.02,
pytest.raises(ValueError, evoked.get_peak, ch_type='mag', tmin=1)
pytest.raises(ValueError, evoked.get_peak, ch_type='mag', tmax=0.9)
pytest.raises(ValueError, evoked.get_peak, ch_type='mag', tmin=0.02,
tmax=0.01)
assert_raises(ValueError, evoked.get_peak, ch_type='mag', mode='foo')
assert_raises(RuntimeError, evoked.get_peak, ch_type=None, mode='foo')
assert_raises(ValueError, evoked.get_peak, ch_type='misc', mode='foo')
pytest.raises(ValueError, evoked.get_peak, ch_type='mag', mode='foo')
pytest.raises(RuntimeError, evoked.get_peak, ch_type=None, mode='foo')
pytest.raises(ValueError, evoked.get_peak, ch_type='misc', mode='foo')
ch_name, time_idx = evoked.get_peak(ch_type='mag')
assert_true(ch_name in evoked.ch_names)
assert_true(time_idx in evoked.times)
assert (ch_name in evoked.ch_names)
assert (time_idx in evoked.times)
ch_name, time_idx, max_amp = evoked.get_peak(ch_type='mag',
time_as_index=True,
return_amplitude=True)
assert_true(time_idx < len(evoked.times))
assert (time_idx < len(evoked.times))
assert_equal(ch_name, 'MEG 1421')
assert_allclose(max_amp, 7.17057e-13, rtol=1e-5)
assert_raises(ValueError, evoked.get_peak, ch_type='mag', merge_grads=True)
pytest.raises(ValueError, evoked.get_peak, ch_type='mag', merge_grads=True)
ch_name, time_idx = evoked.get_peak(ch_type='grad', merge_grads=True)
assert_equal(ch_name, 'MEG 244X')
@@ -365,8 +362,8 @@ def test_get_peak():
assert_equal(time_idx, 2)
assert_allclose(max_amp, 2.)
assert_raises(ValueError, _get_peak, data + 1e3, times, mode='neg')
assert_raises(ValueError, _get_peak, data - 1e3, times, mode='pos')
pytest.raises(ValueError, _get_peak, data + 1e3, times, mode='neg')
pytest.raises(ValueError, _get_peak, data - 1e3, times, mode='pos')
def test_drop_channels_mixin():
@@ -388,7 +385,7 @@ def test_drop_channels_mixin():
assert_equal(len(ch_names), len(evoked.data))
for ch_names in ([1, 2], "fake", ["fake"]):
assert_raises(ValueError, evoked.drop_channels, ch_names)
pytest.raises(ValueError, evoked.drop_channels, ch_names)
def test_pick_channels_mixin():
@@ -407,12 +404,12 @@ def test_pick_channels_mixin():
assert_equal(len(ch_names), len(evoked.data))
evoked = read_evokeds(fname, condition=0, proj=True)
assert_true('meg' in evoked)
assert_true('eeg' in evoked)
assert ('meg' in evoked)
assert ('eeg' in evoked)
evoked.pick_types(meg=False, eeg=True)
assert_true('meg' not in evoked)
assert_true('eeg' in evoked)
assert_true(len(evoked.ch_names) == 60)
assert ('meg' not in evoked)
assert ('eeg' in evoked)
assert (len(evoked.ch_names) == 60)
def test_equalize_channels():
@@ -463,8 +460,8 @@ def test_arithmetic():
ev1.comment = None
ev = combine_evoked([ev1, -ev2], weights=[1, -1])
assert_equal(ev.comment.count('unknown'), 2)
assert_true('-unknown' in ev.comment)
assert_true(' + ' in ev.comment)
assert ('-unknown' in ev.comment)
assert (' + ' in ev.comment)
ev1.comment = old_comment1
ev2.comment = old_comment2
@@ -481,8 +478,8 @@ def test_arithmetic():
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])
pytest.raises(ValueError, combine_evoked, [ev1, ev2], weights='foo')
pytest.raises(ValueError, combine_evoked, [ev1, ev2], weights=[1])
# grand average
evoked1, evoked2 = read_evokeds(fname, condition=[0, 1], proj=True)
@@ -494,7 +491,7 @@ def test_arithmetic():
assert_equal(gave.data.shape, [len(ch_names), evoked1.data.shape[1]])
assert_equal(ch_names, gave.ch_names)
assert_equal(gave.nave, 2)
assert_raises(TypeError, grand_average, [1, evoked1])
pytest.raises(TypeError, grand_average, [1, evoked1])
def test_array_epochs():
@@ -534,14 +531,14 @@ def test_array_epochs():
assert_equal(evoked1.nave, evoked3.nave)
# test kind check
assert_raises(TypeError, EvokedArray, data1, info, tmin=0, kind=1)
assert_raises(ValueError, EvokedArray, data1, info, kind='mean')
pytest.raises(TypeError, EvokedArray, data1, info, tmin=0, kind=1)
pytest.raises(ValueError, EvokedArray, data1, info, kind='mean')
# test match between channels info and data
ch_names = ['EEG %03d' % (i + 1) for i in range(19)]
types = ['eeg'] * 19
info = create_info(ch_names, sfreq, types)
assert_raises(ValueError, EvokedArray, data1, info, tmin=-0.01)
pytest.raises(ValueError, EvokedArray, data1, info, tmin=-0.01)
def test_time_as_index():
@@ -564,24 +561,24 @@ def test_add_channels():
evoked_stim = evoked.copy().pick_types(meg=False, stim=True)
evoked_eeg_meg = evoked.copy().pick_types(meg=True, eeg=True)
evoked_new = evoked_meg.copy().add_channels([evoked_eeg, evoked_stim])
assert_true(all(ch in evoked_new.ch_names
for ch in evoked_stim.ch_names + evoked_meg.ch_names))
assert (all(ch in evoked_new.ch_names
for ch in evoked_stim.ch_names + evoked_meg.ch_names))
evoked_new = evoked_meg.copy().add_channels([evoked_eeg])
assert_true(ch in evoked_new.ch_names for ch in evoked.ch_names)
assert (ch in evoked_new.ch_names for ch in evoked.ch_names)
assert_array_equal(evoked_new.data, evoked_eeg_meg.data)
assert_true(all(ch not in evoked_new.ch_names
for ch in evoked_stim.ch_names))
assert (all(ch not in evoked_new.ch_names
for ch in evoked_stim.ch_names))
# Now test errors
evoked_badsf = evoked_eeg.copy()
evoked_badsf.info['sfreq'] = 3.1415927
evoked_eeg = evoked_eeg.crop(-.1, .1)
assert_raises(RuntimeError, evoked_meg.add_channels, [evoked_badsf])
assert_raises(AssertionError, evoked_meg.add_channels, [evoked_eeg])
assert_raises(ValueError, evoked_meg.add_channels, [evoked_meg])
assert_raises(TypeError, evoked_meg.add_channels, evoked_badsf)
pytest.raises(RuntimeError, evoked_meg.add_channels, [evoked_badsf])
pytest.raises(AssertionError, evoked_meg.add_channels, [evoked_eeg])
pytest.raises(ValueError, evoked_meg.add_channels, [evoked_meg])
pytest.raises(TypeError, evoked_meg.add_channels, evoked_badsf)
def test_evoked_baseline():
@@ -598,4 +595,5 @@ def test_evoked_baseline():
assert_allclose(evoked.data, np.zeros_like(evoked.data))
run_tests_if_main()
+2 -3
View File
@@ -259,7 +259,6 @@ def test_resample():
def test_resample_stim_channel():
"""Test resampling of stim channels."""
# Downsampling
assert_array_equal(
_resample_stim_channels([1, 0, 0, 0, 2, 0, 0, 0], 1, 2),
@@ -421,7 +420,7 @@ def test_filters():
def test_filter_auto():
"""Test filter auto parameters"""
"""Test filter auto parameters."""
# test that our overlap-add filtering doesn't introduce strange
# artifacts (from mne_analyze mailing list 2015/06/25)
N = 300
@@ -459,7 +458,7 @@ def test_filter_auto():
def test_cuda():
"""Test CUDA-based filtering"""
"""Test CUDA-based filtering."""
# NOTE: don't make test_cuda() the last test, or pycuda might spew
# some warnings about clean-up failing
# Also, using `n_jobs='cuda'` on a non-CUDA system should be fine,
+2 -1
View File
@@ -15,7 +15,7 @@ from mne.fixes import _sosfiltfilt as mne_sosfiltfilt, _sph_harm
def test_filtfilt():
"""Test SOS filtfilt replacement"""
"""Test SOS filtfilt replacement."""
x = np.r_[1, np.zeros(100)]
# Filter with an impulse
y = filtfilt([1, 0], [1, 0], x, padlen=0)
@@ -36,4 +36,5 @@ def test_spherical_harmonics():
sph_scipy = sph_harm(order, degree, az, pol)
assert_allclose(sph, sph_scipy, atol=1e-7)
run_tests_if_main()
+1 -4
View File
@@ -25,7 +25,7 @@ if len(bad) > 0:
out.append('scipy submodules: %s' % list(bad))
# check sklearn and others
_sklearn = _pandas = _nose = _mayavi = _matplotlib = False
_sklearn = _pandas = _mayavi = _matplotlib = False
for x in sys.modules.keys():
if x.startswith('sklearn') and not _sklearn:
out.append('sklearn')
@@ -33,9 +33,6 @@ for x in sys.modules.keys():
if x.startswith('pandas') and not _pandas:
out.append('pandas')
_pandas = True
if x.startswith('nose') and not _nose:
out.append('nose')
_nose = True
if x.startswith('mayavi') and not _mayavi:
out.append('mayavi')
_mayavi = True
+69 -68
View File
@@ -7,8 +7,8 @@ import warnings
import numpy as np
from scipy import sparse
from numpy.testing import assert_array_equal, assert_array_almost_equal
from nose.tools import assert_equal, assert_true, assert_false, assert_raises
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
assert_equal)
import pytest
from mne.datasets import testing
@@ -150,6 +150,7 @@ def _stc_to_label(stc, src, smooth, subjects_dir=None):
def assert_labels_equal(l0, l1, decimal=5, comment=True, color=True):
"""Assert two labels are equal."""
if comment:
assert_equal(l0.comment, l1.comment)
if color:
@@ -178,10 +179,10 @@ def test_label_subject():
"""Test label subject name extraction."""
label = read_label(label_fname)
assert_is(label.subject, None)
assert_true('unknown' in repr(label))
assert ('unknown' in repr(label))
label = read_label(label_fname, subject='fsaverage')
assert_true(label.subject == 'fsaverage')
assert_true('fsaverage' in repr(label))
assert (label.subject == 'fsaverage')
assert ('fsaverage' in repr(label))
def test_label_addition():
@@ -201,10 +202,10 @@ def test_label_addition():
l_good.subject = 'sample'
l_bad = l1.copy()
l_bad.subject = 'foo'
assert_raises(ValueError, l_good.__add__, l_bad)
assert_raises(TypeError, l_good.__add__, 'foo')
assert_raises(ValueError, l_good.__sub__, l_bad)
assert_raises(TypeError, l_good.__sub__, 'foo')
pytest.raises(ValueError, l_good.__add__, l_bad)
pytest.raises(TypeError, l_good.__add__, 'foo')
pytest.raises(ValueError, l_good.__sub__, l_bad)
pytest.raises(TypeError, l_good.__sub__, 'foo')
# adding non-overlapping labels
l01 = l0 + l1
@@ -231,7 +232,7 @@ def test_label_addition():
assert_equal(bhl.hemi, 'both')
assert_equal(len(bhl), len(l0) + len(l2))
assert_equal(bhl.color, l02.color)
assert_true('BiHemiLabel' in repr(bhl))
assert ('BiHemiLabel' in repr(bhl))
# subtraction
assert_labels_equal(bhl - l0, l2)
assert_labels_equal(bhl - l2, l0)
@@ -241,7 +242,7 @@ def test_label_addition():
assert_equal(bhl2.color, _blend_colors(l1.color, bhl.color))
assert_array_equal((l2 + bhl).rh.vertices, bhl.rh.vertices) # rh label
assert_array_equal((bhl + bhl).lh.vertices, bhl.lh.vertices)
assert_raises(TypeError, bhl.__add__, 5)
pytest.raises(TypeError, bhl.__add__, 5)
# subtraction
bhl_ = bhl2 - l1
@@ -280,7 +281,7 @@ def test_label_in_src():
# test exception
vertices = np.append([-1], vert_in_src)
assert_raises(ValueError, Label(vertices, hemi='lh').fill, src)
pytest.raises(ValueError, Label(vertices, hemi='lh').fill, src)
# test filling empty label
label = Label([], hemi='lh')
@@ -295,8 +296,8 @@ def test_label_io_and_time_course_estimates():
label = read_label(real_label_fname)
stc_label = stc.in_label(label)
assert_true(len(stc_label.times) == stc_label.data.shape[1])
assert_true(len(stc_label.vertices[0]) == stc_label.data.shape[0])
assert (len(stc_label.times) == stc_label.data.shape[1])
assert (len(stc_label.vertices[0]) == stc_label.data.shape[0])
@testing.requires_testing_data
@@ -325,11 +326,11 @@ def test_label_io():
def _assert_labels_equal(labels_a, labels_b, ignore_pos=False):
"""Make sure two sets of labels are equal"""
"""Ensure two sets of labels are equal."""
for label_a, label_b in zip(labels_a, labels_b):
assert_array_equal(label_a.vertices, label_b.vertices)
assert_true(label_a.name == label_b.name)
assert_true(label_a.hemi == label_b.hemi)
assert (label_a.name == label_b.name)
assert (label_a.hemi == label_b.hemi)
if not ignore_pos:
assert_array_equal(label_a.pos, label_b.pos)
@@ -352,7 +353,7 @@ def test_annot_io():
shutil.copy(os.path.join(surf_src, 'rh.white'), surf_dir)
# read original labels
assert_raises(IOError, read_labels_from_annot, subject, 'PALS_B12_Lobesey',
pytest.raises(IOError, read_labels_from_annot, subject, 'PALS_B12_Lobesey',
subjects_dir=tempdir)
labels = read_labels_from_annot(subject, 'PALS_B12_Lobes',
subjects_dir=tempdir)
@@ -371,8 +372,8 @@ def test_annot_io():
write_labels_to_annot(parc, subject, 'myparc2', hemi='lh',
subjects_dir=tempdir)
annot_fname = os.path.join(tempdir, subject, 'label', '%sh.myparc2.annot')
assert_true(os.path.isfile(annot_fname % 'l'))
assert_false(os.path.isfile(annot_fname % 'r'))
assert os.path.isfile(annot_fname % 'l')
assert not os.path.isfile(annot_fname % 'r')
parc1 = read_labels_from_annot(subject, 'myparc2',
annot_fname=annot_fname % 'l',
subjects_dir=tempdir)
@@ -385,17 +386,17 @@ def test_annot_io():
def test_read_labels_from_annot():
"""Test reading labels from FreeSurfer parcellation."""
# test some invalid inputs
assert_raises(ValueError, read_labels_from_annot, 'sample', hemi='bla',
pytest.raises(ValueError, read_labels_from_annot, 'sample', hemi='bla',
subjects_dir=subjects_dir)
assert_raises(ValueError, read_labels_from_annot, 'sample',
pytest.raises(ValueError, read_labels_from_annot, 'sample',
annot_fname='bla.annot', subjects_dir=subjects_dir)
# read labels using hemi specification
labels_lh = read_labels_from_annot('sample', hemi='lh',
subjects_dir=subjects_dir)
for label in labels_lh:
assert_true(label.name.endswith('-lh'))
assert_true(label.hemi == 'lh')
assert (label.name.endswith('-lh'))
assert (label.hemi == 'lh')
assert_is_not(label.color, None)
# read labels using annot_fname
@@ -403,8 +404,8 @@ def test_read_labels_from_annot():
labels_rh = read_labels_from_annot('sample', annot_fname=annot_fname,
subjects_dir=subjects_dir)
for label in labels_rh:
assert_true(label.name.endswith('-rh'))
assert_true(label.hemi == 'rh')
assert (label.name.endswith('-rh'))
assert (label.hemi == 'rh')
assert_is_not(label.color, None)
# combine the lh, rh, labels and sort them
@@ -422,18 +423,18 @@ def test_read_labels_from_annot():
_assert_labels_equal(labels_lhrh, labels_both)
# aparc has 68 cortical labels
assert_true(len(labels_both) == 68)
assert (len(labels_both) == 68)
# test regexp
label = read_labels_from_annot('sample', parc='aparc.a2009s',
regexp='Angu', subjects_dir=subjects_dir)[0]
assert_true(label.name == 'G_pariet_inf-Angular-lh')
assert (label.name == 'G_pariet_inf-Angular-lh')
# silly, but real regexp:
label = read_labels_from_annot('sample', 'aparc.a2009s',
regexp='.*-.{4,}_.{3,3}-L',
subjects_dir=subjects_dir)[0]
assert_true(label.name == 'G_oc-temp_med-Lingual-lh')
assert_raises(RuntimeError, read_labels_from_annot, 'sample', parc='aparc',
assert (label.name == 'G_oc-temp_med-Lingual-lh')
pytest.raises(RuntimeError, read_labels_from_annot, 'sample', parc='aparc',
annot_fname=annot_fname, regexp='JackTheRipper',
subjects_dir=subjects_dir)
@@ -468,24 +469,24 @@ def test_write_labels_to_annot():
# test automatic filenames
dst = op.join(tempdir, 'sample', 'label', '%s.%s.annot')
write_labels_to_annot(labels, 'sample', 'test1', subjects_dir=tempdir)
assert_true(op.exists(dst % ('lh', 'test1')))
assert_true(op.exists(dst % ('rh', 'test1')))
assert (op.exists(dst % ('lh', 'test1')))
assert (op.exists(dst % ('rh', 'test1')))
# lh only
for label in labels:
if label.hemi == 'lh':
break
write_labels_to_annot([label], 'sample', 'test2', subjects_dir=tempdir)
assert_true(op.exists(dst % ('lh', 'test2')))
assert_true(op.exists(dst % ('rh', 'test2')))
assert (op.exists(dst % ('lh', 'test2')))
assert (op.exists(dst % ('rh', 'test2')))
# rh only
for label in labels:
if label.hemi == 'rh':
break
write_labels_to_annot([label], 'sample', 'test3', subjects_dir=tempdir)
assert_true(op.exists(dst % ('lh', 'test3')))
assert_true(op.exists(dst % ('rh', 'test3')))
assert (op.exists(dst % ('lh', 'test3')))
assert (op.exists(dst % ('rh', 'test3')))
# label alone
assert_raises(TypeError, write_labels_to_annot, labels[0], 'sample',
pytest.raises(TypeError, write_labels_to_annot, labels[0], 'sample',
'test4', subjects_dir=tempdir)
# write left and right hemi labels with filenames:
@@ -522,7 +523,7 @@ def test_write_labels_to_annot():
assert_labels_equal(label, labels3[idx])
# make sure we can't overwrite things
assert_raises(ValueError, write_labels_to_annot, labels, 'sample',
pytest.raises(ValueError, write_labels_to_annot, labels, 'sample',
annot_fname=fnames[0], subjects_dir=subjects_dir)
# however, this works
@@ -538,13 +539,13 @@ def test_write_labels_to_annot():
# duplicate color
labels_[0].color = labels_[2].color
assert_raises(ValueError, write_labels_to_annot, labels_, 'sample',
pytest.raises(ValueError, write_labels_to_annot, labels_, 'sample',
annot_fname=fnames[0], overwrite=True,
subjects_dir=subjects_dir)
# invalid color inputs
labels_[0].color = (1.1, 1., 1., 1.)
assert_raises(ValueError, write_labels_to_annot, labels_, 'sample',
pytest.raises(ValueError, write_labels_to_annot, labels_, 'sample',
annot_fname=fnames[0], overwrite=True,
subjects_dir=subjects_dir)
@@ -553,7 +554,7 @@ def test_write_labels_to_annot():
cuneus_lh = labels[6]
precuneus_lh = labels[50]
labels_.append(precuneus_lh + cuneus_lh)
assert_raises(ValueError, write_labels_to_annot, labels_, 'sample',
pytest.raises(ValueError, write_labels_to_annot, labels_, 'sample',
annot_fname=fnames[0], overwrite=True,
subjects_dir=subjects_dir)
@@ -567,12 +568,12 @@ def test_write_labels_to_annot():
label0 = labels_lh[0]
label1 = labels_reloaded[-1]
assert_equal(label1.name, "unknown-lh")
assert_true(np.all(np.in1d(label0.vertices, label1.vertices)))
assert (np.all(np.in1d(label0.vertices, label1.vertices)))
# unnamed labels
labels4 = labels[:]
labels4[0].name = None
assert_raises(ValueError, write_labels_to_annot, labels4,
pytest.raises(ValueError, write_labels_to_annot, labels4,
annot_fname=fnames[0])
@@ -585,7 +586,7 @@ def test_split_label():
lingual = aparc[0]
# Test input error
assert_raises(ValueError, lingual.split, 'bad_input_string')
pytest.raises(ValueError, lingual.split, 'bad_input_string')
# split with names
parts = ('lingual_post', 'lingual_ant')
@@ -651,35 +652,35 @@ def test_stc_to_label():
labels_lh, labels_rh = stc_to_label(stc, src=src, smooth=True,
connected=True)
assert_true(len(w) > 0)
assert_raises(ValueError, stc_to_label, stc, 'sample', smooth=True,
assert (len(w) > 0)
pytest.raises(ValueError, stc_to_label, stc, 'sample', smooth=True,
connected=True)
assert_raises(RuntimeError, stc_to_label, stc, smooth=True, src=src_bad,
pytest.raises(RuntimeError, stc_to_label, stc, smooth=True, src=src_bad,
connected=True)
assert_equal(len(labels_lh), 1)
assert_equal(len(labels_rh), 1)
# test getting tris
tris = labels_lh[0].get_tris(src[0]['use_tris'], vertices=stc.vertices[0])
assert_raises(ValueError, spatial_tris_connectivity, tris,
pytest.raises(ValueError, spatial_tris_connectivity, tris,
remap_vertices=False)
connectivity = spatial_tris_connectivity(tris, remap_vertices=True)
assert_true(connectivity.shape[0] == len(stc.vertices[0]))
assert (connectivity.shape[0] == len(stc.vertices[0]))
# "src" as a subject name
assert_raises(TypeError, stc_to_label, stc, src=1, smooth=False,
pytest.raises(TypeError, stc_to_label, stc, src=1, smooth=False,
connected=False, subjects_dir=subjects_dir)
assert_raises(ValueError, stc_to_label, stc, src=SourceSpaces([src[0]]),
pytest.raises(ValueError, stc_to_label, stc, src=SourceSpaces([src[0]]),
smooth=False, connected=False, subjects_dir=subjects_dir)
assert_raises(ValueError, stc_to_label, stc, src='sample', smooth=False,
pytest.raises(ValueError, stc_to_label, stc, src='sample', smooth=False,
connected=True, subjects_dir=subjects_dir)
assert_raises(ValueError, stc_to_label, stc, src='sample', smooth=True,
pytest.raises(ValueError, stc_to_label, stc, src='sample', smooth=True,
connected=False, subjects_dir=subjects_dir)
labels_lh, labels_rh = stc_to_label(stc, src='sample', smooth=False,
connected=False,
subjects_dir=subjects_dir)
assert_true(len(labels_lh) > 1)
assert_true(len(labels_rh) > 1)
assert (len(labels_lh) > 1)
assert (len(labels_rh) > 1)
# with smooth='patch'
with warnings.catch_warnings(record=True) as w: # connectedness warning
@@ -703,12 +704,12 @@ def test_morph():
for grade in [5, [np.arange(10242), np.arange(10242)], np.arange(10242)]:
label = label_orig.copy()
# this should throw an error because the label has all zero values
assert_raises(ValueError, label.morph, 'sample', 'fsaverage')
pytest.raises(ValueError, label.morph, 'sample', 'fsaverage')
label.values.fill(1)
label = label.morph(None, 'fsaverage', 5, grade, subjects_dir, 1)
label = label.morph('fsaverage', 'sample', 5, None, subjects_dir, 2)
assert_true(np.in1d(label_orig.vertices, label.vertices).all())
assert_true(len(label.vertices) < 3 * len(label_orig.vertices))
assert (np.in1d(label_orig.vertices, label.vertices).all())
assert (len(label.vertices) < 3 * len(label_orig.vertices))
vals.append(label.vertices)
assert_array_equal(vals[0], vals[1])
# make sure label smoothing can run
@@ -718,9 +719,9 @@ def test_morph():
label.hemi = hemi
with warnings.catch_warnings(record=True): # morph map maybe missing
label.morph(None, 'fsaverage', 5, verts, subjects_dir, 2)
assert_raises(TypeError, label.morph, None, 1, 5, verts,
pytest.raises(TypeError, label.morph, None, 1, 5, verts,
subjects_dir, 2)
assert_raises(TypeError, label.morph, None, 'fsaverage', 5.5, verts,
pytest.raises(TypeError, label.morph, None, 'fsaverage', 5.5, verts,
subjects_dir, 2)
with warnings.catch_warnings(record=True): # morph map could be missing
label.smooth(subjects_dir=subjects_dir) # make sure this runs
@@ -740,8 +741,8 @@ def test_grow_labels():
tgt_hemis = ['lh', 'rh']
for label, seed, hemi, sh, name in zip(labels, seeds, tgt_hemis,
should_be_in, tgt_names):
assert_true(np.any(label.vertices == seed))
assert_true(np.all(np.in1d(sh, label.vertices)))
assert (np.any(label.vertices == seed))
assert (np.all(np.in1d(sh, label.vertices)))
assert_equal(label.hemi, hemi)
assert_equal(label.name, name)
@@ -791,7 +792,7 @@ def test_random_parcellation():
for label in labels:
if label.hemi == hemi:
# test that labels are not empty
assert_true(len(label.vertices) > 0)
assert (len(label.vertices) > 0)
# vertices of hemi covered by labels
vertices_total = np.append(vertices_total, label.vertices)
@@ -853,10 +854,10 @@ def test_label_center_of_mass():
for label, expected in zip([labels[2], labels[3], labels[-5]],
[141162, 145221, 55979]):
label.values[:] = -1
assert_raises(ValueError, label.center_of_mass,
pytest.raises(ValueError, label.center_of_mass,
subjects_dir=subjects_dir)
label.values[:] = 0
assert_raises(ValueError, label.center_of_mass,
pytest.raises(ValueError, label.center_of_mass,
subjects_dir=subjects_dir)
label.values[:] = 1
assert_equal(label.center_of_mass(subjects_dir=subjects_dir), expected)
@@ -880,11 +881,11 @@ def test_label_center_of_mass():
restrict_vertices=src),
src_expected)
# degenerate cases
assert_raises(ValueError, label.center_of_mass, subjects_dir=subjects_dir,
pytest.raises(ValueError, label.center_of_mass, subjects_dir=subjects_dir,
restrict_vertices='foo')
assert_raises(TypeError, label.center_of_mass, subjects_dir=subjects_dir,
pytest.raises(TypeError, label.center_of_mass, subjects_dir=subjects_dir,
surf=1)
assert_raises(IOError, label.center_of_mass, subjects_dir=subjects_dir,
pytest.raises(IOError, label.center_of_mass, subjects_dir=subjects_dir,
surf='foo')
+6 -5
View File
@@ -4,11 +4,12 @@
# License: BSD (3-clause)
import os
from nose.tools import assert_raises
from unittest import SkipTest
from os import path as op
import sys
import pytest
from mne.utils import run_tests_if_main, _TempDir, _get_root_dir
@@ -27,7 +28,7 @@ skip_files = (
def _assert_line_endings(dir_):
"""Check line endings for a directory"""
"""Check line endings for a directory."""
if sys.platform == 'win32':
raise SkipTest('Skipping line endings check on Windows')
report = list()
@@ -56,17 +57,17 @@ def _assert_line_endings(dir_):
def test_line_endings():
"""Test line endings of mne-python"""
"""Test line endings of mne-python."""
tempdir = _TempDir()
with open(op.join(tempdir, 'foo'), 'wb') as fid:
fid.write('bad\r\ngood\n'.encode('ascii'))
_assert_line_endings(tempdir)
with open(op.join(tempdir, 'bad.py'), 'wb') as fid:
fid.write(b'\x97')
assert_raises(AssertionError, _assert_line_endings, tempdir)
pytest.raises(AssertionError, _assert_line_endings, tempdir)
with open(op.join(tempdir, 'bad.py'), 'wb') as fid:
fid.write('bad\r\ngood\n'.encode('ascii'))
assert_raises(AssertionError, _assert_line_endings, tempdir)
pytest.raises(AssertionError, _assert_line_endings, tempdir)
# now check mne
_assert_line_endings(_get_root_dir())

Some files were not shown because too many files have changed in this diff Show More