Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Update ruff, address complaints #1405

Merged
merged 11 commits into from
Jan 14, 2025
4 changes: 4 additions & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# Sun Jan 12 12:22:13 2025 -0500 - [email protected] - sty: ruff format [git-blame-ignore-rev]
40e41208a0f04063b3c4e373a65da1a2a6a275b5
# Sun Jan 12 11:51:49 2025 -0500 - [email protected] - STY: ruff format [git-blame-ignore-rev]
7e5d584910c67851dcfcd074ff307122689b61f5
# Sun Jan 1 12:38:02 2023 -0500 - [email protected] - STY: Run pre-commit config on all files
d14c1cf282a9c3b19189f490f10c35f5739e24d1
# Thu Dec 29 22:53:17 2022 -0500 - [email protected] - STY: Reduce array().astype() and similar constructs
Expand Down
6 changes: 3 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
exclude: ".*/data/.*"
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
rev: v5.0.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
Expand All @@ -13,7 +13,7 @@ repos:
- id: check-merge-conflict
- id: check-vcs-permalinks
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.6.4
rev: v0.9.1
hooks:
- id: ruff
args: [ --fix ]
Expand All @@ -24,7 +24,7 @@ repos:
args: [ --select, ISC001, --fix ]
exclude: = ["doc", "tools"]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.11.2
rev: v1.14.1
hooks:
- id: mypy
# Sync with project.optional-dependencies.typing
Expand Down
3 changes: 1 addition & 2 deletions bin/parrec2nii
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#!python
"""PAR/REC to NIfTI converter
"""
"""PAR/REC to NIfTI converter"""

from nibabel.cmdline.parrec2nii import main

Expand Down
15 changes: 8 additions & 7 deletions nibabel/benchmarks/bench_array_to_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,24 +29,25 @@ def bench_array_to_file():
sys.stdout.flush()
print_git_title('\nArray to file')
mtime = measure('array_to_file(arr, BytesIO(), np.float32)', repeat)
print('%30s %6.2f' % ('Save float64 to float32', mtime))
fmt = '{:30s} {:6.2f}'.format
print(fmt('Save float64 to float32', mtime))
mtime = measure('array_to_file(arr, BytesIO(), np.int16)', repeat)
print('%30s %6.2f' % ('Save float64 to int16', mtime))
print(fmt('Save float64 to int16', mtime))
# Set a lot of NaNs to check timing
arr[:, :, :, 1] = np.nan
mtime = measure('array_to_file(arr, BytesIO(), np.float32)', repeat)
print('%30s %6.2f' % ('Save float64 to float32, NaNs', mtime))
print(fmt('Save float64 to float32, NaNs', mtime))
mtime = measure('array_to_file(arr, BytesIO(), np.int16)', repeat)
print('%30s %6.2f' % ('Save float64 to int16, NaNs', mtime))
print(fmt('Save float64 to int16, NaNs', mtime))
# Set a lot of infs to check timing
arr[:, :, :, 1] = np.inf
mtime = measure('array_to_file(arr, BytesIO(), np.float32)', repeat)
print('%30s %6.2f' % ('Save float64 to float32, infs', mtime))
print(fmt('Save float64 to float32, infs', mtime))
mtime = measure('array_to_file(arr, BytesIO(), np.int16)', repeat)
print('%30s %6.2f' % ('Save float64 to int16, infs', mtime))
print(fmt('Save float64 to int16, infs', mtime))
# Int16 input, float output
arr = np.random.random_integers(low=-1000, high=1000, size=img_shape)
arr = arr.astype(np.int16)
mtime = measure('array_to_file(arr, BytesIO(), np.float32)', repeat)
print('%30s %6.2f' % ('Save Int16 to float32', mtime))
print(fmt('Save Int16 to float32', mtime))
sys.stdout.flush()
2 changes: 1 addition & 1 deletion nibabel/benchmarks/bench_arrayproxy_slicing.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def fmt_sliceobj(sliceobj):
slcstr.append(s)
else:
slcstr.append(str(int(s * SHAPE[i])))
return f"[{', '.join(slcstr)}]"
return f'[{", ".join(slcstr)}]'

with InTemporaryDirectory():
print(f'Generating test data... ({int(round(np.prod(SHAPE) * 4 / 1048576.0))} MB)')
Expand Down
9 changes: 5 additions & 4 deletions nibabel/benchmarks/bench_finite_range.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,17 @@ def bench_finite_range():
sys.stdout.flush()
print_git_title('\nFinite range')
mtime = measure('finite_range(arr)', repeat)
print('%30s %6.2f' % ('float64 all finite', mtime))
fmt = '{:30s} {:6.2f}'.format
print(fmt('float64 all finite', mtime))
arr[:, :, :, 1] = np.nan
mtime = measure('finite_range(arr)', repeat)
print('%30s %6.2f' % ('float64 many NaNs', mtime))
print(fmt('float64 many NaNs', mtime))
arr[:, :, :, 1] = np.inf
mtime = measure('finite_range(arr)', repeat)
print('%30s %6.2f' % ('float64 many infs', mtime))
print(fmt('float64 many infs', mtime))
# Int16 input, float output
arr = np.random.random_integers(low=-1000, high=1000, size=img_shape)
arr = arr.astype(np.int16)
mtime = measure('finite_range(arr)', repeat)
print('%30s %6.2f' % ('int16', mtime))
print(fmt('int16', mtime))
sys.stdout.flush()
15 changes: 8 additions & 7 deletions nibabel/benchmarks/bench_load_save.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,20 +34,21 @@ def bench_load_save():
print_git_title('Image load save')
hdr.set_data_dtype(np.float32)
mtime = measure('sio.truncate(0); img.to_file_map()', repeat)
print('%30s %6.2f' % ('Save float64 to float32', mtime))
fmt = '{:30s} {:6.2f}'.format
print(fmt('Save float64 to float32', mtime))
mtime = measure('img.from_file_map(img.file_map)', repeat)
print('%30s %6.2f' % ('Load from float32', mtime))
print(fmt('Load from float32', mtime))
hdr.set_data_dtype(np.int16)
mtime = measure('sio.truncate(0); img.to_file_map()', repeat)
print('%30s %6.2f' % ('Save float64 to int16', mtime))
print(fmt('Save float64 to int16', mtime))
mtime = measure('img.from_file_map(img.file_map)', repeat)
print('%30s %6.2f' % ('Load from int16', mtime))
print(fmt('Load from int16', mtime))
# Set a lot of NaNs to check timing
arr[:, :, :20] = np.nan
mtime = measure('sio.truncate(0); img.to_file_map()', repeat)
print('%30s %6.2f' % ('Save float64 to int16, NaNs', mtime))
print(fmt('Save float64 to int16, NaNs', mtime))
mtime = measure('img.from_file_map(img.file_map)', repeat)
print('%30s %6.2f' % ('Load from int16, NaNs', mtime))
print(fmt('Load from int16, NaNs', mtime))
# Int16 input, float output
arr = np.random.random_integers(low=-1000, high=1000, size=img_shape)
arr = arr.astype(np.int16)
Expand All @@ -57,5 +58,5 @@ def bench_load_save():
hdr = img.header
hdr.set_data_dtype(np.float32)
mtime = measure('sio.truncate(0); img.to_file_map()', repeat)
print('%30s %6.2f' % ('Save Int16 to float32', mtime))
print(fmt('Save Int16 to float32', mtime))
sys.stdout.flush()
2 changes: 1 addition & 1 deletion nibabel/benchmarks/butils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@

def print_git_title(title):
"""Prints title string with git hash if possible, and underline"""
title = f"{title} for git revision {get_info()['commit_hash']}"
title = f'{title} for git revision {get_info()["commit_hash"]}'
print(title)
print('-' * len(title))
2 changes: 1 addition & 1 deletion nibabel/brikhead.py
Original file line number Diff line number Diff line change
Expand Up @@ -555,7 +555,7 @@ def filespec_to_file_map(klass, filespec):
fname = fholder.filename
if key == 'header' and not os.path.exists(fname):
for ext in klass._compressed_suffixes:
fname = fname[: -len(ext)] if fname.endswith(ext) else fname
fname = fname.removesuffix(ext)
elif key == 'image' and not os.path.exists(fname):
for ext in klass._compressed_suffixes:
if os.path.exists(fname + ext):
Expand Down
3 changes: 1 addition & 2 deletions nibabel/cifti2/cifti2.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,8 +294,7 @@ def __setitem__(self, key, value):
self._labels[key] = Cifti2Label(*([key] + list(value)))
except ValueError:
raise ValueError(
'Key should be int, value should be sequence '
'of str and 4 floats between 0 and 1'
'Key should be int, value should be sequence of str and 4 floats between 0 and 1'
)

def __delitem__(self, key):
Expand Down
6 changes: 4 additions & 2 deletions nibabel/cifti2/cifti2_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -634,8 +634,10 @@ def __eq__(self, other):
return (
(
self.affine is None
or np.allclose(self.affine, other.affine)
and self.volume_shape == other.volume_shape
or (
np.allclose(self.affine, other.affine)
and self.volume_shape == other.volume_shape
)
)
and self.nvertices == other.nvertices
and np.array_equal(self.name, other.name)
Expand Down
3 changes: 1 addition & 2 deletions nibabel/cifti2/parse_cifti2.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,8 +384,7 @@ def StartElementHandler(self, name, attrs):
model = self.struct_state[-1]
if not isinstance(model, Cifti2BrainModel):
raise Cifti2HeaderError(
'VertexIndices element can only be a child '
'of the CIFTI-2 BrainModel element'
'VertexIndices element can only be a child of the CIFTI-2 BrainModel element'
)
self.fsm_state.append('VertexIndices')
model.vertex_indices = index
Expand Down
2 changes: 1 addition & 1 deletion nibabel/cmdline/dicomfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@

if opts.verbose:
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.setLevel(opts.verbose > 1 and logging.DEBUG or logging.INFO)
logger.setLevel(logging.DEBUG if opts.verbose > 1 else logging.INFO)

Check warning on line 234 in nibabel/cmdline/dicomfs.py

View check run for this annotation

Codecov / codecov/patch

nibabel/cmdline/dicomfs.py#L234

Added line #L234 was not covered by tests

if len(files) != 2:
sys.stderr.write(f'Please provide two arguments:\n{parser.usage}\n')
Expand Down
4 changes: 2 additions & 2 deletions nibabel/cmdline/ls.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ def proc_file(f, opts):

row += [
str(safe_get(h, 'data_dtype')),
f"@l[{ap(safe_get(h, 'data_shape'), '%3g')}]",
f"@l{ap(safe_get(h, 'zooms'), '%.2f', 'x')}",
f'@l[{ap(safe_get(h, "data_shape"), "%3g")}]',
f'@l{ap(safe_get(h, "zooms"), "%.2f", "x")}',
]
# Slope
if (
Expand Down
4 changes: 2 additions & 2 deletions nibabel/cmdline/tests/test_conform.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ def test_nondefault(tmpdir):
voxel_size = (1, 2, 4)
orientation = 'LAS'
args = (
f"{infile} {outfile} --out-shape {' '.join(map(str, out_shape))} "
f"--voxel-size {' '.join(map(str, voxel_size))} --orientation {orientation}"
f'{infile} {outfile} --out-shape {" ".join(map(str, out_shape))} '
f'--voxel-size {" ".join(map(str, voxel_size))} --orientation {orientation}'
)
main(args.split())
assert outfile.isfile()
Expand Down
2 changes: 1 addition & 1 deletion nibabel/cmdline/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def table2string(table, out=None):
# eat whole entry while computing width for @w (for wide)
markup_strip = re.compile('^@([lrc]|w.*)')
col_width = [max(len(markup_strip.sub('', x)) for x in column) for column in zip(*table)]
trans = str.maketrans("lrcw", "<>^^")
trans = str.maketrans('lrcw', '<>^^')
lines = []
for row in table:
line = []
Expand Down
2 changes: 1 addition & 1 deletion nibabel/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ def make_datasource(pkg_def, **kwargs):
pkg_hint = pkg_def.get('install hint', DEFAULT_INSTALL_HINT)
msg = f'{e}; Is it possible you have not installed a data package?'
if 'name' in pkg_def:
msg += f"\n\nYou may need the package \"{pkg_def['name']}\""
msg += f'\n\nYou may need the package "{pkg_def["name"]}"'
if pkg_hint is not None:
msg += f'\n\n{pkg_hint}'
raise DataError(msg)
Expand Down
2 changes: 1 addition & 1 deletion nibabel/deprecator.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ def __call__(
messages.append('* deprecated from version: ' + since)
if until:
messages.append(
f"* {'Raises' if self.is_bad_version(until) else 'Will raise'} "
f'* {"Raises" if self.is_bad_version(until) else "Will raise"} '
f'{exception} as of version: {until}'
)
message = '\n'.join(messages)
Expand Down
3 changes: 1 addition & 2 deletions nibabel/filename_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,7 @@ def types_filenames(
template_fname = _stringify_path(template_fname)
if not isinstance(template_fname, str):
raise TypesFilenamesError('Need file name as input to set_filenames')
if template_fname.endswith('.'):
template_fname = template_fname[:-1]
template_fname = template_fname.removesuffix('.')
filename, found_ext, ignored, guessed_name = parse_filename(
template_fname, types_exts, trailing_suffixes, match_case
)
Expand Down
6 changes: 3 additions & 3 deletions nibabel/gifti/tests/test_parse_gifti_fast.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,9 +177,9 @@ def assert_default_types(loaded):
continue
with suppress_warnings():
loadedtype = type(getattr(loaded, attr))
assert (
loadedtype == defaulttype
), f'Type mismatch for attribute: {attr} ({loadedtype} != {defaulttype})'
assert loadedtype == defaulttype, (
f'Type mismatch for attribute: {attr} ({loadedtype} != {defaulttype})'
)


def test_default_types():
Expand Down
2 changes: 1 addition & 1 deletion nibabel/nifti1.py
Original file line number Diff line number Diff line change
Expand Up @@ -1804,7 +1804,7 @@ def set_slice_times(self, slice_times):
raise HeaderDataError(f'slice ordering of {st_order} fits with no known scheme')
if len(matching_labels) > 1:
warnings.warn(
f"Multiple slice orders satisfy: {', '.join(matching_labels)}. "
f'Multiple slice orders satisfy: {", ".join(matching_labels)}. '
'Choosing the first one'
)
label = matching_labels[0]
Expand Down
8 changes: 4 additions & 4 deletions nibabel/parrec.py
Original file line number Diff line number Diff line change
Expand Up @@ -782,10 +782,10 @@ def as_analyze_map(self):
# Here we set the parameters we can to simplify PAR/REC
# to NIfTI conversion.
descr = (
f"{self.general_info['exam_name']};"
f"{self.general_info['patient_name']};"
f"{self.general_info['exam_date'].replace(' ', '')};"
f"{self.general_info['protocol_name']}"
f'{self.general_info["exam_name"]};'
f'{self.general_info["patient_name"]};'
f'{self.general_info["exam_date"].replace(" ", "")};'
f'{self.general_info["protocol_name"]}'
)[:80]
is_fmri = self.general_info['max_dynamics'] > 1
# PAR/REC uses msec, but in _calc_zooms we convert to sec
Expand Down
2 changes: 1 addition & 1 deletion nibabel/pointset.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ def to_mask(self, shape=None) -> SpatialImage:
class GridIndices:
"""Class for generating indices just-in-time"""

__slots__ = ('gridshape', 'dtype', 'shape')
__slots__ = ('dtype', 'gridshape', 'shape')
ndim = 2

def __init__(self, shape, dtype=None):
Expand Down
2 changes: 1 addition & 1 deletion nibabel/rstutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def rst_table(
cross = format_chars.pop('cross', '+')
title_heading = format_chars.pop('title_heading', '*')
if len(format_chars) != 0:
raise ValueError(f"Unexpected ``format_char`` keys {', '.join(format_chars)}")
raise ValueError(f'Unexpected ``format_char`` keys {", ".join(format_chars)}')
down_joiner = ' ' + down + ' '
down_starter = down + ' '
down_ender = ' ' + down
Expand Down
3 changes: 1 addition & 2 deletions nibabel/streamlines/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,7 @@ def save(tractogram, filename, **kwargs):
tractogram_file = tractogram
if tractogram_file_class is None or not isinstance(tractogram_file, tractogram_file_class):
msg = (
'The extension you specified is unusual for the provided'
" 'TractogramFile' object."
"The extension you specified is unusual for the provided 'TractogramFile' object."
)
warnings.warn(msg, ExtensionWarning)

Expand Down
2 changes: 1 addition & 1 deletion nibabel/streamlines/array_sequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def fn_binary_op(self, value):
'__xor__',
):
_wrap(cls, op=op, inplace=False)
_wrap(cls, op=f"__i{op.strip('_')}__", inplace=True)
_wrap(cls, op=f'__i{op.strip("_")}__', inplace=True)

for op in ('__eq__', '__ne__', '__lt__', '__le__', '__gt__', '__ge__'):
_wrap(cls, op)
Expand Down
2 changes: 1 addition & 1 deletion nibabel/streamlines/tests/test_array_sequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ def _test_binary(op, arrseq, scalars, seqs, inplace=False):
if op in CMP_OPS:
continue

op = f"__i{op.strip('_')}__"
op = f'__i{op.strip("_")}__'
_test_binary(op, seq, SCALARS, ARRSEQS, inplace=True)

if op == '__itruediv__':
Expand Down
2 changes: 1 addition & 1 deletion nibabel/streamlines/trk.py
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,7 @@ def _read_header(fileobj):
header_rec = header_rec.view(header_rec.dtype.newbyteorder())
if header_rec['hdr_size'] != TrkFile.HEADER_SIZE:
msg = (
f"Invalid hdr_size: {header_rec['hdr_size']} "
f'Invalid hdr_size: {header_rec["hdr_size"]} '
f'instead of {TrkFile.HEADER_SIZE}'
)
raise HeaderError(msg)
Expand Down
4 changes: 2 additions & 2 deletions nibabel/tests/data/check_parrec_reslice.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def gmean_norm(data):
normal_data = normal_img.get_fdata()
normal_normed = gmean_norm(normal_data)

print(f'RMS of standard image {normal_fname:<44}: {np.sqrt(np.sum(normal_normed ** 2))}')
print(f'RMS of standard image {normal_fname:<44}: {np.sqrt(np.sum(normal_normed**2))}')

for parfile in glob.glob('*.PAR'):
if parfile == normal_fname:
Expand All @@ -69,4 +69,4 @@ def gmean_norm(data):
fixed_img = resample_img2img(normal_img, funny_img)
fixed_data = fixed_img.get_fdata()
difference_data = normal_normed - gmean_norm(fixed_data)
print(f'RMS resliced {parfile:<52} : {np.sqrt(np.sum(difference_data ** 2))}')
print(f'RMS resliced {parfile:<52} : {np.sqrt(np.sum(difference_data**2))}')
12 changes: 6 additions & 6 deletions nibabel/tests/test_funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,9 @@ def test_concat():
except ValueError as ve:
assert expect_error, str(ve)
else:
assert (
not expect_error
), 'Expected a concatenation error, but got none.'
assert not expect_error, (
'Expected a concatenation error, but got none.'
)
assert_array_equal(all_imgs.get_fdata(), all_data)
assert_array_equal(all_imgs.affine, affine)

Expand All @@ -117,9 +117,9 @@ def test_concat():
except ValueError as ve:
assert expect_error, str(ve)
else:
assert (
not expect_error
), 'Expected a concatenation error, but got none.'
assert not expect_error, (
'Expected a concatenation error, but got none.'
)
assert_array_equal(all_imgs.get_fdata(), all_data)
assert_array_equal(all_imgs.affine, affine)

Expand Down
Loading
Loading