Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Jan 31, 2024
1 parent 519d8c4 commit 51a2741
Show file tree
Hide file tree
Showing 70 changed files with 533 additions and 492 deletions.
4 changes: 1 addition & 3 deletions mne/fixes.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,6 @@ def _get_param_names(cls):
" of their __init__ (no varargs)."
# " %s with constructor %s doesn't "
f"{cls} with constructor {init_signature} doesn't follow this convention."

)
# Extract and sort argument names excluding 'self'
return sorted([p.name for p in parameters])
Expand Down Expand Up @@ -270,7 +269,7 @@ def set_params(self, **params):
# "Invalid parameter %s for estimator %s. "
f"Invalid parameter{name}for estimator{self}"
"Check the list of available parameters "
"with `estimator.get_params().keys()`."
"with `estimator.get_params().keys()`."
)
sub_object = valid_params[name]
sub_object.set_params(**{sub_name: value})
Expand All @@ -282,7 +281,6 @@ def set_params(self, **params):
f"Invalid parameter {key}for estimator{self.__class__.__name__} for estimator"
"Check the list of available parameters "
"with `estimator.get_params().keys()`."

)
setattr(self, key, value)
return self
Expand Down
11 changes: 5 additions & 6 deletions mne/forward/_make_forward.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,6 @@ def _setup_bem(bem, bem_extra, neeg, mri_head_t, allow_none=False, verbose=None)
raise RuntimeError(
# "BEM is in %s coordinates, should be in MRI"
f"BEM is in {_coord_frame_name(bem["surfs"][0]["coord_frame"]),} coordinates, should be in MRI"

)
if neeg > 0 and len(bem["surfs"]) == 1:
raise RuntimeError(
Expand Down Expand Up @@ -690,14 +689,14 @@ def make_forward_solution(
info_extra = "instance of Info"

# Report the setup
logger.info(f"Source space :{src} " )
logger.info(f"MRI -> head transform : {trans}" )
logger.info(f"Measurement data : {info_extra}" )
logger.info(f"Source space :{src} ")
logger.info(f"MRI -> head transform : {trans}")
logger.info(f"Measurement data : {info_extra}")
if isinstance(bem, ConductorModel) and bem["is_sphere"]:
logger.info(f"Sphere model : origin at {(bem["r0"],)} mm" )
logger.info(f"Sphere model : origin at {(bem["r0"],)} mm")
logger.info("Standard field computations")
else:
logger.info(f"Conductor model : { bem_extra}" )
logger.info(f"Conductor model : { bem_extra}")
logger.info("Accurate field computations")
logger.info(
"Do computations in %s coordinates", _coord_frame_name(FIFF.FIFFV_COORD_HEAD)
Expand Down
15 changes: 6 additions & 9 deletions mne/forward/forward.py
Original file line number Diff line number Diff line change
Expand Up @@ -1259,7 +1259,7 @@ def compute_orient_prior(forward, loose="auto", verbose=None):
raise ValueError(
"loose must be 0. with forward operator "
# "with fixed orientation, got %s" % (loose,)
f"with fixed orientation, got {loose,}"
f"with fixed orientation, got {loose,}"
)
return orient_prior
if all(v == 1.0 for v in loose.values()):
Expand All @@ -1270,7 +1270,7 @@ def compute_orient_prior(forward, loose="auto", verbose=None):
raise ValueError(
"Forward operator is not oriented in surface "
"coordinates. loose parameter should be 1. "
f"not {loose,}."
f"not {loose,}."
)
start = 0
logged = dict()
Expand Down Expand Up @@ -1422,13 +1422,12 @@ def compute_depth_prior(
raise ValueError(
'limit_depth_chs, if str, must be "whiten", got '
# "%s" % (limit_depth_chs,)
f"{limit_depth_chs,}"

f"{limit_depth_chs,}"
)
if not isinstance(noise_cov, Covariance):
raise ValueError(
'With limit_depth_chs="whiten", noise_cov must be'
f" a Covariance, got {type(noise_cov),}"
f" a Covariance, got {type(noise_cov),}"
)
if combine_xyz is not False: # private / expert option
_check_option("combine_xyz", combine_xyz, ("fro", "spectral"))
Expand Down Expand Up @@ -1490,9 +1489,7 @@ def compute_depth_prior(
limit = ws[ind]
n_limit = ind

logger.info(
f" limit = {n_limit + 1}/{len(d)} = {np.sqrt(limit / ws[0])}"
)
logger.info(f" limit = {n_limit + 1}/{len(d)} = {np.sqrt(limit / ws[0])}")
scale = 1.0 / limit
logger.info(f" scale = {scale:g} exp = {exp:g}")

Expand All @@ -1518,7 +1515,7 @@ def _stc_src_sel(
if not len(src) == len(vertices):
raise RuntimeError(
f"Mismatch between number of source spaces ({len(src)}) and "
f"STC vertices ({len(vertices)})"
f"STC vertices ({len(vertices)})"
)
src_sels, stc_sels, out_vertices = [], [], []
src_offset = stc_offset = 0
Expand Down
6 changes: 2 additions & 4 deletions mne/inverse_sparse/mxne_inverse.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,7 @@ def _prepare_weights(forward, gain, source_weighting, weights, weights_min):
weights = np.max(np.abs(weights.data), axis=1)
weights_max = np.max(weights)
if weights_min > weights_max:
raise ValueError(
f"weights_min > weights_max ({weights_min} > {weights_max})"
)
raise ValueError(f"weights_min > weights_max ({weights_min} > {weights_max})")
weights_min = weights_min / weights_max
weights = weights / weights_max
n_dip_per_pos = 1 if is_fixed_orient(forward) else 3
Expand Down Expand Up @@ -813,7 +811,7 @@ def tf_mixed_norm(
if len(tstep) != len(wsize):
raise ValueError(
"The same number of window sizes and steps must be "
f"passed. Got tstep = {tstep} and wsize = {wsize}"
f"passed. Got tstep = {tstep} and wsize = {wsize}"
)

forward, gain, gain_info, whitener, source_weighting, mask = _prepare_gain(
Expand Down
7 changes: 3 additions & 4 deletions mne/inverse_sparse/mxne_optim.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ def _mixed_norm_solver_bcd(
)

if gap < tol:
logger.debug(f"Convergence reached ! (gap: {gap} < {tol})" )
logger.debug(f"Convergence reached ! (gap: {gap} < {tol})")
break

# using Anderson acceleration of the primal variable for faster
Expand Down Expand Up @@ -641,7 +641,7 @@ def gprime(w):
if weight_init is not None and weight_init.shape != (G.shape[1],):
raise ValueError(
f"Wrong dimension for weight initialization. Got {weight_init.shape}. "
f"Expected {(G.shape[1],)}."
f"Expected {(G.shape[1],)}."
)

weights = weight_init if weight_init is not None else np.ones(G.shape[1])
Expand Down Expand Up @@ -1268,7 +1268,6 @@ def _tf_mixed_norm_solver_bcd_(
E.append(p_obj)
logger.info(
f"\n Iteration {i + 1} :: n_active {np.sum(active_set) / n_orient}"

)
logger.info(f"dgap {gap}.2e :: p_obj {p_obj} :: d_obj {d_obj}")

Expand Down Expand Up @@ -1504,7 +1503,7 @@ def tf_mixed_norm_solver(
if len(tstep) != len(wsize):
raise ValueError(
"The same number of window sizes and steps must be "
f"passed. Got tstep = {tstep} and wsize = {wsize}"
f"passed. Got tstep = {tstep} and wsize = {wsize}"
)

n_steps = np.ceil(M.shape[1] / tstep.astype(float)).astype(int)
Expand Down
4 changes: 3 additions & 1 deletion mne/io/artemis123/artemis123.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,9 @@ def _get_artemis123_info(fname, pos_fname=None):
tmp[k] = v
header_info["channels"].append(tmp)
elif sectionFlag == 3:
header_info["comments"] = f"{header_info["comments"]},{line.strip()}"
header_info[
"comments"
] = f"{header_info["comments"]},{line.strip()}"
elif sectionFlag == 4:
header_info["num_samples"] = int(line.strip())
elif sectionFlag == 5:
Expand Down
9 changes: 6 additions & 3 deletions mne/io/artemis123/tests/test_artemis123.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,13 @@ def _assert_trans(actual, desired, dist_tol=0.017, angle_tol=5.0):

angle = np.rad2deg(_angle_between_quats(quat_est, quat))
dist = np.linalg.norm(trans - trans_est)
assert f"{1000 * dist:.3f} > {1000 * dist_tol:.3f} mm translation", f"{1000 * dist:.3f} > {1000 * dist_tol:.3f} mm translation"

assert f"{angle:.3f} > {angle_tol:.3f}° rotation", f"{angle:.3f} > {angle_tol:.3f}° rotation"
assert (
f"{1000 * dist:.3f} > {1000 * dist_tol:.3f} mm translation"
), f"{1000 * dist:.3f} > {1000 * dist_tol:.3f} mm translation"

assert (
f"{angle:.3f} > {angle_tol:.3f}° rotation"
), f"{angle:.3f} > {angle_tol:.3f}° rotation"


@pytest.mark.timeout(60) # ~25 s on Travis Linux OpenBLAS
Expand Down
30 changes: 14 additions & 16 deletions mne/io/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,6 @@ def _read_segment(
if data_buffer.shape != data_shape:
raise ValueError(
f"data_buffer has incorrect shape: {data_buffer.shape} != {data_shape}"

)
data = data_buffer
else:
Expand Down Expand Up @@ -1486,9 +1485,11 @@ def crop(self, tmin=0.0, tmax=None, include_tmax=True, *, verbose=None):
if tmin > tmax:
raise ValueError(f"tmin ({tmin}) must be less than tmax ({tmax})")
if tmin < 0.0:
raise ValueError(f"tmin ({tmin}) must be >= 0" )
raise ValueError(f"tmin ({tmin}) must be >= 0")
elif tmax - int(not include_tmax) / self.info["sfreq"] > max_time:
raise ValueError(f"tmax ({tmax}) must be less than or equal to the max time ({max_time:.4f} s)")
raise ValueError(
f"tmax ({tmax}) must be less than or equal to the max time ({max_time:.4f} s)"
)

smin, smax = np.where(
_time_mask(
Expand Down Expand Up @@ -1767,9 +1768,7 @@ def _tmin_tmax_to_start_stop(self, tmin, tmax):
stop = self.time_as_index(float(tmax), use_rounding=True)[0] + 1
stop = min(stop, self.last_samp - self.first_samp + 1)
if stop <= start or stop <= 0:
raise ValueError(
f"tmin ({tmin}) and tmax ({tmax}) yielded no samples"
)
raise ValueError(f"tmin ({tmin}) and tmax ({tmax}) yielded no samples")
return start, stop

@copy_function_doc_to_method_doc(plot_raw)
Expand Down Expand Up @@ -2055,10 +2054,10 @@ def __repr__(self): # noqa: D105
name = self.filenames[0]
name = "" if name is None else op.basename(name) + ", "
size_str = str(sizeof_fmt(self._size)) # str in case it fails -> None
size_str += f", data{"" if self.preload else " not"} loaded"
size_str += f", data{"" if self.preload else " not"} loaded"
s = f"{name}{len(self.ch_names)} x {self.n_times} ({self.times[-1]:.1f} s), ~{size_str}"

return f"<{self.__class__.__name__} | {s}>"
return f"<{self.__class__.__name__} | {s}>"

@repr_html
def _repr_html_(self, caption=None):
Expand Down Expand Up @@ -2111,13 +2110,13 @@ def add_events(self, events, stim_channel=None, replace=False):
stim_channel = _get_stim_channel(stim_channel, self.info)
pick = pick_channels(self.ch_names, stim_channel, ordered=False)
if len(pick) == 0:
raise ValueError(f"Channel {stim_channel} not found" )
raise ValueError(f"Channel {stim_channel} not found")
pick = pick[0]
idx = events[:, 0].astype(int)
if np.any(idx < self.first_samp) or np.any(idx > self.last_samp):
raise ValueError(
f"event sample numbers must be between {self.first_samp} and {self.last_samp}"
)
f"event sample numbers must be between {self.first_samp} and {self.last_samp}"
)

if not all(idx == events[:, 0]):
raise ValueError("event sample numbers must be integers")
Expand Down Expand Up @@ -2792,11 +2791,10 @@ def _write_raw_data(
# This should occur on the first buffer write of the file, so
# we should mention the space required for the meas info
raise ValueError(
f"buffer size ({this_buff_size_bytes}) is too large for the given split size ({split_size}) "
f"by {overage} bytes after writing info ({pos_prev}) and leaving enough space "
f'for end tags ({_NEXT_FILE_BUFFER}): decrease "buffer_size_sec" or increase "split_size".'
)

f"buffer size ({this_buff_size_bytes}) is too large for the given split size ({split_size}) "
f"by {overage} bytes after writing info ({pos_prev}) and leaving enough space "
f'for end tags ({_NEXT_FILE_BUFFER}): decrease "buffer_size_sec" or increase "split_size".'
)

new_start = last
# Split files if necessary, leave some space for next file info
Expand Down
19 changes: 9 additions & 10 deletions mne/io/brainvision/brainvision.py
Original file line number Diff line number Diff line change
Expand Up @@ -863,17 +863,16 @@ def _get_hdr_info(hdr_fname, eog, misc, scale):
nyquist = ", Nyquist limit"
else:
nyquist = ""
# warn(
# "Channels contain different lowpass filters. "
# "Highest (weakest) filter setting (%0.2f Hz%s) "
# "will be stored." % (info["lowpass"], nyquist)
# )
# warn(
# "Channels contain different lowpass filters. "
# "Highest (weakest) filter setting (%0.2f Hz%s) "
# "will be stored." % (info["lowpass"], nyquist)
# )
warn(
f"Channels contain different lowpass filters. "
f"Highest (weakest) filter setting ({info['lowpass']:.2f} Hz{nyquist}) "
"will be stored."
)

f"Channels contain different lowpass filters. "
f"Highest (weakest) filter setting ({info['lowpass']:.2f} Hz{nyquist}) "
"will be stored."
)

# Creates a list of dicts of eeg channels for raw.info
logger.info("Setting channel info structure...")
Expand Down
2 changes: 1 addition & 1 deletion mne/io/cnt/cnt.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ def _get_cnt_info(input_fname, eog, ecg, emg, misc, data_format, date_format, he
fid.seek(205)
session_label = read_str(fid, 20)

session_date = f"{read_str(fid, 10)} {read_str(fid, 12)}"
session_date = f"{read_str(fid, 10)} {read_str(fid, 12)}"
meas_date = _session_date_2_meas_date(session_date, date_format)

fid.seek(370)
Expand Down
5 changes: 3 additions & 2 deletions mne/io/ctf/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ def _check_comp_ch(cch, kind, desired=None):
if cch["grad_order_no"] != desired:
raise RuntimeError(
f"{kind} channel with inconsistent compensation "
f"grade{cch["grad_order_no"]} , should be {desired}"
f"grade{cch["grad_order_no"]} , should be {desired}"
)
return desired

Expand Down Expand Up @@ -218,7 +218,8 @@ def _convert_channel_info(res4, t, use_eeg_pos):
text += " ref"
warn(
f"{text} channel {ch["ch_name"]} did not have position assigned, so "
"it was changed to a MISC channel" )
"it was changed to a MISC channel"
)
continue
ch["unit"] = FIFF.FIFF_UNIT_T
# Set up the local coordinate frame
Expand Down
6 changes: 2 additions & 4 deletions mne/io/egi/egimff.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,15 +64,15 @@ def _read_mff_header(filepath):
record_time,
)
if g is None:
raise RuntimeError(f"Could not parse recordTime {record_time}" )
raise RuntimeError(f"Could not parse recordTime {record_time}")
frac = g.groups()[0]
assert len(frac) in (6, 9) and all(f.isnumeric() for f in frac) # regex
div = 1000 if len(frac) == 6 else 1000000
for key in ("last_samps", "first_samps"):
# convert from times in µS to samples
for ei, e in enumerate(epochs[key]):
if e % div != 0:
raise RuntimeError(f"Could not parse epoch time {e}" )
raise RuntimeError(f"Could not parse epoch time {e}")
epochs[key][ei] = e // div
epochs[key] = np.array(epochs[key], np.uint64)
# I guess they refer to times in milliseconds?
Expand Down Expand Up @@ -105,7 +105,6 @@ def _read_mff_header(filepath):
raise RuntimeError(
"EGI epoch first/last samps could not be parsed:\n"
f"{list(epochs['first_samps'])}\n{list(epochs['last_samps'])}"

)
summaryinfo.update(epochs)
# index which samples in raw are actually readable from disk (i.e., not
Expand Down Expand Up @@ -159,7 +158,6 @@ def _read_mff_header(filepath):
"PNS and signals samples did not match:\n"
# "%s\nvs\n%s" % (list(pns_samples), list(signal_samples))
f"{list(pns_samples)}\nvs\n{list(signal_samples)}"

)

pns_file = op.join(filepath, "pnsSet.xml")
Expand Down
16 changes: 7 additions & 9 deletions mne/io/eyelink/tests/test_eyelink.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,19 +233,17 @@ def _simulate_eye_tracking_data(in_file, out_file):
else:
fp.write(f"{line}\n")

fp.write(f"START\t7452389\tRIGHT\tSAMPLES\tEVENTS\n")
fp.write(f"{new_samples_line}\n" )
fp.write("START\t7452389\tRIGHT\tSAMPLES\tEVENTS\n")
fp.write(f"{new_samples_line}\n")

for timestamp in np.arange(7452389, 7453390): # simulate a second block
fp.write(
f"{timestamp}\t-2434.0\t-1760.0\t840.0\t100\t20\t45\t45\t127.0\t"
"...\t1497\t5189\t512.5\t.............\n"
)


# fp.write("%s\n" % "END\t7453390\tRIGHT\tSAMPLES\tEVENTS")
fp.write(f"END\t7453390\tRIGHT\tSAMPLES\tEVENTS\n")
f"{timestamp}\t-2434.0\t-1760.0\t840.0\t100\t20\t45\t45\t127.0\t"
"...\t1497\t5189\t512.5\t.............\n"
)

# fp.write("%s\n" % "END\t7453390\tRIGHT\tSAMPLES\tEVENTS")
fp.write("END\t7453390\tRIGHT\tSAMPLES\tEVENTS\n")


@requires_testing_data
Expand Down
Loading

0 comments on commit 51a2741

Please sign in to comment.