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 code using vulture confidence 60 #12575

Merged
merged 5 commits into from
May 21, 2024
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 14 additions & 1 deletion doc/sphinxext/gen_commands.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.
import glob
import os
import shutil
from importlib import import_module
from pathlib import Path

from mne.utils import ArgvSetter, _replace_md5
from mne.utils import ArgvSetter, hashfunc


def setup(app):
Expand Down Expand Up @@ -106,6 +108,17 @@ def generate_commands_rst(app=None):
_replace_md5(str(out_fname))


def _replace_md5(fname):
"""Replace a file based on MD5sum."""
# adapted from sphinx-gallery
assert fname.endswith(".new")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this won't work for Path objects, is that OK?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Must be, this is just copy-pasted 🙂

fname_old = fname[:-4]
if os.path.isfile(fname_old) and hashfunc(fname) == hashfunc(fname_old):
os.remove(fname)
else:
shutil.move(fname, fname_old)


# This is useful for testing/iterating to see what the result looks like
if __name__ == "__main__":
generate_commands_rst()
27 changes: 0 additions & 27 deletions mne/_fiff/reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,33 +25,6 @@
from .proj import _has_eeg_average_ref_proj, make_eeg_average_ref_proj, setup_proj


def _copy_channel(inst, ch_name, new_ch_name):
"""Add a copy of a channel specified by ch_name.

Input data can be in the form of Raw, Epochs or Evoked.

The instance object is modified inplace.

Parameters
----------
inst : instance of Raw | Epochs | Evoked
Data containing the EEG channels
ch_name : str
Name of the channel to copy.
new_ch_name : str
Name given to the copy of the channel.

Returns
-------
inst : instance of Raw | Epochs | Evoked
The data with a copy of a given channel.
"""
new_inst = inst.copy().pick([ch_name])
new_inst.rename_channels({ch_name: new_ch_name})
inst.add_channels([new_inst], force_update_info=True)
return inst


def _check_before_reference(inst, ref_from, ref_to, ch_type):
"""Prepare instance for referencing."""
# Check to see that data is preloaded
Expand Down
25 changes: 0 additions & 25 deletions mne/_fiff/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,31 +301,6 @@ def _create_chs(ch_names, cals, ch_coil, ch_kind, eog, ecg, emg, misc):
return chs


def _synthesize_stim_channel(events, n_samples):
"""Synthesize a stim channel from events read from an event file.

Parameters
----------
events : array, shape (n_events, 3)
Each row representing an event.
n_samples : int
The number of samples.

Returns
-------
stim_channel : array, shape (n_samples,)
An array containing the whole recording's event marking.
"""
# select events overlapping buffer
events = events.copy()
events[events[:, 1] < 1, 1] = 1
# create output buffer
stim_channel = np.zeros(n_samples, int)
for onset, duration, trigger in events:
stim_channel[onset : onset + duration] = trigger
return stim_channel


def _construct_bids_filename(base, ext, part_idx, validate=True):
"""Construct a BIDS compatible filename for split files."""
# insert index in filename
Expand Down
13 changes: 2 additions & 11 deletions mne/_fiff/write.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,21 +414,12 @@ def write_float_sparse_rcs(fid, kind, mat):
return write_float_sparse(fid, kind, mat, fmt="csr")


def write_float_sparse_ccs(fid, kind, mat):
"""Write a single-precision sparse compressed column matrix tag."""
return write_float_sparse(fid, kind, mat, fmt="csc")


def write_float_sparse(fid, kind, mat, fmt="auto"):
"""Write a single-precision floating-point sparse matrix tag."""
if fmt == "auto":
fmt = "csr" if isinstance(mat, csr_matrix) else "csc"
if fmt == "csr":
need = csr_matrix
matrix_type = FIFF.FIFFT_SPARSE_RCS_MATRIX
else:
need = csc_matrix
matrix_type = FIFF.FIFFT_SPARSE_CCS_MATRIX
need = csr_matrix if fmt == "csr" else csc_matrix
matrix_type = getattr(FIFF, f"FIFFT_SPARSE_{fmt[-1].upper()}CS_MATRIX")
_validate_type(mat, need, "sparse")
matrix_type = matrix_type | FIFF.FIFFT_MATRIX | FIFF.FIFFT_FLOAT
nnzm = mat.nnz
Expand Down
17 changes: 0 additions & 17 deletions mne/_freesurfer.py
Original file line number Diff line number Diff line change
Expand Up @@ -506,23 +506,6 @@ def estimate_head_mri_t(subject, subjects_dir=None, verbose=None):
return invert_transform(compute_native_head_t(montage))


def _ensure_image_in_surface_RAS(image, subject, subjects_dir):
"""Check if the image is in Freesurfer surface RAS space."""
nib = _import_nibabel("load a volume image")
if not isinstance(image, nib.spatialimages.SpatialImage):
image = nib.load(image)
image = nib.MGHImage(image.dataobj.astype(np.float32), image.affine)
fs_img = nib.load(op.join(subjects_dir, subject, "mri", "brain.mgz"))
if not np.allclose(image.affine, fs_img.affine, atol=1e-6):
raise RuntimeError(
"The `image` is not aligned to Freesurfer "
"surface RAS space. This space is required as "
"it is the space where the anatomical "
"segmentation and reconstructed surfaces are"
)
return image # returns MGH image for header


def _get_affine_from_lta_info(lines):
"""Get the vox2ras affine from lta file info."""
volume_data = np.loadtxt([line.split("=")[1] for line in lines])
Expand Down
55 changes: 0 additions & 55 deletions mne/channels/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -970,61 +970,6 @@ def _pair_grad_sensors(
return picks


# this function is used to pair grad when info is not present
# it is the case of Projection that don't have the info.
def _pair_grad_sensors_ch_names_vectorview(ch_names):
"""Find the indices for pairing grad channels in a Vectorview system.

Parameters
----------
ch_names : list of str
A list of channel names.

Returns
-------
indexes : list of int
Indices of the grad channels, ordered in pairs.
"""
pairs = defaultdict(list)
for i, name in enumerate(ch_names):
if name.startswith("MEG"):
if name.endswith(("2", "3")):
key = name[-4:-1]
pairs[key].append(i)

pairs = [p for p in pairs.values() if len(p) == 2]

grad_chs = sum(pairs, [])
return grad_chs


# this function is used to pair grad when info is not present
# it is the case of Projection that don't have the info.
def _pair_grad_sensors_ch_names_neuromag122(ch_names):
"""Find the indices for pairing grad channels in a Neuromag 122 system.

Parameters
----------
ch_names : list of str
A list of channel names.

Returns
-------
indexes : list of int
Indices of the grad channels, ordered in pairs.
"""
pairs = defaultdict(list)
for i, name in enumerate(ch_names):
if name.startswith("MEG"):
key = (int(name[-3:]) - 1) // 2
pairs[key].append(i)

pairs = [p for p in pairs.values() if len(p) == 2]

grad_chs = sum(pairs, [])
return grad_chs


def _merge_ch_data(data, ch_type, names, method="rms"):
"""Merge data from channel pairs.

Expand Down
34 changes: 1 addition & 33 deletions mne/channels/tests/test_montage.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,6 @@
locs_montage_fname = data_path / "EEGLAB" / "test_chans.locs"
evoked_fname = data_path / "montage" / "level2_raw-ave.fif"
eeglab_fname = data_path / "EEGLAB" / "test_raw.set"
bdf_fname1 = data_path / "BDF" / "test_generator_2.bdf"
bdf_fname2 = data_path / "BDF" / "test_bdf_stim_channel.bdf"
egi_fname1 = data_path / "EGI" / "test_egi.mff"
cnt_fname = data_path / "CNT" / "scan41_short.cnt"
fnirs_dname = data_path / "NIRx" / "nirscout" / "nirx_15_2_recording_w_short"
mgh70_fname = data_path / "SSS" / "mgh70_raw.fif"
subjects_dir = data_path / "subjects"
Expand All @@ -104,10 +100,8 @@
fif_fname = io_dir / "tests" / "data" / "test_raw.fif"
edf_path = io_dir / "edf" / "tests" / "data" / "test.edf"
bdf_path = io_dir / "edf" / "tests" / "data" / "test_bdf_eeglab.mat"
egi_fname2 = io_dir / "egi" / "tests" / "data" / "test_egi.raw"
vhdr_path = io_dir / "brainvision" / "tests" / "data" / "test.vhdr"
ctf_fif_fname = io_dir / "tests" / "data" / "test_ctf_comp_raw.fif"
nicolet_fname = io_dir / "nicolet" / "tests" / "data" / "test_nicolet_raw.data"


def _make_toy_raw(n_channels):
Expand Down Expand Up @@ -1108,17 +1102,6 @@ def test_egi_dig_montage(tmp_path):
_check_roundtrip(dig_montage_in_head, fname_temp)


def _pop_montage(dig_montage, ch_name):
# remove reference that was not used in old API
name_idx = dig_montage.ch_names.index(ch_name)
dig_idx = dig_montage._get_dig_names().index(ch_name)

del dig_montage.dig[dig_idx]
del dig_montage.ch_names[name_idx]
for k in range(dig_idx, len(dig_montage.dig)):
dig_montage.dig[k]["ident"] -= 1


@testing.requires_testing_data
def test_read_dig_captrak(tmp_path):
"""Test reading a captrak montage file."""
Expand Down Expand Up @@ -1444,21 +1427,6 @@ def _check_roundtrip(montage, fname, coord_frame="head"):
assert_dig_allclose(montage, montage_read)


def _fake_montage(ch_names):
pos = np.random.RandomState(42).randn(len(ch_names), 3)
return make_dig_montage(ch_pos=dict(zip(ch_names, pos)), coord_frame="head")


cnt_ignore_warns = [
pytest.mark.filterwarnings(
"ignore:.*Could not parse meas date from the header. Setting to None."
),
pytest.mark.filterwarnings(
"ignore:.*Could not define the number of bytes automatically. Defaulting to 2."
),
]


def test_digmontage_constructor_errors():
"""Test proper error messaging."""
with pytest.raises(ValueError, match="does not match the number"):
Expand Down Expand Up @@ -1966,7 +1934,7 @@ def test_montage_add_fiducials():
subjects_dir = data_path / "subjects"
subject = "sample"
fid_fname = subjects_dir / subject / "bem" / "sample-fiducials.fif"
test_fids, test_coord_frame = read_fiducials(fid_fname)
test_fids, _ = read_fiducials(fid_fname)
test_fids = np.array([f["r"] for f in test_fids])

# create test montage and add estimated fiducials
Expand Down
6 changes: 0 additions & 6 deletions mne/chpi.py
Original file line number Diff line number Diff line change
Expand Up @@ -1085,12 +1085,6 @@ def _fit_chpi_quat_subset(coil_dev_rrs, coil_head_rrs, use_idx):
return quat, g, np.array(out_idx, int)


@jit()
def _unit_quat_constraint(x):
"""Constrain our 3 quaternion rot params (ignoring w) to have norm <= 1."""
return 1 - (x * x).sum()


@verbose
def compute_chpi_snr(
raw, t_step_min=0.01, t_window="auto", ext_order=1, tmin=0, tmax=None, verbose=None
Expand Down
28 changes: 0 additions & 28 deletions mne/coreg.py
Original file line number Diff line number Diff line change
Expand Up @@ -760,28 +760,6 @@ def _is_mri_subject(subject, subjects_dir=None):
)


def _is_scaled_mri_subject(subject, subjects_dir=None):
"""Check whether a directory in subjects_dir is a scaled mri subject.

Parameters
----------
subject : str
Name of the potential subject/directory.
subjects_dir : None | path-like
Override the SUBJECTS_DIR environment variable.

Returns
-------
is_scaled_mri_subject : bool
Whether ``subject`` is a scaled mri subject.
"""
subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
if not _is_mri_subject(subject, subjects_dir):
return False
fname = subjects_dir / subject / "MRI scaling parameters.cfg"
return fname.exists()


def _mri_subject_has_bem(subject, subjects_dir=None):
"""Check whether an mri subject has a file matching the bem pattern.

Expand Down Expand Up @@ -1479,15 +1457,13 @@ def __init__(
self._scale_mode = None
self._on_defects = on_defects

self._rot_trans = None
self._default_parameters = np.array(
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0]
)

self._rotation = self._default_parameters[:3]
self._translation = self._default_parameters[3:6]
self._scale = self._default_parameters[6:9]
self._icp_iterations = 20
self._icp_angle = 0.2
self._icp_distance = 0.2
self._icp_scale = 0.2
Expand Down Expand Up @@ -1869,10 +1845,6 @@ def _has_rpa_data(self):
def _processed_high_res_mri_points(self):
return self._get_processed_mri_points("high")

@property
def _processed_low_res_mri_points(self):
return self._get_processed_mri_points("low")

def _get_processed_mri_points(self, res):
bem = self._bem_low_res if res == "low" else self._bem_high_res
points = bem["rr"].copy()
Expand Down
3 changes: 2 additions & 1 deletion mne/decoding/time_delaying_ridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,9 @@ def _compute_corrs(
assert X.shape[:2] == y.shape[:2]
len_trf = smax - smin
len_x, n_epochs, n_ch_x = X.shape
len_y, n_epcohs, n_ch_y = y.shape
len_y, n_epochs_y, n_ch_y = y.shape
assert len_x == len_y
assert n_epochs == n_epochs_y

n_fft = next_fast_len(2 * X.shape[0] - 1)

Expand Down
12 changes: 0 additions & 12 deletions mne/epochs.py
Original file line number Diff line number Diff line change
Expand Up @@ -4480,18 +4480,6 @@ def bootstrap(epochs, random_state=None):
return epochs_bootstrap


def _check_merge_epochs(epochs_list):
"""Aux function."""
if len({tuple(epochs.event_id.items()) for epochs in epochs_list}) != 1:
raise NotImplementedError("Epochs with unequal values for event_id")
if len({epochs.tmin for epochs in epochs_list}) != 1:
raise NotImplementedError("Epochs with unequal values for tmin")
if len({epochs.tmax for epochs in epochs_list}) != 1:
raise NotImplementedError("Epochs with unequal values for tmax")
if len({epochs.baseline for epochs in epochs_list}) != 1:
raise NotImplementedError("Epochs with unequal values for baseline")


def _concatenate_epochs(
epochs_list, *, with_data=True, add_offset=True, on_mismatch="raise"
):
Expand Down