Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

test(geometry): resolve Ruff PT018 compound assertions (#5482)

Daniele Loru4594edf75a1f
diff --git a/testing/half_precision_eager_rng.py b/testing/half_precision_eager_rng.py
index 691223eeb..772440e8c 100644
--- a/testing/half_precision_eager_rng.py
+++ b/testing/half_precision_eager_rng.py
@@ -188,7 +188,7 @@ AUDITED_EAGER_RNG_CALLS = tuple(
),
*_audited(
"tests/geometry/subpix/test_dsnt.py",
- 149,
+ 151,
"torch.randn",
1,
(
diff --git a/tests/geometry/epipolar/test_essential.py b/tests/geometry/epipolar/test_essential.py
index 1b12da2da..e62d6a833 100644
--- a/tests/geometry/epipolar/test_essential.py
+++ b/tests/geometry/epipolar/test_essential.py
@@ -176,7 +176,8 @@ class TestFindEssential(BaseTester):
points1 = torch.stack([scene["x1"], degenerate1]).to(device, dtype)
points2 = torch.stack([scene["x2"], degenerate2]).to(device, dtype)
candidates = epi.find_essential(points1, points2)
- assert candidates.shape == (2, 10, 3, 3) and candidates.device == points1.device
+ assert candidates.shape == (2, 10, 3, 3)
+ assert candidates.device == points1.device
assert self._true_e_error(candidates[0], scene["E"]) < 1e-3
alone = epi.find_essential(points1[:1], points2[:1])[0]
assert torch.equal(torch.isfinite(candidates[0]), torch.isfinite(alone))
@@ -214,13 +215,15 @@ class TestFindEssential(BaseTester):
on_cpu = epi.find_essential(x1, x2)
points1 = x1.to(device).requires_grad_()
on_mps = epi.find_essential(points1, x2.to(device))
- assert on_mps.device == points1.device and on_mps.dtype == torch.float32
+ assert on_mps.device == points1.device
+ assert on_mps.dtype == torch.float32
assert torch.equal(torch.isfinite(on_mps).cpu(), torch.isfinite(on_cpu))
self.assert_close(on_mps.cpu().nan_to_num(7.0), on_cpu.nan_to_num(7.0), atol=1e-6, rtol=0)
assert self._true_e_error(on_mps[0].detach(), scene["E"]) < 1e-4
on_mps.nan_to_num().sum().backward()
assert points1.grad.device == points1.device
- assert torch.isfinite(points1.grad).all() and bool((points1.grad != 0).any())
+ assert torch.isfinite(points1.grad).all()
+ assert bool((points1.grad != 0).any())
def test_repeated_calls_are_bitwise_equal(self, device, dtype):
# No atomic accumulation: CUDA's scatter_add_ summed the determinant polynomial in a varying order.
@@ -1046,7 +1049,8 @@ class TestConventionEssential(BaseTester):
for E_in in (E, -E, 3.0 * E):
Rs, ts = epi.motion_from_essential(E_in)
R1, R2, t_dec = epi.decompose_essential_matrix(E_in)
- assert Rs.shape == (1, 4, 3, 3) and ts.shape == (1, 4, 3, 1)
+ assert Rs.shape == (1, 4, 3, 3)
+ assert ts.shape == (1, 4, 3, 1)
# Order [(R1, t), (R1, -t), (R2, t), (R2, -t)] of decompose_essential_matrix, with a unit t.
self.assert_close(Rs[:, 0], R1)
self.assert_close(Rs[:, 1], R1)
@@ -1112,7 +1116,8 @@ class TestConventionEssential(BaseTester):
R_sw, t_sw = epi.relative_camera_motion(R @ Ra, R @ ta + t, Ra, ta)
self.assert_close(R_sw, R.transpose(-2, -1), low_tolerance=True)
self.assert_close(t_sw, -R.transpose(-2, -1) @ t, low_tolerance=True)
- assert (R_sw - R).abs().max() > 0.1 and (t_sw - t).abs().max() > 0.5
+ assert (R_sw - R).abs().max() > 0.1
+ assert (t_sw - t).abs().max() > 0.5
def test_wart_find_essential_ignores_weights_4876(self, device, dtype):
two_view = two_view_scene(device, dtype)
@@ -1144,15 +1149,19 @@ class TestConventionEssential(BaseTester):
# (1, 3, 3) next to t of shape (3, 1). All outputs now keep the leading dims of the input.
E = _gt_essential(two_view)
R1, R2, t = epi.decompose_essential_matrix(E[0])
- assert R1.shape == (3, 3) and R2.shape == (3, 3) and t.shape == (3, 1)
+ assert R1.shape == (3, 3)
+ assert R2.shape == (3, 3)
+ assert t.shape == (3, 1)
Rs, ts = epi.motion_from_essential(E[0])
- assert Rs.shape == (4, 3, 3) and ts.shape == (4, 3, 1)
+ assert Rs.shape == (4, 3, 3)
+ assert ts.shape == (4, 3, 1)
R1b, R2b, tb = epi.decompose_essential_matrix(E)
self.assert_close(R1, R1b[0])
self.assert_close(R2, R2b[0])
self.assert_close(t, tb[0])
Rsb, tsb = epi.motion_from_essential(E.expand(2, 1, 3, 3))
- assert Rsb.shape == (2, 1, 4, 3, 3) and tsb.shape == (2, 1, 4, 3, 1)
+ assert Rsb.shape == (2, 1, 4, 3, 3)
+ assert tsb.shape == (2, 1, 4, 3, 1)
def test_convention_choose_solution_reports_valid_count_4879(self, device, dtype):
two_view = two_view_scene(device, dtype)
@@ -1195,10 +1204,12 @@ class TestConventionEssential(BaseTester):
return (Rm @ Rm.transpose(-2, -1) - eye).norm(dim=(-2, -1))
R1, R2, t = epi.decompose_essential_matrix_no_svd(E)
- assert orthogonality_error(R1).max() < 0.25 and orthogonality_error(R2).max() < 0.25
+ assert orthogonality_error(R1).max() < 0.25
+ assert orthogonality_error(R2).max() < 0.25
for B in (2, 3):
R1b, R2b, tb = epi.decompose_essential_matrix_no_svd(E.repeat(B, 1, 1))
- assert orthogonality_error(R1b).max() < 0.25 and orthogonality_error(R2b).max() < 0.25
+ assert orthogonality_error(R1b).max() < 0.25
+ assert orthogonality_error(R2b).max() < 0.25
self.assert_close(R1b, R1.expand_as(R1b))
self.assert_close(R2b, R2.expand_as(R2b))
self.assert_close(tb, t.expand_as(tb))
diff --git a/tests/geometry/epipolar/test_fundamental.py b/tests/geometry/epipolar/test_fundamental.py
index fb15ed646..8de9337c3 100644
--- a/tests/geometry/epipolar/test_fundamental.py
+++ b/tests/geometry/epipolar/test_fundamental.py
@@ -740,7 +740,8 @@ class TestConventionFundamental(BaseTester):
F_sw_unit = F_sw / F_sw.norm()
assert _epipolar_residual(F_sw_unit, x1, x2).max() > 1e3 * _epipolar_residual(F_unit, x1, x2).max()
# Not normalised: neither F[2, 2] = 1 nor unit Frobenius norm.
- assert (F[..., 2, 2] - 1.0).abs().max() > 1.0 and (F.norm() - 1.0).abs() > 1.0
+ assert (F[..., 2, 2] - 1.0).abs().max() > 1.0
+ assert (F.norm() - 1.0).abs() > 1.0
# For P1 = [I | 0], P2 = [R | t] it is the negative of essential_from_Rt for the same motion, at its scale.
R, t = two_view["R"], two_view["t"]
eye = torch.eye(3, device=device, dtype=dtype)[None]
@@ -791,7 +792,8 @@ class TestConventionFundamental(BaseTester):
self.assert_close(mean_dist, torch.full_like(mean_dist, 2.0**0.5))
self.assert_close((_hom(points) @ T.transpose(-2, -1))[..., :2], points_norm, low_tolerance=True)
assert T[0, 0, 0] == T[0, 1, 1]
- assert T[0, 0, 1] == 0 and T[0, 1, 0] == 0
+ assert T[0, 0, 1] == 0
+ assert T[0, 1, 0] == 0
def test_convention_normalize_transformation_keeps_zero_last_entry(self, device, dtype):
# The F[2, 2] = 1 scaling skips a last entry within eps of zero, such as the F of an exactly rectified pair
@@ -885,7 +887,9 @@ class TestConventionFundamental(BaseTester):
F = epi.fundamental_from_projections(P1, P2)
assert F.dtype == torch.float16
F_ref = epi.fundamental_from_projections(P1.cpu().double(), P2.cpu().double())
- assert F_ref[:2].abs().amax() > 1e9 and F_ref[1].abs().amax() < 1 and (F_ref[2] == 0).all()
+ assert F_ref[:2].abs().amax() > 1e9
+ assert F_ref[1].abs().amax() < 1
+ assert (F_ref[2] == 0).all()
F_ref[:2] = F_ref[:2] / F_ref[:2].abs().amax(dim=(-2, -1), keepdim=True)
self.assert_close(F.cpu().double(), F_ref, rtol=0.0, atol=1e-3)
diff --git a/tests/geometry/epipolar/test_projection.py b/tests/geometry/epipolar/test_projection.py
index b79f05b04..c82814f8d 100644
--- a/tests/geometry/epipolar/test_projection.py
+++ b/tests/geometry/epipolar/test_projection.py
@@ -295,7 +295,9 @@ class TestConventionProjection(BaseTester):
return
K_true, R_true, t_true = two_view["K2"], two_view["R"], two_view["t"]
K, R, t = epi.KRt_from_projection(two_view["P2"])
- assert K.shape == (1, 3, 3) and R.shape == (1, 3, 3) and t.shape == (1, 3, 1)
+ assert K.shape == (1, 3, 3)
+ assert R.shape == (1, 3, 3)
+ assert t.shape == (1, 3, 1)
# K is upper triangular with a positive diagonal; R is a rotation.
assert torch.tril(K, diagonal=-1).abs().max() <= 1e-6 * K.abs().max()
assert (K.diagonal(dim1=-2, dim2=-1) > 0).all()
@@ -382,7 +384,8 @@ class TestConventionProjection(BaseTester):
image = torch.zeros(2, 3, 4, 6, device=device, dtype=dtype) # H = 4, W = 6
K = epi.intrinsics_like(500.0, image)
assert K.shape == (2, 3, 3)
- assert K.dtype == dtype and K.device == image.device
+ assert K.dtype == dtype
+ assert K.device == image.device
# fx = fy = focal, no skew, K[2] = [0, 0, 1].
self.assert_close(K[:, [0, 1], [0, 1]], torch.full((2, 2), 500.0, device=device, dtype=dtype))
zeros = torch.zeros(2, device=device, dtype=dtype)
diff --git a/tests/geometry/epipolar/test_scene.py b/tests/geometry/epipolar/test_scene.py
index e354a1684..77b932b22 100644
--- a/tests/geometry/epipolar/test_scene.py
+++ b/tests/geometry/epipolar/test_scene.py
@@ -45,7 +45,9 @@ class TestConventionScene(BaseTester):
K_again = epi.random_intrinsics(low, high)
torch.manual_seed(0)
draws = torch.distributions.Uniform(low, high).sample((4,))
- assert K.shape == (1, 3, 3) and K.dtype == dtype and K.device == low.device
+ assert K.shape == (1, 3, 3)
+ assert K.dtype == dtype
+ assert K.device == low.device
assert torch.equal(K, K_again)
assert not torch.equal(K, K_next)
self.assert_close(K[0, [0, 1, 0, 1], [0, 1, 2, 2]], draws)
diff --git a/tests/geometry/epipolar/test_triangulation.py b/tests/geometry/epipolar/test_triangulation.py
index 84dc28429..3d5c8c736 100644
--- a/tests/geometry/epipolar/test_triangulation.py
+++ b/tests/geometry/epipolar/test_triangulation.py
@@ -436,7 +436,8 @@ class TestConventionTriangulation(BaseTester):
x2 = torch.cat([two_view["x2"], x2_inf], -2).requires_grad_()
out = epi.triangulate_points(p1, p2, x1, x2, solver=solver)
finite = ~out.isnan().any(-1)
- assert not finite[..., -1].any() and finite[..., :-1].all()
+ assert not finite[..., -1].any()
+ assert finite[..., :-1].all()
for grad in torch.autograd.grad(out[finite].sum(), (p1, p2, x1, x2)):
assert torch.isfinite(grad).all()
diff --git a/tests/geometry/liegroup/test_se2.py b/tests/geometry/liegroup/test_se2.py
index fe4e766df..cd68c1a9b 100644
--- a/tests/geometry/liegroup/test_se2.py
+++ b/tests/geometry/liegroup/test_se2.py
@@ -366,7 +366,8 @@ class TestSe2(BaseTester):
z = Se2.random(1000, device=device, dtype=dtype).so2.z
self.assert_close(z.abs(), torch.ones(1000, device=device, dtype=dtype))
theta = z.imag.atan2(z.real)
- assert theta.min() < -math.pi / 2 and theta.max() > math.pi / 2, (theta.min(), theta.max())
+ assert theta.min() < -math.pi / 2, (theta.min(), theta.max())
+ assert theta.max() > math.pi / 2, (theta.min(), theta.max())
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
def test_trans(self, device, dtype, batch_size):
@@ -415,7 +416,8 @@ class TestSe2(BaseTester):
# still be registered so ``state_dict`` and ``.to()`` / ``.double()`` reach it.
v = torch.rand(2, 3, device=device, dtype=dtype, requires_grad=True)
s = Se2.exp(v)
- assert s.t.grad_fn is not None and s.so2.z.grad_fn is not None
+ assert s.t.grad_fn is not None
+ assert s.so2.z.grad_fn is not None
assert set(s.state_dict()) == {"_translation", "_rotation._z"}
restored = Se2(So2.identity(2, device, dtype), torch.zeros(2, 2, device=device, dtype=dtype))
restored.load_state_dict(s.state_dict())
@@ -667,7 +669,8 @@ class TestSe2(BaseTester):
if dtype != torch.float16: # So2.inverse divides a ComplexHalf z, which the CPU does not implement
poses.append(identity.inverse())
for pose in poses:
- assert isinstance(pose.t, torch.Tensor) and pose.t.shape == (1, 2)
+ assert isinstance(pose.t, torch.Tensor)
+ assert pose.t.shape == (1, 2)
assert "_translation" in pose.state_dict()
self.assert_close(identity.t[..., 0], torch.zeros(1, device=device, dtype=dtype))
for g in (from_exp, identity, from_exp * identity):
@@ -683,5 +686,6 @@ class TestSe2(BaseTester):
torch.manual_seed(0)
t = Se2.random(1000, device=device, dtype=dtype).t
assert t.shape == (1000, 2)
- assert t.min() >= 0 and t.max() <= 1, (t.min(), t.max())
+ assert t.min() >= 0, (t.min(), t.max())
+ assert t.max() <= 1, (t.min(), t.max())
assert 0.45 < t.mean() < 0.55, t.mean()
diff --git a/tests/geometry/liegroup/test_se3.py b/tests/geometry/liegroup/test_se3.py
index ac015bf8c..4e23a6342 100644
--- a/tests/geometry/liegroup/test_se3.py
+++ b/tests/geometry/liegroup/test_se3.py
@@ -441,8 +441,10 @@ class TestSe3(BaseTester):
self.assert_close(restored.matrix(), s.matrix().detach())
other = torch.float16 if dtype == torch.float32 else torch.float32 # float64 is unavailable on MPS
moved = s.to(other)
- assert moved.t.dtype == other and moved.t.grad_fn is not None
- assert moved.quaternion.data.dtype == other and moved.quaternion.data.grad_fn is not None
+ assert moved.t.dtype == other
+ assert moved.t.grad_fn is not None
+ assert moved.quaternion.data.dtype == other
+ assert moved.quaternion.data.grad_fn is not None
moved.t.sum().backward()
assert v.grad is not None
@@ -545,7 +547,8 @@ class TestSe3(BaseTester):
identity.inverse(),
)
for pose in poses:
- assert isinstance(pose.t, torch.Tensor) and pose.t.shape == (1, 3)
+ assert isinstance(pose.t, torch.Tensor)
+ assert pose.t.shape == (1, 3)
assert "_translation" in pose.state_dict()
self.assert_close(identity.t[..., 0], torch.zeros(1, device=device, dtype=dtype))
self.assert_close(Se3.from_qxyz(qxyz).t, qxyz[..., 4:])
@@ -569,7 +572,8 @@ class TestSe3(BaseTester):
assert list(src.state_dict()) == ["_translation", "_rotation._q._data"]
assert list(Se3.identity(1, device, dtype).state_dict()) == list(src.state_dict())
result = dst.load_state_dict(src.state_dict())
- assert not result.missing_keys and not result.unexpected_keys
+ assert not result.missing_keys
+ assert not result.unexpected_keys
self.assert_close(dst.t, src.t.detach())
self.assert_close(dst.quaternion.data, src.quaternion.data)
self.assert_close(dst.r.matrix(), src.r.matrix())
@@ -607,5 +611,6 @@ class TestSe3(BaseTester):
torch.manual_seed(0)
t = Se3.random(1000, device=device, dtype=dtype).t
assert t.shape == (1000, 3)
- assert t.min() >= 0 and t.max() <= 1, (t.min(), t.max())
+ assert t.min() >= 0, (t.min(), t.max())
+ assert t.max() <= 1, (t.min(), t.max())
assert 0.45 < t.mean() < 0.55, t.mean()
diff --git a/tests/geometry/liegroup/test_so2.py b/tests/geometry/liegroup/test_so2.py
index f3ebf8647..9b51d244f 100644
--- a/tests/geometry/liegroup/test_so2.py
+++ b/tests/geometry/liegroup/test_so2.py
@@ -260,7 +260,8 @@ class TestSo2(BaseTester):
]
assert min(counts) > 150, counts
# the draws reach both ends of the range: P(none of 1000 within 0.05 of -pi, or of pi) = 3e-4 each
- assert theta.min() < -torch.pi + 0.05 and theta.max() > torch.pi - 0.05, (theta.min(), theta.max())
+ assert theta.min() < -torch.pi + 0.05, (theta.min(), theta.max())
+ assert theta.max() > torch.pi - 0.05, (theta.min(), theta.max())
self.assert_close(So2.random(device=device, dtype=dtype).z.abs(), torch.tensor(1.0, device=device, dtype=dtype))
@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])
@@ -364,11 +365,13 @@ class TestSo2(BaseTester):
self.assert_close(moved, paired)
# (1, 1) becomes (1,), while (1,) and () are unchanged
assert So2.exp(theta[:1, None]).z.shape == (1,)
- assert So2.exp(theta[:1]).z.shape == (1,) and So2.exp(theta[0]).z.shape == ()
+ assert So2.exp(theta[:1]).z.shape == (1,)
+ assert So2.exp(theta[0]).z.shape == ()
# the (B,) reading is a view, so the gradient reaches the (B, 1) angle
column = column.clone().requires_grad_()
(So2.exp(column) * p).sum().backward()
- assert column.grad.shape == (3, 1) and torch.isfinite(column.grad).all()
+ assert column.grad.shape == (3, 1)
+ assert torch.isfinite(column.grad).all()
def test_so2_column_parameter_stays_the_module_parameter_4932(self, device, dtype):
# Reading a (B, 1) z as (B,) must not take a caller's nn.Parameter away from the module: it stays its own
diff --git a/tests/geometry/subpix/test_dsnt.py b/tests/geometry/subpix/test_dsnt.py
index c6f2bf88d..8032f7aeb 100644
--- a/tests/geometry/subpix/test_dsnt.py
+++ b/tests/geometry/subpix/test_dsnt.py
@@ -90,8 +90,10 @@ class TestRenderGaussian2d(BaseTester):
self.assert_close(heatmap[0, :, 0], y_profile.to(device=device, dtype=dtype))
self.assert_close(heatmap[..., 1:], torch.zeros_like(heatmap[..., 1:]))
(heatmap * torch.arange(25, device=device, dtype=dtype).view(1, 5, 5)).sum().backward()
- assert mean.grad is not None and std.grad is not None
- assert torch.isfinite(mean.grad).all() and torch.isfinite(std.grad).all()
+ assert mean.grad is not None
+ assert std.grad is not None
+ assert torch.isfinite(mean.grad).all()
+ assert torch.isfinite(std.grad).all()
def test_dynamo(self, device, dtype, torch_optimizer):
mean = torch.tensor([0.0, 0.0], dtype=dtype, device=device)
diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.py
index cf79813d0..1955e101d 100644
--- a/tests/geometry/test_boxes.py
+++ b/tests/geometry/test_boxes.py
@@ -316,7 +316,8 @@ class TestBoxes2D(BaseTester):
masked, indexed = lb[mask], lb[indices]
assert masked._N == indexed._N == [2, 0]
masked_boxes, indexed_boxes = masked.to_tensor("xyxy"), indexed.to_tensor("xyxy")
- assert isinstance(masked_boxes, list) and isinstance(indexed_boxes, list)
+ assert isinstance(masked_boxes, list)
+ assert isinstance(indexed_boxes, list)
for actual, expected in zip(masked_boxes, indexed_boxes):
self.assert_close(actual, expected)
assert [boxes.shape[0] for boxes in masked_boxes] == [1, 3]
diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.py
index 2c42cc7ed..ef08e2ac6 100644
--- a/tests/geometry/test_conversions.py
+++ b/tests/geometry/test_conversions.py
@@ -4974,7 +4974,8 @@ class TestCamtoworldRtToPoseRt(BaseTester):
out_R, out_t = fn(permutation, translation, check_rotation=True)
expected_R, expected_t = fn(permutation, translation)
assert out_R.dtype == torch.int64
- assert torch.equal(out_R, expected_R) and torch.equal(out_t, expected_t)
+ assert torch.equal(out_R, expected_R)
+ assert torch.equal(out_t, expected_t)
rotation = 2 * torch.eye(3, device=device, dtype=torch.int64)[None]
with pytest.raises(ValueError, match="not a rotation matrix"):
fn(rotation, translation, check_rotation=True)
diff --git a/tests/geometry/test_degensac.py b/tests/geometry/test_degensac.py
index 46404771e..c90dd0ede 100644
--- a/tests/geometry/test_degensac.py
+++ b/tests/geometry/test_degensac.py
@@ -160,7 +160,8 @@ class TestHDegenerateSample:
if reference is None:
assert result is None
else:
- assert result is not None and torch.equal(result, reference)
+ assert result is not None
+ assert torch.equal(result, reference)
@pytest.mark.parametrize("count", [0, 3])
def test_empty_or_invalid_batch(self, count):
@@ -225,7 +226,8 @@ class TestInnerHomography:
x1, x2 = _plane_with_outliers(H, torch.Generator().manual_seed(4))
first = _inner_homography(H, x1, x2, self.THRESHOLD, torch.Generator().manual_seed(5))
second = _inner_homography(H, x1, x2, self.THRESHOLD, torch.Generator().manual_seed(5))
- assert torch.equal(first[0], second[0]) and torch.equal(first[1], second[1])
+ assert torch.equal(first[0], second[0])
+ assert torch.equal(first[1], second[1])
def test_repetitions_without_inliers_contribute_nothing(self, monkeypatch):
# When every subset model h0 has fewer than 4 inliers, iterH returns an empty score, h0 included, so innerH
@@ -287,7 +289,9 @@ class TestPlaneParallaxSearch:
found = _plane_parallax_search(H_normalized, y1, y2, 2.0 * scale**2, 256, torch.Generator().manual_seed(8))
assert found is not None
models, support = found
- assert len(models) <= 8 and bool((support > 4).all()) and int(support[0]) >= 38
+ assert len(models) <= 8
+ assert bool((support > 4).all())
+ assert int(support[0]) >= 38
best = T.T @ models[0] @ T # y = T x, so y2^T F y1 = x2^T (T^T F T) x1
assert _same_up_to_scale(best, F) < 1e-6
diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.py
index ca775dcdf..56b4f1e51 100644
--- a/tests/geometry/test_homography.py
+++ b/tests/geometry/test_homography.py
@@ -379,7 +379,8 @@ class TestSampsonHomographyDistance(BaseTester):
H = torch.eye(3, device=device, dtype=dtype)[None]
for squared in (True, False):
distances = sampson_homography_distance(pts, pts + 0.1, H, squared=squared)
- assert bool(torch.isnan(distances[0, 1])) and bool(torch.isfinite(distances[0, [0, 2]]).all())
+ assert bool(torch.isnan(distances[0, 1]))
+ assert bool(torch.isfinite(distances[0, [0, 2]]).all())
nan_homography = torch.full((1, 3, 3), float("nan"), device=device, dtype=dtype)
assert bool(torch.isnan(sampson_homography_distance(pts[:, :1], pts[:, :1], nan_homography)).all())
@@ -421,7 +422,8 @@ class TestSampsonHomographyDistance(BaseTester):
pts1 = torch.tensor([[[0, 0]]], device=device)
pts2 = torch.tensor([[[1, 0]]], device=device)
distance = sampson_homography_distance(pts1, pts2, torch.eye(3, dtype=torch.long, device=device)[None])
- assert distance.dtype == torch.float32 and distance.tolist() == [[0.5]]
+ assert distance.dtype == torch.float32
+ assert distance.tolist() == [[0.5]]
def test_singular_jacobian_is_inf(self, device, dtype):
# The zero matrix makes both residual rows and the Jacobian vanish: no finite correction exists.
@@ -1222,7 +1224,8 @@ class TestConventionHomography(BaseTester):
self.assert_close(default, there_and_back)
unsquared = symmetric_transfer_error(p1, p2_off, H, squared=False)
self.assert_close(unsquared[0, 5], default[0, 5].sqrt())
- assert default[0, 5] > 50.0 and default[0, others].max() < 1e-6
+ assert default[0, 5] > 50.0
+ assert default[0, others].max() < 1e-6
assert symmetric_transfer_error(p2_off, p1, H).min() > 1e3
def test_convention_sample_is_valid_for_homography_rejects_reflection(self, device, dtype):
@@ -1249,7 +1252,8 @@ class TestConventionHomography(BaseTester):
mask = sample_is_valid_for_homography(
torch.tensor([view1] * 3, device=device, dtype=dtype), torch.tensor([view2] * 3, device=device, dtype=dtype)
)
- assert mask.dtype == torch.bool and mask.shape == (3,)
+ assert mask.dtype == torch.bool
+ assert mask.shape == (3,)
@pytest.mark.parametrize("model", ["points", "lines"])
def test_convention_find_homography_dlt_iterated_n_iter_counts_solves(self, model, device, dtype, monkeypatch):
@@ -1426,7 +1430,8 @@ class TestConventionHomography(BaseTester):
):
for squared in (True, False):
out = fn(p1, p2, H, squared=squared)
- assert bool(out[0, 0].isposinf()) and out[0, 1] == 0, out
+ assert bool(out[0, 0].isposinf()), out
+ assert out[0, 1] == 0, out
(grad,) = torch.autograd.grad(out.sum(), p1)
assert torch.isfinite(grad).all(), grad
diff --git a/tests/geometry/test_keypoints.py b/tests/geometry/test_keypoints.py
index a9362f5bb..2bfa13738 100644
--- a/tests/geometry/test_keypoints.py
+++ b/tests/geometry/test_keypoints.py
@@ -457,7 +457,8 @@ class TestConventionsKeypoints(BaseTester):
assert (brightest % width, brightest // width) == landed
assert landed != (col, row)
value = self._value_at(out_image, out_keypoints[0, 0])
- assert value is not None and value > 0.5
+ assert value is not None
+ assert value > 0.5
# Relabel control: the same pixel read as (row, col) = (2, 8) leaves the image or lands on a dark pixel
# ((0, 0) after rotate90, row 8 of a 7-row image after the translation).
diff --git a/tests/geometry/test_linalg.py b/tests/geometry/test_linalg.py
index e2dc8fc61..ea270c95d 100644
--- a/tests/geometry/test_linalg.py
+++ b/tests/geometry/test_linalg.py
@@ -565,7 +565,8 @@ class TestLinalgConventions(BaseTester):
# transform is a pure translation
assert (t01 @ t02 - t02 @ t01).abs().max() > 0.5
eye = torch.eye(3, device=device, dtype=dtype)
- assert (t01[:3, :3] - eye).abs().max() > 0.1 and (t02[:3, :3] - eye).abs().max() > 0.1
+ assert (t01[:3, :3] - eye).abs().max() > 0.1
+ assert (t02[:3, :3] - eye).abs().max() > 0.1
return t01, t02
def test_convention_relative_transformation_is_inverse_first_times_second(self, device, dtype):
diff --git a/tests/geometry/test_line.py b/tests/geometry/test_line.py
index 2151f3bb7..1f7ff04a2 100644
--- a/tests/geometry/test_line.py
+++ b/tests/geometry/test_line.py
@@ -291,7 +291,8 @@ class TestParametrizedLine(BaseTester):
self.assert_close(restored.direction, line.direction.detach())
other = torch.float16 if dtype == torch.float32 else torch.float32 # float64 is unavailable on MPS
moved = line.to(other)
- assert moved.origin.dtype == other and moved.direction.dtype == other
+ assert moved.origin.dtype == other
+ assert moved.direction.dtype == other
assert moved.direction.grad_fn is not None
moved.direction.sum().backward()
assert p1.grad is not None
@@ -301,11 +302,13 @@ class TestParametrizedLine(BaseTester):
origin = torch.tensor([0.5, 1.0], device=device, dtype=dtype, requires_grad=True)
direction = torch.tensor([0.6, 0.8], device=device, dtype=dtype, requires_grad=True)
line = ParametrizedLine(origin, direction)
- assert line.origin is origin and line.direction is direction
+ assert line.origin is origin
+ assert line.direction is direction
assert [name for name, _ in line.named_buffers()] == ["_origin", "_direction"]
assert list(line.state_dict()) == ["_origin", "_direction"]
line.point_at(2.0).sum().backward()
- assert origin.grad is not None and direction.grad is not None
+ assert origin.grad is not None
+ assert direction.grad is not None
self.assert_close(origin.grad, torch.ones_like(origin))
self.assert_close(direction.grad, torch.full_like(direction, 2.0))
# a tensor that does not require grad still becomes an optimizable parameter
diff --git a/tests/geometry/test_pose.py b/tests/geometry/test_pose.py
index 74424f401..e6c198d9c 100644
--- a/tests/geometry/test_pose.py
+++ b/tests/geometry/test_pose.py
@@ -212,7 +212,8 @@ class TestNamedPoseConventions(BaseTester):
m1, m2 = g1.matrix(), g2.matrix()
assert (m1 @ m2 - m2 @ m1).abs().max() > 0.5
eye = torch.eye(3, device=device, dtype=dtype)
- assert (m1[:3, :3] - eye).abs().max() > 0.1 and (m2[:3, :3] - eye).abs().max() > 0.1
+ assert (m1[:3, :3] - eye).abs().max() > 0.1
+ assert (m2[:3, :3] - eye).abs().max() > 0.1
return g1, g2
def test_convention_named_pose_composition_order(self, device, dtype):
diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.py
index 3a1249623..1f07344ef 100644
--- a/tests/geometry/test_ransac.py
+++ b/tests/geometry/test_ransac.py
@@ -720,7 +720,9 @@ class TestConventionRANSAC(BaseTester):
# A (3, 3) model and an (N,) bool mask; the model maps kp1 onto kp2, and the control (applying it to kp2)
# misses kp1 by about 213 px.
assert model.shape == (3, 3)
- assert mask.shape == (16,) and mask.dtype == torch.bool and bool(mask.all())
+ assert mask.shape == (16,)
+ assert mask.dtype == torch.bool
+ assert bool(mask.all())
assert _max_transfer(model, kp1, kp2) < 0.05 * _max_transfer(model, kp2, kp1)
swapped, _ = RANSAC("homography", inl_th=5.0, seed=0, max_iter=3, batch_size=64)(kp2, kp1)
assert _max_transfer(swapped, kp2, kp1) < 0.05 * _max_transfer(swapped, kp1, kp2)
@@ -729,7 +731,9 @@ class TestConventionRANSAC(BaseTester):
unrelated_2 = torch.tensor(_UNRELATED_2[:12], device=device, dtype=dtype)
model, mask = RANSAC("homography", inl_th=0.5, seed=0, max_iter=3, batch_size=64)(unrelated_1, unrelated_2)
assert bool((model == 0).all())
- assert mask.shape == (12,) and mask.dtype == torch.bool and not bool(mask.any())
+ assert mask.shape == (12,)
+ assert mask.dtype == torch.bool
+ assert not bool(mask.any())
# "homography" screens its minimal samples with sample_is_valid_for_homography: when every sample is
# rejected, no model is estimated from the exact matches either.
samples = []
@@ -742,8 +746,10 @@ class TestConventionRANSAC(BaseTester):
model, mask = RANSAC("homography", inl_th=5.0, seed=0, max_iter=3, batch_size=64)(kp1, kp2)
# Every sample is rejected, so nothing stops early: max_iter=3 batches of batch_size=64 minimal samples,
# the documented maximum.
- assert len(samples) == 3 and all(shape == (64, 4, 2) for shape in samples)
- assert bool((model == 0).all()) and not bool(mask.any())
+ assert len(samples) == 3
+ assert all(shape == (64, 4, 2) for shape in samples)
+ assert bool((model == 0).all())
+ assert not bool(mask.any())
@pytest.mark.parametrize("model_type", ["homography", "fundamental"])
def test_convention_ransac_inl_th_is_pixels_for_point_models(self, model_type, device, dtype):
@@ -758,7 +764,8 @@ class TestConventionRANSAC(BaseTester):
kp2_bad[9, 0] += 10.0 # an interior match, displaced along x
for inl_th, expected in ((4.0, False), (15.0, True)):
_, mask = RANSAC("homography", inl_th=inl_th, max_iter=20, seed=0)(kp1, kp2_bad)
- assert mask.dtype == torch.bool and mask.shape == (16,)
+ assert mask.dtype == torch.bool
+ assert mask.shape == (16,)
assert bool(mask[9]) is expected
assert int(mask.sum()) == 15 + int(expected)
# With the true H fixed, the moved match's one-way error is exactly 10 px (its symmetric error is
@@ -829,7 +836,8 @@ class TestConventionRANSAC(BaseTester):
assert torch.equal(torch.get_rng_state(), state)
torch.manual_seed(123)
model_b, mask_b = run(11)
- assert torch.equal(model_a, model_b) and torch.equal(mask_a, mask_b)
+ assert torch.equal(model_a, model_b)
+ assert torch.equal(mask_a, mask_b)
# seed=None draws from the global generator: it advances it, and reseeding it reproduces the result.
torch.manual_seed(5)
state = torch.get_rng_state()
@@ -837,7 +845,8 @@ class TestConventionRANSAC(BaseTester):
assert not torch.equal(torch.get_rng_state(), state)
torch.manual_seed(5)
model_d, mask_d = run(None)
- assert torch.equal(model_c, model_d) and torch.equal(mask_c, mask_d)
+ assert torch.equal(model_c, model_d)
+ assert torch.equal(mask_c, mask_d)
def test_convention_ransac_linesegment_threshold_units_4867(self, device, dtype):
_cpu_only(device)
@@ -867,13 +876,15 @@ class TestConventionRANSAC(BaseTester):
model, mask = RANSAC("homography", inl_th=5.0, score_type="ransac", seed=0, max_iter=5, batch_size=256)(
kp1, kp2
)
- assert bool(mask[:16].all()) and not bool(mask[16:].any())
+ assert bool(mask[:16].all())
+ assert not bool(mask[16:].any())
# MSAC ranks candidates by their truncated residuals and accepts them by inlier count, so it finds the same
# sixteen. #4868 compared the MSAC score N - sum(min(err, inl_th**2)) with the minimal sample size, a count,
# and returned no model here.
model, mask = RANSAC("homography", inl_th=5.0, score_type="msac", seed=0, max_iter=5, batch_size=256)(kp1, kp2)
assert bool(model.abs().amax() > 0)
- assert bool(mask[:16].all()) and not bool(mask[16:].any())
+ assert bool(mask[:16].all())
+ assert not bool(mask[16:].any())
def test_convention_ransac_prosac_sampling_4869(self, device, dtype):
_cpu_only(device)
@@ -1752,8 +1763,12 @@ class TestRANSACLevenbergMarquardt(BaseTester):
kp1, kp2, _, _, inliers = _scene(model_type, 200, 60, 0.0, seed=0)
ransac = RANSAC(model_type, inl_th=_px(model_type, 1.0), seed=0)
model, mask = ransac(kp1.to(device, dtype), kp2.to(device, dtype))
- assert model.shape == (3, 3) and model.dtype == dtype and model.device == kp1.to(device, dtype).device
- assert mask.shape == (200,) and mask.dtype == torch.bool and mask.device == model.device
+ assert model.shape == (3, 3)
+ assert model.dtype == dtype
+ assert model.device == kp1.to(device, dtype).device
+ assert mask.shape == (200,)
+ assert mask.dtype == torch.bool
+ assert mask.device == model.device
assert torch.equal(mask.cpu(), inliers)
tolerance = _px(model_type, 1e-4 if dtype == torch.float64 else 5e-2)
assert _model_errors(model_type, model, kp1[inliers], kp2[inliers]).max() < tolerance
@@ -1817,8 +1832,11 @@ class TestRANSACLevenbergMarquardt(BaseTester):
kp2 = _to_input_units(model_type, torch.rand(40, 2, generator=generator) * 600).to(device, dtype)
# A sample's model fits its own points; at 1e-4 px no other random point is expected on an epipolar line.
model, mask = RANSAC(model_type, inl_th=_px(model_type, 1e-4), seed=0, max_samples=512)(kp1, kp2)
- assert bool((model == 0).all()) and model.dtype == dtype
- assert mask.shape == (40,) and mask.dtype == torch.bool and not bool(mask.any())
+ assert bool((model == 0).all())
+ assert model.dtype == dtype
+ assert mask.shape == (40,)
+ assert mask.dtype == torch.bool
+ assert not bool(mask.any())
@pytest.mark.parametrize("model_type", _LM_MODELS)
def test_nonfinite_correspondences_are_outliers(self, device, dtype, model_type):
@@ -1830,7 +1848,8 @@ class TestRANSACLevenbergMarquardt(BaseTester):
ransac = RANSAC(model_type, inl_th=_px(model_type, 1.0), seed=0)
model, mask = ransac(kp1.to(device, dtype), kp2.to(device, dtype))
assert torch.isfinite(model).all()
- assert not bool(mask[:6].any()) and bool(mask[6:].all())
+ assert not bool(mask[:6].any())
+ assert bool(mask[6:].all())
@pytest.mark.parametrize("model_type", _LM_MODELS)
def test_seeded_call_is_reproducible_and_private(self, device, dtype, model_type):
@@ -1842,7 +1861,8 @@ class TestRANSACLevenbergMarquardt(BaseTester):
assert torch.equal(torch.get_rng_state(), state)
torch.manual_seed(123)
model_b, mask_b = RANSAC(model_type, inl_th=th, seed=11, max_samples=1024)(kp1, kp2)
- assert torch.equal(model_a, model_b) and torch.equal(mask_a, mask_b)
+ assert torch.equal(model_a, model_b)
+ assert torch.equal(mask_a, mask_b)
@pytest.mark.parametrize("score_type", ["msac", "ransac"])
def test_score_types(self, device, dtype, score_type):
@@ -1862,7 +1882,8 @@ class TestRANSACLevenbergMarquardt(BaseTester):
kp1, kp2 = kp1 / 60, kp2 / 60
kp2[:16] = torch.rand(16, 2, generator=torch.Generator().manual_seed(0), dtype=torch.float64) * 10 + 20
model, mask = RANSAC("homography", inl_th=0.5, seed=0)(kp1.to(device, dtype), kp2.to(device, dtype))
- assert model.dtype == dtype and torch.isfinite(model).all()
+ assert model.dtype == dtype
+ assert torch.isfinite(model).all()
assert torch.equal(mask.cpu(), inliers)
@pytest.mark.parametrize(
@@ -1951,7 +1972,8 @@ class TestRANSACEssentialLevenbergMarquardt(BaseTester):
E, mask = RANSAC("essential", inl_th=_px("essential", 1.0), seed=0)(
kp1.to(device, dtype), kp2.to(device, dtype)
)
- assert E.shape == (3, 3) and mask.shape == (n,)
+ assert E.shape == (3, 3)
+ assert mask.shape == (n,)
# Noise-free: every correspondence is an inlier and E is the true one, up to sign.
assert bool(mask.all())
E = E.cpu().double()
@@ -1963,7 +1985,8 @@ class TestRANSACEssentialLevenbergMarquardt(BaseTester):
# Pixel coordinates are not a valid input for "essential", but must not produce NaN or raise.
kp1, kp2, _, _, _ = _two_view_scene(100, 30, 0.0, seed=4)
E, mask = RANSAC("essential", inl_th=1.0, seed=0)(kp1.to(device, dtype), kp2.to(device, dtype))
- assert torch.isfinite(E).all() and mask.shape == (100,)
+ assert torch.isfinite(E).all()
+ assert mask.shape == (100,)
@pytest.mark.parametrize("seed", [0, 1, 2])
def test_planar_scene(self, device, dtype, seed):
@@ -2097,7 +2120,8 @@ class TestRANSACScoring(BaseTester):
scores, support, masks = ransac._lm_score_models(models, basis, threshold, max_residuals=137 * 7)
self.assert_close(scores, expected_scores)
self.assert_close(support, expected_support.to(support.dtype), rtol=0, atol=0)
- assert scores[0] == 0 and support[0] == 0
+ assert scores[0] == 0
+ assert support[0] == 0
if prosac:
assert masks is not None
self.assert_close(support, masks.sum(1).to(support.dtype), rtol=0, atol=0)
@@ -2156,8 +2180,12 @@ class TestRANSACCompiled(BaseTester):
th = _px(model_type, 1.5)
_, eager_mask = RANSAC(model_type, inl_th=th, seed=0)(kp1, kp2)
model, mask = RANSAC(model_type, inl_th=th, seed=0, compile=True)(kp1, kp2)
- assert model.shape == (3, 3) and model.dtype == dtype and model.device == kp1.device
- assert mask.shape == (300,) and mask.dtype == torch.bool and mask.device == kp1.device
+ assert model.shape == (3, 3)
+ assert model.dtype == dtype
+ assert model.device == kp1.device
+ assert mask.shape == (300,)
+ assert mask.dtype == torch.bool
+ assert mask.device == kp1.device
# The mask holds the inliers of the returned model, as in eager mode.
assert torch.equal(mask.cpu(), _model_errors(model_type, model, kp1, kp2) <= th)
# The same algorithm with its own random stream: the same consensus up to borderline correspondences.
@@ -2205,7 +2233,8 @@ class TestRANSACCompiled(BaseTester):
state = torch.get_rng_state()
first = ransac(kp1.float(), kp2.float())
second = ransac(kp1.float(), kp2.float())
- assert torch.equal(first[0], second[0]) and torch.equal(first[1], second[1])
+ assert torch.equal(first[0], second[0])
+ assert torch.equal(first[1], second[1])
assert torch.equal(torch.get_rng_state(), state)
for index, cuda_state in enumerate(cuda_states):
assert torch.equal(torch.cuda.get_rng_state(index), cuda_state)
@@ -2231,7 +2260,8 @@ class TestRANSACCompiled(BaseTester):
unrelated = executor.submit(torch.rand, 32)
second = executor.submit(run, 7)
first, unrelated, second = first.result(), unrelated.result(), second.result()
- assert torch.equal(first, expected) and torch.equal(second, expected)
+ assert torch.equal(first, expected)
+ assert torch.equal(second, expected)
assert torch.equal(unrelated, unrelated_expected)
@pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
@@ -2300,7 +2330,8 @@ class TestRANSACCompiled(BaseTester):
state = torch.get_rng_state()
for seed in [0, (1 << 63) - 1, -(1 << 63), -1]:
first = keys(seed, 0)
- assert first.dtype == torch.float64 and first.shape == (4, 8)
+ assert first.dtype == torch.float64
+ assert first.shape == (4, 8)
assert bool(((first >= 0) & (first < 1)).all())
assert torch.equal(first, keys(seed, 0))
assert torch.equal(first.cpu(), keys(seed, 0, target=torch.device("cpu")))
@@ -2322,7 +2353,9 @@ class TestRANSACCompiled(BaseTester):
pytest.skip("the compiled program supports CPU and CUDA")
draws = 105_000
samples = _draw_samples(4, 10, draws, device, torch.tensor(5), torch.tensor(0)).cpu()
- assert samples.shape == (draws, 4) and samples.min() >= 0 and samples.max() < 10
+ assert samples.shape == (draws, 4)
+ assert samples.min() >= 0
+ assert samples.max() < 10
ordered = samples.sort(1).values
assert (ordered[:, 1:] != ordered[:, :-1]).all()
_, counts = (ordered * torch.tensor([1000, 100, 10, 1])).sum(1).unique(return_counts=True)
@@ -2353,7 +2386,8 @@ class TestRANSACCompiled(BaseTester):
try:
with torch.autocast("cpu", dtype=torch.bfloat16):
with _ransac_program._compiled_autocast_disabled():
- assert not torch.is_autocast_enabled("cpu") and not torch.is_autocast_enabled("cuda")
+ assert not torch.is_autocast_enabled("cpu")
+ assert not torch.is_autocast_enabled("cuda")
estimator(points, points)
torch.set_default_dtype(torch.float64)
torch.set_num_threads(changed_threads)
@@ -2427,7 +2461,8 @@ class TestRANSACCompiled(BaseTester):
seed=0,
compile=True,
)(kp1, kp2)
- assert torch.isfinite(model).all() and mask.shape == (count,)
+ assert torch.isfinite(model).all()
+ assert mask.shape == (count,)
assert mask.sum() == count
@pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
@@ -2451,7 +2486,8 @@ class TestRANSACCompiled(BaseTester):
first = program(points)
second = program(points)
assert calls == {"artifact": 1, "traced": 2}
- assert torch.equal(first[0], second[0]) and torch.equal(first[1], second[1])
+ assert torch.equal(first[0], second[0])
+ assert torch.equal(first[1], second[1])
@pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
def test_compile_artifact_runtime_error_propagates(self):
@@ -2538,7 +2574,8 @@ class TestRANSACCompiled(BaseTester):
assert not mask[[50, 60, 70]].any()
expected = inliers.to(device).clone()
expected[[50, 60, 70]] = False
- assert (mask & expected).sum() >= 0.95 * expected.sum() and (mask & ~expected).sum() == 0
+ assert (mask & expected).sum() >= 0.95 * expected.sum()
+ assert (mask & ~expected).sum() == 0
@pytest.mark.slow
@pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
@@ -2571,7 +2608,9 @@ class TestRANSACCompiled(BaseTester):
outputs.append(result.stdout.split())
assert list((tmp_path / "kornia_ransac").glob("*.bin"))
assert [output[0] for output in outputs] == ["300"] * 3
- assert int(outputs[0][1]) >= 1 and int(outputs[1][1]) >= 1 and outputs[2][1] == "0"
+ assert int(outputs[0][1]) >= 1
+ assert int(outputs[1][1]) >= 1
+ assert outputs[2][1] == "0"
class TestRANSACDegensacOptions(BaseTester):
@@ -2616,7 +2655,8 @@ class TestRANSACDegensacOptions(BaseTester):
models, origin = ransac._lm_minimal_models(x1, x2)
assert origin is None
tracked_models, tracked_origin = ransac._lm_minimal_models(x1, x2, track_origins=True)
- assert tracked_origin is not None and len(tracked_origin) == len(models)
+ assert tracked_origin is not None
+ assert len(tracked_origin) == len(models)
assert torch.equal(models.isnan(), tracked_models.isnan())
self.assert_close(models.nan_to_num(), tracked_models.nan_to_num(), atol=0, rtol=0)
@@ -2638,7 +2678,8 @@ class TestRANSACDegensacOptions(BaseTester):
x2 = torch.cat([torch.rand(16, m, 2, generator=generator), torch.ones(16, m, 1)], -1)
models, rows = ransac._lm_minimal_models(x1.to(device, work), x2.to(device, work), track_origins=True)
assert rows is not None
- assert rows.shape == (len(models),) and rows.dtype == torch.long
+ assert rows.shape == (len(models),)
+ assert rows.dtype == torch.long
assert bool((rows[1:] >= rows[:-1]).all()) # draw order
finite = torch.isfinite(models).flatten(1).all(1)
models, rows = models[finite].cpu().double(), rows[finite].cpu()
@@ -2717,7 +2758,8 @@ class TestRANSACDegensacRecovery(BaseTester):
assert masks is None
# One model per recovery, as Chum's rFtH returns one: near-duplicates from one search would crowd the
# eight-model pool (on the loftr_fund pair they cost test_real_dirty_7pt its margin in 2 of 20 seeds).
- assert out_models.shape == (1, 3, 3) and scores.shape == counts.shape == (1,)
+ assert out_models.shape == (1, 3, 3)
+ assert scores.shape == counts.shape == (1,)
best = out_models[int(scores.argmax())].cpu().double()
assert _explains_off_plane(t2.mT @ best @ t1, clean1.cpu(), clean2.cpu())
assert flagged >= 5
@@ -2738,7 +2780,8 @@ class TestRANSACDegensacRecovery(BaseTester):
monkeypatch.setattr(ransac_module, "_h_degenerate_sample", scalar_check)
kp1, kp2, _, clean1, clean2 = create_dominant_plane_scene(1000, 0.6, 0.95, 0, device=device, dtype=dtype)
F, _ = RANSAC("fundamental", inl_th=1.0, seed=0, degensac=True)(kp1, kp2)
- assert sizes and max(sizes) > 1
+ assert sizes
+ assert max(sizes) > 1
assert _explains_off_plane(F.cpu(), clean1.cpu(), clean2.cpu())
@pytest.mark.parametrize("score_type", ["msac", "ransac"])
@@ -2753,7 +2796,8 @@ class TestRANSACDegensacRecovery(BaseTester):
monkeypatch.setattr(ransac_module, "_h_degenerate_samples", scalar_checks)
scalar = estimator(kp1, kp2)
- assert torch.equal(batched[0], scalar[0]) and torch.equal(batched[1], scalar[1])
+ assert torch.equal(batched[0], scalar[0])
+ assert torch.equal(batched[1], scalar[1])
def test_unseeded_recoveries_leave_the_global_generator(self, device, dtype):
# The minimal samples of an unseeded call come from the global generator. Recoveries drawing from it too
@@ -2812,7 +2856,9 @@ class TestRANSACDegensacRecovery(BaseTester):
torch.manual_seed(global_seed)
RANSAC("fundamental", inl_th=1.0, degensac=True)(kp1, kp2)
per_call.append(set(seeds))
- assert per_call[0] and per_call[1] and per_call[0] != per_call[1]
+ assert per_call[0]
+ assert per_call[1]
+ assert per_call[0] != per_call[1]
def test_repeated_plane_is_searched_once(self, device, dtype, monkeypatch):
# Every degenerate record setter of a dominant plane finds the same plane (the refined planes of repeated
@@ -2847,7 +2893,8 @@ class TestRANSACDegensacRecovery(BaseTester):
recoveries = ransac._degensac_batch(
models, samples[rows], scores, -1.0, x1, x2, x1_host, x2_host, basis, threshold, 0
)
- assert len(calls) == 1 and len(recoveries) == 1
+ assert len(calls) == 1
+ assert len(recoveries) == 1
def test_dominant_plane_is_refined_once_per_call(self, device, dtype, monkeypatch):
# A later record setter's homography is noisier than the refined plane (Jaccard index 0.03-1.0 against it at
@@ -2893,7 +2940,8 @@ class TestRANSACDegensacRecovery(BaseTester):
_skip_half(dtype)
raw = self._recover_once(0, "ransac", 5, device, dtype)
refined = self._recover_once(5, "ransac", 5, device, dtype)
- assert raw is not None and refined is not None
+ assert raw is not None
+ assert refined is not None
assert float(refined[1][0]) >= float(raw[1][0])
def test_worse_refinement_keeps_the_raw_model(self, device, dtype, monkeypatch):
@@ -2902,8 +2950,10 @@ class TestRANSACDegensacRecovery(BaseTester):
# A "refinement" that returns a scrambled model scores far below the raw one.
monkeypatch.setattr(RANSAC, "_lm_refine", lambda self, models, *args: models.roll(1, dims=-1))
kept = self._recover_once(5, "msac", 0, device, dtype)
- assert raw is not None and kept is not None
- assert torch.equal(kept[0], raw[0]) and torch.equal(kept[1], raw[1])
+ assert raw is not None
+ assert kept is not None
+ assert torch.equal(kept[0], raw[0])
+ assert torch.equal(kept[1], raw[1])
def test_non_degenerate_sample_returns_none(self, device, dtype):
# Seven off-plane correspondences are not always in general position at the test's tolerance: a five-point
@@ -2969,7 +3019,8 @@ class TestRANSACDegensac(BaseTester):
kp1, kp2, _, _, _ = create_dominant_plane_scene(1000, 0.6, 0.95, 0, device=device, dtype=dtype)
F, mask = RANSAC("fundamental", inl_th=1.0, seed=0, degensac=True)(kp1, kp2)
F_plain, mask_plain = RANSAC("fundamental", inl_th=1.0, seed=0, degensac=False)(kp1, kp2)
- assert torch.equal(F, F_plain) and torch.equal(mask, mask_plain)
+ assert torch.equal(F, F_plain)
+ assert torch.equal(mask, mask_plain)
def test_scene_without_plane_keeps_its_accuracy(self, device, dtype, monkeypatch):
# Without a dominant plane, record setters are still often H-degenerate at Chum's 3 t: five of seven
@@ -3038,7 +3089,8 @@ class TestRANSACDegensac(BaseTester):
first = RANSAC("fundamental", inl_th=1.0, seed=3, degensac=True)(kp1, kp2)
second = RANSAC("fundamental", inl_th=1.0, seed=3, degensac=True)(kp1, kp2)
assert calls # the recovery drew
- assert torch.equal(first[0], second[0]) and torch.equal(first[1], second[1])
+ assert torch.equal(first[0], second[0])
+ assert torch.equal(first[1], second[1])
assert torch.equal(torch.get_rng_state(), cpu_state)
if accelerator_state is not None:
assert torch.equal(device_state(), accelerator_state)
@@ -3060,7 +3112,8 @@ class TestRANSACDegensac(BaseTester):
_skip_half(dtype)
kp1, kp2, labels, _, _ = create_dominant_plane_scene(1000, 0.6, 1.0, 0, device=device, dtype=dtype)
F, mask = RANSAC("fundamental", inl_th=1.0, seed=0, degensac=True)(kp1, kp2)
- assert F.shape == (3, 3) and bool(F.abs().sum() > 0)
+ assert F.shape == (3, 3)
+ assert bool(F.abs().sum() > 0)
plane = labels == 0
assert float((mask & plane).sum()) >= 0.9 * float(plane.sum())
@@ -3069,7 +3122,9 @@ class TestRANSACDegensac(BaseTester):
def test_tiny_inputs(self, device, dtype, num_points):
kp1, kp2, _, _, _ = create_dominant_plane_scene(num_points, 0.8, 0.9, 0, device=device, dtype=dtype)
F, mask = RANSAC("fundamental", inl_th=1.0, seed=0, degensac=True)(kp1, kp2)
- assert F.shape == (3, 3) and mask.shape == (num_points,) and mask.dtype == torch.bool
+ assert F.shape == (3, 3)
+ assert mask.shape == (num_points,)
+ assert mask.dtype == torch.bool
# Review focus 4: PROSAC's stopping rule takes the recovered incumbent's mask.
def test_prosac(self, device, dtype, monkeypatch):
@@ -3096,7 +3151,8 @@ class TestRANSACDegensac(BaseTester):
F, _ = RANSAC("fundamental", inl_th=1.0, seed=0, prosac_sampling=True, degensac=True)(kp1[order], kp2[order])
assert _explains_off_plane(F.cpu(), clean1.cpu(), clean2.cpu())
# The recovered incumbent's stopping bound is PROSAC's test on its own inlier mask.
- assert recovered and any(torch.equal(mask, inliers) for mask in recovered for inliers in tested)
+ assert recovered
+ assert any(torch.equal(mask, inliers) for mask in recovered for inliers in tested)
# Review focus 5: half-precision correspondences run the float64 host recovery and float32 device scoring.
def test_half_precision_smoke(self, device):
@@ -3105,4 +3161,6 @@ class TestRANSACDegensac(BaseTester):
for dtype in (torch.float16, torch.bfloat16):
kp1, kp2, _, _, _ = create_dominant_plane_scene(500, 0.6, 0.95, 0, device=device, dtype=dtype)
F, mask = RANSAC("fundamental", inl_th=2.0, seed=0, degensac=True)(kp1, kp2)
- assert F.shape == (3, 3) and F.dtype == dtype and mask.shape == (500,)
+ assert F.shape == (3, 3)
+ assert F.dtype == dtype
+ assert mask.shape == (500,)
diff --git a/tests/geometry/transform/test_imgwarp.py b/tests/geometry/transform/test_imgwarp.py
index 65ea73fd7..145270c36 100644
--- a/tests/geometry/transform/test_imgwarp.py
+++ b/tests/geometry/transform/test_imgwarp.py
@@ -67,7 +67,8 @@ def test_empty_destination_forward_runs_on_every_backend(op_name, dsize, batch,
assert out.shape == (batch, 3, *dsize)
assert out.numel() == 0
- assert out.device.type == device.type and out.dtype == dtype
+ assert out.device.type == device.type
+ assert out.dtype == dtype
@pytest.mark.parametrize("op_name", ["warp_affine", "warp_perspective", "remap"])
@@ -122,7 +123,8 @@ def test_empty_destination_samples_a_constant_1x1_stand_in(device, dtype, monkey
out = kornia.geometry.transform.warp_affine(src, transform, (0, 2_000_000))
assert out.shape == (1, 3, 0, 2_000_000)
- assert sampled_grids and all(shape == (1, 1, 1, 2) for shape in sampled_grids)
+ assert sampled_grids
+ assert all(shape == (1, 1, 1, 2) for shape in sampled_grids)
@pytest.mark.parametrize("op_name", ["warp_affine", "warp_perspective"])
@@ -150,8 +152,10 @@ def test_empty_destination_is_autograd_connected(op_name, dsize, align_corners,
assert out.shape == (1, 3, *dsize)
assert out.numel() == 0
out.sum().backward()
- assert src.grad is not None and torch.count_nonzero(src.grad) == 0
- assert transform.grad is not None and torch.count_nonzero(transform.grad) == 0
+ assert src.grad is not None
+ assert torch.count_nonzero(src.grad) == 0
+ assert transform.grad is not None
+ assert torch.count_nonzero(transform.grad) == 0
@pytest.mark.parametrize("op_name", ["warp_affine", "warp_perspective"])
@@ -167,7 +171,8 @@ def test_empty_source_policy(op_name, device, dtype):
empty = op(src, transform, (0, 4))
assert empty.shape == (1, 3, 0, 4)
empty.sum().backward()
- assert src.grad is not None and transform.grad is not None
+ assert src.grad is not None
+ assert transform.grad is not None
with pytest.raises(ValueError, match="must be positive"):
op(src, transform, (3, 4))
diff --git a/tests/geometry/transform/test_imgwarp3d.py b/tests/geometry/transform/test_imgwarp3d.py
index 753d5d70c..5e9a7074a 100644
--- a/tests/geometry/transform/test_imgwarp3d.py
+++ b/tests/geometry/transform/test_imgwarp3d.py
@@ -40,8 +40,10 @@ def test_empty_destination_is_autograd_connected(op_name, dsize, align_corners,
assert out.shape == (1, 2, *dsize)
assert out.numel() == 0
out.sum().backward()
- assert src.grad is not None and torch.count_nonzero(src.grad) == 0
- assert transform.grad is not None and torch.count_nonzero(transform.grad) == 0
+ assert src.grad is not None
+ assert torch.count_nonzero(src.grad) == 0
+ assert transform.grad is not None
+ assert torch.count_nonzero(transform.grad) == 0
@pytest.mark.parametrize("op_name", ["warp_affine3d", "warp_perspective3d"])
@@ -57,7 +59,8 @@ def test_empty_source_policy(op_name, device, dtype):
empty = op(src, transform, (0, 4, 5))
assert empty.shape == (1, 2, 0, 4, 5)
empty.sum().backward()
- assert src.grad is not None and transform.grad is not None
+ assert src.grad is not None
+ assert transform.grad is not None
with pytest.raises(ValueError, match="must be positive"):
op(src, transform, (3, 4, 5))