Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MAINT: Remove unnecessary checks #11582

Merged
merged 7 commits into from
Mar 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions mne/beamformer/_compute_beamformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from ..minimum_norm.inverse import _get_vertno, _prepare_forward
from ..source_space import label_src_vertno_sel
from ..utils import (verbose, check_fname, _reg_pinv, _check_option, logger,
_pl, _check_src_normal, check_version, _sym_mat_pow, warn,
_pl, _check_src_normal, _sym_mat_pow, warn,
_import_h5io_funcs)
from ..time_frequency.csd import CrossSpectralDensity

Expand Down Expand Up @@ -214,9 +214,6 @@ def _compute_beamformer(G, Cm, reg, n_orient, weight_norm, pick_ori,
assert Gk.shape == (n_sources, n_channels, n_orient)
sk = np.reshape(orient_std, (n_sources, n_orient))
del G, orient_std
pinv_kwargs = dict()
if check_version('numpy', '1.17'):
pinv_kwargs['hermitian'] = True

_check_option('reduce_rank', reduce_rank, (True, False))

Expand Down
5 changes: 5 additions & 0 deletions mne/gui/tests/test_gui_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,4 +396,9 @@ def test_gui_api_qt(renderer_interactive_pyvistaqt):
"""Test GUI API with the Qt backend."""
_, api = _check_qt_version(return_api=True)
n_warn = int(api in ('PySide6', 'PyQt6'))
# TODO: After merging https://github.com/mne-tools/mne-python/pull/11567
# The Qt CI run started failing about 50% of the time, so let's skip this
# for now.
if api == 'PySide6':
pytest.skip('PySide6 causes segfaults on CIs sometimes')
test_gui_api(None, None, n_warn=n_warn, backend='qt')
11 changes: 2 additions & 9 deletions mne/io/curry/tests/test_curry.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from mne.io.bti import read_raw_bti
from mne.io.curry import read_raw_curry
from mne.io.tests.test_raw import _test_raw_reader
from mne.utils import check_version, catch_logging, _record_warnings
from mne.utils import catch_logging
from mne.annotations import read_annotations
from mne.io.curry.curry import (_get_curry_version, _get_curry_file_structure,
_read_events_curry, FILE_EXTENSIONS)
Expand Down Expand Up @@ -62,14 +62,7 @@ def bdf_curry_ref():
@pytest.mark.parametrize('preload', [True, False])
def test_read_raw_curry(fname, tol, preload, bdf_curry_ref):
"""Test reading CURRY files."""
with _record_warnings() as wrn:
raw = read_raw_curry(fname, preload=preload)

if not check_version('numpy', '1.16') and preload and fname.endswith(
'ASCII.dat'):
assert len(wrn) > 0
else:
assert len(wrn) == 0
raw = read_raw_curry(fname, preload=preload)

assert hasattr(raw, '_data') == preload
assert raw.n_times == bdf_curry_ref.n_times
Expand Down
12 changes: 2 additions & 10 deletions mne/label.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
_mesh_borders, mesh_edges, mesh_dist)
from .utils import (get_subjects_dir, _check_subject, logger, verbose, warn,
check_random_state, _validate_type, fill_doc,
_check_option, check_version, _check_fname)
_check_option, _check_fname)


def _blend_colors(color_1, color_2):
Expand Down Expand Up @@ -436,12 +436,7 @@ def fill(self, src, name=None):
"information is needed. To avoid this in the future, run "
"mne.add_source_space_distances() on the source space "
"and save it to disk.")
if check_version('scipy', '1.3'):
dist_limit = 0
else:
warn('SciPy < 1.3 detected, adding source space patch '
'information will be slower. Consider upgrading SciPy.')
dist_limit = np.inf
dist_limit = 0
add_source_space_distances(src, dist_limit=dist_limit)
nearest = hemi_src['nearest']

Expand Down Expand Up @@ -810,9 +805,6 @@ def distances_to_outside(self, subject=None, subjects_dir=None,
.. versionadded:: 0.24
"""
from scipy.sparse.csgraph import dijkstra
if not check_version('scipy', '1.3'):
raise RuntimeError(
'scipy >= 1.3 is required to calculate distances to the edge')
rr, tris = self._load_surface(subject, subjects_dir, surface)
adjacency = mesh_dist(tris, rr)
mask = np.zeros(len(rr))
Expand Down
4 changes: 0 additions & 4 deletions mne/morph.py
Original file line number Diff line number Diff line change
Expand Up @@ -1187,10 +1187,6 @@ def grade_to_vertices(subject, grade, subjects_dir=None, n_jobs=None,
def _surf_nearest(vertices, adj_mat):
from scipy import sparse
from scipy.sparse.csgraph import dijkstra
if not check_version('scipy', '1.3'):
raise ValueError('scipy >= 1.3 is required to use nearest smoothing, '
'consider upgrading SciPy or using a different '
'smoothing value')
# Vertices can be out of order, so sort them to start ...
order = np.argsort(vertices)
vertices = vertices[order]
Expand Down
7 changes: 1 addition & 6 deletions mne/report/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,13 +430,8 @@ def _get_bem_contour_figs_as_arrays(
list of array
A list of NumPy arrays that represent the generated Matplotlib figures.
"""
# Matplotlib <3.2 doesn't work nicely with process-based parallelization
kwargs = dict()
if not check_version('matplotilb', '3.2'):
kwargs['prefer'] = 'threads'

parallel, p_fun, n_jobs = parallel_func(
_plot_mri_contours, n_jobs, max_jobs=len(sl), **kwargs)
_plot_mri_contours, n_jobs, max_jobs=len(sl), prefer='threads')
outs = parallel(
p_fun(
slices=s, mri_fname=mri_fname, surfaces=surfaces,
Expand Down
7 changes: 2 additions & 5 deletions mne/simulation/tests/test_evoked.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from mne.io import read_raw_fif
from mne.io.pick import pick_channels_cov
from mne.cov import regularize, whiten_evoked
from mne.utils import catch_logging, check_version
from mne.utils import catch_logging

data_path = testing.data_path(download=False)
fwd_fname = (
Expand Down Expand Up @@ -108,10 +108,7 @@ def test_simulate_evoked():
@pytest.mark.filterwarnings('ignore:Epochs are not baseline corrected')
def test_add_noise():
"""Test noise addition."""
if check_version('numpy', '1.17'):
rng = np.random.default_rng(0)
else:
rng = np.random.RandomState(0)
rng = np.random.default_rng(0)
raw = read_raw_fif(raw_fname)
raw.del_proj()
picks = pick_types(raw.info, meg=True, eeg=True, exclude=())
Expand Down
8 changes: 1 addition & 7 deletions mne/simulation/tests/test_raw.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
from mne.surface import _get_ico_surface
from mne.io import read_raw_fif, RawArray
from mne.io.constants import FIFF
from mne.utils import catch_logging, check_version
from mne.utils import catch_logging

raw_fname_short = (
Path(__file__).parent.parent.parent
Expand Down Expand Up @@ -283,12 +283,6 @@ def test_simulate_raw_sphere(raw_data, tmp_path):
assert_allclose(raw_sim[:][0], raw_sim_hann[:][0], rtol=1e-1, atol=1e-14)
del raw_sim_hann

# check that new Generator objects can be used
if check_version('numpy', '1.17'):
random_state = np.random.default_rng(seed)
add_ecg(raw_sim, random_state=random_state)
add_eog(raw_sim, random_state=random_state)


def test_degenerate(raw_data):
"""Test degenerate conditions."""
Expand Down
7 changes: 0 additions & 7 deletions mne/simulation/tests/test_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
convert_forward_solution)
from mne.label import Label
from mne.simulation import simulate_stc, simulate_sparse_stc, SourceSimulator
from mne.utils import check_version


data_path = testing.data_path(download=False)
Expand Down Expand Up @@ -236,12 +235,6 @@ def test_simulate_sparse_stc_single_hemi(_get_fwd_labels):
assert_array_equal(stc_1.lh_vertno, stc_2.lh_vertno)
assert_array_equal(stc_1.rh_vertno, stc_2.rh_vertno)

# smoke test for new API
if check_version('numpy', '1.17'):
simulate_sparse_stc(fwd['src'], len(labels_single_hemi), times,
labels=labels_single_hemi,
random_state=np.random.default_rng(0))


@testing.requires_testing_data
def test_simulate_stc_labels_overlap(_get_fwd_labels):
Expand Down
10 changes: 2 additions & 8 deletions mne/source_space.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,9 @@
from ._freesurfer import (_get_mri_info_data, _get_atlas_values, # noqa: F401
read_freesurfer_lut, get_mni_fiducials, _check_mri)
from .utils import (get_subjects_dir, check_fname, logger, verbose, fill_doc,
_ensure_int, check_version, _get_call_line, warn,
_ensure_int, _get_call_line, warn, object_size, sizeof_fmt,
_check_fname, _path_like, _check_sphere, _import_nibabel,
_validate_type, _check_option, _is_numeric, _pl, _suggest,
object_size, sizeof_fmt)
_validate_type, _check_option, _is_numeric, _pl, _suggest)
from .parallel import parallel_func
from .transforms import (invert_transform, apply_trans, _print_coord_trans,
combine_transforms, _get_trans,
Expand Down Expand Up @@ -2465,11 +2464,6 @@ def add_source_space_distances(src, dist_limit=np.inf, n_jobs=None, *,
raise ValueError('dist_limit must be non-negative, got %s'
% (dist_limit,))
patch_only = (dist_limit == 0)
if patch_only and not check_version('scipy', '1.3'):
raise RuntimeError('scipy >= 1.3 is required to calculate patch '
'information only, consider upgrading SciPy or '
'using dist_limit=np.inf when running '
'add_source_space_distances')
if src.kind != 'surface':
raise RuntimeError('Currently all source spaces must be of surface '
'type')
Expand Down
8 changes: 2 additions & 6 deletions mne/stats/tests/test_cluster_level.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@
spatio_temporal_cluster_test,
spatio_temporal_cluster_1samp_test,
ttest_1samp_no_p, summarize_clusters_stc)
from mne.utils import (catch_logging, check_version, requires_sklearn,
_record_warnings)
from mne.utils import catch_logging, requires_sklearn, _record_warnings


n_space = 50
Expand Down Expand Up @@ -120,10 +119,7 @@ def test_cache_dir(tmp_path, numba_conditional):
assert 'independently' not in log_file.getvalue()
# ensure that non-independence yields warning
stat_fun = partial(ttest_1samp_no_p, sigma=1e-3)
if check_version('numpy', '1.17'):
random_state = np.random.default_rng(0)
else:
random_state = 0
random_state = np.random.default_rng(0)
with pytest.warns(RuntimeWarning, match='independently'):
permutation_cluster_1samp_test(
X, buffer_size=10, n_jobs=2, n_permutations=1,
Expand Down
5 changes: 0 additions & 5 deletions mne/stats/tests/test_permutations.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from mne.stats import permutation_cluster_1samp_test
from mne.stats.permutations import (permutation_t_test, _ci,
bootstrap_confidence_interval)
from mne.utils import check_version


def test_permutation_t_test():
Expand Down Expand Up @@ -75,7 +74,3 @@ def test_ci():
bootstrap_confidence_interval(arr, stat_fun="mean",
random_state=0),
rtol=.1)
# smoke test for new API
if check_version('numpy', '1.17'):
random_state = np.random.default_rng(0)
bootstrap_confidence_interval(arr, random_state=random_state)
27 changes: 13 additions & 14 deletions mne/tests/test_coreg.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
coregister_fiducials, get_mni_fiducials, Coregistration)
from mne.io import read_fiducials, read_info
from mne.io.constants import FIFF
from mne.utils import check_version, catch_logging
from mne.utils import catch_logging
from mne.source_space import write_source_spaces
from mne.channels import DigMontage

Expand Down Expand Up @@ -156,20 +156,19 @@ def test_scale_mri(tmp_path, few_surfaces, scale):
assert ssrc[0]['nearest'] is not None

# check patch info computation (only if SciPy is new enough to be fast)
if check_version('scipy', '1.3'):
for s in src_dist:
for key in ('dist', 'dist_limit'):
s[key] = None
write_source_spaces(
bem_path / (bem_fname % "ico-0"), src_dist, overwrite=True
)
for s in src_dist:
for key in ('dist', 'dist_limit'):
s[key] = None
write_source_spaces(
bem_path / (bem_fname % "ico-0"), src_dist, overwrite=True
)

# scale with distances
os.remove(spath / (spath_fname % "ico-0"))
scale_source_space('flachkopf', 'ico-0', subjects_dir=tmp_path)
ssrc = mne.read_source_spaces(spath / (spath_fname % "ico-0"))
assert ssrc[0]['dist'] is None
assert ssrc[0]['nearest'] is not None
# scale with distances
os.remove(spath / (spath_fname % "ico-0"))
scale_source_space('flachkopf', 'ico-0', subjects_dir=tmp_path)
ssrc = mne.read_source_spaces(spath / (spath_fname % "ico-0"))
assert ssrc[0]['dist'] is None
assert ssrc[0]['nearest'] is not None


@pytest.mark.slowtest # can take forever on OSX Travis
Expand Down
16 changes: 6 additions & 10 deletions mne/tests/test_epochs.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@
EpochsArray, concatenate_epochs, BaseEpochs, average_movements,
_handle_event_repeated, make_metadata)
from mne.utils import (requires_pandas, object_diff, use_log_level,
catch_logging, _FakeNoPandas,
assert_meg_snr, check_version, _dt_to_stamp)
catch_logging, _FakeNoPandas, assert_meg_snr,
_dt_to_stamp)

data_path = testing.data_path(download=False)
fname_raw_testing = (
Expand Down Expand Up @@ -1236,15 +1236,13 @@ def test_epochs_io_preload(tmp_path, preload):
('1.5MB', 9, 6, 1572864),
('3MB', 18, 3, 3 * 1024 * 1024),
])
@pytest.mark.parametrize('metadata', [
False,
pytest.param(True, marks=pytest.mark.skipif(
not check_version('pandas'), reason='Requires Pandas'))
])
@pytest.mark.parametrize('metadata', [False, True])
@pytest.mark.parametrize('concat', (False, True))
def test_split_saving(tmp_path, split_size, n_epochs, n_files, size, metadata,
concat):
"""Test saving split epochs."""
if metadata:
pytest.importorskip('pandas')
# See gh-5102
fs = 1000.
n_times = int(round(fs * (n_epochs + 1)))
Expand Down Expand Up @@ -1936,9 +1934,7 @@ def test_bootstrap():
raw, events, picks = _get_data()
epochs = Epochs(raw, events[:5], event_id, tmin, tmax, picks=picks,
preload=True, reject=reject, flat=flat)
random_states = [0]
if check_version('numpy', '1.17'):
random_states += [np.random.default_rng(0)]
random_states = [0, np.random.default_rng(0)]
for random_state in random_states:
epochs2 = bootstrap(epochs, random_state=random_state)
assert (len(epochs2.events) == len(epochs.events))
Expand Down
17 changes: 3 additions & 14 deletions mne/tests/test_label.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import os
import pickle
import shutil
from contextlib import nullcontext
from itertools import product
from pathlib import Path

Expand All @@ -29,8 +28,7 @@
from mne.source_space import SourceSpaces
from mne.source_estimate import mesh_edges
from mne.surface import _mesh_borders
from mne.utils import (requires_sklearn, get_subjects_dir, check_version,
_record_warnings)
from mne.utils import requires_sklearn, get_subjects_dir, _record_warnings


data_path = testing.data_path(download=False)
Expand Down Expand Up @@ -266,7 +264,7 @@ def test_label_fill_restrict(fname):
label_src = label.restrict(src)
vert_in_src = label_src.vertices
values_in_src = label_src.values
if check_version('scipy', '1.3') and fname == real_label_fname:
if fname == real_label_fname:
# Check that we can auto-fill patch info quickly for one condition
for s in src:
s['nearest'] = None
Expand Down Expand Up @@ -1049,16 +1047,7 @@ def test_label_geometry(fname, area):
assert 0 < len(label_sparse.vertices) < len(label.vertices)
with pytest.warns(RuntimeWarning, match='No complete triangles'):
assert label_sparse.compute_area(subjects_dir=subjects_dir) == 0.
if not check_version('scipy', '1.3'):
ctx = pytest.raises(RuntimeError, match='required to calculate')
stop = True
else:
ctx = nullcontext()
stop = False
with ctx:
dist, outside = label.distances_to_outside(subjects_dir=subjects_dir)
if stop:
return
dist, outside = label.distances_to_outside(subjects_dir=subjects_dir)
rr, tris = read_surface(subjects_dir / "sample" / "surf" / "lh.white")
mask = np.zeros(len(rr), bool)
mask[label.vertices] = 1
Expand Down
Loading