Skip to content

Commit

Permalink
Fixes for #12360 Replacing percent format with f-strings (#12464)
Browse files Browse the repository at this point in the history
Co-authored-by: Clemens Brunner <clemens.brunner@gmail.com>
Co-authored-by: Daniel McCloy <dan@mccloy.info>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Eric Larson <larson.eric.d@gmail.com>
  • Loading branch information
5 people committed Mar 19, 2024
1 parent f65bc00 commit b8d9c17
Show file tree
Hide file tree
Showing 91 changed files with 504 additions and 629 deletions.
2 changes: 2 additions & 0 deletions doc/changes/devel/12464.other.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Replacing percent format with f-strings format specifiers , by :newcontrib:`Hasrat Ali Arzoo`.

2 changes: 2 additions & 0 deletions doc/changes/names.inc
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,8 @@

.. _Hari Bharadwaj: https://github.com/haribharadwaj

.. _Hasrat Ali Arzoo: https://github.com/hasrat17

.. _Henrich Kolkhorst: https://github.com/hekolk

.. _Hongjiang Ye: https://github.com/hongjiang-ye
Expand Down
4 changes: 3 additions & 1 deletion doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -683,7 +683,9 @@ def append_attr_meth_examples(app, what, name, obj, options, lines):
if what in ("attribute", "method"):
size = os.path.getsize(
os.path.join(
os.path.dirname(__file__), "generated", "%s.examples" % (name,)
os.path.dirname(__file__),
"generated",
f"{name}.examples",
)
)
if size > 0:
Expand Down
14 changes: 5 additions & 9 deletions doc/sphinxext/flow_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,14 @@
sensor_color = "#7bbeca"
source_color = "#ff6347"

legend = """
<<FONT POINT-SIZE="%s">
legend = f"""
<<FONT POINT-SIZE="{edge_size}">
<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="4" CELLPADDING="4">
<TR><TD BGCOLOR="%s"> </TD><TD ALIGN="left">
<TR><TD BGCOLOR="{sensor_color}"> </TD><TD ALIGN="left">
Sensor (M/EEG) space</TD></TR>
<TR><TD BGCOLOR="%s"> </TD><TD ALIGN="left">
<TR><TD BGCOLOR="{source_color}"> </TD><TD ALIGN="left">
Source (brain) space</TD></TR>
</TABLE></FONT>>""" % (
edge_size,
sensor_color,
source_color,
)
</TABLE></FONT>>"""
legend = "".join(legend.split("\n"))

nodes = dict(
Expand Down
12 changes: 4 additions & 8 deletions doc/sphinxext/mne_substitutions.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,14 @@ def run(self, **kwargs): # noqa: D102
):
keys.append(key)
rst = "- " + "\n- ".join(
"``%r``: **%s** (scaled by %g to plot in *%s*)"
% (
key,
DEFAULTS["titles"][key],
DEFAULTS["scalings"][key],
DEFAULTS["units"][key],
)
f"``{repr(key)}``: **{DEFAULTS['titles'][key]}** "
f"(scaled by {DEFAULTS['scalings'][key]} to "
f"plot in *{DEFAULTS['units'][key]}*)"
for key in keys
)
else:
raise self.error(
"MNE directive unknown in %s: %r"
"MNE directive unknown in %s: %r" # noqa: UP031
% (
env.doc2path(env.docname, base=None),
self.arguments[0],
Expand Down
4 changes: 2 additions & 2 deletions mne/epochs.py
Original file line number Diff line number Diff line change
Expand Up @@ -3860,8 +3860,8 @@ def _is_good(
bad_names = [ch_names[idx[i]] for i in idx_deltas]
if not has_printed:
logger.info(
" Rejecting %s epoch based on %s : "
"%s" % (t, name, bad_names)
f" Rejecting {t} epoch based on {name} : "
f"{bad_names}"
)
has_printed = True
if not full_report:
Expand Down
16 changes: 8 additions & 8 deletions mne/fixes.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def _safe_svd(A, **kwargs):
except np.linalg.LinAlgError as exp:
from .utils import warn

warn("SVD error (%s), attempting to use GESVD instead of GESDD" % (exp,))
warn(f"SVD error ({exp}), attempting to use GESVD instead of GESDD")
return linalg.svd(A, lapack_driver="gesvd", **kwargs)


Expand Down Expand Up @@ -192,8 +192,8 @@ def _get_param_names(cls):
"scikit-learn estimators should always "
"specify their parameters in the signature"
" of their __init__ (no varargs)."
" %s with constructor %s doesn't "
" follow this convention." % (cls, init_signature)
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 @@ -264,20 +264,20 @@ def set_params(self, **params):
name, sub_name = split
if name not in valid_params:
raise ValueError(
"Invalid parameter %s for estimator %s. "
f"Invalid parameter {name} for estimator {self}. "
"Check the list of available parameters "
"with `estimator.get_params().keys()`." % (name, self)
"with `estimator.get_params().keys()`."
)
sub_object = valid_params[name]
sub_object.set_params(**{sub_name: value})
else:
# simple objects case
if key not in valid_params:
raise ValueError(
"Invalid parameter %s for estimator %s. "
f"Invalid parameter {key} for estimator "
f"{self.__class__.__name__}. "
"Check the list of available parameters "
"with `estimator.get_params().keys()`."
% (key, self.__class__.__name__)
)
setattr(self, key, value)
return self
Expand All @@ -287,7 +287,7 @@ def __repr__(self): # noqa: D105
pprint(self.get_params(deep=False), params)
params.seek(0)
class_name = self.__class__.__name__
return "%s(%s)" % (class_name, params.read().strip())
return f"{class_name}({params.read().strip()})"

# __getstate__ and __setstate__ are omitted because they only contain
# conditionals that are not satisfied by our objects (e.g.,
Expand Down
2 changes: 1 addition & 1 deletion mne/forward/_compute_forward.py
Original file line number Diff line number Diff line change
Expand Up @@ -661,7 +661,7 @@ def _magnetic_dipole_field_vec(rrs, coils, too_close="raise"):
rmags, cosmags, ws, bins = _triage_coils(coils)
fwd, min_dist = _compute_mdfv(rrs, rmags, cosmags, ws, bins, too_close)
if min_dist < _MIN_DIST_LIMIT:
msg = "Coil too close (dist = %g mm)" % (min_dist * 1000,)
msg = f"Coil too close (dist = {min_dist * 1000:g} mm)"
if too_close == "raise":
raise RuntimeError(msg)
func = warn if too_close == "warning" else logger.info
Expand Down
4 changes: 2 additions & 2 deletions mne/forward/_lead_dots.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,12 @@ def _get_legen_table(
# Updated due to API change (GH 1167)
os.makedirs(fname)
if ch_type == "meg":
fname = op.join(fname, "legder_%s_%s.bin" % (n_coeff, n_interp))
fname = op.join(fname, f"legder_{n_coeff}_{n_interp}.bin")
leg_fun = _get_legen_der
extra_str = " derivative"
lut_shape = (n_interp + 1, n_coeff, 3)
else: # 'eeg'
fname = op.join(fname, "legval_%s_%s.bin" % (n_coeff, n_interp))
fname = op.join(fname, f"legval_{n_coeff}_{n_interp}.bin")
leg_fun = _get_legen
extra_str = ""
lut_shape = (n_interp + 1, n_coeff)
Expand Down
6 changes: 3 additions & 3 deletions mne/forward/_make_forward.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,8 +299,8 @@ def _setup_bem(bem, bem_extra, neeg, mri_head_t, allow_none=False, verbose=None)
else:
if bem["surfs"][0]["coord_frame"] != FIFF.FIFFV_COORD_MRI:
raise RuntimeError(
"BEM is in %s coordinates, should be in MRI"
% (_coord_frame_name(bem["surfs"][0]["coord_frame"]),)
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 @@ -693,7 +693,7 @@ def make_forward_solution(
logger.info("MRI -> head transform : %s" % trans)
logger.info("Measurement data : %s" % info_extra)
if isinstance(bem, ConductorModel) and bem["is_sphere"]:
logger.info("Sphere model : origin at %s mm" % (bem["r0"],))
logger.info(f"Sphere model : origin at {bem['r0']} mm")
logger.info("Standard field computations")
else:
logger.info("Conductor model : %s" % bem_extra)
Expand Down
15 changes: 7 additions & 8 deletions mne/forward/forward.py
Original file line number Diff line number Diff line change
Expand Up @@ -1258,7 +1258,7 @@ def compute_orient_prior(forward, loose="auto", verbose=None):
if any(v > 0.0 for v in loose.values()):
raise ValueError(
"loose must be 0. with forward operator "
"with fixed orientation, got %s" % (loose,)
f"with fixed orientation, got {loose}"
)
return orient_prior
if all(v == 1.0 for v in loose.values()):
Expand All @@ -1269,7 +1269,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. "
"not %s." % (loose,)
f"not {loose}."
)
start = 0
logged = dict()
Expand Down Expand Up @@ -1419,13 +1419,12 @@ def compute_depth_prior(
if isinstance(limit_depth_chs, str):
if limit_depth_chs != "whiten":
raise ValueError(
'limit_depth_chs, if str, must be "whiten", got '
"%s" % (limit_depth_chs,)
f'limit_depth_chs, if str, must be "whiten", got {limit_depth_chs}'
)
if not isinstance(noise_cov, Covariance):
raise ValueError(
'With limit_depth_chs="whiten", noise_cov must be'
" a Covariance, got %s" % (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 @@ -1491,7 +1490,7 @@ def compute_depth_prior(
" limit = %d/%d = %f" % (n_limit + 1, len(d), np.sqrt(limit / ws[0]))
)
scale = 1.0 / limit
logger.info(" scale = %g exp = %g" % (scale, exp))
logger.info(f" scale = {scale:g} exp = {exp:g}")
w = np.minimum(w / limit, 1)
depth_prior = w**exp

Expand All @@ -1513,8 +1512,8 @@ def _stc_src_sel(
del stc
if not len(src) == len(vertices):
raise RuntimeError(
"Mismatch between number of source spaces (%s) and "
"STC vertices (%s)" % (len(src), len(vertices))
f"Mismatch between number of source spaces ({len(src)}) and "
f"STC vertices ({len(vertices)})"
)
src_sels, stc_sels, out_vertices = [], [], []
src_offset = stc_offset = 0
Expand Down
8 changes: 3 additions & 5 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(
"weights_min > weights_max (%s > %s)" % (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 "
"passed. Got tstep = %s and wsize = %s" % (tstep, wsize)
f"passed. Got tstep = {tstep} and wsize = {wsize}"
)

forward, gain, gain_info, whitener, source_weighting, mask = _prepare_gain(
Expand Down Expand Up @@ -1090,7 +1088,7 @@ def _compute_sure_val(coef1, coef2, gain, M, sigma, delta, eps):
for i, (coef1, coef2) in enumerate(zip(coefs_grid_1, coefs_grid_2)):
sure_path[i] = _compute_sure_val(coef1, coef2, gain, M, sigma, delta, eps)
if verbose:
logger.info("alpha %s :: sure %s" % (alpha_grid[i], sure_path[i]))
logger.info(f"alpha {alpha_grid[i]} :: sure {sure_path[i]}")
best_alpha_ = alpha_grid[np.argmin(sure_path)]

X = coefs_grid_1[np.argmin(sure_path)]
Expand Down
16 changes: 8 additions & 8 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("Convergence reached ! (gap: %s < %s)" % (gap, tol))
logger.debug(f"Convergence reached ! (gap: {gap} < {tol})")
break

# using Anderson acceleration of the primal variable for faster
Expand Down Expand Up @@ -525,7 +525,7 @@ def mixed_norm_solver(
)
)
if gap < tol:
logger.info("Convergence reached ! (gap: %s < %s)" % (gap, tol))
logger.info(f"Convergence reached ! (gap: {gap} < {tol})")
break

# add sources if not last iteration
Expand All @@ -545,7 +545,7 @@ def mixed_norm_solver(
idx = np.searchsorted(idx_active_set, idx_old_active_set)
X_init[idx] = X
else:
warn("Did NOT converge ! (gap: %s > %s)" % (gap, tol))
warn(f"Did NOT converge ! (gap: {gap} > {tol})")
else:
X, active_set, E = l21_solver(
M, G, alpha, lc, maxit=maxit, tol=tol, n_orient=n_orient, init=None
Expand Down Expand Up @@ -640,8 +640,8 @@ def gprime(w):

if weight_init is not None and weight_init.shape != (G.shape[1],):
raise ValueError(
"Wrong dimension for weight initialization. Got %s. "
"Expected %s." % (weight_init.shape, (G.shape[1],))
f"Wrong dimension for weight initialization. Got {weight_init.shape}. "
f"Expected {(G.shape[1],)}."
)

weights = weight_init if weight_init is not None else np.ones(G.shape[1])
Expand Down Expand Up @@ -1270,7 +1270,7 @@ def _tf_mixed_norm_solver_bcd_(
"\n Iteration %d :: n_active %d"
% (i + 1, np.sum(active_set) / n_orient)
)
logger.info(" dgap %.2e :: p_obj %f :: d_obj %f" % (gap, p_obj, d_obj))
logger.info(f" dgap {gap:.2e} :: p_obj {p_obj} :: d_obj {d_obj}")

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

n_steps = np.ceil(M.shape[1] / tstep.astype(float)).astype(int)
Expand Down Expand Up @@ -1624,7 +1624,7 @@ def iterative_tf_mixed_norm_solver(
if len(tstep) != len(wsize):
raise ValueError(
"The same number of window sizes and steps must be "
"passed. Got tstep = %s and wsize = %s" % (tstep, wsize)
f"passed. Got tstep = {tstep} and wsize = {wsize}"
)

n_steps = np.ceil(n_times / tstep.astype(float)).astype(int)
Expand Down
5 changes: 1 addition & 4 deletions mne/io/artemis123/artemis123.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,7 @@ def _get_artemis123_info(fname, pos_fname=None):
tmp[k] = v
header_info["channels"].append(tmp)
elif sectionFlag == 3:
header_info["comments"] = "%s%s" % (
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
7 changes: 3 additions & 4 deletions mne/io/artemis123/tests/test_artemis123.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,10 @@ 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 dist <= dist_tol, "%0.3f > %0.3f mm translation" % (
1000 * dist,
1000 * dist_tol,
assert dist <= dist_tol, (
f"{1000 * dist:0.3f} > {1000 * dist_tol:0.3f} " "mm translation"
)
assert angle <= angle_tol, "%0.3f > %0.3f° rotation" % (angle, angle_tol)
assert angle <= angle_tol, f"{angle:0.3f} > {angle_tol:0.3f}° rotation"


@pytest.mark.timeout(60) # ~25 s on Travis Linux OpenBLAS
Expand Down
Loading

0 comments on commit b8d9c17

Please sign in to comment.