Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

refactor: resolve and enforce Ruff SIM103, SIM201, SIM210, and SIM211 (#5381)

Alex518debeaf5c0
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index 3f2a3ea84..d28afb9a7 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -329,11 +329,8 @@ def _check_patch_fit(original_size: Tuple[int, int], window_size: Tuple[int, int
# the remainder takes into account half a window on each side,
# the rest of the image is divided based on the stride, not the window
# size
- if (remainder_horizontal != 0) or (remainder_vertical != 0):
- # needs padding to fit
- return False
- # we can fit a full number of patches in, based on the stride
- return True
+ # we can fit a full number of patches in, based on the stride, only if nothing remains
+ return remainder_horizontal == 0 and remainder_vertical == 0
def combine_tensor_patches(
diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.py
index e7423b129..1bc7731a2 100644
--- a/kornia/core/mixin/image_module.py
+++ b/kornia/core/mixin/image_module.py
@@ -207,9 +207,7 @@ class ImageModuleMixIn:
# A PIL image exists only once PIL is imported: look the module up instead of importing it through the lazy
# loader, which would raise on an install without the "image" extra for every non-image argument.
pil_image = sys.modules.get("PIL.Image")
- if pil_image is not None and isinstance(arg, pil_image.Image):
- return True
- return False
+ return pil_image is not None and isinstance(arg, pil_image.Image)
def to_tensor(self, x: Any) -> torch.Tensor:
"""Convert input to tensor.
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index 65b7ff3e4..5b149a793 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -40,9 +40,7 @@ from kornia.core.exceptions import DeviceError, TypeCheckError
def xla_is_available() -> bool:
"""Return whether `torch_xla` is available in the system."""
- if importlib.util.find_spec("torch_xla") is not None:
- return True
- return False
+ return importlib.util.find_spec("torch_xla") is not None
def is_mps_tensor_safe(x: torch.Tensor) -> bool:
diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.py
index aff617e6d..616d57014 100644
--- a/kornia/feature/sold2/sold2_detector.py
+++ b/kornia/feature/sold2/sold2_detector.py
@@ -272,7 +272,7 @@ class LineSegmentDetectionModule:
num_iter = math.ceil(num_cand / group_size)
sampled_feat_lst = []
for iter_idx in range(num_iter):
- if not iter_idx == num_iter - 1:
+ if iter_idx != num_iter - 1:
cand_h_ = cand_h[iter_idx * group_size : (iter_idx + 1) * group_size, :]
cand_w_ = cand_w[iter_idx * group_size : (iter_idx + 1) * group_size, :]
normalized_seg_length_ = normalized_seg_length[iter_idx * group_size : (iter_idx + 1) * group_size]
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index cde87224f..6ccd66d2b 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -85,10 +85,7 @@ def validate_bbox(boxes: torch.Tensor) -> bool:
if torch.any(width_diff > 1e-4):
return False
- if torch.any(height_diff > 1e-4):
- return False
-
- return True
+ return not torch.any(height_diff > 1e-4)
def validate_bbox3d(boxes: torch.Tensor) -> bool:
@@ -671,7 +668,7 @@ def transform_bbox(
transformed_boxes: torch.Tensor = transform_points(trans_mat, boxes.view(boxes.shape[0], -1, 2))
transformed_boxes = transformed_boxes.view_as(boxes)
- if (restore_coordinates is None or restore_coordinates) and not (boxes.shape[-2:] == torch.Size([4, 2])):
+ if (restore_coordinates is None or restore_coordinates) and boxes.shape[-2:] != torch.Size([4, 2]):
restored_boxes = transformed_boxes.clone()
# In case the boxes are flipped, we ensure it is ordered like left-top -> right-bot points
restored_boxes[..., 0] = torch.min(transformed_boxes[..., [0, 2]], dim=-1)[0]
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 7f64686bc..a47f7db3c 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -259,7 +259,7 @@ class Boxes:
if not (3 <= boxes.ndim <= 4 and boxes.shape[-2:] == (4, 2)):
raise ValueError(f"Boxes shape must be (N, 4, 2) or (B, N, 4, 2). Got {boxes.shape}.")
- self._is_batched = False if boxes.ndim == 3 else True
+ self._is_batched = boxes.ndim != 3
self._data = boxes
self._mode = mode
@@ -1188,7 +1188,7 @@ class Boxes3D:
if not (3 <= boxes.ndim <= 4 and boxes.shape[-2:] == (8, 3)):
raise ValueError(f"3D bbox shape must be (N, 8, 3) or (B, N, 8, 3). Got {boxes.shape}.")
- self._is_batched = False if boxes.ndim == 3 else True
+ self._is_batched = boxes.ndim != 3
self._data = boxes
self._mode = mode
diff --git a/kornia/geometry/keypoints.py b/kornia/geometry/keypoints.py
index dd5c59659..cc954ea4e 100644
--- a/kornia/geometry/keypoints.py
+++ b/kornia/geometry/keypoints.py
@@ -81,7 +81,7 @@ class Keypoints:
if not (2 <= keypoints.ndim <= 3 and keypoints.shape[-1:] == (2,)):
raise ValueError(f"Keypoints shape must be (N, 2) or (B, N, 2). Got {keypoints.shape}.")
- self._is_batched = False if keypoints.ndim == 2 else True
+ self._is_batched = keypoints.ndim != 2
self._data = keypoints
@@ -375,7 +375,7 @@ class Keypoints3D:
if not (2 <= keypoints.ndim <= 3 and keypoints.shape[-1:] == (3,)):
raise ValueError(f"Keypoints shape must be (N, 3) or (B, N, 3). Got {keypoints.shape}.")
- self._is_batched = False if keypoints.ndim == 2 else True
+ self._is_batched = keypoints.ndim != 2
self._data = keypoints
diff --git a/kornia/models/segmentation/base.py b/kornia/models/segmentation/base.py
index 4e60a6a5e..f1f62f897 100644
--- a/kornia/models/segmentation/base.py
+++ b/kornia/models/segmentation/base.py
@@ -248,7 +248,7 @@ class SemanticSegmentation(ModelBase):
colors = self.get_colormap(semantic_masks.size(1), colormap, manual_seed=manual_seed)
outputs = self.visualize_output(semantic_masks, colors)
- return self._tensor_to_type(outputs, output_type, is_batch=True if isinstance(outputs, torch.Tensor) else False)
+ return self._tensor_to_type(outputs, output_type, is_batch=isinstance(outputs, torch.Tensor))
def save(
self,
diff --git a/pyproject.toml b/pyproject.toml
index 6bdead75d..3f0f24030 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -226,7 +226,11 @@ select = [
"RSE", # flake8-raise
"RUF", # Ruff-specific rules
"S", # flake8-bandit
+ "SIM103", # needless-bool
"SIM115", # open-file-with-context-handler
+ "SIM201", # negate-equal-op
+ "SIM210", # if-expr-with-true-false
+ "SIM211", # if-expr-with-false-true
"SIM222", # expr-or-true
"SIM910", # dict-get-with-none-default
"SLOT", # flake8-slots
diff --git a/tests/contrib/test_extract_tensor_patch.py b/tests/contrib/test_extract_tensor_patch.py
index 9f3e7dd06..5f4d6ce3c 100644
--- a/tests/contrib/test_extract_tensor_patch.py
+++ b/tests/contrib/test_extract_tensor_patch.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+import warnings
+
import pytest
import torch
@@ -150,3 +152,12 @@ class TestExtractTensorPatches(BaseTester):
)
# 5 patches vertical, 6 2/3 = 7 horizontal = 35 patches
assert patches.shape == (1, 35, 1, *window_size)
+
+ @pytest.mark.parametrize("img_shape, fits", [((4, 4), True), ((5, 4), False), ((4, 5), False)])
+ def test_warns_when_the_window_does_not_fit(self, device, dtype, img_shape, fits):
+ # With window 2 and stride 2, a remainder along either axis alone leaves pixels uncovered.
+ img = torch.zeros(1, 1, *img_shape, device=device, dtype=dtype)
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ kornia.contrib.extract_tensor_patches(img, window_size=2, stride=2)
+ assert any("will not fit" in str(w.message) for w in caught) is not fits
diff --git a/tests/geometry/test_bbox.py b/tests/geometry/test_bbox.py
index f044105a4..a614d90a2 100644
--- a/tests/geometry/test_bbox.py
+++ b/tests/geometry/test_bbox.py
@@ -108,6 +108,10 @@ class TestBbox2D(BaseTester):
trapezoid = torch.tensor([[[[0.0, 0.0], [10.0, 0.0], [10.0, 5.0], [3.0, 5.0]]]], device=device, dtype=dtype)
assert validate_bbox(trapezoid) is False
+ # The edge vectors share their x component and differ only in y, so only the second comparison rejects it.
+ tilted_bottom = torch.tensor([[[[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 1.0]]]], device=device, dtype=dtype)
+ assert validate_bbox(tilted_bottom) is False
+
def test_convention_validate_bbox_accepts_noncontiguous_rank4_layout_4174(self, device, dtype):
# kornia#4174: a rank-4 input whose leading dimensions cannot be merged by view returns a boolean.
boxes = torch.zeros(2, 3, 4, 2, device=device, dtype=dtype).transpose(0, 1)