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

Replace isort and black with ruff #38

Merged
merged 2 commits into from
Aug 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 0 additions & 8 deletions .github/workflows/code-style.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,12 @@ jobs:
uses: actions/setup-python@v5
with:
python-version: '3.10'
#architecture: 'x64'
- name: Install dependencies
run: |
python -m pip install --progress-bar off --upgrade pip setuptools wheel
python -m pip install --progress-bar off .[style]
- name: Run Ruff
run: ruff check .
- name: Run isort
uses: isort/isort-action@master
- name: Run black
uses: psf/black@stable
with:
options: "--check --verbose"
version: "23.10.1"
- name: Run codespell
uses: codespell-project/actions-codespell@master
with:
Expand Down
44 changes: 15 additions & 29 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,7 @@ doc = [
]
style = [
'bibclean',
'black',
'codespell',
'isort',
'pydocstyle[toml]',
'ruff',
]
Expand Down Expand Up @@ -109,32 +107,6 @@ exclude = ['whippersnappy*tests']
[tool.setuptools.package-data]
whippersnappy = ['*.ttf']

[tool.black]
line-length = 88
target-version = ['py310']
include = '\.pyi?$'
extend-exclude = '''
(
__pycache__
| .github
| setup.py
| doc/
| whippersnappy/read_geometry.py
)
'''

[tool.isort]
profile = 'black'
multi_line_output = 3
line_length = 88
py_version = 310
extend_skip_glob = [
'setup.py',
'data/*',
'doc/*',
'examples/*',
]

[tool.pydocstyle]
convention = 'numpy'
ignore-decorators = '(copy_doc|property|.*setter|.*getter|pyqtSlot|Slot)'
Expand All @@ -150,7 +122,21 @@ extend-exclude = [
]

[tool.ruff.lint]
select = ["NPY201"]
# https://docs.astral.sh/ruff/linter/#rule-selection
select = [
# pycodestyle
"E",
# Pyflakes
"F",
# pyupgrade
"UP",
# flake8-bugbear
"B",
# flake8-simplify
# "SIM",
# isort
"I",
]

[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]
Expand Down
4 changes: 1 addition & 3 deletions whippersnappy/cli/whippersnap.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,7 @@ def show_window(
found_surfname = get_surf_name(sdir, hemi)
if found_surfname is None:
print(
"[ERROR] Could not find a valid surf file in {} for hemi: {}!".format(
sdir, hemi
)
f"[ERROR] Could not find a valid surf file in {sdir} for hemi: {hemi}!"
)
sys.exit(0)
meshpath = os.path.join(sdir, "surf", hemi + "." + found_surfname)
Expand Down
2 changes: 1 addition & 1 deletion whippersnappy/config_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def __init__(
initial_fthresh_value=2.0,
initial_fmax_value=4.0,
):
super(ConfigWindow, self).__init__(parent)
super().__init__(parent)

self.current_fthresh_value = initial_fthresh_value
self.current_fmax_value = initial_fmax_value
Expand Down
20 changes: 9 additions & 11 deletions whippersnappy/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -650,7 +650,7 @@ def create_colorbar(fmin, fmax, invert, neg=True, font_file=None):
cwidth = 200
cheight = 30
# img = Image.new("RGB", (cwidth, cheight), color=(90, 90, 90))
values = np.nan * np.ones((cwidth))
values = np.nan * np.ones(cwidth)
gapspace = 0
if fmin > 0.01:
# leave gray gap
Expand Down Expand Up @@ -682,13 +682,13 @@ def create_colorbar(fmin, fmax, invert, neg=True, font_file=None):
font = ImageFont.truetype(font_file, 12)
if neg:
# Left
caption = " <{:.2f}".format(-fmax)
caption = f" <{-fmax:.2f}"
xpos = 0 # 10- 0.5*(font.getlength(caption))
ImageDraw.Draw(image).text(
(xpos, image.height - 17), caption, (220, 220, 220), font=font
)
# Right
caption = ">{:.2f} ".format(fmax)
caption = f">{fmax:.2f} "
xpos = image.width - (font.getlength(caption))
ImageDraw.Draw(image).text(
(xpos, image.height - 17), caption, (220, 220, 220), font=font
Expand All @@ -700,25 +700,25 @@ def create_colorbar(fmin, fmax, invert, neg=True, font_file=None):
(xpos, image.height - 17), caption, (220, 220, 220), font=font
)
else:
caption = "{:.2f}".format(-fmin)
caption = f"{-fmin:.2f}"
xpos = 0.5 * image.width - 0.5 * font.getlength(caption) - gapspace - 5
ImageDraw.Draw(image).text(
(xpos, image.height - 17), caption, (220, 220, 220), font=font
)
caption = "{:.2f}".format(fmin)
caption = f"{fmin:.2f}"
xpos = 0.5 * image.width - 0.5 * font.getlength(caption) + gapspace + 5
ImageDraw.Draw(image).text(
(xpos, image.height - 17), caption, (220, 220, 220), font=font
)
else:
# Right
caption = ">{:.2f} ".format(fmax)
caption = f">{fmax:.2f} "
xpos = image.width - (font.getlength(caption))
ImageDraw.Draw(image).text(
(xpos, image.height - 17), caption, (220, 220, 220), font=font
)
# Left
caption = " {:.2f}".format(fmin)
caption = f" {fmin:.2f}"
xpos = gapspace
if gapspace == 0:
caption = " 0"
Expand Down Expand Up @@ -824,9 +824,7 @@ def snap4(

if found_surfname is None:
print(
"[ERROR] Could not find valid surf file in {} for hemi: {}!".format(
sdir, hemi
)
f"[ERROR] Could not find valid surface in {sdir} for hemi: {hemi}!"
)
sys.exit(1)
meshpath = os.path.join(sdir, "surf", hemi + "." + found_surfname)
Expand Down Expand Up @@ -902,7 +900,7 @@ def snap4(
image.paste(bar, (xpos, ypos))

if outpath:
print("[INFO] Saving snapshot to {}".format(outpath))
print(f"[INFO] Saving snapshot to {outpath}")
image.save(outpath)


Expand Down
63 changes: 28 additions & 35 deletions whippersnappy/read_geometry.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,7 @@
# IMPORTS
import warnings
from collections import OrderedDict

import nibabel as nib
import numpy as np

"""
Read FreeSurfer geometry (fix for dev, ll 126-128);
"""Read FreeSurfer geometry (fix for dev, ll 126-128);

Code was taken from nibabel.freesurfer package
(https://github.com/nipy/nibabel/blob/master/nibabel/freesurfer/io.py).

This software is licensed under the following license:

The MIT License
Expand Down Expand Up @@ -42,10 +33,15 @@
THE SOFTWARE.
"""

import warnings
from collections import OrderedDict

import nibabel as nib
import numpy as np


def _fread3(fobj):
"""
Read a 3-byte int from an open binary file object
"""Read a 3-byte int from an open binary file object.

Parameters
----------
Expand All @@ -62,15 +58,26 @@ def _fread3(fobj):


def _read_volume_info(fobj):
"""Helper for reading the footer from a surface file."""
"""Read the footer from a surface file.

Parameters
----------
fobj : file
File descriptor

Returns
-------
volume_info : array
Key-value pairs found in the file.
"""
volume_info = OrderedDict()
head = np.fromfile(fobj, ">i4", 1)
if not np.array_equal(head, [20]): # Read two bytes more
head = np.concatenate([head, np.fromfile(fobj, ">i4", 2)])
if not np.array_equal(head, [2, 0, 20]) and not np.array_equal(
head, [2, 1, 20]
):
warnings.warn("Unknown extension code.")
warnings.warn("Unknown extension code.", stacklevel=2)
return volume_info
head = [2, 0, 20]

Expand All @@ -87,7 +94,7 @@ def _read_volume_info(fobj):
]:
pair = fobj.readline().decode("utf-8").split("=")
if pair[0].strip() != key or len(pair) != 2:
raise IOError("Error parsing volume info.")
raise OSError("Error parsing volume info.")
if key in ("valid", "filename"):
volume_info[key] = pair[1].strip()
elif key == "volume":
Expand All @@ -99,34 +106,23 @@ def _read_volume_info(fobj):


def read_geometry(filepath, read_metadata=False, read_stamp=False):
"""
Read a triangular format Freesurfer surface mesh.
"""Read a triangular format Freesurfer surface mesh.

Parameters
----------
filepath : str
Path to surface file.
read_metadata : bool, optional
If True, read and return metadata as key-value pairs.

Valid keys:

* 'head' : array of int

* 'valid' : str

* 'filename' : str

* 'volume' : array of int, shape (3,)

* 'voxelsize' : array of float, shape (3,)

* 'xras' : array of float, shape (3,)

* 'yras' : array of float, shape (3,)

* 'zras' : array of float, shape (3,)

* 'cras' : array of float, shape (3,)
read_stamp : bool, optional
Return the comment from the file
Expand Down Expand Up @@ -173,7 +169,7 @@ def read_geometry(filepath, read_metadata=False, read_stamp=False):
ret = (coords, faces)
if read_metadata:
if len(volume_info) == 0:
warnings.warn("No volume information contained in the file")
warnings.warn("No volume information contained in the file", stacklevel=2)
ret += (volume_info,)
if read_stamp:
ret += (create_stamp,)
Expand All @@ -182,8 +178,8 @@ def read_geometry(filepath, read_metadata=False, read_stamp=False):


def read_morph_data(filepath):
"""
Read a Freesurfer morphometry data file.
"""Read a Freesurfer morphometry data file.

This function reads in what Freesurfer internally calls "curv" file types,
(e.g. ?h. curv, ?h.thickness), but as that has the potential to cause
confusion where "curv" also refers to the surface curvature values,
Expand Down Expand Up @@ -212,8 +208,7 @@ def read_morph_data(filepath):


def read_mgh_data(filepath):
"""
Read an MGH image file and return its data array.
"""Read an MGH image file and return its data array.

Parameters
----------
Expand All @@ -231,8 +226,6 @@ def read_mgh_data(filepath):
len(data_array.shape) == 3
and data_array.shape[1] == 1
and data_array.shape[2] == 1
), "Expected data array to have shape Nx1x1. Instead, got {}".format(
data_array.shape
)
), f"Expected data array to have shape Nx1x1. Instead, got {data_array.shape}"

return data_array.squeeze()
4 changes: 2 additions & 2 deletions whippersnappy/utils/_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import sys
from functools import partial
from importlib.metadata import requires, version
from typing import IO, Callable, List, Optional
from typing import IO, Callable, Optional

import psutil

Expand Down Expand Up @@ -67,7 +67,7 @@ def sys_info(fid: Optional[IO] = None, developer: bool = False):
_list_dependencies_info(out, ljust, dependencies)


def _list_dependencies_info(out: Callable, ljust: int, dependencies: List[str]):
def _list_dependencies_info(out: Callable, ljust: int, dependencies: list[str]):
"""List dependencies names and versions.

Parameters
Expand Down