Skip to content

Commit

Permalink
Use Ruff for formatting (#1204)
Browse files Browse the repository at this point in the history
* Use Ruff for formatting

* Remove Black
  • Loading branch information
fepegar authored Sep 22, 2024
1 parent 9f8a727 commit b99e850
Show file tree
Hide file tree
Showing 138 changed files with 346 additions and 321 deletions.
22 changes: 1 addition & 21 deletions .github/workflows/code_quality.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ jobs:
fail-fast: false
matrix:
tox_env:
- format
- lint
- types

Expand All @@ -39,27 +40,6 @@ jobs:
- name: Run check for tox env "${{ matrix.tox_env }}"
run: tox -e ${{ matrix.tox_env }}

black:
name: Code formatting
runs-on: ubuntu-latest

steps:
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"

- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0

- name: Install black
run: pip install black

- name: Run black
run: black --check --diff .

docs:
name: Documentation
runs-on: ubuntu-latest
Expand Down
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ repos:
rev: v0.6.7
hooks:
- id: ruff
# - id: ruff-format
- id: ruff-format

- repo: https://github.com/pre-commit/pygrep-hooks
rev: v1.10.0
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ at [OpenAI](https://openai.com/) ([link](https://jack-clark.net/2020/03/17/)).
<b>Code</b>
</td>
<td align="center">
<a href="https://github.com/psf/black">
<img src="https://img.shields.io/badge/code%20style-black-000000.svg" alt="Code quality">
<a href="https://docs.astral.sh/ruff/">
<img src="https://camo.githubusercontent.com/bb88127790fb054cba2caf3f3be2569c1b97bb45a44b47b52d738f8781a8ede4/68747470733a2f2f696d672e736869656c64732e696f2f656e64706f696e743f75726c3d68747470733a2f2f7261772e67697468756275736572636f6e74656e742e636f6d2f636861726c6965726d617273682f727566662f6d61696e2f6173736574732f62616467652f76312e6a736f6e" alt="Code style">
</a>
<a href="https://scrutinizer-ci.com/g/fepegar/torchio/?branch=main">
<img src="https://img.shields.io/scrutinizer/g/fepegar/torchio.svg?label=Code%20quality&logo=scrutinizer" alt="Code quality">
Expand Down
1 change: 1 addition & 0 deletions docs/examples/plot_3d_to_2d.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import matplotlib.pyplot as plt
import torch

import torchio as tio

torch.manual_seed(0)
Expand Down
1 change: 1 addition & 0 deletions docs/examples/plot_custom_z_spacing.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"""

import torch

import torchio as tio


Expand Down
5 changes: 2 additions & 3 deletions docs/examples/plot_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import matplotlib.pyplot as plt
import torch

import torchio as tio

torch.manual_seed(0)
Expand All @@ -38,9 +39,7 @@
pprint.pprint(transformed.history) # noqa: T203
print('\nComposed transform to reproduce history:') # noqa: T201
print(transformed.get_composed_history()) # noqa: T201
print(
'\nComposed transform to invert applied transforms when possible:'
) # noqa: T201, B950
print('\nComposed transform to invert applied transforms when possible:')
print(transformed.get_inverse_transform(ignore_intensity=False)) # noqa: T201

loader = tio.SubjectsLoader(
Expand Down
2 changes: 1 addition & 1 deletion docs/examples/plot_include_exclude.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
"""

import torch
import torchio as tio

import torchio as tio

torch.manual_seed(0)

Expand Down
5 changes: 3 additions & 2 deletions docs/examples/plot_video.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@
import matplotlib.pyplot as plt
import numpy as np
import torch
import torchio as tio
from PIL import Image

import torchio as tio


def read_clip(path, undersample=4):
"""Read a GIF a return an array of shape (C, W, H, T)."""
Expand Down Expand Up @@ -49,7 +50,7 @@ def get_frame(image, i):
)


# Source: https://thehigherlearning.wordpress.com/2014/06/25/watching-a-cell-divide-under-an-electron-microscope-is-mesmerizing-gif/ # noqa: B950
# Source: https://thehigherlearning.wordpress.com/2014/06/25/watching-a-cell-divide-under-an-electron-microscope-is-mesmerizing-gif/
array, delay = read_clip('nBTu3oi.gif')
plt.imshow(array[..., 0].transpose(1, 2, 0))
plt.plot()
Expand Down
8 changes: 4 additions & 4 deletions docs/source/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ TorchIO
#######

|PyPI-downloads| |PyPI-version| |Conda-version| |Google-Colab-notebook|
|Docs-status| |Tests-status| |Black|
|Docs-status| |Tests-status| |Ruff|
|Coverage-codecov| |Code-Quality| |Code-Maintainability| |pre-commit|
|Slack| |Twitter| |Twitter-commits| |YouTube|

Expand Down Expand Up @@ -89,9 +89,9 @@ If you found a bug or have a feature request, please open an issue:
:target: https://github.com/fepegar/torchio/actions/workflows/tests.yml
:alt: Tests status

.. |Black| image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/psf/black
:alt: Code style: black
.. |Ruff| image:: https://camo.githubusercontent.com/bb88127790fb054cba2caf3f3be2569c1b97bb45a44b47b52d738f8781a8ede4/68747470733a2f2f696d672e736869656c64732e696f2f656e64706f696e743f75726c3d68747470733a2f2f7261772e67697468756275736572636f6e74656e742e636f6d2f636861726c6965726d617273682f727566662f6d61696e2f6173736574732f62616467652f76312e6a736f6e
:target: https://docs.astral.sh/ruff/
:alt: Code style: Ruff

.. |Coverage-codecov| image:: https://codecov.io/gh/fepegar/torchio/branch/main/graphs/badge.svg
:target: https://codecov.io/github/fepegar/torchio
Expand Down
6 changes: 2 additions & 4 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@
# further. For a list of options available for each theme, see the
# documentation.
#
url = 'https://www.journals.elsevier.com/computer-methods-and-programs-in-biomedicine/most-downloaded-articles' # noqa: B950
url = 'https://www.journals.elsevier.com/computer-methods-and-programs-in-biomedicine/most-downloaded-articles'
text = 'CMPB'
html_href = f'<a href="{url}">{text}</a>'
message = f'TorchIO becomes one of the most downloaded articles from {html_href}!'
Expand Down Expand Up @@ -221,9 +221,7 @@
epub_exclude_files = ['search.html']

# CopyButton configuration
copybutton_prompt_text = (
r'>>> |\.\.\. |\$ |In \[\d*\]: | {2,5}\.\.\.: | {5,8}: ' # noqa: B950,FS003
)
copybutton_prompt_text = (r'>>> |\.\.\. |\$ |In \[\d*\]: | {2,5}\.\.\.: | {5,8}: ',)
copybutton_prompt_is_regexp = True

# def setup(app):
Expand Down
14 changes: 7 additions & 7 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ csv = [
"pandas",
]
dev = [
"black",
"bump2version",
"coverage",
"mypy",
Expand Down Expand Up @@ -98,11 +97,6 @@ Source = "https://github.com/fepegar/torchio"
Documentation = "http://torchio.rtfd.io"
"Release notes" = "https://github.com/fepegar/torchio/releases"

[tool.black]
preview = false
skip-string-normalization = true
target-version = ['py311']

[tool.mypy]
pretty = true

Expand All @@ -127,11 +121,17 @@ markers = [
"slow: marks tests as slow (deselect with '-m \"not slow\"')",
"serial",
]

filterwarnings = [
# Ignore SimpleITK Swig warnings
"ignore:builtin type .* has no __module__ attribute",
"ignore:Casting complex values to real discards the imaginary part",
# Raised by SimpleITK on CI
"ignore:invalid escape sequence",
]

[tool.ruff]
format.quote-style = 'single'
lint.select = ["F", "I"]

[tool.ruff.lint.isort]
force-single-line = true
37 changes: 17 additions & 20 deletions src/torchio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,26 @@
__version__ = '0.20.0'


from . import datasets
from . import reference
from . import utils
from .constants import * # noqa: F401, F403
from .data import GridAggregator
from .data import GridSampler
from .data import Image
from .data import LabelMap
from .data import LabelSampler
from .data import Queue
from .data import ScalarImage
from .data import Subject
from .data import SubjectsDataset
from .data import SubjectsLoader
from .data import UniformSampler
from .data import WeightedSampler
from .data import inference
from .data import io
from .data import sampler
from .transforms import * # noqa: F401, F403
from .data import (
io,
sampler,
inference,
SubjectsDataset,
SubjectsLoader,
Image,
ScalarImage,
LabelMap,
Queue,
Subject,
WeightedSampler,
UniformSampler,
LabelSampler,
GridSampler,
GridAggregator,
)
from . import datasets
from . import reference


__all__ = [
'utils',
Expand Down
10 changes: 6 additions & 4 deletions src/torchio/cli/apply_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
from pathlib import Path

import typer
from rich.progress import Progress, SpinnerColumn, TextColumn

from rich.progress import Progress
from rich.progress import SpinnerColumn
from rich.progress import TextColumn

app = typer.Typer()

Expand Down Expand Up @@ -61,9 +62,10 @@ def main(
Example:
$ tiotr input.nrrd RandomMotion output.nii "degrees=(-5,15) num_transforms=3" -v
""" # noqa: B950
"""
# Imports are placed here so that the tool loads faster if not being run
import torch

import torchio.transforms as transforms
from torchio.utils import apply_transform_to_file

Expand All @@ -79,7 +81,7 @@ def main(
torch.manual_seed(seed)
with Progress(
SpinnerColumn(),
TextColumn('[progress.description]{task.description}'), # noqa: FS003
TextColumn('[progress.description]{task.description}'),
transient=True,
disable=not show_progress,
) as progress:
Expand Down
1 change: 0 additions & 1 deletion src/torchio/cli/print_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

import typer


app = typer.Typer()


Expand Down
1 change: 0 additions & 1 deletion src/torchio/data/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
from .sampler import WeightedSampler
from .subject import Subject


__all__ = [
'Queue',
'Subject',
Expand Down
2 changes: 1 addition & 1 deletion src/torchio/data/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class SubjectsDataset(Dataset):
.. tip:: To quickly iterate over the subjects without loading the images,
use :meth:`dry_iter()`.
""" # noqa: B950
"""

def __init__(
self,
Expand Down
11 changes: 5 additions & 6 deletions src/torchio/data/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@
from ..typing import TypeTripletFloat
from ..typing import TypeTripletInt
from ..utils import get_stem
from ..utils import to_tuple
from ..utils import guess_external_viewer
from ..utils import is_iterable
from ..utils import to_tuple
from .io import check_uint_to_int
from .io import ensure_4d
from .io import get_rotation_and_spacing_from_affine
Expand All @@ -48,7 +48,6 @@
from .io import sitk_to_nib
from .io import write_image


PROTECTED_KEYS = DATA, AFFINE, TYPE, PATH, STEM
TypeBound = Tuple[float, float]
TypeBounds = Tuple[TypeBound, TypeBound, TypeBound]
Expand Down Expand Up @@ -128,7 +127,7 @@ class Image(dict):
.. _FSL docs: https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/Orientation%20Explained
.. _SimpleITK docs: https://simpleitk.readthedocs.io/en/master/fundamentalConcepts.html
.. _Graham Wideman's website: http://www.grahamwideman.com/gw/brain/orientation/orientterms.htm
""" # noqa: B950
"""

def __init__(
self,
Expand Down Expand Up @@ -470,7 +469,7 @@ def _parse_path(
# https://github.com/fepegar/torchio/pull/838
raise TypeError('The path argument cannot be a dictionary')
elif self._is_paths_sequence(path):
return [self._parse_single_path(p) for p in path] # type: ignore[union-attr] # noqa: B950
return [self._parse_single_path(p) for p in path] # type: ignore[union-attr]
else:
return self._parse_single_path(path) # type: ignore[arg-type]

Expand Down Expand Up @@ -655,7 +654,7 @@ def from_sitk(cls, sitk_image):
>>> sitk_image = sitk.Image((224, 224), sitk.sitkVectorFloat32, 3)
>>> tio.ScalarImage.from_sitk(sitk_image)
ScalarImage(shape: (3, 224, 224, 1); spacing: (1.00, 1.00, 1.00); orientation: LPS+; memory: 588.0 KiB; dtype: torch.FloatTensor)
""" # noqa: B950
"""
tensor, affine = sitk_to_nib(sitk_image)
return cls(tensor=tensor, affine=affine)

Expand Down Expand Up @@ -712,7 +711,7 @@ def to_gif(
eliminating unused colors. This is only useful if the palette
can be compressed to the next smaller power of 2 elements.
reverse: Reverse the temporal order of frames.
""" # noqa: B950
"""
from ..visualization import make_gif # avoid circular import

make_gif(
Expand Down
2 changes: 1 addition & 1 deletion src/torchio/data/inference/aggregator.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class GridAggregator:
.. note:: Adapted from NiftyNet. See `this NiftyNet tutorial
<https://niftynet.readthedocs.io/en/dev/window_sizes.html>`_ for more
information about patch-based sampling.
""" # noqa: B950
"""

def __init__(self, sampler: GridSampler, overlap_mode: str = 'crop'):
subject = sampler.subject
Expand Down
1 change: 0 additions & 1 deletion src/torchio/data/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
from ..typing import TypeTripletFloat
from ..typing import TypeTripletInt


# Matrices used to switch between LPS and RAS
FLIPXY_33 = np.diag([-1, -1, 1])
FLIPXY_44 = np.diag([-1, -1, 1, 1])
Expand Down
3 changes: 1 addition & 2 deletions src/torchio/data/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,11 @@

import numpy as np
import torch
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from torch.utils.data import Dataset

from .subject import Subject


T = TypeVar('T')


Expand Down
Loading

0 comments on commit b99e850

Please sign in to comment.