Skip to content

Commit

Permalink
[pre-commit.ci] pre-commit autoupdate (mne-tools#12988)
Browse files Browse the repository at this point in the history
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Mathieu Scheltienne <[email protected]>
Co-authored-by: Eric Larson <[email protected]>
  • Loading branch information
3 people authored Nov 26, 2024
1 parent 98f9949 commit 535b401
Show file tree
Hide file tree
Showing 53 changed files with 470 additions and 430 deletions.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
repos:
# Ruff mne
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.7.4
rev: v0.8.0
hooks:
- id: ruff
name: ruff lint mne
Expand Down Expand Up @@ -58,7 +58,7 @@ repos:
args: ["--ignore-case"]

- repo: https://github.com/pappasam/toml-sort
rev: v0.24.1
rev: v0.24.2
hooks:
- id: toml-sort-fix
files: pyproject.toml
Expand Down
3 changes: 2 additions & 1 deletion doc/sphinxext/contrib_avatars.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,10 @@ def generate_contrib_avatars(app, config):
driver.get(f"file://{infile}")
wait = WebDriverWait(driver, 20)
wait.until(lambda d: d.find_element(by=By.ID, value="contributor-avatars"))
body = driver.find_element(by=By.TAG_NAME, value="body").get_attribute(
body = driver.find_element(by=By.TAG_NAME, value="body").get_property(
"innerHTML"
)
assert isinstance(body, str), type(body)
driver.quit()
with open(outfile, "w") as fid:
fid.write(body)
Expand Down
7 changes: 3 additions & 4 deletions mne/_fiff/matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,9 @@ def write_named_matrix(fid, kind, mat):
if n_tot < mat["data"].size and ratio > 0:
ratio = 1 / ratio
raise ValueError(
"Cannot write matrix: row (%i) and column (%i) "
"total element (%i) mismatch with data size (%i), "
"appears to be off by a factor of %gx"
% (mat["nrow"], mat["ncol"], n_tot, mat["data"].size, ratio)
f"Cannot write matrix: row ({mat['nrow']}) and column ({mat['ncol']}) "
f"total element ({n_tot}) mismatch with data size ({mat['data'].size}), "
f"appears to be off by a factor of {ratio:g}x"
)
start_block(fid, FIFF.FIFFB_MNE_NAMED_MATRIX)
write_int(fid, FIFF.FIFF_MNE_NROW, mat["nrow"])
Expand Down
4 changes: 2 additions & 2 deletions mne/_fiff/tests/test_pick.py
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ def test_picks_by_channels():
rng = np.random.RandomState(909)

test_data = rng.random_sample((4, 2000))
ch_names = ["MEG %03d" % i for i in [1, 2, 3, 4]]
ch_names = [f"MEG {i:03d}" for i in [1, 2, 3, 4]]
ch_types = ["grad", "mag", "mag", "eeg"]
sfreq = 250.0
info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)
Expand All @@ -496,7 +496,7 @@ def test_picks_by_channels():
assert pick_list2[0][0] == "meg"

test_data = rng.random_sample((4, 2000))
ch_names = ["MEG %03d" % i for i in [1, 2, 3, 4]]
ch_names = [f"MEG {i:03d}" for i in [1, 2, 3, 4]]
ch_types = ["mag", "mag", "mag", "mag"]
sfreq = 250.0
info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)
Expand Down
12 changes: 3 additions & 9 deletions mne/_ola.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,15 +318,9 @@ def __init__(
sfreq = float(sfreq)
pl = "s" if len(self.starts) != 1 else ""
logger.info(
" Processing %4d data chunk%s of (at least) %0.1f s "
"with %0.1f s overlap and %s windowing"
% (
len(self.starts),
pl,
self._n_samples / sfreq,
self._n_overlap / sfreq,
window_name,
)
f" Processing {len(self.starts):4d} data chunk{pl} of (at least) "
f"{self._n_samples / sfreq:0.1f} s with "
f"{self._n_overlap / sfreq:0.1f} s overlap and {window_name} windowing"
)
del window, window_name
if delta > 0:
Expand Down
4 changes: 2 additions & 2 deletions mne/channels/_dig_montage_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ def _read_dig_montage_egi(

# EEG Channels
if kind == 0:
dig_ch_pos["EEG %03d" % number] = coordinates
dig_ch_pos[f"EEG {number:03d}"] = coordinates
# Reference
elif kind == 1:
dig_ch_pos["EEG %03d" % (len(dig_ch_pos.keys()) + 1)] = coordinates
dig_ch_pos[f"EEG {len(dig_ch_pos) + 1:03d}"] = coordinates
# Fiducials
elif kind == 2:
fid_name = fid_name_map[name]
Expand Down
7 changes: 2 additions & 5 deletions mne/channels/channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -1648,13 +1648,10 @@ def fix_mag_coil_types(info, use_cal=False):
Therefore the use of ``fix_mag_coil_types`` is not mandatory.
"""
old_mag_inds = _get_T1T2_mag_inds(info, use_cal)

n_mag = len(pick_types(info, meg="mag", exclude=[]))
for ii in old_mag_inds:
info["chs"][ii]["coil_type"] = FIFF.FIFFV_COIL_VV_MAG_T3
logger.info(
"%d of %d magnetometer types replaced with T3."
% (len(old_mag_inds), len(pick_types(info, meg="mag", exclude=[])))
)
logger.info(f"{len(old_mag_inds)} of {n_mag} magnetometer types replaced with T3.")
info._check_consistency()


Expand Down
17 changes: 6 additions & 11 deletions mne/channels/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,9 @@ def save(self, fname, overwrite=False):
raise ValueError("Unknown layout type. Should be of type .lout or .lay.")

for ii in range(x.shape[0]):
out_str += "%03d %8.2f %8.2f %8.2f %8.2f %s\n" % (
self.ids[ii],
x[ii],
y[ii],
width[ii],
height[ii],
self.names[ii],
out_str += (
f"{self.ids[ii]:03d} {x[ii]:8.2f} {y[ii]:8.2f} "
f"{width[ii]:8.2f} {height[ii]:8.2f} {self.names[ii]}\n"
)

f = open(fname, "w")
Expand Down Expand Up @@ -945,14 +941,13 @@ def _auto_topomap_coords(info, picks, ignore_overlap, to_sphere, sphere):
if len(locs3d) == 0:
raise RuntimeError(
"Did not find any digitization points of "
"kind FIFFV_POINT_EEG (%d) in the info." % FIFF.FIFFV_POINT_EEG
f"kind {FIFF.FIFFV_POINT_EEG} in the info."
)

if len(locs3d) != len(eeg_ch_names):
raise ValueError(
"Number of EEG digitization points (%d) "
"doesn't match the number of EEG channels "
"(%d)" % (len(locs3d), len(eeg_ch_names))
f"Number of EEG digitization points ({len(locs3d)}) doesn't match the "
f"number of EEG channels ({len(eeg_ch_names)})"
)

# We no longer center digitization points on head origin, as we work
Expand Down
8 changes: 4 additions & 4 deletions mne/channels/montage.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,8 +341,8 @@ def __init__(self, *, dig=None, ch_names=None):
n_eeg = sum([1 for d in dig if d["kind"] == FIFF.FIFFV_POINT_EEG])
if n_eeg != len(ch_names):
raise ValueError(
"The number of EEG channels (%d) does not match the number"
" of channel names provided (%d)" % (n_eeg, len(ch_names))
f"The number of EEG channels ({n_eeg}) does not match the number"
f" of channel names provided ({len(ch_names)})"
)

self.dig = dig
Expand Down Expand Up @@ -845,7 +845,7 @@ def read_dig_fif(fname):
ch_names = []
for d in dig:
if d["kind"] == FIFF.FIFFV_POINT_EEG:
ch_names.append("EEG%03d" % d["ident"])
ch_names.append(f"EEG{d['ident']:03d}")

montage = DigMontage(dig=dig, ch_names=ch_names)
return montage
Expand Down Expand Up @@ -927,7 +927,7 @@ def read_dig_hpts(fname, unit="mm"):
out = np.genfromtxt(fname, comments="#", dtype=(_str, _str, "f8", "f8", "f8"))
kind, label = _str_names(out["f0"]), _str_names(out["f1"])
kind = [k.lower() for k in kind]
xyz = np.array([out["f%d" % ii] for ii in range(2, 5)]).T
xyz = np.array([out[f"f{ii}"] for ii in range(2, 5)]).T
xyz *= _scale
del _scale
fid_idx_to_label = {"1": "lpa", "2": "nasion", "3": "rpa"}
Expand Down
20 changes: 10 additions & 10 deletions mne/channels/tests/test_montage.py
Original file line number Diff line number Diff line change
Expand Up @@ -1086,11 +1086,11 @@ def test_fif_dig_montage(tmp_path):
raw_bv = read_raw_brainvision(bv_fname, preload=True)
raw_bv_2 = raw_bv.copy()
mapping = dict()
for ii, ch_name in enumerate(raw_bv.ch_names):
mapping[ch_name] = "EEG%03d" % (ii + 1,)
for ii, ch_name in enumerate(raw_bv.ch_names, 1):
mapping[ch_name] = f"EEG{ii:03d}"
raw_bv.rename_channels(mapping)
for ii, ch_name in enumerate(raw_bv_2.ch_names):
mapping[ch_name] = "EEG%03d" % (ii + 33,)
for ii, ch_name in enumerate(raw_bv_2.ch_names, 33):
mapping[ch_name] = f"EEG{ii:03d}"
raw_bv_2.rename_channels(mapping)
raw_bv.add_channels([raw_bv_2])
for ch in raw_bv.info["chs"]:
Expand Down Expand Up @@ -1119,7 +1119,7 @@ def test_fif_dig_montage(tmp_path):
# Roundtrip of non-FIF start
montage = make_dig_montage(hsp=read_polhemus_fastscan(hsp), hpi=read_mrk(hpi))
elp_points = read_polhemus_fastscan(elp)
ch_pos = {"EEG%03d" % (k + 1): pos for k, pos in enumerate(elp_points[8:])}
ch_pos = {f"EEG{k:03d}": pos for k, pos in enumerate(elp_points[8:], 1)}
montage += make_dig_montage(
nasion=elp_points[0], lpa=elp_points[1], rpa=elp_points[2], ch_pos=ch_pos
)
Expand Down Expand Up @@ -1398,7 +1398,7 @@ def test_set_montage_mgh(rename):

def renamer(x):
try:
return "EEG %03d" % (_MGH60.index(x) + 1,)
return f"EEG {_MGH60.index(x) + 1:03d}"
except ValueError:
return x

Expand Down Expand Up @@ -1920,11 +1920,11 @@ def test_get_montage():
# rename channels to make it have the full set
# of channels
mapping = dict()
for ii, ch_name in enumerate(raw_bv.ch_names):
mapping[ch_name] = "EEG%03d" % (ii + 1,)
for ii, ch_name in enumerate(raw_bv.ch_names, 1):
mapping[ch_name] = f"EEG{ii:03d}"
raw_bv.rename_channels(mapping)
for ii, ch_name in enumerate(raw_bv_2.ch_names):
mapping[ch_name] = "EEG%03d" % (ii + 33,)
for ii, ch_name in enumerate(raw_bv_2.ch_names, 33):
mapping[ch_name] = f"EEG{ii:03d}"
raw_bv_2.rename_channels(mapping)
raw_bv.add_channels([raw_bv_2])
for ch in raw_bv.info["chs"]:
Expand Down
53 changes: 28 additions & 25 deletions mne/cov.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,8 @@
_read_proj,
_write_proj,
)
from ._fiff.proj import (
activate_proj as _activate_proj,
)
from ._fiff.proj import (
make_projector as _make_projector,
)
from ._fiff.proj import activate_proj as _activate_proj
from ._fiff.proj import make_projector as _make_projector
from ._fiff.tag import find_tag
from ._fiff.tree import dir_tree_find
from .defaults import (
Expand Down Expand Up @@ -267,7 +263,7 @@ def _get_square(self):
if self["diag"] != (self.data.ndim == 1):
raise RuntimeError(
"Covariance attributes inconsistent, got data with "
"dimensionality %d but diag=%s" % (self.data.ndim, self["diag"])
f"dimensionality {self.data.ndim} but diag={self['diag']}"
)
return np.diag(self.data) if self["diag"] else self.data.copy()

Expand Down Expand Up @@ -564,8 +560,8 @@ def _check_n_samples(n_samples, n_chan):
raise ValueError("No samples found to compute the covariance matrix")
if n_samples < n_samples_min:
warn(
"Too few samples (required : %d got : %d), covariance "
"estimate may be unreliable" % (n_samples_min, n_samples)
f"Too few samples (required : {n_samples_min} got : {n_samples}), "
"covariance estimate may be unreliable"
)


Expand Down Expand Up @@ -743,7 +739,7 @@ def compute_raw_covariance(
_check_n_samples(n_samples, len(picks))
data -= mu[:, None] * (mu[None, :] / n_samples)
data /= n_samples - 1.0
logger.info("Number of samples used : %d" % n_samples)
logger.info("Number of samples used : %d", n_samples)
logger.info("[done]")
ch_names = [raw.info["ch_names"][k] for k in picks]
bads = [b for b in raw.info["bads"] if b in ch_names]
Expand Down Expand Up @@ -1182,7 +1178,7 @@ def _unpack_epochs(epochs):
# add extra info
cov.update(method=this_method, **data)
covs.append(cov)
logger.info("Number of samples used : %d" % n_samples_tot)
logger.info("Number of samples used : %d", n_samples_tot)
covs.sort(key=lambda c: c["loglik"], reverse=True)

if len(covs) > 1:
Expand Down Expand Up @@ -1466,8 +1462,8 @@ def _auto_low_rank_model(
max_n = max(list(deepcopy(iter_n_components)))
if max_n > data.shape[1]:
warn(
"You are trying to estimate %i components on matrix "
"with %i features." % (max_n, data.shape[1])
f"You are trying to estimate {max_n} components on matrix "
f"with {data.shape[1]} features."
)

for ii, n in enumerate(iter_n_components):
Expand All @@ -1479,7 +1475,7 @@ def _auto_low_rank_model(
if np.isinf(score) or score > 0:
logger.info("... infinite values encountered. stopping estimation")
break
logger.info("... rank: %i - loglik: %0.3f" % (n, score))
logger.info("... rank: %i - loglik: %0.3f", n, score)
if score != -np.inf:
scores[ii] = score

Expand All @@ -1498,7 +1494,7 @@ def _auto_low_rank_model(

i_score = np.nanargmax(scores)
best = est.n_components = iter_n_components[i_score]
logger.info("... best model at rank = %i" % best)
logger.info("... best model at rank = %i", best)
runtime_info = {
"ranks": np.array(iter_n_components),
"scores": scores,
Expand Down Expand Up @@ -1831,7 +1827,7 @@ def _smart_eigh(
if isinstance(C, Covariance):
C = C["data"]
if ncomp > 0:
logger.info(" Created an SSP operator (subspace dimension = %d)" % ncomp)
logger.info(" Created an SSP operator (subspace dimension = %d)", ncomp)
C = np.dot(proj, np.dot(C, proj.T))

noise_cov = Covariance(C, ch_names, [], projs, 0)
Expand Down Expand Up @@ -2274,8 +2270,9 @@ def compute_whitener(
n_nzero = nzero.sum()
logger.info(
" Created the whitener using a noise covariance matrix "
"with rank %d (%d small eigenvalues omitted)"
% (n_nzero, noise_cov["dim"] - n_nzero)
"with rank %d (%d small eigenvalues omitted)",
n_nzero,
noise_cov["dim"] - n_nzero,
)

# Do the requested projection
Expand Down Expand Up @@ -2403,8 +2400,10 @@ def _read_cov(fid, node, cov_kind, limited=False, verbose=None):
data = tag.data
diag = True
logger.info(
" %d x %d diagonal covariance (kind = "
"%d) found." % (dim, dim, cov_kind)
" %d x %d diagonal covariance (kind = " "%d) found.",
dim,
dim,
cov_kind,
)

else:
Expand All @@ -2417,15 +2416,19 @@ def _read_cov(fid, node, cov_kind, limited=False, verbose=None):
data.flat[:: dim + 1] /= 2.0
diag = False
logger.info(
" %d x %d full covariance (kind = %d) "
"found." % (dim, dim, cov_kind)
" %d x %d full covariance (kind = %d) " "found.",
dim,
dim,
cov_kind,
)
else:
diag = False
data = tag.data
logger.info(
" %d x %d sparse covariance (kind = %d)"
" found." % (dim, dim, cov_kind)
" %d x %d sparse covariance (kind = %d)" " found.",
dim,
dim,
cov_kind,
)

# Read the possibly precomputed decomposition
Expand Down Expand Up @@ -2468,7 +2471,7 @@ def _read_cov(fid, node, cov_kind, limited=False, verbose=None):

return cov

logger.info(" Did not find the desired covariance matrix (kind = %d)" % cov_kind)
logger.info(" Did not find the desired covariance matrix (kind = %d)", cov_kind)

return None

Expand Down
7 changes: 5 additions & 2 deletions mne/datasets/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -765,8 +765,11 @@ def _manifest_check_download(manifest_path, destination, url, hash_):
if not (destination / name).is_file():
need.append(name)
logger.info(
"%d file%s missing from %s in %s"
% (len(need), _pl(need), manifest_path.name, destination)
"%d file%s missing from %s in %s",
len(need),
_pl(need),
manifest_path.name,
destination,
)
if len(need) > 0:
downloader = pooch.HTTPDownloader(**_downloader_params())
Expand Down
Loading

0 comments on commit 535b401

Please sign in to comment.