Exemplo n.º 1
0
def test_copyfile_eeglab(tmp_path, fname):
    """Test the copying of EEGlab set and fdt files."""
    if (fname == 'test_raw_chanloc.set'
            and _compare_version(testing.get_version(), '<', '0.112')):
        return

    bids_root = str(tmp_path)
    data_path = op.join(testing.data_path(), 'EEGLAB')
    raw_fname = op.join(data_path, fname)
    new_name = op.join(bids_root, 'tested_conversion.set')

    # IO error testing
    with pytest.raises(ValueError, match="Need to move data with same ext"):
        copyfile_eeglab(raw_fname, new_name + '.wrong')

    # Test copying and reading
    copyfile_eeglab(raw_fname, new_name)
    if fname == 'test_raw_chanloc.set':  # combined set+fdt
        with pytest.warns(RuntimeWarning,
                          match="The data contains 'boundary' events"):
            raw = mne.io.read_raw_eeglab(new_name)
            assert 'Fp1' in raw.ch_names
    else:  # combined set+fdt and single set (new EEGLAB format)
        raw = mne.io.read_raw_eeglab(new_name, preload=True)
        assert 'EEG 001' in raw.ch_names
    assert isinstance(raw, mne.io.BaseRaw)
Exemplo n.º 2
0
def _check_pyqtgraph():
    try:
        import PyQt5  # noqa: F401
    except ModuleNotFoundError:
        pytest.skip('PyQt5 is not installed but needed for pyqtgraph!')
    if not _compare_version(_check_pyqt5_version(), '>=', '5.12'):
        pytest.skip(f'PyQt5 has version {_check_pyqt5_version()}'
                    f'but pyqtgraph needs >= 5.12!')
    try:
        import mne_qt_browser  # noqa: F401
    except Exception:
        pytest.skip('Requires mne_qt_browser')
Exemplo n.º 3
0
def _check_pyqtgraph(request):
    # Check PyQt5
    try:
        import PyQt5  # noqa: F401
    except ModuleNotFoundError:
        pytest.skip('PyQt5 is not installed but needed for pyqtgraph!')
    if not _compare_version(_check_pyqt5_version(), '>=', '5.12'):
        pytest.skip(f'PyQt5 has version {_check_pyqt5_version()}'
                    f'but pyqtgraph needs >= 5.12!')
    # Check mne-qt-browser
    try:
        import mne_qt_browser  # noqa: F401
        # Check mne-qt-browser version
        lower_2_0 = _compare_version(mne_qt_browser.__version__, '<', '0.2.0')
        m_name = request.function.__module__
        f_name = request.function.__name__
        if lower_2_0 and m_name in pre_2_0_skip_modules:
            pytest.skip(f'Test-Module "{m_name}" was skipped for'
                        f' mne-qt-browser < 0.2.0')
        elif lower_2_0 and f_name in pre_2_0_skip_funcs:
            pytest.skip(f'Test "{f_name}" was skipped for '
                        f'mne-qt-browser < 0.2.0')
    except Exception:
        pytest.skip('Requires mne_qt_browser')
Exemplo n.º 4
0
def _check_pyqtgraph(request):
    # Check Qt
    qt_version, api = _check_qt_version(return_api=True)
    if (not qt_version) or _compare_version(qt_version, '<', '5.12'):
        pytest.skip(f'Qt API {api} has version {qt_version} '
                    f'but pyqtgraph needs >= 5.12!')
    try:
        import mne_qt_browser  # noqa: F401
        # Check mne-qt-browser version
        lower_2_0 = _compare_version(mne_qt_browser.__version__, '<', '0.2.0')
        m_name = request.function.__module__
        f_name = request.function.__name__
        if lower_2_0 and m_name in pre_2_0_skip_modules:
            pytest.skip(f'Test-Module "{m_name}" was skipped for'
                        f' mne-qt-browser < 0.2.0')
        elif lower_2_0 and f_name in pre_2_0_skip_funcs:
            pytest.skip(f'Test "{f_name}" was skipped for '
                        f'mne-qt-browser < 0.2.0')
    except Exception:
        pytest.skip('Requires mne_qt_browser')
    else:
        ver = mne_qt_browser.__version__
        if api != 'PyQt5' and _compare_version(ver, '<=', '0.2.6'):
            pytest.skip(f'mne_qt_browser {ver} requires PyQt5, API is {api}')
Exemplo n.º 5
0
"""Inspect and annotate BIDS raw data."""
# Authors: Richard Höchenberger <*****@*****.**>
#          Stefan Appelhoff <*****@*****.**>
#
# License: BSD-3-Clause

from pathlib import Path

import numpy as np

import mne

from mne.utils import logger, verbose
from mne.fixes import _compare_version

if _compare_version(mne.__version__, '<', '1.0.dev0'):  # pragma: no cover
    from mne.preprocessing import annotate_flat
    _annotate_flat_func = annotate_flat
else:
    from mne.preprocessing import annotate_amplitude
    _annotate_flat_func = annotate_amplitude

from mne_bids import read_raw_bids, mark_channels
from mne_bids.read import _from_tsv, _read_events
from mne_bids.write import _events_tsv
from mne_bids.config import ALLOWED_DATATYPE_EXTENSIONS


@verbose
def inspect_dataset(bids_path,
                    find_flat=True,
Exemplo n.º 6
0
        mlab.close()
        scrapers += ('mayavi', )
        push_exception_handler(reraise_exceptions=True)
    elif backend in ('notebook', 'pyvistaqt'):
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", category=DeprecationWarning)
            import pyvista
        pyvista.OFF_SCREEN = False
        brain_scraper = mne.viz._brain._BrainScraper()
        scrapers += (brain_scraper, 'pyvista')
    report_scraper = mne.report._ReportScraper()
    scrapers += (report_scraper, )
    del backend
try:
    import mne_qt_browser
    _min_ver = _compare_version(mne_qt_browser.__version__, '>=', '0.2')
    if mne.viz.get_browser_backend() == 'qt' and _min_ver:
        scrapers += (mne.viz._scraper._MNEQtBrowserScraper(), )
except ImportError:
    pass

# Resolve binder filepath_prefix. From the docs:
# "A prefix to append to the filepath in the Binder links. You should use this
# if you will store your built documentation in a sub-folder of a repository,
# instead of in the root."
# we will store dev docs in a `dev` subdirectory and all other docs in a
# directory "v" + version_str. E.g., "v0.3"
# if 'dev' in version:
#     filepath_prefix = 'main'
# else:
#     filepath_prefix = 'v{}'.format(version)
Exemplo n.º 7
0
def test_pos_semidef_inv(ndim, dtype, n, deficient, reduce_rank, psdef, func):
    """Test positive semidefinite matrix inverses."""
    if _compare_version(np.__version__, '>=', '1.19'):
        svd = np.linalg.svd
    else:
        from mne.fixes import svd
    # make n-dimensional matrix
    n_extra = 2  # how many we add along the other dims
    rng = np.random.RandomState(73)
    shape = (n_extra,) * (ndim - 2) + (n, n)
    mat = rng.randn(*shape) + 1j * rng.randn(*shape)
    proj = np.eye(n)
    if deficient:
        vec = np.ones(n) / np.sqrt(n)
        proj -= np.outer(vec, vec)
    with _record_warnings():  # intentionally discard imag
        mat = mat.astype(dtype)
    # now make it conjugate symmetric or positive semi-definite
    if psdef:
        mat = np.matmul(mat, mat.swapaxes(-2, -1).conj())
    else:
        mat += mat.swapaxes(-2, -1).conj()
    assert_allclose(mat, mat.swapaxes(-2, -1).conj(), atol=1e-6)
    s = svd(mat, hermitian=True)[1]
    assert (s >= 0).all()
    # make it rank deficient (maybe)
    if deficient:
        mat = np.matmul(np.matmul(proj, mat), proj)
    # if the dtype is complex, the conjugate transpose != transpose
    kwargs = dict(atol=1e-10, rtol=1e-10)
    orig_eq_t = np.allclose(
        mat, mat.swapaxes(-2, -1), **kwargs)
    t_eq_ct = np.allclose(
        mat.swapaxes(-2, -1), mat.conj().swapaxes(-2, -1), **kwargs)
    if np.iscomplexobj(mat):
        assert not orig_eq_t
        assert not t_eq_ct
    else:
        assert t_eq_ct
        assert orig_eq_t
    assert mat.shape == shape
    # ensure pos-semidef
    s = np.linalg.svd(mat, compute_uv=False)
    assert s.shape == shape[:-1]
    rank = (s > s[..., :1] * 1e-12).sum(-1)
    want_rank = n - deficient
    assert_array_equal(rank, want_rank)
    # assert equiv with NumPy
    mat_pinv = np.linalg.pinv(mat)
    if func is _sym_mat_pow:
        if not psdef:
            with pytest.raises(ValueError, match='not positive semi-'):
                func(mat, -1)
            return
        mat_symv = func(mat, -1, reduce_rank=reduce_rank)
        mat_sqrt = func(mat, 0.5)
        if ndim == 2:
            mat_sqrt_scipy = linalg.sqrtm(mat)
            assert_allclose(mat_sqrt, mat_sqrt_scipy, atol=1e-6)
        mat_2 = np.matmul(mat_sqrt, mat_sqrt)
        assert_allclose(mat, mat_2, atol=1e-6)
        mat_symv_2 = func(mat, -0.5, reduce_rank=reduce_rank)
        mat_symv_2 = np.matmul(mat_symv_2, mat_symv_2)
        assert_allclose(mat_symv_2, mat_symv, atol=1e-6)
    else:
        assert func is _reg_pinv
        mat_symv, _, _ = func(mat, rank=None)
    assert_allclose(mat_pinv, mat_symv, **kwargs)
    want = np.dot(proj, np.eye(n))
    if deficient:
        want -= want.mean(axis=0)
    for _ in range(ndim - 2):
        want = np.repeat(want[np.newaxis], n_extra, axis=0)
    assert_allclose(np.matmul(mat_symv, mat), want, **kwargs)
    assert_allclose(np.matmul(mat, mat_symv), want, **kwargs)