Skip to content

Commit dbbcce0

Browse files
MAINT: Trim redundant RNG tests
1 parent d37e0e8 commit dbbcce0

9 files changed

Lines changed: 10 additions & 248 deletions

File tree

mne/preprocessing/tests/test_ica.py

Lines changed: 7 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,6 @@ def test_ica_max_iter_(method, max_iter_default):
292292

293293
def test_ica_rng_transition():
294294
"""Test the transition from random_state to rng."""
295-
_ICA(random_state=0)
296295
with pytest.raises(TypeError, match="only one"):
297296
_ICA(random_state=0, rng=0)
298297

@@ -301,46 +300,26 @@ def test_ica_rng_transition():
301300
info["highpass"] = 1.0
302301
raw = RawArray(np.random.default_rng(0).standard_normal((3, 200)), info)
303302
unmixings = []
304-
for random_state in (0, check_random_state(0)):
303+
for kwargs in (
304+
dict(random_state=0),
305+
dict(random_state=check_random_state(0)),
306+
dict(rng=0),
307+
):
305308
ica = _ICA(
306309
n_components=2,
307310
method="fastica",
308311
max_iter=1000,
309-
random_state=random_state,
312+
**kwargs,
310313
)
311314
with _record_warnings(): # ICA does not necessarily converge
312315
ica.fit(raw)
313316
unmixings.append(ica.unmixing_matrix_)
314-
ica = _ICA(n_components=2, method="fastica", max_iter=1000, rng=0)
315-
with _record_warnings(): # ICA does not necessarily converge
316-
ica.fit(raw)
317-
unmixings.append(ica.unmixing_matrix_)
318317
assert_array_equal(unmixings[0], unmixings[1])
319318
# at the ICA/sklearn boundary an integer ``rng`` seed is forwarded verbatim,
320-
# so it matches the same integer passed to the deprecated parameter
319+
# so it matches the same integer passed to the legacy parameter
321320
assert_array_equal(unmixings[0], unmixings[2])
322321

323322

324-
def test_ica_infomax_fit_params_verbose():
325-
"""Test Infomax fit_params can suppress its private logging scope."""
326-
info = create_info(["Fz", "Cz", "Pz"], 100.0, "eeg")
327-
with info._unlock():
328-
info["highpass"] = 1.0
329-
raw = RawArray(np.random.default_rng(0).standard_normal((3, 200)), info)
330-
ica = _ICA(
331-
n_components=2,
332-
method="infomax",
333-
fit_params={"verbose": False},
334-
max_iter=1,
335-
rng=0,
336-
)
337-
with catch_logging(True) as log:
338-
ica.fit(raw, verbose=True)
339-
log = log.getvalue()
340-
assert "Fitting ICA to data" in log
341-
assert "Computing Infomax ICA" not in log
342-
343-
344323
@pytest.mark.parametrize("method", ["infomax", "fastica", "picard"])
345324
def test_ica_n_iter_(method, tmp_path):
346325
"""Test that ICA.n_iter_ is set after fitting."""

mne/simulation/tests/test_source.py

Lines changed: 0 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
from numpy.testing import assert_array_almost_equal, assert_array_equal, assert_equal
88

99
from mne import (
10-
SourceSpaces,
1110
convert_forward_solution,
1211
pick_types_forward,
1312
read_forward_solution,
@@ -16,7 +15,6 @@
1615
from mne.datasets import testing
1716
from mne.label import Label
1817
from mne.simulation import SourceSimulator, simulate_sparse_stc, simulate_stc
19-
from mne.utils import check_random_state
2018

2119
data_path = testing.data_path(download=False)
2220
fname_fwd = data_path / "MEG" / "sample" / "sample_audvis_trunc-meg-eeg-oct-6-fwd.fif"
@@ -49,38 +47,6 @@ def _get_idx_label_stc(label, stc):
4947
return idx
5048

5149

52-
def test_simulate_sparse_stc_legacy_rng_nested():
53-
"""Test legacy RNGs survive nested label-source selection."""
54-
src = SourceSpaces(
55-
[
56-
dict(
57-
type="surf",
58-
vertno=np.arange(1, 4) + 3 * hemi,
59-
nuse=3,
60-
subject_his_id="sample",
61-
)
62-
for hemi in range(2)
63-
]
64-
)
65-
labels = [
66-
Label(np.arange(1, 4) + 3 * idx, hemi=hemi, subject="sample")
67-
for idx, hemi in enumerate(("lh", "rh"))
68-
]
69-
results = []
70-
for random_state in (0, check_random_state(0)):
71-
results.append(
72-
simulate_sparse_stc(
73-
src,
74-
2,
75-
np.arange(2.0),
76-
labels=labels,
77-
random_state=random_state,
78-
)
79-
)
80-
for hemi in (0, 1):
81-
assert_array_equal(results[0].vertices[hemi], results[1].vertices[hemi])
82-
83-
8450
def test_simulate_stc(_get_fwd_labels):
8551
"""Test generation of source estimate."""
8652
fwd, labels = _get_fwd_labels

mne/stats/tests/test_cluster_level.py

Lines changed: 1 addition & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
summarize_clusters_stc,
2929
ttest_1samp_no_p,
3030
)
31-
from mne.utils import _record_warnings, catch_logging, check_random_state
31+
from mne.utils import _record_warnings, catch_logging
3232

3333
n_space = 50
3434

@@ -56,41 +56,6 @@ def _get_conditions():
5656
return condition1_1d, condition2_1d, condition1_2d, condition2_2d
5757

5858

59-
@pytest.mark.parametrize(
60-
"function, make_X",
61-
(
62-
(
63-
spatio_temporal_cluster_1samp_test,
64-
lambda rng: rng.standard_normal((8, 3, 1)),
65-
),
66-
(
67-
spatio_temporal_cluster_test,
68-
lambda rng: [
69-
rng.standard_normal((8, 3, 1)),
70-
rng.standard_normal((8, 3, 1)),
71-
],
72-
),
73-
),
74-
)
75-
def test_spatio_temporal_cluster_legacy_rng_nested(function, make_X):
76-
"""Test legacy RNGs survive nested spatio-temporal wrappers."""
77-
data = make_X(np.random.default_rng(0))
78-
results = []
79-
for seed in (0, check_random_state(0)):
80-
results.append(
81-
function(
82-
data,
83-
threshold=0,
84-
n_permutations=2,
85-
seed=seed,
86-
out_type="mask",
87-
)
88-
)
89-
assert_array_equal(results[0][0], results[1][0])
90-
assert_array_equal(results[0][2], results[1][2])
91-
assert_array_equal(results[0][3], results[1][3])
92-
93-
9459
def test_thresholds(numba_conditional):
9560
"""Test automatic threshold calculations."""
9661
# within subjects

mne/tests/test_cov.py

Lines changed: 0 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -673,40 +673,6 @@ def get_data(n_samples, n_features, rank, sigma):
673673
)
674674

675675

676-
@pytest.mark.parametrize(
677-
("mode", "method_params"),
678-
(
679-
("pca", dict(svd_solver="randomized")),
680-
("factor_analysis", dict(svd_method="randomized")),
681-
),
682-
)
683-
def test_auto_low_rank_ignores_global_rng(mode, method_params):
684-
"""Test low-rank covariance models use an explicit sklearn RNG state."""
685-
pytest.importorskip("sklearn")
686-
rng = np.random.default_rng(42)
687-
mixing = rng.standard_normal((10, 10))
688-
data = rng.standard_normal((400, 5))
689-
data = data @ _safe_svd(mixing.copy())[0][:, :5].T
690-
data += rng.normal(scale=0.1 * rng.random(10) + 0.05, size=data.shape)
691-
data *= 1e8
692-
global_rng = np.random.mtrand._rand
693-
original_rng_state = global_rng.get_state()
694-
try:
695-
global_rng.set_state(np.random.RandomState(42).get_state())
696-
global_rng_state = global_rng.get_state()
697-
est, _ = _auto_low_rank_model(
698-
data,
699-
mode=mode,
700-
n_jobs=1,
701-
method_params=dict(iter_n_components=[4], **method_params),
702-
cv=2,
703-
)
704-
assert_array_equal(global_rng.get_state()[1], global_rng_state[1])
705-
assert est.random_state == 0
706-
finally:
707-
global_rng.set_state(original_rng_state)
708-
709-
710676
@pytest.mark.slowtest
711677
@pytest.mark.parametrize("rank", ("full", None, "info"))
712678
def test_compute_covariance_auto_reg(rank):

mne/tests/test_epochs.py

Lines changed: 0 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -3021,44 +3021,6 @@ def test_equalize_epoch_counts_random():
30213021
assert len(epochs_1) == len(epochs_2)
30223022

30233023

3024-
@pytest.mark.parametrize(
3025-
"api, legacy, want",
3026-
(
3027-
("counts", True, ([], [3, 4], [0, 3, 4])),
3028-
("counts", False, ([], [1, 2], [0, 1, 2])),
3029-
("events", True, [6, 7, 8, 11, 12]),
3030-
("events", False, [4, 5, 8, 9, 10]),
3031-
),
3032-
)
3033-
def test_equalize_epoch_counts_rng_streams(api, legacy, want):
3034-
"""Test legacy integers re-seed while new RNG streams advance."""
3035-
info = create_info(["EEG 001"], 100.0, "eeg")
3036-
epochs = [
3037-
EpochsArray(
3038-
np.zeros((length, 1, 1)),
3039-
info,
3040-
events=np.column_stack(
3041-
(np.arange(length), np.zeros(length, int), np.full(length, code))
3042-
),
3043-
event_id={str(code): code},
3044-
verbose=False,
3045-
)
3046-
for code, length in enumerate((3, 5, 6), 1)
3047-
]
3048-
kwargs = {"random_state" if legacy else "rng": 0}
3049-
if api == "counts":
3050-
equalize_epoch_counts(epochs, method="random", **kwargs)
3051-
got = [
3052-
np.flatnonzero([entry == ("EQUALIZED_COUNT",) for entry in epoch.drop_log])
3053-
for epoch in epochs
3054-
]
3055-
else:
3056-
epochs = concatenate_epochs(epochs)
3057-
_, got = epochs.equalize_event_counts(method="random", **kwargs)
3058-
for this_got, expected in zip(got, want, strict=True):
3059-
assert_array_equal(this_got, expected)
3060-
3061-
30623024
def test_access_by_name(tmp_path):
30633025
"""Test accessing epochs by event name and on_missing for rare events."""
30643026
raw, events, picks = _get_data()

mne/utils/tests/test_check.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,6 @@ def test_check_rng():
5858
assert_array_equal(rng.integers(10, size=3), _check_rng(0).integers(10, size=3))
5959

6060
assert _check_rng(rng) is rng
61-
bit_generator = np.random.default_rng(0).bit_generator
62-
assert isinstance(_check_rng(bit_generator.seed_seq), np.random.Generator)
63-
assert isinstance(_check_rng(bit_generator), np.random.Generator)
6461
# legacy RandomState instances are passed through for scikit-learn interop
6562
random_state = np.random.RandomState(0)
6663
assert _check_rng(random_state) is random_state
@@ -81,9 +78,6 @@ def _func(random_state=None, seed=None, *, rng=None):
8178
# no argument: a fresh generator is created
8279
assert isinstance(_func(), np.random.Generator)
8380
assert isinstance(_func(rng=0), np.random.Generator)
84-
assert_array_equal(
85-
_func(rng=0).integers(10, size=3), _func(rng=0).integers(10, size=3)
86-
)
8781
# legacy RandomState passthrough
8882
random_state = np.random.RandomState(0)
8983
assert _func(rng=random_state) is random_state

mne/utils/tests/test_numerics.py

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
from copy import deepcopy
66
from datetime import date
7-
from inspect import signature
87
from io import StringIO
98
from pathlib import Path
109

@@ -34,7 +33,6 @@
3433
_time_mask,
3534
_undo_scaling_array,
3635
_undo_scaling_cov,
37-
check_random_state,
3836
compute_corr,
3937
create_slices,
4038
grand_average,
@@ -232,26 +230,6 @@ def test_random_permutation():
232230
)
233231

234232

235-
@pytest.mark.parametrize("use_keyword", (False, True))
236-
def test_random_permutation_legacy_none(use_keyword):
237-
"""Test explicit legacy None uses NumPy's global RandomState."""
238-
global_rng = check_random_state(None)
239-
original_state = global_rng.get_state()
240-
want = np.array([6, 5, 4, 0, 3, 8, 9, 2, 7, 1])
241-
try:
242-
global_rng.set_state(check_random_state(42).get_state())
243-
if use_keyword:
244-
got = random_permutation(10, random_state=None)
245-
else:
246-
got = random_permutation(10, None)
247-
assert_array_equal(got, want)
248-
finally:
249-
global_rng.set_state(original_state)
250-
assert str(signature(random_permutation)) == (
251-
"(n_samples, random_state=None, *, rng=None)"
252-
)
253-
254-
255233
def test_cov_scaling():
256234
"""Test rescaling covs."""
257235
evoked = read_evokeds(ave_fname, condition=0, baseline=(None, 0), proj=True)

mne/viz/tests/test_circle.py

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
import matplotlib
77
import numpy as np
88
import pytest
9-
from numpy.testing import assert_allclose
109

1110
from mne.viz import plot_channel_labels_circle
1211
from mne.viz.circle import _plot_connectivity_circle
@@ -83,16 +82,3 @@ def test_plot_connectivity_circle_label_orientation():
8382
f"Node '{name}' at {angle:.1f}° (left half) should have "
8483
f"ha='right', got '{ha}'"
8584
)
86-
87-
88-
def test_plot_connectivity_circle_jitter_reproducible():
89-
"""Test connectivity-circle edge jitter uses a fixed local Generator."""
90-
con = np.array([[0.0, 1.0, 2.0], [1.0, 0.0, 3.0], [2.0, 3.0, 0.0]])
91-
vertices = []
92-
for _ in range(2):
93-
fig, ax = _plot_connectivity_circle(
94-
con, ["a", "b", "c"], colorbar=False, interactive=False, show=False
95-
)
96-
vertices.append(ax.patches[0].get_path().vertices)
97-
fig.clear()
98-
assert_allclose(*vertices)

0 commit comments

Comments
 (0)