Skip to content

Commit

Permalink
Fix linting errors (#1207)
Browse files Browse the repository at this point in the history
  • Loading branch information
fepegar authored Sep 22, 2024
1 parent e5d302e commit 85fceff
Show file tree
Hide file tree
Showing 8 changed files with 49 additions and 30 deletions.
20 changes: 17 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,23 @@ filterwarnings = [
"ignore:invalid escape sequence",
]

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

[tool.ruff.lint]
select = [
"B",
"E",
"F",
"I",
"W",
]
ignore = [
"E203",
"E501",
"N813",
]


[tool.ruff.lint.isort]
force-single-line = true
4 changes: 2 additions & 2 deletions src/torchio/data/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,12 @@ def __len__(self):
def __getitem__(self, index: int) -> Subject:
try:
index = int(index)
except (RuntimeError, TypeError):
except (RuntimeError, TypeError) as err:
message = (
f'Index "{index}" must be int or compatible dtype,'
f' but an object of type "{type(index)}" was passed'
)
raise ValueError(message)
raise ValueError(message) from err

subject = self._subjects[index]
subject = copy.deepcopy(subject) # cheap since images not loaded yet
Expand Down
21 changes: 11 additions & 10 deletions src/torchio/data/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import SimpleITK as sitk
import torch
from deprecated import deprecated
from nibabel.affines import apply_affine

from ..constants import AFFINE
from ..constants import DATA
Expand Down Expand Up @@ -359,8 +360,8 @@ def bounds(self) -> np.ndarray:
"""Position of centers of voxels in smallest and largest indices."""
ini = 0, 0, 0
fin = np.array(self.spatial_shape) - 1
point_ini = nib.affines.apply_affine(self.affine, ini)
point_fin = nib.affines.apply_affine(self.affine, fin)
point_ini = apply_affine(self.affine, ini)
point_fin = apply_affine(self.affine, fin)
return np.array((point_ini, point_fin))

@property
Expand Down Expand Up @@ -415,7 +416,7 @@ def flip_axis(axis: str) -> str:
labels = 'LRPAISTBDV'
first = labels[::2]
last = labels[1::2]
flip_dict = {a: b for a, b in zip(first + last, last + first)}
flip_dict = dict(zip(first + last, last + first))
axis = axis[0].upper()
flipped_axis = flip_dict.get(axis)
if flipped_axis is None:
Expand All @@ -433,8 +434,8 @@ def get_bounds(self) -> TypeBounds:
"""Get minimum and maximum world coordinates occupied by the image."""
first_index = 3 * (-0.5,)
last_index = np.array(self.spatial_shape) - 0.5
first_point = nib.affines.apply_affine(self.affine, first_index)
last_point = nib.affines.apply_affine(self.affine, last_index)
first_point = apply_affine(self.affine, first_index)
last_point = apply_affine(self.affine, last_index)
array = np.array((first_point, last_point))
bounds_x, bounds_y, bounds_z = array.T.tolist()
return bounds_x, bounds_y, bounds_z
Expand All @@ -445,15 +446,15 @@ def _parse_single_path(
) -> Path:
try:
path = Path(path).expanduser()
except TypeError:
except TypeError as err:
message = (
f'Expected type str or Path but found {path} with type'
f' {type(path)} instead'
)
raise TypeError(message)
except RuntimeError:
raise TypeError(message) from err
except RuntimeError as err:
message = f'Conversion to path not possible for variable: {path}'
raise RuntimeError(message)
raise RuntimeError(message) from err

if not (path.is_file() or path.is_dir()): # might be a dir with DICOM
raise FileNotFoundError(f'File not found: "{path}"')
Expand Down Expand Up @@ -735,7 +736,7 @@ def get_center(self, lps: bool = False) -> TypeTripletFloat:
"""
size = np.array(self.spatial_shape)
center_index = (size - 1) / 2
r, a, s = nib.affines.apply_affine(self.affine, center_index)
r, a, s = apply_affine(self.affine, center_index)
if lps:
return (-r, -a, s)
else:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ def parse_gaussian_parameter(
)
return min_value, max_value

def apply_transform(self, subject: Subject) -> Subject:
def _guess_label_key(self, subject: Subject) -> None:
if self.label_key is None:
iterable = subject.get_images_dict(intensity_only=False).items()
for name, image in iterable:
Expand All @@ -221,6 +221,9 @@ def apply_transform(self, subject: Subject) -> Subject:
message = f'No label maps found in subject: {subject}'
raise RuntimeError(message)

def apply_transform(self, subject: Subject) -> Subject:
self._guess_label_key(subject)

arguments = {
'label_key': self.label_key,
'mean': [],
Expand Down
7 changes: 4 additions & 3 deletions src/torchio/transforms/transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,11 +314,12 @@ def _parse_range(

try:
min_value, max_value = nums_range # type: ignore[misc]
except (TypeError, ValueError):
raise ValueError(
except (TypeError, ValueError) as err:
message = (
f'If {name} is not a single number, it must be'
f' a sequence of len 2, not {nums_range}',
f' a sequence of len 2, not {nums_range}'
)
raise ValueError(message) from err

min_is_number = isinstance(min_value, numbers.Number)
max_is_number = isinstance(max_value, numbers.Number)
Expand Down
4 changes: 2 additions & 2 deletions src/torchio/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,9 @@ def compress(
def check_sequence(sequence: Sequence, name: str) -> None:
try:
iter(sequence)
except TypeError:
except TypeError as err:
message = f'"{name}" must be a sequence, not {type(name)}'
raise TypeError(message)
raise TypeError(message) from err


def get_major_sitk_version() -> int:
Expand Down
8 changes: 4 additions & 4 deletions tests/data/test_subject.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,17 +41,17 @@ def test_inconsistent_shape(self):
a=tio.ScalarImage(tensor=torch.rand(1, 2, 3, 4)),
b=tio.ScalarImage(tensor=torch.rand(2, 2, 3, 4)),
)
subject.spatial_shape
_ = subject.spatial_shape
with pytest.raises(RuntimeError):
subject.shape
_ = subject.shape

def test_inconsistent_spatial_shape(self):
subject = tio.Subject(
a=tio.ScalarImage(tensor=torch.rand(1, 3, 3, 4)),
b=tio.ScalarImage(tensor=torch.rand(2, 2, 3, 4)),
)
with pytest.raises(RuntimeError):
subject.spatial_shape
_ = subject.spatial_shape

@pytest.mark.slow
@pytest.mark.skipif(sys.platform == 'win32', reason='Unstable on Windows')
Expand Down Expand Up @@ -133,7 +133,7 @@ def test_delete_image(self):
with pytest.raises(KeyError):
subject['t1']
with pytest.raises(AttributeError):
subject.t1
_ = subject.t1

def test_2d(self):
subject = self.make_2d(self.sample_subject)
Expand Down
10 changes: 5 additions & 5 deletions tests/transforms/test_transforms.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import copy

import nibabel as nib
import numpy as np
import pytest
import SimpleITK as sitk
import torch
from nibabel.nifti1 import Nifti1Image

import torchio as tio

Expand Down Expand Up @@ -360,17 +360,17 @@ def test_label_keys(self):

def test_nibabel_input(self):
image = self.sample_subject.t1
image_nib = nib.Nifti1Image(image.data[0].numpy(), image.affine)
image_nib = Nifti1Image(image.data[0].numpy(), image.affine)
transformed = tio.RandomAffine()(image_nib)
transformed.get_fdata()
transformed.affine
_ = transformed.affine

image = self.subject_4d.t1
tensor_5d = image.data[np.newaxis].permute(2, 3, 4, 0, 1)
image_nib = nib.Nifti1Image(tensor_5d.numpy(), image.affine)
image_nib = Nifti1Image(tensor_5d.numpy(), image.affine)
transformed = tio.RandomAffine()(image_nib)
transformed.get_fdata()
transformed.affine
_ = transformed.affine

def test_bad_shape(self):
tensor = torch.rand(1, 2, 3)
Expand Down

0 comments on commit 85fceff

Please sign in to comment.