Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/mne-tools/mne-python into e…
Browse files Browse the repository at this point in the history
…poch_reject
  • Loading branch information
withmywoessner committed Jan 16, 2024
2 parents b2686c0 + 2040898 commit 3ae37a4
Show file tree
Hide file tree
Showing 205 changed files with 998 additions and 1,203 deletions.
1 change: 1 addition & 0 deletions .mailmap
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ Mikołaj Magnuski <[email protected]> Mikolaj Magnuski <[email protected]
Mikołaj Magnuski <[email protected]> mmagnuski <[email protected]>
Mohamed Sherif <[email protected]> mohdsherif <[email protected]>
Mohammad Daneshzand <[email protected]> mdaneshzand <[email protected]>
Motofumi Fushimi <[email protected]> motofumi-fushimi <[email protected]>
Natalie Klein <[email protected]> natalieklein <[email protected]>
Nathalie Gayraud <[email protected]> Nathalie <[email protected]>
Nathalie Gayraud <[email protected]> Nathalie <[email protected]>
Expand Down
11 changes: 5 additions & 6 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
repos:
# Ruff mne
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.11
rev: v0.1.13
hooks:
- id: ruff
name: ruff lint mne
args: ["--fix"]
files: ^mne/
- id: ruff
name: ruff lint mne preview
args: ["--fix", "--preview", "--select=NPY201"]
files: ^mne/
- id: ruff-format
name: ruff format mne
files: ^mne/

# Ruff tutorials and examples
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.11
hooks:
- id: ruff
name: ruff lint tutorials and examples
# D103: missing docstring in public function
Expand Down
1 change: 1 addition & 0 deletions doc/changes/devel/12348.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix bug in :func:`mne.preprocessing.maxwell_filter` where calibration was incorrectly applied during virtual sensor reconstruction, by `Eric Larson`_ and :newcontrib:`Motofumi Fushimi`.
1 change: 1 addition & 0 deletions doc/changes/devel/12358.other.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Refresh code base to use Python 3.9 syntax using Ruff UP rules (pyupgrade), by `Clemens Brunner`_.
2 changes: 2 additions & 0 deletions doc/changes/names.inc
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,8 @@

.. _Moritz Gerster: https://github.com/moritz-gerster

.. _Motofumi Fushimi: https://github.com/motofumi-fushimi/motofumi-fushimi.github.io

.. _Natalie Klein: https://github.com/natalieklein

.. _Nathalie Gayraud: https://github.com/ngayraud
Expand Down
2 changes: 1 addition & 1 deletion examples/datasets/limo_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@
# get levels of phase coherence
levels = sorted(phase_coh.unique())
# create labels for levels of phase coherence (i.e., 0 - 85%)
labels = ["{0:.2f}".format(i) for i in np.arange(0.0, 0.90, 0.05)]
labels = [f"{i:.2f}" for i in np.arange(0.0, 0.90, 0.05)]

# create dict of evokeds for each level of phase-coherence
evokeds = {
Expand Down
4 changes: 2 additions & 2 deletions examples/datasets/opm_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,8 @@
)
idx = np.argmax(dip_opm.gof)
print(
"Best dipole at t=%0.1f ms with %0.1f%% GOF"
% (1000 * dip_opm.times[idx], dip_opm.gof[idx])
f"Best dipole at t={1000 * dip_opm.times[idx]:0.1f} ms with "
f"{dip_opm.gof[idx]:0.1f}% GOF"
)

# Plot N20m dipole as an example
Expand Down
4 changes: 1 addition & 3 deletions examples/decoding/decoding_csp_eeg.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,7 @@
# Printing the results
class_balance = np.mean(labels == labels[0])
class_balance = max(class_balance, 1.0 - class_balance)
print(
"Classification accuracy: %f / Chance level: %f" % (np.mean(scores), class_balance)
)
print(f"Classification accuracy: {np.mean(scores)} / Chance level: {class_balance}")

# plot CSP patterns estimated on full data for visualization
csp.fit_transform(epochs_data, labels)
Expand Down
14 changes: 7 additions & 7 deletions examples/decoding/receptive_field_mtrf.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@
coefs = np.zeros((n_splits, n_channels, n_delays))
scores = np.zeros((n_splits, n_channels))
for ii, (train, test) in enumerate(cv.split(speech)):
print("split %s / %s" % (ii + 1, n_splits))
print(f"split {ii + 1} / {n_splits}")
rf.fit(speech[train], Y[train])
scores[ii] = rf.score(speech[test], Y[test])
# coef_ is shape (n_outputs, n_features, n_delays). we only have 1 feature
Expand Down Expand Up @@ -212,7 +212,7 @@
patterns = coefs.copy()
scores = np.zeros((n_splits,))
for ii, (train, test) in enumerate(cv.split(speech)):
print("split %s / %s" % (ii + 1, n_splits))
print(f"split {ii + 1} / {n_splits}")
sr.fit(Y[train], speech[train])
scores[ii] = sr.score(Y[test], speech[test])[0]
# coef_ is shape (n_outputs, n_features, n_delays). We have 128 features
Expand Down Expand Up @@ -272,9 +272,7 @@
show=False,
vlim=(-max_coef, max_coef),
)
ax[0].set(
title="Model coefficients\nbetween delays %s and %s" % (time_plot[0], time_plot[1])
)
ax[0].set(title=f"Model coefficients\nbetween delays {time_plot[0]} and {time_plot[1]}")

mne.viz.plot_topomap(
np.mean(mean_patterns[:, ix_plot], axis=1),
Expand All @@ -284,8 +282,10 @@
vlim=(-max_patterns, max_patterns),
)
ax[1].set(
title="Inverse-transformed coefficients\nbetween delays %s and %s"
% (time_plot[0], time_plot[1])
title=(
f"Inverse-transformed coefficients\nbetween delays {time_plot[0]} and "
f"{time_plot[1]}"
)
)

# %%
Expand Down
2 changes: 1 addition & 1 deletion examples/inverse/compute_mne_inverse_raw_in_label.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
)

# Save result in stc files
stc.save("mne_%s_raw_inverse_%s" % (method, label_name), overwrite=True)
stc.save(f"mne_{method}_raw_inverse_{label_name}", overwrite=True)

# %%
# View activation time-series
Expand Down
2 changes: 1 addition & 1 deletion examples/inverse/compute_mne_inverse_volume.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,5 @@
index_img(img, 61),
str(t1_fname),
threshold=8.0,
title="%s (t=%.1f s.)" % (method, stc.times[61]),
title=f"{method} (t={stc.times[61]:.1f} s.)",
)
12 changes: 2 additions & 10 deletions examples/inverse/evoked_ers_source_power.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,7 @@
data_path = somato.data_path()
subject = "01"
task = "somato"
raw_fname = (
data_path
/ "sub-{}".format(subject)
/ "meg"
/ "sub-{}_task-{}_meg.fif".format(subject, task)
)
raw_fname = data_path / f"sub-{subject}" / "meg" / f"sub-{subject}_task-{task}_meg.fif"

# crop to 5 minutes to save memory
raw = mne.io.read_raw_fif(raw_fname).crop(0, 300)
Expand All @@ -59,10 +54,7 @@

# Read forward operator and point to freesurfer subject directory
fname_fwd = (
data_path
/ "derivatives"
/ "sub-{}".format(subject)
/ "sub-{}_task-{}-fwd.fif".format(subject, task)
data_path / "derivatives" / f"sub-{subject}" / f"sub-{subject}_task-{task}-fwd.fif"
)
subjects_dir = data_path / "derivatives" / "freesurfer" / "subjects"

Expand Down
2 changes: 1 addition & 1 deletion examples/inverse/label_source_activations.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@
ax.set(
xlabel="Time (ms)",
ylabel="Source amplitude",
title="Mean vector activations in Label %r" % (label.name,),
title=f"Mean vector activations in Label {label.name!r}",
xlim=xlim,
ylim=ylim,
)
4 changes: 2 additions & 2 deletions examples/inverse/mixed_norm_inverse.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@
forward["src"],
stc,
bgcolor=(1, 1, 1),
fig_name="%s (cond %s)" % (solver, condition),
fig_name=f"{solver} (cond {condition})",
opacity=0.1,
)

Expand All @@ -159,7 +159,7 @@
src_fsaverage,
stc_fsaverage,
bgcolor=(1, 1, 1),
fig_name="Morphed %s (cond %s)" % (solver, condition),
fig_name=f"Morphed {solver} (cond {condition})",
opacity=0.1,
)

Expand Down
4 changes: 1 addition & 3 deletions examples/inverse/read_stc.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@
stc = mne.read_source_estimate(fname)

n_vertices, n_samples = stc.data.shape
print(
"stc data size: %s (nb of vertices) x %s (nb of samples)" % (n_vertices, n_samples)
)
print(f"stc data size: {n_vertices} (nb of vertices) x {n_samples} (nb of samples)")

# View source activations
plt.plot(stc.times, stc.data[::100, :].T)
Expand Down
2 changes: 1 addition & 1 deletion examples/preprocessing/define_target_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@

# average epochs and get an Evoked dataset.

early, late = [epochs[k].average() for k in event_id]
early, late = (epochs[k].average() for k in event_id)

# %%
# View evoked response
Expand Down
11 changes: 1 addition & 10 deletions examples/preprocessing/eeg_bridging.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,16 +384,7 @@
raw = raw_data[1]
# typically impedances < 25 kOhm are acceptable for active systems and
# impedances < 5 kOhm are desirable for a passive system
impedances = (
rng.random(
(
len(
raw.ch_names,
)
)
)
* 30
)
impedances = rng.random(len(raw.ch_names)) * 30
impedances[10] = 80 # set a few bad impendances
impedances[25] = 99
cmap = LinearSegmentedColormap.from_list(
Expand Down
2 changes: 1 addition & 1 deletion examples/preprocessing/ica_comparison.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def run_ica(method, fit_params=None):
t0 = time()
ica.fit(raw, reject=reject)
fit_time = time() - t0
title = "ICA decomposition using %s (took %.1fs)" % (method, fit_time)
title = f"ICA decomposition using {method} (took {fit_time:.1f}s)"
ica.plot_components(title=title)


Expand Down
10 changes: 2 additions & 8 deletions examples/preprocessing/otp.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,15 +79,9 @@ def compute_bias(raw):


bias = compute_bias(raw)
print("Raw bias: %0.1fmm (worst: %0.1fmm)" % (np.mean(bias), np.max(bias)))
print(f"Raw bias: {np.mean(bias):0.1f}mm (worst: {np.max(bias):0.1f}mm)")
bias_clean = compute_bias(raw_clean)
print(
"OTP bias: %0.1fmm (worst: %0.1fmm)"
% (
np.mean(bias_clean),
np.max(bias_clean),
)
)
print(f"OTP bias: {np.mean(bias_clean):0.1f}mm (worst: {np.max(bias_clean):0.1f}m)")

# %%
# References
Expand Down
4 changes: 2 additions & 2 deletions examples/simulation/simulate_raw_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@ def data_fun(times):
global n
n_samp = len(times)
window = np.zeros(n_samp)
start, stop = [
start, stop = (
int(ii * float(n_samp) / (2 * n_dipoles)) for ii in (2 * n, 2 * n + 1)
]
)
window[start:stop] = 1.0
n += 1
data = 25e-9 * np.sin(2.0 * np.pi * 10.0 * n * times)
Expand Down
2 changes: 1 addition & 1 deletion examples/time_frequency/time_frequency_simulated.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@
power.plot(
[0], baseline=(0.0, 0.1), mode="mean", axes=ax, show=False, colorbar=False
)
ax.set_title("Sim: Using S transform, width = {:0.1f}".format(width))
ax.set_title(f"Sim: Using S transform, width = {width:0.1f}")

# %%
# Morlet Wavelets
Expand Down
2 changes: 1 addition & 1 deletion examples/visualization/evoked_topomap.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@
colorbar=False,
sphere=(0.0, 0.0, 0.0, 0.09),
)
ax.set_title("%s %s" % (ch_type.upper(), extr), fontsize=14)
ax.set_title(f"{ch_type.upper()} {extr}", fontsize=14)

# %%
# More advanced usage
Expand Down
2 changes: 1 addition & 1 deletion examples/visualization/evoked_whitening.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@

print("Covariance estimates sorted from best to worst")
for c in noise_covs:
print("%s : %s" % (c["method"], c["loglik"]))
print(f'{c["method"]} : {c["loglik"]}')

# %%
# Show the evoked data:
Expand Down
30 changes: 13 additions & 17 deletions mne/_fiff/_digitization.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,14 +132,15 @@ def __repr__(self): # noqa: D105
id_ = _cardinal_kind_rev.get(self["ident"], "Unknown cardinal")
else:
id_ = _dig_kind_proper[_dig_kind_rev.get(self["kind"], "unknown")]
id_ = "%s #%s" % (id_, self["ident"])
id_ = f"{id_} #{self['ident']}"
id_ = id_.rjust(10)
cf = _coord_frame_name(self["coord_frame"])
x, y, z = self["r"]
if "voxel" in cf:
pos = ("(%0.1f, %0.1f, %0.1f)" % tuple(self["r"])).ljust(25)
pos = (f"({x:0.1f}, {y:0.1f}, {z:0.1f})").ljust(25)
else:
pos = ("(%0.1f, %0.1f, %0.1f) mm" % tuple(1000 * self["r"])).ljust(25)
return "<DigPoint | %s : %s : %s frame>" % (id_, pos, cf)
pos = (f"({x * 1e3:0.1f}, {y * 1e3:0.1f}, {z * 1e3:0.1f}) mm").ljust(25)
return f"<DigPoint | {id_} : {pos} : {cf} frame>"

# speed up info copy by only deep copying the mutable item
def __deepcopy__(self, memodict):
Expand Down Expand Up @@ -362,8 +363,8 @@ def _coord_frame_const(coord_frame):

if not isinstance(coord_frame, str) or coord_frame not in _str_to_frame:
raise ValueError(
"coord_frame must be one of %s, got %s"
% (sorted(_str_to_frame.keys()), coord_frame)
f"coord_frame must be one of {sorted(_str_to_frame.keys())}, got "
f"{coord_frame}"
)
return _str_to_frame[coord_frame]

Expand Down Expand Up @@ -414,9 +415,7 @@ def _make_dig_points(
if lpa is not None:
lpa = np.asarray(lpa)
if lpa.shape != (3,):
raise ValueError(
"LPA should have the shape (3,) instead of %s" % (lpa.shape,)
)
raise ValueError(f"LPA should have the shape (3,) instead of {lpa.shape}")
dig.append(
{
"r": lpa,
Expand All @@ -429,7 +428,7 @@ def _make_dig_points(
nasion = np.asarray(nasion)
if nasion.shape != (3,):
raise ValueError(
"Nasion should have the shape (3,) instead of %s" % (nasion.shape,)
f"Nasion should have the shape (3,) instead of {nasion.shape}"
)
dig.append(
{
Expand All @@ -442,9 +441,7 @@ def _make_dig_points(
if rpa is not None:
rpa = np.asarray(rpa)
if rpa.shape != (3,):
raise ValueError(
"RPA should have the shape (3,) instead of %s" % (rpa.shape,)
)
raise ValueError(f"RPA should have the shape (3,) instead of {rpa.shape}")
dig.append(
{
"r": rpa,
Expand All @@ -457,8 +454,7 @@ def _make_dig_points(
hpi = np.asarray(hpi)
if hpi.ndim != 2 or hpi.shape[1] != 3:
raise ValueError(
"HPI should have the shape (n_points, 3) instead "
"of %s" % (hpi.shape,)
f"HPI should have the shape (n_points, 3) instead of {hpi.shape}"
)
for idx, point in enumerate(hpi):
dig.append(
Expand All @@ -473,8 +469,8 @@ def _make_dig_points(
extra_points = np.asarray(extra_points)
if len(extra_points) and extra_points.shape[1] != 3:
raise ValueError(
"Points should have the shape (n_points, 3) "
"instead of %s" % (extra_points.shape,)
"Points should have the shape (n_points, 3) instead of "
f"{extra_points.shape}"
)
for idx, point in enumerate(extra_points):
dig.append(
Expand Down
Loading

0 comments on commit 3ae37a4

Please sign in to comment.