Skip to content

Commit

Permalink
[pre-commit.ci] pre-commit autoupdate (mne-tools#12492)
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 and snwnde committed Mar 20, 2024
1 parent 11bb3c3 commit 9cee1ce
Show file tree
Hide file tree
Showing 23 changed files with 78 additions and 106 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.3.0
rev: v0.3.2
hooks:
- id: ruff
name: ruff lint mne
Expand Down Expand Up @@ -48,7 +48,7 @@ repos:

# mypy
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.8.0
rev: v1.9.0
hooks:
- id: mypy
# Avoid the conflict between mne/__init__.py and mne/__init__.pyi by ignoring the former
Expand Down
9 changes: 3 additions & 6 deletions examples/preprocessing/eeg_bridging.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,12 +320,9 @@
# compute variance of residuals
print(
"Variance of residual (interpolated data - original data)\n\n"
"With adding virtual channel: {}\n"
"Compared to interpolation only using other channels: {}"
"".format(
np.mean(np.var(data_virtual - data_orig, axis=1)),
np.mean(np.var(data_comp - data_orig, axis=1)),
)
f"With adding virtual channel: {np.mean(np.var(data_virtual - data_orig, axis=1))}\n"
f"Compared to interpolation only using other channels: {np.mean(np.var(data_comp - data_orig, axis=1))}"
""
)

# plot results
Expand Down
2 changes: 1 addition & 1 deletion mne/_freesurfer.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ def get_volume_labels_from_aseg(mgz_fname, return_colors=False, atlas_ids=None):
if atlas_ids is None:
atlas_ids, colors = read_freesurfer_lut()
elif return_colors:
raise ValueError("return_colors must be False if atlas_ids are " "provided")
raise ValueError("return_colors must be False if atlas_ids are provided")
# restrict to the ones in the MRI, sorted by label name
keep = np.isin(list(atlas_ids.values()), want)
keys = sorted(
Expand Down
10 changes: 3 additions & 7 deletions mne/_ola.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,13 +370,9 @@ def feed(self, *datas, verbose=None, **kwargs):
or self._in_buffers[di].dtype != data.dtype
):
raise TypeError(
"data must dtype {} and shape[:-1]=={}, got dtype {} shape[:-1]="
"{}".format(
self._in_buffers[di].dtype,
self._in_buffers[di].shape[:-1],
data.dtype,
data.shape[:-1],
)
f"data must dtype {self._in_buffers[di].dtype} and "
f"shape[:-1]=={self._in_buffers[di].shape[:-1]}, got dtype "
f"{data.dtype} shape[:-1]={data.shape[:-1]}"
)
logger.debug(
" + Appending %d->%d"
Expand Down
17 changes: 7 additions & 10 deletions mne/annotations.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,11 +307,9 @@ def __repr__(self):
kinds = ", ".join(["{} ({})".format(*k) for k in sorted(counter.items())])
kinds = (": " if len(kinds) > 0 else "") + kinds
ch_specific = ", channel-specific" if self._any_ch_names() else ""
s = "Annotations | {} segment{}{}{}".format(
len(self.onset),
_pl(len(self.onset)),
ch_specific,
kinds,
s = (
f"Annotations | {len(self.onset)} segment"
f"{_pl(len(self.onset))}{ch_specific}{kinds}"
)
return "<" + shorten(s, width=77, placeholder=" ...") + ">"

Expand Down Expand Up @@ -820,11 +818,10 @@ def set_annotations(self, annotations, on_missing="raise", *, verbose=None):
else:
if getattr(self, "_unsafe_annot_add", False):
warn(
"Adding annotations to Epochs created (and saved to "
"disk) before 1.0 will yield incorrect results if "
"decimation or resampling was performed on the instance, "
"we recommend regenerating the Epochs and re-saving them "
"to disk."
"Adding annotations to Epochs created (and saved to disk) before "
"1.0 will yield incorrect results if decimation or resampling was "
"performed on the instance, we recommend regenerating the Epochs "
"and re-saving them to disk."
)
new_annotations = annotations.copy()
new_annotations._prune_ch_names(self.info, on_missing)
Expand Down
9 changes: 4 additions & 5 deletions mne/bem.py
Original file line number Diff line number Diff line change
Expand Up @@ -1082,10 +1082,9 @@ def get_fitting_dig(info, dig_kinds="auto", exclude_frontal=True, verbose=None):

if len(hsp) <= 10:
kinds_str = ", ".join(['"%s"' % _dig_kind_rev[d] for d in sorted(dig_kinds)])
msg = "Only {} head digitization points of the specified kind{} ({},)".format(
len(hsp),
_pl(dig_kinds),
kinds_str,
msg = (
f"Only {len(hsp)} head digitization points of the specified "
f"kind{_pl(dig_kinds)} ({kinds_str},)"
)
if len(hsp) < 4:
raise ValueError(msg + ", at least 4 required")
Expand Down Expand Up @@ -2455,7 +2454,7 @@ def check_seghead(surf_path=subj_path / "surf"):

surf = check_seghead()
if surf is None:
raise RuntimeError("mkheadsurf did not produce the standard output " "file.")
raise RuntimeError("mkheadsurf did not produce the standard output file.")

bem_dir = subjects_dir / subject / "bem"
if not bem_dir.is_dir():
Expand Down
8 changes: 3 additions & 5 deletions mne/channels/montage.py
Original file line number Diff line number Diff line change
Expand Up @@ -1709,11 +1709,9 @@ def compute_dev_head_t(montage):

if not (len(hpi_head) == len(hpi_dev) and len(hpi_dev) > 0):
raise ValueError(
(
"To compute Device-to-Head transformation, the same number of HPI"
" points in device and head coordinates is required. (Got {dev}"
" points in device and {head} points in head coordinate systems)"
).format(dev=len(hpi_dev), head=len(hpi_head))
"To compute Device-to-Head transformation, the same number of HPI"
f" points in device and head coordinates is required. (Got {len(hpi_dev)}"
f" points in device and {len(hpi_head)} points in head coordinate systems)"
)

trans = _quat_to_affine(_fit_matched_points(hpi_dev, hpi_head)[0])
Expand Down
8 changes: 4 additions & 4 deletions mne/coreg.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def coregister_fiducials(info, fiducials, tol=0.01):
coord_frame_to = FIFF.FIFFV_COORD_MRI
frames_from = {d["coord_frame"] for d in info["dig"]}
if len(frames_from) > 1:
raise ValueError("info contains fiducials from different coordinate " "frames")
raise ValueError("info contains fiducials from different coordinate frames")
else:
coord_frame_from = frames_from.pop()
coords_from = _fiducial_coords(info["dig"])
Expand Down Expand Up @@ -220,7 +220,7 @@ def create_default_subject(fs_home=None, update=False, subjects_dir=None, verbos
fs_src = os.path.join(fs_home, "subjects", "fsaverage")
if not os.path.exists(fs_src):
raise OSError(
"fsaverage not found at %r. Is fs_home specified " "correctly?" % fs_src
"fsaverage not found at %r. Is fs_home specified correctly?" % fs_src
)
for name in ("label", "mri", "surf"):
dirname = os.path.join(fs_src, name)
Expand Down Expand Up @@ -468,7 +468,7 @@ def fit_matched_points(
return trans
else:
raise ValueError(
"Invalid out parameter: %r. Needs to be 'params' or " "'trans'." % out
"Invalid out parameter: %r. Needs to be 'params' or 'trans'." % out
)


Expand Down Expand Up @@ -1945,7 +1945,7 @@ def fit_fiducials(
n_scale_params = self._n_scale_params
if n_scale_params == 3:
# enforce 1 even for 3-axis here (3 points is not enough)
logger.info("Enforcing 1 scaling parameter for fit " "with fiducials.")
logger.info("Enforcing 1 scaling parameter for fit with fiducials.")
n_scale_params = 1
self._lpa_weight = lpa_weight
self._nasion_weight = nasion_weight
Expand Down
14 changes: 6 additions & 8 deletions mne/cov.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,12 @@

def _check_covs_algebra(cov1, cov2):
if cov1.ch_names != cov2.ch_names:
raise ValueError("Both Covariance do not have the same list of " "channels.")
raise ValueError("Both Covariance do not have the same list of channels.")
projs1 = [str(c) for c in cov1["projs"]]
projs2 = [str(c) for c in cov1["projs"]]
if projs1 != projs2:
raise ValueError(
"Both Covariance do not have the same list of " "SSP projections."
"Both Covariance do not have the same list of SSP projections."
)


Expand Down Expand Up @@ -859,7 +859,7 @@ def _check_method_params(
for p, v in _method_params.items():
if v.get("assume_centered", None) is False:
raise ValueError(
"`assume_centered` must be True" " if `keep_sample_mean` is False"
"`assume_centered` must be True if `keep_sample_mean` is False"
)
return method, _method_params

Expand Down Expand Up @@ -1074,9 +1074,7 @@ def _unpack_epochs(epochs):
and keep_sample_mean
for epochs_t in epochs
):
warn(
"Epochs are not baseline corrected, covariance " "matrix may be inaccurate"
)
warn("Epochs are not baseline corrected, covariance matrix may be inaccurate")

orig = epochs[0].info["dev_head_t"]
_check_on_missing(on_mismatch, "on_mismatch")
Expand Down Expand Up @@ -1372,7 +1370,7 @@ def _compute_covariance_auto(
estimator_cov_info.append((fa, fa.get_covariance(), _info))
del fa
else:
raise ValueError("Oh no! Your estimator does not have" " a .fit method")
raise ValueError("Oh no! Your estimator does not have a .fit method")
logger.info("Done.")

if len(method) > 1:
Expand Down Expand Up @@ -2338,7 +2336,7 @@ def _read_cov(fid, node, cov_kind, limited=False, verbose=None):
names = _safe_name_list(tag.data, "read", "names")
if len(names) != dim:
raise ValueError(
"Number of names does not match " "covariance matrix dimension"
"Number of names does not match covariance matrix dimension"
)

tag = find_tag(fid, this, FIFF.FIFF_MNE_COV)
Expand Down
12 changes: 5 additions & 7 deletions mne/dipole.py
Original file line number Diff line number Diff line change
Expand Up @@ -1532,13 +1532,13 @@ def fit_dipole(
]
if len(R) == 0:
raise RuntimeError(
"No MEG channels found, but MEG-only " "sphere model used"
"No MEG channels found, but MEG-only sphere model used"
)
R = np.min(np.sqrt(np.sum(R * R, axis=1))) # use dist to sensors
kind = "max_rad"
logger.info(
"Sphere model : origin at ({: 7.2f} {: 7.2f} {: 7.2f}) mm, "
"{} = {:6.1f} mm".format(1000 * r0[0], 1000 * r0[1], 1000 * r0[2], kind, R)
f"Sphere model : origin at ({1000 * r0[0]: 7.2f} {1000 * r0[1]: 7.2f} "
f"{1000 * r0[2]: 7.2f}) mm, {kind} = {R:6.1f} mm"
)
inner_skull = dict(R=R, r0=r0) # NB sphere model defined in head frame
del R, r0
Expand All @@ -1548,17 +1548,15 @@ def fit_dipole(
fixed_position = True
pos = np.array(pos, float)
if pos.shape != (3,):
raise ValueError(
"pos must be None or a 3-element array-like," f" got {pos}"
)
raise ValueError(f"pos must be None or a 3-element array-like, got {pos}")
logger.info(
"Fixed position : {:6.1f} {:6.1f} {:6.1f} mm".format(*tuple(1000 * pos))
)
if ori is not None:
ori = np.array(ori, float)
if ori.shape != (3,):
raise ValueError(
"oris must be None or a 3-element array-like," f" got {ori}"
f"oris must be None or a 3-element array-like, got {ori}"
)
norm = np.sqrt(np.sum(ori * ori))
if not np.isclose(norm, 1):
Expand Down
10 changes: 5 additions & 5 deletions mne/epochs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1163,8 +1163,8 @@ def _compute_aggregate(self, picks, mode="mean"):
assert len(self.events) == len(self._data)
if data.shape != self._data.shape[1:]:
raise RuntimeError(
"You passed a function that resulted n data of shape {}, "
"but it should be {}.".format(data.shape, self._data.shape[1:])
f"You passed a function that resulted n data of shape "
f"{data.shape}, but it should be {self._data.shape[1:]}."
)
else:
if mode not in {"mean", "std"}:
Expand Down Expand Up @@ -2464,7 +2464,7 @@ def equalize_event_counts(self, event_ids=None, method="mintime"):
for ii, id_ in enumerate(event_ids):
if len(id_) == 0:
raise KeyError(
f"{orig_ids[ii]} not found in the epoch " "object's event_id."
f"{orig_ids[ii]} not found in the epoch object's event_id."
)
elif len({sub_id in ids for sub_id in id_}) != 1:
err = (
Expand Down Expand Up @@ -3593,11 +3593,11 @@ def __init__(
data = np.asanyarray(data, dtype=dtype)
if data.ndim != 3:
raise ValueError(
"Data must be a 3D array of shape (n_epochs, " "n_channels, n_samples)"
"Data must be a 3D array of shape (n_epochs, n_channels, n_samples)"
)

if len(info["ch_names"]) != data.shape[1]:
raise ValueError("Info and data must have same number of " "channels.")
raise ValueError("Info and data must have same number of channels.")
if events is None:
n_epochs = len(data)
events = _gen_events(n_epochs)
Expand Down
2 changes: 1 addition & 1 deletion mne/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -1030,7 +1030,7 @@ def concatenate_events(events, first_samps, last_samps):
_validate_type(events, list, "events")
if not (len(events) == len(last_samps) and len(events) == len(first_samps)):
raise ValueError(
"events, first_samps, and last_samps must all have " "the same lengths"
"events, first_samps, and last_samps must all have the same lengths"
)
first_samps = np.array(first_samps)
last_samps = np.array(last_samps)
Expand Down
4 changes: 2 additions & 2 deletions mne/evoked.py
Original file line number Diff line number Diff line change
Expand Up @@ -2075,12 +2075,12 @@ def _get_peak(data, times, tmin=None, tmax=None, mode="abs", *, strict=True):
if mode == "pos":
if strict and not np.any(data[~mask] > 0):
raise ValueError(
"No positive values encountered. Cannot " "operate in pos mode."
"No positive values encountered. Cannot operate in pos mode."
)
elif mode == "neg":
if strict and not np.any(data[~mask] < 0):
raise ValueError(
"No negative values encountered. Cannot " "operate in neg mode."
"No negative values encountered. Cannot operate in neg mode."
)
maxfun = np.argmin

Expand Down
22 changes: 4 additions & 18 deletions mne/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -873,12 +873,7 @@ def construct_iir_filter(
# ensure we have a valid ftype
if "ftype" not in iir_params:
raise RuntimeError(
"ftype must be an entry in iir_params if "
"b"
" "
"and "
"a"
" are not specified"
"ftype must be an entry in iir_params if 'b' and 'a' are not specified."
)
ftype = iir_params["ftype"]
if ftype not in known_filters:
Expand Down Expand Up @@ -932,14 +927,7 @@ def construct_iir_filter(
Ws = np.asanyarray(f_stop) / (float(sfreq) / 2)
if "gpass" not in iir_params or "gstop" not in iir_params:
raise ValueError(
"iir_params must have at least "
"gstop"
" and"
" "
"gpass"
" (or "
"N"
") entries"
"iir_params must have at least 'gstop' and 'gpass' (or N) entries."
)
system = signal.iirdesign(
Wp,
Expand Down Expand Up @@ -1488,7 +1476,7 @@ def create_filter(
freq = np.r_[freq, [sfreq / 2.0]]
gain = np.r_[gain, [1.0]]
if np.any(np.abs(np.diff(gain, 2)) > 1):
raise ValueError("Stop bands are not sufficiently " "separated.")
raise ValueError("Stop bands are not sufficiently separated.")
if method == "fir":
out = _construct_fir_filter(
sfreq, freq, gain, filter_length, phase, fir_window, fir_design
Expand Down Expand Up @@ -2392,9 +2380,7 @@ def float_array(c):
if l_freq is not None:
l_check = min(np.atleast_1d(l_trans_bandwidth))
mult_fact = 2.0 if fir_design == "firwin2" else 1.0
filter_length = "{}s".format(
_length_factors[fir_window] * mult_fact / float(min(h_check, l_check)),
)
filter_length = f"{_length_factors[fir_window] * mult_fact / float(min(h_check, l_check))}s" # noqa: E501
next_pow_2 = False # disable old behavior
else:
next_pow_2 = isinstance(filter_length, str) and phase == "zero-double"
Expand Down
5 changes: 3 additions & 2 deletions mne/forward/_make_forward.py
Original file line number Diff line number Diff line change
Expand Up @@ -819,8 +819,9 @@ def make_forward_dipole(dipole, bem, info, trans=None, n_jobs=None, *, verbose=N
head = "The following dipoles are outside the inner skull boundary"
msg = len(head) * "#" + "\n" + head + "\n"
for t, pos in zip(times[np.logical_not(inuse)], pos[np.logical_not(inuse)]):
msg += " t={:.0f} ms, pos=({:.0f}, {:.0f}, {:.0f}) mm\n".format(
t * 1000.0, pos[0] * 1000.0, pos[1] * 1000.0, pos[2] * 1000.0
msg += (
f" t={t * 1000.0:.0f} ms, pos=({pos[0] * 1000.0:.0f}, "
f"{pos[1] * 1000.0:.0f}, {pos[2] * 1000.0:.0f}) mm\n"
)
msg += len(head) * "#"
logger.error(msg)
Expand Down
5 changes: 2 additions & 3 deletions mne/io/array/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,8 @@ def __init__(self, data, info, first_samp=0, copy="auto", verbose=None):
"to get to double floating point precision"
)
logger.info(
"Creating RawArray with {} data, n_channels={}, n_times={}".format(
dtype.__name__, data.shape[0], data.shape[1]
)
f"Creating RawArray with {dtype.__name__} data, "
f"n_channels={data.shape[0]}, n_times={data.shape[1]}"
)
super().__init__(
info, data, first_samps=(int(first_samp),), dtype=dtype, verbose=verbose
Expand Down
5 changes: 3 additions & 2 deletions mne/io/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2733,8 +2733,9 @@ def _check_start_stop_within_bounds(self):
# we've done something wrong if we hit this
n_times_max = len(self.raw.times)
error_msg = (
"Can't write raw file with no data: {} -> {} (max: {}) requested"
).format(self.start, self.stop, n_times_max)
f"Can't write raw file with no data: {self.start} -> {self.stop} "
f"(max: {n_times_max}) requested"
)
if self.start >= self.stop or self.stop > n_times_max:
raise RuntimeError(error_msg)

Expand Down
Loading

0 comments on commit 9cee1ce

Please sign in to comment.