Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

refactor: resolve and enforce Ruff SIM102 (#5483)

Alex9f6918cdee44
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 7a684afb1..e7c7e3312 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -238,16 +238,19 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
)
mix_added = False
- if with_mix and len(mix_indices) != 0:
- # Make the selection fair.
- if (torch.rand(1) < ((len(mix_indices) + len(indices)) / len(self))).item():
- mix_idx = torch.multinomial((~multinomial_weights.bool()).float(), 1)
- if len(indices) == 0:
- indices = mix_idx
- else:
- indices[-1] = mix_idx
- indices = indices[torch.randperm(len(indices))]
- mix_added = True
+ # Make the selection fair.
+ if (
+ with_mix
+ and len(mix_indices) != 0
+ and (torch.rand(1) < ((len(mix_indices) + len(indices)) / len(self))).item()
+ ):
+ mix_idx = torch.multinomial((~multinomial_weights.bool()).float(), 1)
+ if len(indices) == 0:
+ indices = mix_idx
+ else:
+ indices[-1] = mix_idx
+ indices = indices[torch.randperm(len(indices))]
+ mix_added = True
return self.get_children_by_indices(indices), mix_added
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index d28afb9a7..ad6e6e368 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -383,23 +383,22 @@ def combine_tensor_patches(
f"Stride={stride} should be less than or equal to Window size={window_size}, information is missing"
)
- if not unpadding:
- # if padding is specified, we leave it up to the user to ensure it fits
- # otherwise we check here if it will fit and offer to calculate padding
- if not _check_patch_fit(original_size, window_size, stride):
- if not allow_auto_unpadding:
- warn(
- f"The window will not fit into the image. \nWindow size: {window_size}\nStride: {stride}\n"
- f"Image size: {original_size}\n"
- "This means we probably cannot correctly recombine patches. By enabling `allow_auto_unpadding`, "
- "the input will be unpadded to fit the window and stride.\n"
- "If the patches have been obtained through `extract_tensor_patches` with the correct padding or "
- "the argument `allow_auto_padding`, this will result in a correct reconstruction.",
- stacklevel=1,
- )
- else:
- unpadding = compute_padding(original_size=original_size, window_size=window_size, stride=stride)
- # TODO: Can't we just do actual size minus original size to get padding?
+ # if padding is specified, we leave it up to the user to ensure it fits
+ # otherwise we check here if it will fit and offer to calculate padding
+ if not unpadding and not _check_patch_fit(original_size, window_size, stride):
+ if not allow_auto_unpadding:
+ warn(
+ f"The window will not fit into the image. \nWindow size: {window_size}\nStride: {stride}\n"
+ f"Image size: {original_size}\n"
+ "This means we probably cannot correctly recombine patches. By enabling `allow_auto_unpadding`, "
+ "the input will be unpadded to fit the window and stride.\n"
+ "If the patches have been obtained through `extract_tensor_patches` with the correct padding or "
+ "the argument `allow_auto_padding`, this will result in a correct reconstruction.",
+ stacklevel=1,
+ )
+ else:
+ unpadding = compute_padding(original_size=original_size, window_size=window_size, stride=stride)
+ # TODO: Can't we just do actual size minus original size to get padding?
if unpadding:
unpadding = create_padding_tuple(unpadding)
@@ -500,20 +499,19 @@ def extract_tensor_patches(
stride = cast(Tuple[int, int], _pair(stride))
original_size = (input.shape[-2], input.shape[-1])
- if not padding:
- # if padding is specified, we leave it up to the user to ensure it fits
- # otherwise we check here if it will fit and offer to calculate padding
- if not _check_patch_fit(original_size, window_size, stride):
- if not allow_auto_padding:
- warn(
- f"The window will not fit into the image. \nWindow size: {window_size}\nStride: {stride}\n"
- f"Image size: {original_size}\n"
- "This means that the final incomplete patches will be dropped. By enabling `allow_auto_padding`, "
- "the input will be padded to fit the window and stride.",
- stacklevel=1,
- )
- else:
- padding = compute_padding(original_size=original_size, window_size=window_size, stride=stride)
+ # if padding is specified, we leave it up to the user to ensure it fits
+ # otherwise we check here if it will fit and offer to calculate padding
+ if not padding and not _check_patch_fit(original_size, window_size, stride):
+ if not allow_auto_padding:
+ warn(
+ f"The window will not fit into the image. \nWindow size: {window_size}\nStride: {stride}\n"
+ f"Image size: {original_size}\n"
+ "This means that the final incomplete patches will be dropped. By enabling `allow_auto_padding`, "
+ "the input will be padded to fit the window and stride.",
+ stacklevel=1,
+ )
+ else:
+ padding = compute_padding(original_size=original_size, window_size=window_size, stride=stride)
if padding:
padding = create_padding_tuple(padding)
diff --git a/kornia/core/check.py b/kornia/core/check.py
index 0e4274438..1a5d3ab5e 100644
--- a/kornia/core/check.py
+++ b/kornia/core/check.py
@@ -160,7 +160,7 @@ def KORNIA_CHECK_SHAPE(x: torch.Tensor, shape: list[str], msg: Optional[str] = N
True
"""
- if not torch.jit.is_scripting():
+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
if not _KORNIA_CHECKS_ENABLED:
return True
@@ -242,7 +242,7 @@ def KORNIA_CHECK(condition: bool, msg: Optional[str] = None, raises: bool = True
True
"""
- if not torch.jit.is_scripting():
+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
if not _KORNIA_CHECKS_ENABLED:
return True
@@ -295,7 +295,7 @@ def KORNIA_CHECK_TYPE(x: Any, typ: _T | tuple[_T, ...], msg: Optional[str] = Non
True
"""
- if not torch.jit.is_scripting():
+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
if not _KORNIA_CHECKS_ENABLED:
return True
@@ -350,7 +350,7 @@ def KORNIA_CHECK_IS_TENSOR(x: Any, msg: Optional[str] = None, raises: bool = Tru
True
"""
- if not torch.jit.is_scripting():
+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
if not _KORNIA_CHECKS_ENABLED:
return True
@@ -404,7 +404,7 @@ def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Optional[Sequence[Any]], raises: bool = Tr
True
"""
- if not torch.jit.is_scripting():
+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
if not _KORNIA_CHECKS_ENABLED:
return True
@@ -449,7 +449,7 @@ def KORNIA_CHECK_SAME_DEVICE(x: torch.Tensor, y: torch.Tensor, raises: bool = Tr
True
"""
- if not torch.jit.is_scripting():
+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
if not _KORNIA_CHECKS_ENABLED:
return True
@@ -492,7 +492,7 @@ def KORNIA_CHECK_SAME_DEVICES(tensors: list[torch.Tensor], msg: Optional[str] =
True
"""
- if not torch.jit.is_scripting():
+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
if not _KORNIA_CHECKS_ENABLED:
return True
@@ -555,7 +555,7 @@ def KORNIA_CHECK_SAME_SHAPE(x: torch.Tensor, y: torch.Tensor, raises: bool = Tru
True
"""
- if not torch.jit.is_scripting():
+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
if not _KORNIA_CHECKS_ENABLED:
return True
@@ -598,7 +598,7 @@ def KORNIA_CHECK_IS_COLOR(x: torch.Tensor, msg: Optional[str] = None, raises: bo
True
"""
- if not torch.jit.is_scripting():
+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
if not _KORNIA_CHECKS_ENABLED:
return True
@@ -635,7 +635,7 @@ def KORNIA_CHECK_IS_GRAY(x: torch.Tensor, msg: Optional[str] = None, raises: boo
True
"""
- if not torch.jit.is_scripting():
+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
if not _KORNIA_CHECKS_ENABLED:
return True
@@ -672,7 +672,7 @@ def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: torch.Tensor, msg: Optional[str] = None, ra
True
"""
- if not torch.jit.is_scripting():
+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
if not _KORNIA_CHECKS_ENABLED:
return True
@@ -719,7 +719,7 @@ def KORNIA_CHECK_IS_IMAGE(x: torch.Tensor, msg: Optional[str] = None, raises: bo
True
"""
- if not torch.jit.is_scripting():
+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
if not _KORNIA_CHECKS_ENABLED:
return True
@@ -777,7 +777,7 @@ def KORNIA_CHECK_DM_DESC(desc1: torch.Tensor, desc2: torch.Tensor, dm: torch.Ten
True
"""
- if not torch.jit.is_scripting():
+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
if not _KORNIA_CHECKS_ENABLED:
return True
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index 85df5bd83..f40b30661 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -74,9 +74,8 @@ def get_mps_device_if_available() -> torch.device:
"""
dev = "cpu"
- if hasattr(torch.backends, "mps"):
- if torch.backends.mps.is_available():
- dev = "mps"
+ if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
+ dev = "mps"
return torch.device(dev)
diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.py
index 324319cfc..4c91b6d2b 100644
--- a/kornia/enhance/normalize.py
+++ b/kornia/enhance/normalize.py
@@ -198,14 +198,12 @@ def normalize(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torc
std = torch.tensor([std] * shape[1], device=data.device, dtype=data.dtype)
# Allow broadcast on channel dimension
- if mean.shape and mean.shape[0] != 1:
- if mean.shape[0] != data.shape[1] and mean.shape[:2] != data.shape[:2]:
- raise ValueError(f"mean length and number of channels do not match. Got {mean.shape} and {data.shape}.")
+ if mean.shape and mean.shape[0] != 1 and mean.shape[0] != data.shape[1] and mean.shape[:2] != data.shape[:2]:
+ raise ValueError(f"mean length and number of channels do not match. Got {mean.shape} and {data.shape}.")
# Allow broadcast on channel dimension
- if std.shape and std.shape[0] != 1:
- if std.shape[0] != data.shape[1] and std.shape[:2] != data.shape[:2]:
- raise ValueError(f"std length and number of channels do not match. Got {std.shape} and {data.shape}.")
+ if std.shape and std.shape[0] != 1 and std.shape[0] != data.shape[1] and std.shape[:2] != data.shape[:2]:
+ raise ValueError(f"std length and number of channels do not match. Got {std.shape} and {data.shape}.")
mean = torch.as_tensor(mean, device=data.device, dtype=data.dtype)
std = torch.as_tensor(std, device=data.device, dtype=data.dtype)
@@ -371,14 +369,12 @@ def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union
std = torch.tensor([std] * shape[1], device=data.device, dtype=data.dtype)
# Allow broadcast on channel dimension
- if mean.shape and mean.shape[0] != 1:
- if mean.shape[0] != data.shape[1] and mean.shape[:2] != data.shape[:2]:
- raise ValueError(f"mean length and number of channels do not match. Got {mean.shape} and {data.shape}.")
+ if mean.shape and mean.shape[0] != 1 and mean.shape[0] != data.shape[1] and mean.shape[:2] != data.shape[:2]:
+ raise ValueError(f"mean length and number of channels do not match. Got {mean.shape} and {data.shape}.")
# Allow broadcast on channel dimension
- if std.shape and std.shape[0] != 1:
- if std.shape[0] != data.shape[1] and std.shape[:2] != data.shape[:2]:
- raise ValueError(f"std length and number of channels do not match. Got {std.shape} and {data.shape}.")
+ if std.shape and std.shape[0] != 1 and std.shape[0] != data.shape[1] and std.shape[:2] != data.shape[:2]:
+ raise ValueError(f"std length and number of channels do not match. Got {std.shape} and {data.shape}.")
mean = torch.as_tensor(mean, device=data.device, dtype=data.dtype)
std = torch.as_tensor(std, device=data.device, dtype=data.dtype)
diff --git a/kornia/feature/adalam/adalam.py b/kornia/feature/adalam/adalam.py
index dbd63a5a5..01f930349 100644
--- a/kornia/feature/adalam/adalam.py
+++ b/kornia/feature/adalam/adalam.py
@@ -266,18 +266,16 @@ class AdalamFilter:
keypoints in k1 and k2.
"""
- if s1 is None or s2 is None:
- if self.config["scale_rate_threshold"] is not None:
- raise AttributeError(
- "Current configuration considers keypoint scales for filtering, but scales have not been provided.\n" # noqa: E501
- "Please either provide scales or set 'scale_rate_threshold' to None to disable scale filtering"
- )
- if o1 is None or o2 is None:
- if self.config["orientation_difference_threshold"] is not None:
- raise AttributeError(
- "Current configuration considers keypoint orientations for filtering, but orientations have not been provided.\n" # noqa: E501
- "Please either provide orientations or set 'orientation_difference_threshold' to None to disable orientations filtering" # noqa: E501
- )
+ if (s1 is None or s2 is None) and self.config["scale_rate_threshold"] is not None:
+ raise AttributeError(
+ "Current configuration considers keypoint scales for filtering, but scales have not been provided.\n"
+ "Please either provide scales or set 'scale_rate_threshold' to None to disable scale filtering"
+ )
+ if (o1 is None or o2 is None) and self.config["orientation_difference_threshold"] is not None:
+ raise AttributeError(
+ "Current configuration considers keypoint orientations for filtering, but orientations have not been provided.\n" # noqa: E501
+ "Please either provide orientations or set 'orientation_difference_threshold' to None to disable orientations filtering" # noqa: E501
+ )
_k1 = torch.as_tensor(k1, device=self.config["device"], dtype=torch.float32)
_k2 = torch.as_tensor(k2, device=self.config["device"], dtype=torch.float32)
_d1 = torch.as_tensor(d1, device=self.config["device"], dtype=torch.float32)
diff --git a/kornia/feature/dedode/decoder.py b/kornia/feature/dedode/decoder.py
index 4f948b897..b386926da 100644
--- a/kornia/feature/dedode/decoder.py
+++ b/kornia/feature/dedode/decoder.py
@@ -131,9 +131,8 @@ class ConvRefiner(nn.Module):
Decoder block (``nn.Sequential``) configured for the requested channels.
"""
num_groups = 1 if not dw else in_dim
- if dw:
- if out_dim % in_dim != 0:
- raise Exception("outdim must be divisible by indim for depthwise")
+ if dw and out_dim % in_dim != 0:
+ raise Exception("outdim must be divisible by indim for depthwise")
conv1 = nn.Conv2d(
in_dim,
out_dim,
diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.py
index 11960ef3e..d3588029e 100644
--- a/kornia/feature/lightglue.py
+++ b/kornia/feature/lightglue.py
@@ -46,9 +46,12 @@ def normalize_keypoints(kpts: torch.Tensor, size: torch.Tensor) -> torch.Tensor:
# backend (CUDA, NPU, XPU, MPS) and on CPU-only builds where
# ``torch.accelerator.current_accelerator()`` would be ``None``.
device_type = kpts.device.type
- if kpts.is_floating_point() and kpts.dtype in (torch.float16, torch.bfloat16):
- if torch.is_autocast_enabled(device_type):
- kpts = kpts.to(torch.float32)
+ if (
+ kpts.is_floating_point()
+ and kpts.dtype in (torch.float16, torch.bfloat16)
+ and torch.is_autocast_enabled(device_type)
+ ):
+ kpts = kpts.to(torch.float32)
shift = size.float().to(kpts) / 2
scale = size.max(1).values.float().to(kpts) / 2
return (kpts - shift[:, None]) / scale[:, None, None]
diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.py
index 4f76b2390..82d3dddcc 100644
--- a/kornia/geometry/calibration/undistort.py
+++ b/kornia/geometry/calibration/undistort.py
@@ -209,14 +209,15 @@ def undistort_image(image: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) ->
if not image.is_floating_point():
raise ValueError(f"Invalid input image data type. Input should be float. Got {image.dtype}.")
- if image.shape[:-3] != K.shape[:-2] or image.shape[:-3] != dist.shape[:-1]:
- # Input with image shape (1, C, H, W), K shape (3, 3), dist shape (4)
- # allowed to avoid a breaking change.
- if not all((image.shape[:-3] == (1,), K.shape[:-2] == (), dist.shape[:-1] == ())):
- raise ValueError(
- "Input shape is invalid. Input batch dimensions should match. "
- f"Got {image.shape[:-3]}, {K.shape[:-2]}, {dist.shape[:-1]}."
- )
+ # Input with image shape (1, C, H, W), K shape (3, 3), dist shape (4)
+ # allowed to avoid a breaking change.
+ if (image.shape[:-3] != K.shape[:-2] or image.shape[:-3] != dist.shape[:-1]) and not all(
+ (image.shape[:-3] == (1,), K.shape[:-2] == (), dist.shape[:-1] == ())
+ ):
+ raise ValueError(
+ "Input shape is invalid. Input batch dimensions should match. "
+ f"Got {image.shape[:-3]}, {K.shape[:-2]}, {dist.shape[:-1]}."
+ )
channels, rows, cols = image.shape[-3:]
B = image.numel() // (channels * rows * cols)
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 2a0786564..00398ecbd 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -2756,7 +2756,7 @@ def _check_Rt_same_batch(R: torch.Tensor, t: torch.Tensor, fn_name: str) -> None
# sizes, so a mismatched (R, t) pair raises here with both shapes in the message. Like the
# KORNIA_CHECK helpers it follows disable_checks(): read the flag at call time, not a copy
# bound at import.
- if not torch.jit.is_scripting():
+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
if not are_checks_enabled():
return
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index 933fbdb75..00d68ed71 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -114,9 +114,13 @@ class ParametrizedLine(nn.Module):
"""
direction = p1 - p0
- if not torch.jit.is_scripting() and are_checks_enabled() and not is_compiling():
- if not bool((direction.abs().amax(dim=-1) > 0).all()):
- raise ValueCheckError("ParametrizedLine.through requires two distinct points; p0 and p1 coincide.")
+ if (
+ not torch.jit.is_scripting()
+ and are_checks_enabled()
+ and not is_compiling()
+ and not bool((direction.abs().amax(dim=-1) > 0).all())
+ ):
+ raise ValueCheckError("ParametrizedLine.through requires two distinct points; p0 and p1 coincide.")
return ParametrizedLine(p0, _normalize_last_dim(direction, 1e-12))
def point_at(self, t: Union[float, torch.Tensor, Scalar]) -> torch.Tensor:
diff --git a/pyproject.toml b/pyproject.toml
index c113fd8b8..982de8c1d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -227,6 +227,7 @@ select = [
"RSE", # flake8-raise
"RUF", # Ruff-specific rules
"S", # flake8-bandit
+ "SIM102", # collapsible-if
"SIM103", # needless-bool
"SIM105", # suppressible-exception
"SIM114", # if-with-same-arms
diff --git a/testing/half_precision_ci.py b/testing/half_precision_ci.py
index 84ee55dff..64db66331 100644
--- a/testing/half_precision_ci.py
+++ b/testing/half_precision_ci.py
@@ -322,9 +322,12 @@ class FailureRecorder:
blockers = eager_rng_calls_for_node(report.nodeid)
if blockers:
self.eager_blockers[report.nodeid] = blockers
- if report.when == "teardown" and report.outcome != "passed":
- if report.nodeid in self.entries or report.nodeid in self.previous_entries:
- self.abort_reasons.append(f"unrepresentable teardown failure for {report.nodeid}")
+ if (
+ report.when == "teardown"
+ and report.outcome != "passed"
+ and (report.nodeid in self.entries or report.nodeid in self.previous_entries)
+ ):
+ self.abort_reasons.append(f"unrepresentable teardown failure for {report.nodeid}")
def _check_completeness(self, session: pytest.Session) -> None:
if session.config.option.collectonly: