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 20, 2025
1 parent bbc4bd2 commit 5bec6b5
Show file tree
Hide file tree
Showing 16 changed files with 63 additions and 87 deletions.
8 changes: 4 additions & 4 deletions examples/mark_bad_channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@
raw = read_raw_bids(bids_path=bids_path, verbose=False)
print(
f"The following channels are currently marked as bad:\n"
f' {", ".join(raw.info["bads"])}\n'
f" {', '.join(raw.info['bads'])}\n"
)

# %%
Expand All @@ -137,7 +137,7 @@
raw = read_raw_bids(bids_path=bids_path, verbose=False)
print(
f"After marking MEG 0112 and MEG 0131 as bad, the following channels "
f'are now marked as bad:\n {", ".join(raw.info["bads"])}\n'
f"are now marked as bad:\n {', '.join(raw.info['bads'])}\n"
)

# %%
Expand All @@ -159,7 +159,7 @@
print(
f"After marking MEG 0112 and MEG 0131 as bad and passing "
f"`overwrite=True`, the following channels "
f'are now marked as bad:\n {", ".join(raw.info["bads"])}\n'
f"are now marked as bad:\n {', '.join(raw.info['bads'])}\n"
)

# %%
Expand All @@ -172,5 +172,5 @@
raw = read_raw_bids(bids_path=bids_path, verbose=False)
print(
f"After passing `ch_names=[]` and `overwrite=True`, the following "
f'channels are now marked as bad:\n {", ".join(raw.info["bads"])}\n'
f"channels are now marked as bad:\n {', '.join(raw.info['bads'])}\n"
)
4 changes: 1 addition & 3 deletions mne_bids/commands/mne_bids_calibration_to_bids.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,7 @@ def run():
opt, args = parser.parse_args()
if args:
parser.print_help()
parser.error(
f"Please do not specify arguments without flags. " f"Got: {args}.\n"
)
parser.error(f"Please do not specify arguments without flags. Got: {args}.\n")

Check warning on line 47 in mne_bids/commands/mne_bids_calibration_to_bids.py

View check run for this annotation

Codecov / codecov/patch

mne_bids/commands/mne_bids_calibration_to_bids.py#L47

Added line #L47 was not covered by tests

if opt.bids_root is None:
parser.print_help()
Expand Down
4 changes: 1 addition & 3 deletions mne_bids/commands/mne_bids_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,7 @@ def run():
opt, args = parser.parse_args()
if args:
parser.print_help()
parser.error(
f"Please do not specify arguments without flags. " f"Got: {args}.\n"
)
parser.error(f"Please do not specify arguments without flags. Got: {args}.\n")

Check warning on line 75 in mne_bids/commands/mne_bids_inspect.py

View check run for this annotation

Codecov / codecov/patch

mne_bids/commands/mne_bids_inspect.py#L75

Added line #L75 was not covered by tests

if opt.bids_root is None:
parser.print_help()
Expand Down
2 changes: 1 addition & 1 deletion mne_bids/commands/mne_bids_mark_channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ def run():
return # XXX should be return with an error code?

logger.info(
f'Marking channels {", ".join(ch_names)} as bad in '
f"Marking channels {', '.join(ch_names)} as bad in "
f"{len(bids_paths)} recording(s) …"
)
for bids_path in bids_paths:
Expand Down
3 changes: 1 addition & 2 deletions mne_bids/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -530,8 +530,7 @@ def _map_options(what, key, fro, to):
mapped_option = mapping_mne_bids.get(key, None)
else:
raise RuntimeError(
f"fro value {fro} and to value {to} are not "
"accepted. Use 'mne', or 'bids'."
f"fro value {fro} and to value {to} are not accepted. Use 'mne', or 'bids'."
)

return mapped_option
Expand Down
10 changes: 5 additions & 5 deletions mne_bids/copyfiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def _get_brainvision_paths(vhdr_path):
"""
fname, ext = _parse_ext(vhdr_path)
if ext != ".vhdr":
raise ValueError(f'Expecting file ending in ".vhdr",' f" but got {ext}")
raise ValueError(f'Expecting file ending in ".vhdr", but got {ext}')

# Header file seems fine
# extract encoding from brainvision header file, or default to utf-8
Expand All @@ -96,14 +96,14 @@ def _get_brainvision_paths(vhdr_path):
eeg_file_match = re.search(r"DataFile=(.*\.(eeg|dat))", " ".join(lines))

if not eeg_file_match:
raise ValueError("Could not find a .eeg or .dat file link in" f" {vhdr_path}")
raise ValueError(f"Could not find a .eeg or .dat file link in {vhdr_path}")
else:
eeg_file = eeg_file_match.groups()[0]

# Try to find marker file .vmrk
vmrk_file_match = re.search(r"MarkerFile=(.*\.vmrk)", " ".join(lines))
if not vmrk_file_match:
raise ValueError("Could not find a .vmrk file link in" f" {vhdr_path}")
raise ValueError(f"Could not find a .vmrk file link in {vhdr_path}")
else:
vmrk_file = vmrk_file_match.groups()[0]

Expand Down Expand Up @@ -275,7 +275,7 @@ def _anonymize_brainvision(vhdr_file, date):

# Go through VHDR
pattern = re.compile(r"^Impedance \[kOhm\] at \d\d:\d\d:\d\d :$")
replace = f'at {date.strftime("%H:%M:%S")} :'
replace = f"at {date.strftime('%H:%M:%S')} :"
_replace_file(vhdr_file, pattern, replace)


Expand Down Expand Up @@ -544,7 +544,7 @@ def copyfile_eeglab(src, dest):
fname_dest, ext_dest = _parse_ext(dest)
if ext_src != ext_dest:
raise ValueError(
f"Need to move data with same extension" f" but got {ext_src}, {ext_dest}"
f"Need to move data with same extension but got {ext_src}, {ext_dest}"
)

# Load the EEG struct
Expand Down
4 changes: 2 additions & 2 deletions mne_bids/dig.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def _handle_electrodes_reading(electrodes_fname, coord_frame, coord_unit):
Handle xyz coordinates and coordinate frame of each channel.
"""
logger.info("Reading electrode " f"coords from {electrodes_fname}.")
logger.info(f"Reading electrode coords from {electrodes_fname}.")
electrodes_dict = _from_tsv(electrodes_fname)
ch_names_tsv = electrodes_dict["name"]

Expand Down Expand Up @@ -142,7 +142,7 @@ def _write_electrodes_tsv(raw, fname, datatype, overwrite=False):
x, y, z, names = list(), list(), list(), list()
for ch in raw.info["chs"]:
if ch["kind"] == FIFF.FIFFV_STIM_CH:
logger.debug(f"Not writing stim chan {ch['ch_name']} " f"to electrodes.tsv")
logger.debug(f"Not writing stim chan {ch['ch_name']} to electrodes.tsv")
continue
elif np.isnan(ch["loc"][:3]).any() or np.allclose(ch["loc"][:3], 0):
x.append("n/a")
Expand Down
23 changes: 11 additions & 12 deletions mne_bids/path.py
Original file line number Diff line number Diff line change
Expand Up @@ -905,9 +905,9 @@ def fpath(self):
msg = (
"Found more than one matching data file for the "
"requested recording. While searching:\n"
f'{indent(repr(self), " ")}\n'
f"{indent(repr(self), ' ')}\n"
f"Found {len(matching_paths)} paths:\n"
f'{indent(matching_paths_str, " ")}\n'
f"{indent(matching_paths_str, ' ')}\n"
"Cannot proceed due to the "
"ambiguity. This is likely a problem with your "
"BIDS dataset. Please run the BIDS validator on "
Expand Down Expand Up @@ -1005,7 +1005,7 @@ def update(self, *, check=None, **kwargs):

if key not in ENTITY_VALUE_TYPE:
raise ValueError(
f"Key must be one of " f"{ALLOWED_PATH_ENTITIES}, got {key}"
f"Key must be one of {ALLOWED_PATH_ENTITIES}, got {key}"
)

if ENTITY_VALUE_TYPE[key] == "label":
Expand Down Expand Up @@ -1152,7 +1152,7 @@ def _check(self):
allowed_spaces_for_dtype = ALLOWED_SPACES.get(datatype, None)
if allowed_spaces_for_dtype is None:
raise ValueError(
f"space entity is not valid for datatype " f"{self.datatype}"
f"space entity is not valid for datatype {self.datatype}"
)
elif space not in allowed_spaces_for_dtype:
raise ValueError(
Expand Down Expand Up @@ -1462,7 +1462,9 @@ def _truncate_tsv_line(line, lim=10):
"""Truncate a line to the specified number of characters."""
return "".join(
[
str(val) + (lim - len(val)) * " " if len(val) < lim else f"{val[:lim - 1]} "
str(val) + (lim - len(val)) * " "
if len(val) < lim
else f"{val[: lim - 1]} "
for val in line.split("\t")
]
)
Expand Down Expand Up @@ -1762,7 +1764,7 @@ def get_entities_from_fname(fname, on_error="raise", verbose=None):

if on_error in ("raise", "warn"):
if key not in fname_vals:
msg = f'Unexpected entity "{key}" found in ' f'filename "{fname}"'
msg = f'Unexpected entity "{key}" found in filename "{fname}"'
if on_error == "raise":
raise KeyError(msg)
elif on_error == "warn":
Expand Down Expand Up @@ -1864,10 +1866,7 @@ def _find_matching_sidecar(bids_path, suffix=None, extension=None, on_error="rai
# If this was expected, simply return None, otherwise, raise an exception.
msg = None
if len(best_candidates) == 0:
msg = (
f"Did not find any {search_suffix} "
f"associated with {bids_path.basename}."
)
msg = f"Did not find any {search_suffix} associated with {bids_path.basename}."
elif len(best_candidates) > 1:
# More than one candidates were tied for best match
msg = (
Expand Down Expand Up @@ -2085,7 +2084,7 @@ def get_entity_vals(

if entity_key not in entities:
raise ValueError(
f'`key` must be one of: {", ".join(entities)}. ' f"Got: {entity_key}"
f"`key` must be one of: {', '.join(entities)}. Got: {entity_key}"
)

ignore_subjects = _ensure_tuple(ignore_subjects)
Expand Down Expand Up @@ -2530,7 +2529,7 @@ def _return_root_paths(root, datatype=None, ignore_json=True, ignore_nosub=False

if datatype is not None:
datatype = _ensure_tuple(datatype)
search_str = f'*/{"|".join(datatype)}/*'
search_str = f"*/{'|'.join(datatype)}/*"
else:
search_str = "*.*"

Expand Down
20 changes: 9 additions & 11 deletions mne_bids/read.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ def _read_events(events, event_id, raw, bids_path=None):
# retrieve events
if isinstance(events, np.ndarray):
if events.ndim != 2:
raise ValueError("Events must have two dimensions, " f"found {events.ndim}")
raise ValueError(f"Events must have two dimensions, found {events.ndim}")
if events.shape[1] != 3:
raise ValueError(
"Events must have second dimension of length 3, "
Expand Down Expand Up @@ -164,7 +164,7 @@ def _read_events(events, event_id, raw, bids_path=None):
f"The provided raw data contains annotations, but "
f'"event_id" does not contain entries for all annotation '
f"descriptions. The following entries are missing: "
f'{", ".join(desc_without_id)}'
f"{', '.join(desc_without_id)}"
)

# If we have events, convert them to Annotations so they can be easily
Expand All @@ -174,7 +174,7 @@ def _read_events(events, event_id, raw, bids_path=None):
if ids_without_desc:
raise ValueError(
f"No description was specified for the following event(s): "
f'{", ".join([str(x) for x in sorted(ids_without_desc)])}. '
f"{', '.join([str(x) for x in sorted(ids_without_desc)])}. "
f"Please add them to the event_id dictionary, or drop them "
f"from the events array."
)
Expand Down Expand Up @@ -409,9 +409,7 @@ def _handle_scans_reading(scans_fname, raw, bids_path):
# Convert time offset to UTC
acq_time = acq_time.astimezone(timezone.utc)

logger.debug(
f"Loaded {scans_fname} scans file to set " f"acq_time as {acq_time}."
)
logger.debug(f"Loaded {scans_fname} scans file to set acq_time as {acq_time}.")
# First set measurement date to None and then call call anonymize() to
# remove any traces of the measurement date we wish
# to replace – it might lurk out in more places than just
Expand Down Expand Up @@ -728,7 +726,7 @@ def _handle_channels_reading(channels_fname, raw):
if ch_diff:
warn(
f"Cannot set channel type for the following channels, as they "
f'are missing in the raw data: {", ".join(sorted(ch_diff))}'
f"are missing in the raw data: {', '.join(sorted(ch_diff))}"
)
raw.set_channel_types(
channel_type_bids_mne_map_available_channels, on_unit_change="ignore"
Expand All @@ -744,7 +742,7 @@ def _handle_channels_reading(channels_fname, raw):
warn(
f'Cannot set "bad" status for the following channels, as '
f"they are missing in the raw data: "
f'{", ".join(sorted(ch_diff))}'
f"{', '.join(sorted(ch_diff))}"
)

raw.info["bads"] = bads_avail
Expand Down Expand Up @@ -875,7 +873,7 @@ def read_raw_bids(
and raw_path.is_symlink()
):
target_path = raw_path.resolve()
logger.info(f"Resolving symbolic link: " f"{raw_path} -> {target_path}")
logger.info(f"Resolving symbolic link: {raw_path} -> {target_path}")
raw_path = target_path
config_path = None

Expand Down Expand Up @@ -1124,7 +1122,7 @@ def get_head_mri_trans(

if t1w_json_path is None or not t1w_json_path.exists():
raise FileNotFoundError(
f"Did not find T1w JSON sidecar file, tried location: " f"{t1w_json_path}"
f"Did not find T1w JSON sidecar file, tried location: {t1w_json_path}"
)
for extension in (".nii", ".nii.gz"):
t1w_path_candidate = t1w_json_path.with_suffix(extension)
Expand All @@ -1135,7 +1133,7 @@ def get_head_mri_trans(
if not t1w_bids_path.fpath.exists():
raise FileNotFoundError(
f"Did not find T1w recording file, tried location: "
f'{t1w_path_candidate.name.replace(".nii.gz", "")}[.nii, .nii.gz]'
f"{t1w_path_candidate.name.replace('.nii.gz', '')}[.nii, .nii.gz]"
)

# Get MRI landmarks from the JSON sidecar
Expand Down
2 changes: 1 addition & 1 deletion mne_bids/report/_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ def _summarize_scans(root, session=None):
if session is None:
search_str = "*_scans.tsv"
else:
search_str = f"*ses-{session}" f"*_scans.tsv"
search_str = f"*ses-{session}*_scans.tsv"

Check warning on line 263 in mne_bids/report/_report.py

View check run for this annotation

Codecov / codecov/patch

mne_bids/report/_report.py#L263

Added line #L263 was not covered by tests
scans_fpaths = list(root.rglob(search_str))
if len(scans_fpaths) == 0:
warn(
Expand Down
6 changes: 3 additions & 3 deletions mne_bids/sidecar_updates.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def update_sidecar_json(bids_path, entries, verbose=None):
# get the file path
fpath = bids_path.fpath
if not fpath.exists():
raise RuntimeError(f"Sidecar file does not " f"exist for {fpath}.")
raise RuntimeError(f"Sidecar file does not exist for {fpath}.")

# sidecar update either from file, or as dictionary
if isinstance(entries, dict):
Expand Down Expand Up @@ -255,7 +255,7 @@ def update_anat_landmarks(
raise ValueError(
f"Could not find an MRI scan. Please check the provided "
f"bids_path. Tried the following filenames: "
f'{", ".join([p.name for p in tried_paths])}'
f"{', '.join([p.name for p in tried_paths])}"
)

if not isinstance(landmarks, DigMontage): # it's pathlike
Expand Down Expand Up @@ -303,7 +303,7 @@ def update_anat_landmarks(
f"The provided DigMontage did not contain all required cardinal "
f"points (nasion and left and right pre-auricular points). The "
f"following points are missing: "
f'{", ".join(missing_points)}'
f"{', '.join(missing_points)}"
)

bids_path_json = bids_path.copy().update(extension=".json")
Expand Down
23 changes: 7 additions & 16 deletions mne_bids/tests/test_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,25 +177,19 @@ def test_search_folder_for_text(capsys):
captured = capsys.readouterr()
assert "sub-01_ses-eeg_task-rest_eeg.json" in captured.out
assert (
(
" 1 name type units low_cutof high_cuto descripti sampling_ status status_de\n" # noqa: E501
" 2 Fp1 EEG µV 0.0159154 1000.0 ElectroEn 5000.0 good n/a" # noqa: E501
)
in captured.out
)
" 1 name type units low_cutof high_cuto descripti sampling_ status status_de\n" # noqa: E501
" 2 Fp1 EEG µV 0.0159154 1000.0 ElectroEn 5000.0 good n/a" # noqa: E501
) in captured.out
# test if pathlib.Path object
search_folder_for_text("n/a", Path(test_dir))

# test returning a string and without line numbers
out = search_folder_for_text("n/a", test_dir, line_numbers=False, return_str=True)
assert "sub-01_ses-eeg_task-rest_eeg.json" in out
assert (
(
" name type units low_cutof high_cuto descripti sampling_ status status_de\n" # noqa: E501
" Fp1 EEG µV 0.0159154 1000.0 ElectroEn 5000.0 good n/a" # noqa: E501
)
in out
)
" name type units low_cutof high_cuto descripti sampling_ status status_de\n" # noqa: E501
" Fp1 EEG µV 0.0159154 1000.0 ElectroEn 5000.0 good n/a" # noqa: E501
) in out


def test_print_dir_tree(capsys):
Expand Down Expand Up @@ -420,10 +414,7 @@ def test_get_entities_from_fname(fname):
"fname",
[
"sub-01_ses-02_task-test_run-3_split-01_meg.fif",
(
"/bids_root/sub-01/ses-02/meg/"
"sub-01_ses-02_task-test_run-3_split-01_meg.fif"
),
("/bids_root/sub-01/ses-02/meg/sub-01_ses-02_task-test_run-3_split-01_meg.fif"),
"sub-01_ses-02_task-test_run-3_split-01_foo-tfr_meg.fif",
],
)
Expand Down
4 changes: 2 additions & 2 deletions mne_bids/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ def test_check_datatype():
# check behavior for unsupported data types
for datatype in (None, "anat"):
with pytest.raises(
ValueError, match=f"The specified datatype " f"{datatype} is currently not"
ValueError, match=f"The specified datatype {datatype} is currently not"
):
_check_datatype(raw_eeg, datatype)
# check behavior for matching data type
Expand All @@ -199,6 +199,6 @@ def test_check_datatype():
(raw_eeg, "ieeg"),
]:
with pytest.raises(
ValueError, match=f"The specified datatype " f"{datatype} was not found"
ValueError, match=f"The specified datatype {datatype} was not found"
):
_check_datatype(raw, datatype)
Loading

0 comments on commit 5bec6b5

Please sign in to comment.