Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

test(augmentation): resolve Ruff PT018 compound assertions (#5373)

Daniele Lorufc0ffae44406
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index bcfc0978c..cbbc9eead 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -1161,7 +1161,8 @@ class TestConventionAugmentationSequential(BaseTester):
out_image, out_masks = seq(image, masks)
restored_image, restored = seq.inverse(out_image, out_masks)
self.assert_close(restored_image, image)
- assert isinstance(restored, list) and len(restored) == 2
+ assert isinstance(restored, list)
+ assert len(restored) == 2
assert [m.dtype for m in restored] == [torch.int64, torch.bool]
for entry, original in zip(restored, masks):
assert torch.equal(entry, original)
diff --git a/tests/augmentation/container/test_sequential_aug.py b/tests/augmentation/container/test_sequential_aug.py
index a20d4672b..58e2fbc29 100644
--- a/tests/augmentation/container/test_sequential_aug.py
+++ b/tests/augmentation/container/test_sequential_aug.py
@@ -115,9 +115,12 @@ class TestConventionImageSequential(BaseTester):
output = aug(image, output_type=output_type)
if output_type == "numpy":
- assert output.shape == (2, 6, 8, 3) and not isinstance(output, torch.Tensor) # channels-last (#5207)
+ # channels-last (#5207)
+ assert output.shape == (2, 6, 8, 3)
+ assert not isinstance(output, torch.Tensor)
else:
- assert len(output) == 2 and all(isinstance(out, PILImage.Image) for out in output)
+ assert len(output) == 2
+ assert all(isinstance(out, PILImage.Image) for out in output)
cached = aug._output_image
assert isinstance(cached, torch.Tensor)
assert not cached.requires_grad
@@ -154,7 +157,8 @@ class TestConventionImageSequential(BaseTester):
seq(image)
current = seq.get_transformation_matrix(image, old_params)
recomputed = seq.get_transformation_matrix(image, old_params, recompute=True)
- assert current is not None and recomputed is not None
+ assert current is not None
+ assert recomputed is not None
assert not torch.equal(current, recomputed)
def test_convention_if_unsupported_ops_raise_raises_not_implemented(self, device, dtype):
diff --git a/tests/augmentation/test_augmentation_mix.py b/tests/augmentation/test_augmentation_mix.py
index 13d1636be..72c6912f5 100644
--- a/tests/augmentation/test_augmentation_mix.py
+++ b/tests/augmentation/test_augmentation_mix.py
@@ -733,7 +733,8 @@ class TestRandomMosaic(BaseTester):
params["batch_prob"] = params["batch_prob"].new_tensor(gate)
_, out = aug(image, boxes, params=params)
- assert isinstance(out, list) and len(out) == 4
+ assert isinstance(out, list)
+ assert len(out) == 4
for b, selected in enumerate(gate):
if not selected:
self.assert_close(out[b], boxes[b])
diff --git a/tests/augmentation/test_conventions_3d.py b/tests/augmentation/test_conventions_3d.py
index 9cc9514a6..3457aeb27 100644
--- a/tests/augmentation/test_conventions_3d.py
+++ b/tests/augmentation/test_conventions_3d.py
@@ -91,7 +91,8 @@ class Test3DAugmentationConventions(BaseTester):
volume = torch.arange(120, device=device, dtype=dtype).reshape(1, 1, 4, 5, 6)
center = K.CenterCrop3D((2, 3, 4), p=1.0)
crop = K.RandomCrop3D((2, 3, 4), p=1.0, same_on_batch=True)
- assert center.flags["align_corners"] and crop.flags["align_corners"]
+ assert center.flags["align_corners"]
+ assert crop.flags["align_corners"]
assert center.flags["resample"].name == crop.flags["resample"].name == "BILINEAR"
assert center(volume).shape == crop(volume).shape == (1, 1, 2, 3, 4)
self.assert_close(center(volume), volume[..., 1:3, 1:4, 1:5])
@@ -148,7 +149,8 @@ class Test3DAugmentationConventions(BaseTester):
affine = K.RandomAffine3D((0.0, 0.0, 0.0), p=1.0)
rotation = K.RandomRotation3D((0.0, 0.0, 0.0), p=1.0)
perspective = K.RandomPerspective3D(0.0, p=1.0)
- assert not affine.flags["align_corners"] and not rotation.flags["align_corners"]
+ assert not affine.flags["align_corners"]
+ assert not rotation.flags["align_corners"]
assert not perspective.flags["align_corners"]
assert (
affine.flags["resample"].name
@@ -188,7 +190,8 @@ class Test3DAugmentationConventions(BaseTester):
output = augmentation(volume)
assert output.shape == volume.shape
- assert output.device == volume.device and output.dtype == dtype
+ assert output.device == volume.device
+ assert output.dtype == dtype
assert torch.isfinite(output).all()
matrix = augmentation.transform_matrix
assert torch.isfinite(matrix).all()
@@ -522,7 +525,8 @@ class Test3DAugmentationConventions(BaseTester):
augmentation = K.RandomMotionBlur3D((3, 7), 35.0, 0.5, p=1.0)
assert augmentation(volume).shape == volume.shape
drawn = augmentation._params["ksize_factor"]
- assert drawn.shape == (6,) and drawn.unique().numel() == 1
+ assert drawn.shape == (6,)
+ assert drawn.unique().numel() == 1
sizes.update(drawn.tolist())
assert sizes == {3, 5, 7}
rounded_up = K.RandomMotionBlur3D((4, 4), 35.0, 0.5, p=1.0)
@@ -622,8 +626,10 @@ class Test3DAugmentationConventions(BaseTester):
aug(torch.rand(64, 1, 5, 6, 7))
scale = aug._params["scale"]
assert scale.shape == (64, 3)
- assert bool((scale[:, 0] == scale[:, 1]).all()) and bool((scale[:, 1] == scale[:, 2]).all())
- assert 0.5 <= float(scale.min()) and float(scale.max()) <= 2.0
+ assert bool((scale[:, 0] == scale[:, 1]).all())
+ assert bool((scale[:, 1] == scale[:, 2]).all())
+ assert 0.5 <= float(scale.min())
+ assert float(scale.max()) <= 2.0
assert len(scale[:, 0].unique()) > 1
self.assert_close(aug.transform_matrix[:, :3, :3].diagonal(dim1=-2, dim2=-1), scale)
shared = K.RandomAffine3D(0.0, scale=(0.5, 2.0), same_on_batch=True, p=1.0)
@@ -632,7 +638,8 @@ class Test3DAugmentationConventions(BaseTester):
per_axis = K.RandomAffine3D(0.0, scale=((0.5, 2.0), (0.5, 2.0), (0.5, 2.0)), p=1.0)
axes = per_axis.forward_parameters(torch.Size([64, 1, 5, 6, 7]))["scale"]
assert axes.shape == (64, 3)
- assert not bool((axes[:, 0] == axes[:, 1]).any()) and not bool((axes[:, 1] == axes[:, 2]).any())
+ assert not bool((axes[:, 0] == axes[:, 1]).any())
+ assert not bool((axes[:, 1] == axes[:, 2]).any())
# The two-value form is range-checked under its own name.
with pytest.raises(ValueError, match="scale out of bounds"):
K.RandomAffine3D(0.0, scale=(-0.5, 2.0), p=1.0)
@@ -642,7 +649,8 @@ class Test3DAugmentationConventions(BaseTester):
pairs = ((1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12))
params = K.RandomAffine3D(0.0, shears=pairs, p=1.0).forward_parameters(torch.Size([64, 1, 4, 5, 6]))
for key, (low, high) in zip(("sxy", "sxz", "syx", "syz", "szx", "szy"), pairs):
- assert low <= float(params[key].min()) and float(params[key].max()) <= high
+ assert low <= float(params[key].min())
+ assert float(params[key].max()) <= high
@pytest.mark.device_agnostic
def test_convention_random_crop3d_padding_modes_are_those_of_f_pad(self):
@@ -660,7 +668,8 @@ class Test3DAugmentationConventions(BaseTester):
assert set(perspective) == {"start_points", "end_points"}
assert perspective["start_points"].shape == perspective["end_points"].shape == (3, 8, 3)
blur = rg.MotionBlurGenerator3D(3, 35.0, 0.5)(shape)
- assert blur["angle_factor"].shape == (3, 3) and blur["ksize_factor"].shape == (3,)
+ assert blur["angle_factor"].shape == (3, 3)
+ assert blur["ksize_factor"].shape == (3,)
# "odd and at least 3": a kernel of one voxel is rejected.
with pytest.raises(AssertionError, match="must be odd and greater than 3"):
K.RandomMotionBlur3D(1, 35.0, 0.5, p=1.0)(torch.rand(1, 1, 5, 5, 5))
diff --git a/tests/augmentation/test_conventions_auto.py b/tests/augmentation/test_conventions_auto.py
index 45c446257..9d246217d 100644
--- a/tests/augmentation/test_conventions_auto.py
+++ b/tests/augmentation/test_conventions_auto.py
@@ -72,13 +72,19 @@ class TestAutoAugmentConventions(BaseTester):
def test_convention_autoaugment_magnitude_bins_select_adjacent_intervals(self):
degrees = AutoAugment(policy=[[("rotate", 1.0, 9)]]).forward_parameters(torch.Size([64, 1, 8, 6]))
degrees = degrees[0].data[0].data["degrees"]
- assert (degrees >= 24.0).all() and (degrees <= 30.0).all()
- assert degrees.min() < 25.0 and degrees.max() > 29.0 # bounds alone pass for a collapsed interval
+ assert (degrees >= 24.0).all()
+ assert (degrees <= 30.0).all()
+ # bounds alone pass for a collapsed interval
+ assert degrees.min() < 25.0
+ assert degrees.max() > 29.0
torch.manual_seed(17)
degrees = AutoAugment(policy=[[("rotate", 1.0, 5)]]).forward_parameters(torch.Size([64, 1, 8, 6]))
degrees = degrees[0].data[0].data["degrees"]
- assert (degrees >= 0.0).all() and (degrees <= 6.0).all() # bin 5 of linspace(-30, 30, 11) is [0, 6]
- assert degrees.min() < 1.0 and degrees.max() > 5.0
+ # bin 5 of linspace(-30, 30, 11) is [0, 6]
+ assert (degrees >= 0.0).all()
+ assert (degrees <= 6.0).all()
+ assert degrees.min() < 1.0
+ assert degrees.max() > 5.0
for magnitude in (-1, 10):
with pytest.raises(ValueError, match=r"in \[0, 9\]"):
AutoAugment(policy=[[("rotate", 1.0, magnitude)]])
@@ -110,8 +116,10 @@ class TestAutoAugmentConventions(BaseTester):
aug = TrivialAugment(policy=[[("rotate", -30.0, 30.0)]])
degrees = aug.forward_parameters(torch.Size([64, 1, 8, 6]))[0].data[0].data["degrees"]
assert (degrees.abs() <= 30.0).all()
- assert (degrees < 0).any() and (degrees > 0).any()
- assert degrees.abs().min() < 5.0 and degrees.abs().max() > 25.0
+ assert (degrees < 0).any()
+ assert (degrees > 0).any()
+ assert degrees.abs().min() < 5.0
+ assert degrees.abs().max() > 25.0
@pytest.mark.device_agnostic
def test_convention_randaugment_maps_m_and_validates_the_policy_cardinality(self):
@@ -121,7 +129,8 @@ class TestAutoAugmentConventions(BaseTester):
params = aug.forward_parameters(torch.Size([64, 1, 8, 6]))
degrees = next(param for param in params if "degrees" in param.data[0].data).data[0].data["degrees"]
self.assert_close(degrees.abs(), torch.full_like(degrees, 15.0))
- assert (degrees < 0).any() and (degrees > 0).any()
+ assert (degrees < 0).any()
+ assert (degrees > 0).any()
for m in (0, 30):
with pytest.raises(ValueError, match=r"Expect `m` in \(0, 30\)"):
RandAugment(n=1, m=m, policy=policy)
@@ -383,7 +392,8 @@ class TestAutoAugmentConventions(BaseTester):
assert operation._magnitude.grad is not None
# The parameter is kept in the state dict, and no sampler is stored on the wrapper or the wrapped op.
assert "_probability" in operation.state_dict()
- assert not hasattr(operation.op, "_p_gen") and not hasattr(operation.op, "_p_batch_gen")
+ assert not hasattr(operation.op, "_p_gen")
+ assert not hasattr(operation.op, "_p_batch_gen")
# So a policy deep-copies after a forward and after train() / eval(), and the copy replays the original.
image = torch.rand(2, 3, 8, 8)
for policy in (AutoAugment(), TrivialAugment(), RandAugment(n=2, m=15)):
@@ -398,7 +408,8 @@ class TestAutoAugmentConventions(BaseTester):
assert {(module[0].op.p, module[0].op.p_batch) for _, module in aug.named_children()} == {(1.0, 1.0)}
# "Each candidate": every entry of the default policy as well, not only the two above.
defaults = [(module[0].op.p, module[0].op.p_batch) for _, module in TrivialAugment().named_children()]
- assert len(defaults) == 12 and set(defaults) == {(1.0, 1.0)}
+ assert len(defaults) == 12
+ assert set(defaults) == {(1.0, 1.0)}
gates = set()
for _ in range(16):
gates.update(aug.forward_parameters(torch.Size([8, 3, 8, 6]))[0].data[0].data["batch_prob"].tolist())
@@ -423,8 +434,10 @@ class TestAutoAugmentConventions(BaseTester):
.data[0]
.data["shear_x"]
)
- assert bool((trivial.abs() <= 0.3 * 180).all()) and trivial.abs().max() > 30.0
- assert (trivial < 0).any() and (trivial > 0).any()
+ assert bool((trivial.abs() <= 0.3 * 180).all())
+ assert trivial.abs().max() > 30.0
+ assert (trivial < 0).any()
+ assert (trivial > 0).any()
# AutoAugment's shear bins are fractions too, so the mapping is applied once: bin b of either shear op spans
# the adjacent points b and b + 1 of linspace(-0.3, 0.3, 11), times 180, and 256 rows reach both ends.
edges = [-0.3 + 0.06 * point for point in range(11)]
@@ -437,8 +450,10 @@ class TestAutoAugmentConventions(BaseTester):
.data[0]
.data[name]
)
- assert bool((auto >= low - 1e-3).all()) and bool((auto <= high + 1e-3).all()), (name, magnitude_bin)
- assert auto.min() < low + 1.0 and auto.max() > high - 1.0, (name, magnitude_bin)
+ assert bool((auto >= low - 1e-3).all()), (name, magnitude_bin)
+ assert bool((auto <= high + 1e-3).all()), (name, magnitude_bin)
+ assert auto.min() < low + 1.0, (name, magnitude_bin)
+ assert auto.max() > high - 1.0, (name, magnitude_bin)
# The same policy entry through RandAugment.
mapped = (
RandAugment(n=1, m=29, policy=[[("shear_x", -0.3, 0.3)]])
@@ -523,4 +538,5 @@ class TestAutoAugmentConventions(BaseTester):
drawn = aug.forward_parameters(torch.Size([8, 1, height, width]))[0].data[0].data[operation._factor_name]
self.assert_close(drawn.abs().float(), torch.full((8,), float(expected)))
checked.append(name)
- assert len(checked) == 12 and {"shear_x", "shear_y", "posterize", "translate_x", "translate_y"} <= set(checked)
+ assert len(checked) == 12
+ assert {"shear_x", "shear_y", "posterize", "translate_x", "translate_y"} <= set(checked)
diff --git a/tests/augmentation/test_conventions_geometric_matrix.py b/tests/augmentation/test_conventions_geometric_matrix.py
index 1714ce707..014a1678b 100644
--- a/tests/augmentation/test_conventions_geometric_matrix.py
+++ b/tests/augmentation/test_conventions_geometric_matrix.py
@@ -108,9 +108,11 @@ class TestConventionGeometricMatrices(BaseTester):
extent = basic_offset.new_tensor([1.75, 1.25])
assert (basic_offset[:, 0] >= 0).all()
- assert (basic_offset[:, 1, 0] <= 0).all() and (basic_offset[:, 1, 1] >= 0).all()
+ assert (basic_offset[:, 1, 0] <= 0).all()
+ assert (basic_offset[:, 1, 1] >= 0).all()
assert (basic_offset[:, 2] <= 0).all()
- assert (basic_offset[:, 3, 0] >= 0).all() and (basic_offset[:, 3, 1] <= 0).all()
+ assert (basic_offset[:, 3, 0] >= 0).all()
+ assert (basic_offset[:, 3, 1] <= 0).all()
assert (basic_offset.abs() <= extent).all()
assert (basic_offset.abs().amax(dim=(0, 1)) > 0.9 * extent).all()
assert (area_offset.abs() <= extent).all()
diff --git a/tests/augmentation/test_conventions_intensity_ops.py b/tests/augmentation/test_conventions_intensity_ops.py
index abd0078b3..69c89bf42 100644
--- a/tests/augmentation/test_conventions_intensity_ops.py
+++ b/tests/augmentation/test_conventions_intensity_ops.py
@@ -116,7 +116,8 @@ class TestBlurConventions(BaseTester):
ones = torch.ones(1, 1, 4, 4, device=device, dtype=dtype)
torch.manual_seed(_FORWARD_SEED)
out = K.RandomMedianBlur((3, 3), p=1.0)(ones)
- assert float(out[0, 0, 0, 0]) == 1.0 and float(out[0, 0, 0, 1]) == 1.0
+ assert float(out[0, 0, 0, 0]) == 1.0
+ assert float(out[0, 0, 0, 1]) == 1.0
assert float(out[0, 0, 1, 1]) == 1.0
# 5x5 on a 6x6 image: reflect padding preserves the constant value across the border,
# so the top row consists entirely of ones.
@@ -142,7 +143,8 @@ class TestBlurConventions(BaseTester):
torch.manual_seed(_FORWARD_SEED)
out = K.RandomBoxBlur(kernel_size, p=1.0)(impulse)
lit = out[0, 0].nonzero()
- assert lit[:, 0].unique().tolist() == rows and lit[:, 1].unique().tolist() == cols
+ assert lit[:, 0].unique().tolist() == rows
+ assert lit[:, 1].unique().tolist() == cols
self.assert_close(out.sum(), impulse.sum())
# A rank filter cannot be read off an impulse, so the detector is a one-row bar. A (1, kW) window slides
@@ -222,11 +224,13 @@ class TestBlurConventions(BaseTester):
sigma = aug._params["sigma"]
assert sigma.shape == (4,)
assert len(set(sigma.flatten().tolist())) == 4
- assert float(sigma.min()) >= 0.5 and float(sigma.max()) <= 1.5
+ assert float(sigma.min()) >= 0.5
+ assert float(sigma.max()) <= 1.5
# Reach, not only containment: a draw shrunk to `[0.5, 0.6]` satisfies the bounds above.
torch.manual_seed(_FORWARD_SEED)
many = aug.forward_parameters((256, 3, 7, 9))["sigma"]
- assert float(many.min()) < 0.6 and float(many.max()) > 1.4
+ assert float(many.min()) < 0.6
+ assert float(many.max()) > 1.4
assert aug.flags["separable"] is True
assert aug.flags["border_type"] == BorderType.REFLECT
assert aug.flags["kernel_size"] == (3, 3)
@@ -381,10 +385,12 @@ class TestBlurConventions(BaseTester):
for resample in ("nearest", "bilinear"):
torch.manual_seed(_FORWARD_SEED)
out = K.RandomMotionBlur(5, (80.0, 80.0), (1.0, 1.0), border_type="reflect", resample=resample, p=1.0)(edge)
- assert float(out.min()) >= -1e-3 and float(out.max()) <= 1.0 + 1e-3, resample
+ assert float(out.min()) >= -1e-3, resample
+ assert float(out.max()) <= 1.0 + 1e-3, resample
torch.manual_seed(_FORWARD_SEED)
out = K.RandomMotionBlur(5, (80.0, 80.0), (1.0, 1.0), border_type="reflect", resample="bicubic", p=1.0)(edge)
- assert float(out.min()) < -0.02 and float(out.max()) > 1.02
+ assert float(out.min()) < -0.02
+ assert float(out.max()) > 1.02
# The four filters do not clamp: a 1.1 impulse is attenuated below one, and the output is linear in the
# input (for the median blur, a negative plateau stays negative), so no wrapper clamp is hiding in there.
@@ -592,7 +598,8 @@ class TestBlurConventions(BaseTester):
torch.manual_seed(_FORWARD_SEED)
positive_out = factories[name]()(positive)
low, high = positive_out.aminmax()
- assert float(low) < 1.0 and float(high) <= 1.0 + 1e-3, "a positive image is pulled below its minimum"
+ assert float(low) < 1.0, "a positive image is pulled below its minimum"
+ assert float(high) <= 1.0 + 1e-3, "a positive image is pulled below its minimum"
negative = torch.full((1, 1, 7, 7), -1.0, device=device, dtype=dtype)
torch.manual_seed(_FORWARD_SEED)
negative_out = factories[name]()(negative)
@@ -806,15 +813,19 @@ class TestNoiseAndWeatherConventions(BaseTester):
tall_rows, tall_cols = extents(torch.zeros(1, 1, 12, 30, device=device, dtype=dtype))
if drop_height > drop_width:
- assert tall_rows >= 5 and tall_cols <= 2
+ assert tall_rows >= 5
+ assert tall_cols <= 2
else:
- assert tall_cols >= 5 and tall_rows <= 2
+ assert tall_cols >= 5
+ assert tall_rows <= 2
# On a 30x12 image the arguments still mean rows and columns.
wide_rows, wide_cols = extents(torch.zeros(1, 1, 30, 12, device=device, dtype=dtype))
if drop_height > drop_width:
- assert wide_rows >= 5 and wide_cols <= 2
+ assert wide_rows >= 5
+ assert wide_cols <= 2
else:
- assert wide_cols >= 5 and wide_rows <= 2
+ assert wide_cols >= 5
+ assert wide_rows <= 2
# A drop is the literal 200/255, not a function of the image.
def test_convention_random_rain_drop_value_is_two_hundred_over_255(self, device, dtype):
@@ -968,7 +979,8 @@ class TestNoiseAndWeatherConventions(BaseTester):
lit = (aug(image)[0, 0] != 0).nonzero()
rows |= set(lit[:, 0].tolist())
cols |= set(lit[:, 1].tolist())
- assert sorted(rows) == list(range(6)) and sorted(cols) == list(range(10))
+ assert sorted(rows) == list(range(6))
+ assert sorted(cols) == list(range(10))
# A single drop paints a bounding box of exactly ``(h, max(|w|, 1))`` inside the image for every legal start
# (#4604); a drop wrapped across opposite edges by a negative index would still satisfy the union pin.
@@ -991,8 +1003,10 @@ class TestNoiseAndWeatherConventions(BaseTester):
rows, cols = lit[:, 0].tolist(), lit[:, 1].tolist()
case = (height, width, drop_height, drop_width, seed)
assert (max(rows) - min(rows) + 1, max(cols) - min(cols) + 1) == expected, case
- assert min(rows) >= 0 and max(rows) < height, case
- assert min(cols) >= 0 and max(cols) < width, case
+ assert min(rows) >= 0, case
+ assert max(rows) < height, case
+ assert min(cols) >= 0, case
+ assert max(cols) < width, case
# Every legal start row is equally likely, not merely reachable (#4604); single-pixel drops on a wide
# image, so each painted cell is one start.
@@ -1068,10 +1082,12 @@ class TestNoiseAndWeatherConventions(BaseTester):
drawn = aug._params[key].flatten()
assert drawn.shape == (4,)
assert len(set(drawn.tolist())) == 4
- assert float(drawn.min()) >= low and float(drawn.max()) <= high
+ assert float(drawn.min()) >= low
+ assert float(drawn.max()) <= high
# Reach, not only containment.
width = high - low
- assert float(many[key].min()) < low + 0.1 * width and float(many[key].max()) > high - 0.1 * width
+ assert float(many[key].min()) < low + 0.1 * width
+ assert float(many[key].max()) > high - 0.1 * width
torch.manual_seed(_FORWARD_SEED)
shared = K.RandomSnow(snow_coefficient=(0.2, 0.8), brightness=(1.5, 3.0), p=1.0, same_on_batch=True)
shared(image)
@@ -1197,7 +1213,8 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
assert float(gradient.float().min()) >= 0.0
else:
assert float(gradient.float().max()) <= 0.0
- assert float(clamped.min()) >= low - 1e-3 and float(clamped.max()) <= high + 1e-3
+ assert float(clamped.min()) >= low - 1e-3
+ assert float(clamped.max()) <= high + 1e-3
raw = constant + gradient.to(device=device, dtype=dtype)
self.assert_close(clamped, raw.clamp(0.0, 1.0))
assert not torch.equal(clamped, raw), "the clamp did not engage, so this leg proves nothing"
@@ -1210,7 +1227,8 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
per_sample = _illumination(name)
per_sample(batch)
directions = [float(per_sample._params["gradient"][b].float().max()) for b in range(batch_size)]
- assert any(value > 0.0 for value in directions) and any(value <= 0.0 for value in directions)
+ assert any(value > 0.0 for value in directions)
+ assert any(value <= 0.0 for value in directions)
torch.manual_seed(_FORWARD_SEED)
shared = _illumination(name, same_on_batch=True)
shared(batch)
diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.py
index 51082b491..38b64c4c4 100644
--- a/tests/augmentation/test_conventions_intensity_values.py
+++ b/tests/augmentation/test_conventions_intensity_values.py
@@ -925,7 +925,8 @@ class TestIntensityColourConventions(BaseTester):
torch.manual_seed(_FORWARD_SEED)
aug = K.RandomRGBShift(r_shift_limit=0.5, g_shift_limit=0.0, b_shift_limit=0.0, p=1.0)
shifts = aug.forward_parameters((512, 3, 2, 2))["r_shift"]
- assert float(shifts.min()) < -0.4 and float(shifts.max()) > 0.4
+ assert float(shifts.min()) < -0.4
+ assert float(shifts.max()) > 0.4
assert float(shifts.abs().max()) <= 0.5
image = torch.tensor([1.5, -0.25], device=device, dtype=dtype).reshape(1, 1, 1, 2).expand(1, 3, 1, 2)
torch.manual_seed(_FORWARD_SEED)
@@ -953,7 +954,8 @@ class TestIntensityColourConventions(BaseTester):
aug(torch.rand(64, 3, 2, 2))
for name, (low, high) in {"r_shift": (0.1, 0.2), "g_shift": (-0.3, -0.1), "b_shift": (-0.05, 0.05)}.items():
drawn = aug._params[name]
- assert bool((drawn >= low).all()) and bool((drawn <= high).all()), name
+ assert bool((drawn >= low).all()), name
+ assert bool((drawn <= high).all()), name
# A 1-D tensor is a pair too, and a pair's domain is as unbounded as a number's.
K.RandomRGBShift(torch.tensor([0.1, 0.2]), (-2.0, 2.0), 2.0)
with pytest.raises(ValueError, match=r"r_shift\[0\] should be smaller than r_shift\[1\]"):
@@ -985,7 +987,8 @@ class TestIntensityColourConventions(BaseTester):
red_gain, blue_gain = (float(value) for value in aug.pl[0])
scaled = torch.stack([image[:, 0] * red_gain, image[:, 1], image[:, 2] * blue_gain], dim=1)
self.assert_close(out, scaled.clamp(max=1.0))
- assert float(out[0, 1, 0, 0]) == 1.0 and float(out[0, 2, 0, 0]) < 0.01
+ assert float(out[0, 1, 0, 0]) == 1.0
+ assert float(out[0, 2, 0, 0]) < 0.01
assert bool((out[..., 1] < 0).all())
# Issue #4574: the coefficient table follows the input dtype, so a half-precision input is not promoted.
@@ -1086,7 +1089,8 @@ class TestIntensityColourConventions(BaseTester):
aug = K.RandomJPEG(jpeg_quality=(50.0, 50.0), p=1.0)
out = aug(image)
assert bool(torch.isfinite(out).all())
- assert float(out.min()) >= 0.0 and float(out.max()) <= 1.0
+ assert float(out.min()) >= 0.0
+ assert float(out.max()) <= 1.0
assert bool(((out > 0.0) & (out < 1.0)).any())
# Quantization can also give a constant black input small positive values, so the range
# assertion alone would not catch a misplaced input clamp.
@@ -1283,7 +1287,8 @@ class TestIntensityColourConventions(BaseTester):
assert K.RandomBrightness(0.5, p=1.0).brightness.tolist() == [0.5, 1.5]
torch.manual_seed(_FORWARD_SEED)
sharpness = K.RandomSharpness(0.5, p=1.0).forward_parameters((2000, 1, 4, 4))["sharpness"]
- assert float(sharpness.min()) >= 0.0 and float(sharpness.max()) <= 0.5
+ assert float(sharpness.min()) >= 0.0
+ assert float(sharpness.max()) <= 0.5
assert float(sharpness.min()) < 0.1 # the lower end is the floored -x, not a centred x / 2
jpeg = K.RandomJPEG(50.0, p=1.0)._param_generator
assert (float(jpeg.jpeg_quality_sampler.low), float(jpeg.jpeg_quality_sampler.high)) == (1.0, 100.0)
@@ -1457,12 +1462,14 @@ class TestIntensityColourConventions(BaseTester):
image = (torch.rand(2, 3, 16, 16) * 0.8 + 0.1).requires_grad_()
torch.manual_seed(_FORWARD_SEED)
fast = K.RandomClahe(p=1.0)(image)
- assert not fast.requires_grad and fast.grad_fn is None
+ assert not fast.requires_grad
+ assert fast.grad_fn is None
torch.manual_seed(_FORWARD_SEED)
slow = K.RandomClahe(p=1.0, slow_and_differentiable=True)(image)
assert slow.requires_grad
slow.sum().backward()
- assert image.grad is not None and float(image.grad.abs().sum()) > 0.0
+ assert image.grad is not None
+ assert float(image.grad.abs().sum()) > 0.0
# The uint8 round trip is a step function, so the gradient below bits=8 is structurally zero even
# though requires_grad stays True; bits=8 skips the round trip and is the identity.
diff --git a/tests/augmentation/test_conventions_mix.py b/tests/augmentation/test_conventions_mix.py
index ddd61fe83..666f75679 100644
--- a/tests/augmentation/test_conventions_mix.py
+++ b/tests/augmentation/test_conventions_mix.py
@@ -96,7 +96,8 @@ class TestMixConventions(BaseTester):
self.assert_close(output, expected)
assert mixed_labels.shape == (4, 3)
label_dtype = _label_dtype(dtype)
- assert output.dtype == dtype and mixed_labels.dtype == label_dtype
+ assert output.dtype == dtype
+ assert mixed_labels.dtype == label_dtype
self.assert_close(mixed_labels[:, 0], labels.to(label_dtype))
self.assert_close(mixed_labels[:, 1], labels.index_select(0, pairs).to(label_dtype))
self.assert_close(mixed_labels[:, 2], torch.full((4,), 0.25, device=device, dtype=label_dtype))
@@ -131,7 +132,8 @@ class TestMixConventions(BaseTester):
assert mixed_labels.shape == (num_mix, 3, 3)
label_dtype = _label_dtype(dtype)
- assert output.dtype == dtype and mixed_labels.dtype == label_dtype
+ assert output.dtype == dtype
+ assert mixed_labels.dtype == label_dtype
self.assert_close(mixed_labels[:, :, 0], labels.to(label_dtype).expand(num_mix, -1))
for mix, pairs in enumerate(aug._params["mix_pairs"].to(device)):
self.assert_close(mixed_labels[mix, :, 1], labels.index_select(0, pairs).to(label_dtype))
@@ -455,7 +457,8 @@ class TestMixConventions(BaseTester):
self.assert_close(crop_src, crop_src[0, 0].expand_as(crop_src), rtol=0, atol=0)
independent = K.RandomCutMixV2(p=1.0, num_mix=2, same_on_batch=False, use_correct_lambda=True)
heights, widths = infer_bbox_shape(independent.forward_parameters(shape)["crop_src"].flatten(0, 1))
- assert heights.unique().numel() > 1 and widths.unique().numel() > 1
+ assert heights.unique().numel() > 1
+ assert widths.unique().numel() > 1
@pytest.mark.device_agnostic
def test_wart_cutmix_same_on_batch_repeats_one_cut_per_mix_4805(self):
@@ -467,7 +470,8 @@ class TestMixConventions(BaseTester):
num_mix=2, same_on_batch=True, p=1.0, use_correct_lambda=True, data_keys=["input", "class"]
)
output, mixed = aug(image, torch.tensor([0, 1, 2, 3]))
- assert mixed.shape[0] == 2 and torch.equal(mixed[0], mixed[1])
+ assert mixed.shape[0] == 2
+ assert torch.equal(mixed[0], mixed[1])
replaced = (output[:, 0] != image[:, 0]).float().mean((-2, -1))
self.assert_close(replaced, 1 - mixed[0, :, 2]) # one cut's area, while two mixes credit the donor
@@ -483,13 +487,16 @@ class TestMixConventions(BaseTester):
aug = K.RandomCutMixV2(p=1.0, cut_size=(0.5, 0.5), num_mix=2, same_on_batch=False, use_correct_lambda=True)
crop_src = aug.forward_parameters(shape)["crop_src"] # (num_mix, B, 4, 2)
heights, widths = infer_bbox_shape(crop_src.flatten(0, 1))
- assert heights.unique().numel() == 1 and widths.unique().numel() == 1 # the sizes are pinned...
+ # the sizes are pinned...
+ assert heights.unique().numel() == 1
+ assert widths.unique().numel() == 1
top_left = crop_src[:, :, 0, :]
assert top_left[0].unique(dim=0).shape[0] > 1 # ...and rows of one mix land in different places,
assert top_left[1].unique(dim=0).shape[0] > 1
assert bool((top_left[0] != top_left[1]).any()) # as do the two mixes of one row.
# Each axis is drawn on its own: sharing only the x or only the y draw would still vary the pairs.
- assert top_left[..., 0].unique().numel() > 1 and top_left[..., 1].unique().numel() > 1
+ assert top_left[..., 0].unique().numel() > 1
+ assert top_left[..., 1].unique().numel() > 1
# Every cut fits inside the image (the far corner is inclusive).
assert bool((crop_src >= 0).all())
assert bool((crop_src[..., 0] <= shape[-1] - 1).all())
@@ -604,7 +611,8 @@ class TestMixConventions(BaseTester):
if x2 <= x1 or y2 <= y1:
continue
values = output[b, 0, y1:y2, x1:x2].unique()
- assert values.numel() == 1 and values.item() != 0, (output_size, seed, b)
+ assert values.numel() == 1, (output_size, seed, b)
+ assert values.item() != 0, (output_size, seed, b)
def test_convention_mosaic_unselected_list_row_keeps_its_own_box_count(self, device, dtype):
# A list input carries its own padding: a one-box sample in a list whose longest sample has two boxes. An
@@ -638,7 +646,8 @@ class TestMixConventions(BaseTester):
_, piped = pipeline(image, boxes, params=params)
_, direct = K.RandomMosaic(data_keys=["input", data_key])(image, boxes, params=params[0].data)
for out_boxes in (direct, piped):
- assert isinstance(out_boxes, list) and len(out_boxes) == 2
+ assert isinstance(out_boxes, list)
+ assert len(out_boxes) == 2
for sample, selected in enumerate(gate):
if not selected:
self.assert_close(out_boxes[sample], boxes[sample])
@@ -731,7 +740,8 @@ class TestMixConventions(BaseTester):
params = dict(aug._params)
params[key] = swapped
output, mixed = aug(image, labels, params=params, data_keys=["input", "class"])
- assert output.dtype == image_dtype and mixed.dtype == torch.float32
+ assert output.dtype == image_dtype
+ assert mixed.dtype == torch.float32
assert mixed[..., 0].flatten().tolist() == [257.0, 999.0]
assert mixed[..., 1].flatten().tolist() == ([999.0, 257.0] if p == 1.0 else [257.0, 999.0])
@@ -750,7 +760,8 @@ class TestMixConventions(BaseTester):
params = aug.forward_parameters(image.shape)
output, mixed = aug(image, labels, params=params, data_keys=["input", "class"])
assert "dtype" not in params # the caller's dictionary is left as it was
- assert torch.equal(output, sampled) and torch.equal(mixed, sampled_labels)
+ assert torch.equal(output, sampled)
+ assert torch.equal(mixed, sampled_labels)
assert mixed.dtype == _label_dtype(image_dtype)
def test_convention_mix_replay_takes_dtype_from_the_input_not_the_dictionary(self):
@@ -834,7 +845,8 @@ class TestMixConventions(BaseTester):
ratios = torch.stack([top_left[:, 0] / 10, top_left[:, 1] / 6], dim=-1)
assert bool(((ratios >= 0.3 - 1e-5) & (ratios <= 0.7 + 1e-5)).all())
# Both entries are bounds on one draw, so both axes vary across the batch.
- assert ratios[:, 0].unique().numel() > 1 and ratios[:, 1].unique().numel() > 1
+ assert ratios[:, 0].unique().numel() > 1
+ assert ratios[:, 1].unique().numel() > 1
# "Draws a pair": the two ratios are separate draws, not one value used twice.
assert not torch.allclose(ratios[:, 0], ratios[:, 1])
@@ -848,4 +860,5 @@ class TestMixConventions(BaseTester):
xs.update(coords[:, 0].tolist())
ys.update(coords[:, 1].tolist())
# Reach as well as containment: every inside corner is drawn, and nothing else.
- assert xs == set(range(10 - 4 + 1)) and ys == set(range(8 - 4 + 1))
+ assert xs == set(range(10 - 4 + 1))
+ assert ys == set(range(8 - 4 + 1))
diff --git a/tests/augmentation/test_conventions_transplantation.py b/tests/augmentation/test_conventions_transplantation.py
index 2ef4df6f9..f4ba49e85 100644
--- a/tests/augmentation/test_conventions_transplantation.py
+++ b/tests/augmentation/test_conventions_transplantation.py
@@ -53,7 +53,8 @@ class TestTransplantationConventions(BaseTester):
image = torch.rand(3, 2, *spatial)
mask = torch.randint(0, 3, (3, *spatial))
out_image, out_mask = K.RandomTransplantation(p=1.0)(image, mask)
- assert out_image.shape == image.shape and out_mask.shape == mask.shape
+ assert out_image.shape == image.shape
+ assert out_mask.shape == mask.shape
@pytest.mark.device_agnostic
def test_convention_the_first_mask_drives_the_transplant(self):
@@ -71,8 +72,11 @@ class TestTransplantationConventions(BaseTester):
image, mask = image.to(device=device, dtype=dtype), mask.to(device)
aug = K.RandomTransplantation(p=1.0, excluded_labels=[0]) # the exclusion list starts on the CPU
out_image, out_mask = aug(image, mask)
- assert out_image.dtype is dtype and out_image.device == image.device and out_mask.device == mask.device
- assert torch.equal(out_image, image.roll(1, dims=0)) and torch.equal(out_mask, mask.roll(1, dims=0))
+ assert out_image.dtype is dtype
+ assert out_image.device == image.device
+ assert out_mask.device == mask.device
+ assert torch.equal(out_image, image.roll(1, dims=0))
+ assert torch.equal(out_mask, mask.roll(1, dims=0))
assert aug._params["selection"].device == mask.device
assert aug._params["selected_labels"].device == mask.device
@@ -229,7 +233,8 @@ class TestTransplantationConventions(BaseTester):
mask = torch.zeros(2, 0, 4, dtype=torch.long)
image = torch.rand(2, 3, 0, 4)
out_image, out_mask = K.RandomTransplantation(p=1.0, excluded_labels=excluded)(image, mask)
- assert out_image.shape == image.shape and out_mask.shape == mask.shape
+ assert out_image.shape == image.shape
+ assert out_mask.shape == mask.shape
@pytest.mark.device_agnostic
def test_convention_params_keys_and_selection_semantics(self):
@@ -287,7 +292,8 @@ class TestTransplantationConventions(BaseTester):
torch.manual_seed(999)
redrawn_image, _ = aug(image, mask, params=redrawn)
self.assert_close(redrawn_image, fresh_image, rtol=0, atol=0)
- assert "selected_labels" in redrawn and aug._params is redrawn
+ assert "selected_labels" in redrawn
+ assert aug._params is redrawn
@pytest.mark.device_agnostic
@pytest.mark.parametrize("excluded_donor", [False, True])
@@ -309,7 +315,8 @@ class TestTransplantationConventions(BaseTester):
before = torch.get_rng_state()
replayed_image, _ = aug(image, mask, params=partial)
assert torch.equal(torch.get_rng_state(), before)
- assert "selected_labels" not in partial and also_dropped in partial
+ assert "selected_labels" not in partial
+ assert also_dropped in partial
assert partial["acceptor_indices"].tolist() == ([0, 1, 3] if excluded_donor else [0, 1, 2, 3])
self.assert_close(replayed_image, expected_image, rtol=0, atol=0)
@@ -328,7 +335,8 @@ class TestTransplantationConventions(BaseTester):
assert torch.equal(params["selection"][0], mask[2] == 0) # the EXCLUDED label 0 of donor 2 was moved
assert torch.equal(params["selection"][1], mask[0] == 1)
assert torch.equal(out_mask[2], mask[2]) # no third label: acceptor 2 is untouched
- assert int((out_mask[1] == 1).sum()) == 6 and int((out_mask[0] == 3).sum()) == 0
+ assert int((out_mask[1] == 1).sum()) == 6
+ assert int((out_mask[0] == 3).sum()) == 0
@pytest.mark.device_agnostic
@pytest.mark.parametrize("p", [0.0, 1.0])
@@ -342,7 +350,8 @@ class TestTransplantationConventions(BaseTester):
for dtype in (torch.bool, torch.uint8, *signed, *floating):
aug = K.RandomTransplantation(p=p, excluded_labels=[0])
_, out_mask = aug(torch.rand(2, 1, 4, 5), mask.to(dtype))
- assert out_mask.dtype is dtype and aug._params["selected_labels"].dtype is dtype
+ assert out_mask.dtype is dtype
+ assert aug._params["selected_labels"].dtype is dtype
image, mask = _labelled_batch(batch=3)
for image_dtype in floating:
out_image, _ = K.RandomTransplantation(p=p)(image.to(image_dtype), mask)
@@ -394,7 +403,8 @@ class TestTransplantationConventions(BaseTester):
self.assert_close(image_only, expected_image, rtol=0, atol=0)
# Outputs follow the input order, whatever it is.
swapped = K.RandomTransplantation(p=1.0)(mask, image, params=recorded, data_keys=["mask", "input"])
- assert torch.equal(swapped[0], expected_mask) and torch.equal(swapped[1], expected_image)
+ assert torch.equal(swapped[0], expected_mask)
+ assert torch.equal(swapped[1], expected_image)
@pytest.mark.device_agnostic
def test_convention_selected_labels_length_is_validated(self):
@@ -416,7 +426,9 @@ class TestTransplantationConventions(BaseTester):
torch.manual_seed(999)
fresh_image, _ = K.RandomTransplantation(p=1.0, excluded_labels=[0])(image, mask)
assert not torch.equal(fresh_image, expected_image) # a redraw under the replay's seed would show
- assert not aug.state_dict() and not list(aug.parameters()) and not list(aug.buffers())
+ assert not aug.state_dict()
+ assert not list(aug.parameters())
+ assert not list(aug.buffers())
for restored in (pickle.loads(pickle.dumps(aug)), copy.deepcopy(aug)): # noqa: S301
assert torch.equal(restored.excluded_labels, aug.excluded_labels)
torch.manual_seed(999)
diff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.py
index 11afea1ed..da5a354f6 100644
--- a/tests/augmentation/test_random_generator.py
+++ b/tests/augmentation/test_random_generator.py
@@ -1790,7 +1790,8 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
counts = torch.bincount(start.long().cpu(), minlength=n_legal)
assert counts.numel() == n_legal, counts # no start past side - cut
expected = len(start) / n_legal
- assert counts.min() > 0.8 * expected and counts.max() < 1.2 * expected, counts
+ assert counts.min() > 0.8 * expected, counts
+ assert counts.max() < 1.2 * expected, counts
def test_start_stays_inside_when_the_draw_rounds_to_one_4730(self, device, dtype, monkeypatch):
# A float16/bfloat16 parameter dtype rounds a float32 draw above 1 - 2**-12 (float16) or 1 - 2**-9
diff --git a/tests/augmentation/test_resize_matrix.py b/tests/augmentation/test_resize_matrix.py
index 8a66be12a..5be142c0a 100644
--- a/tests/augmentation/test_resize_matrix.py
+++ b/tests/augmentation/test_resize_matrix.py
@@ -64,7 +64,8 @@ class TestResizeMatrix(BaseTester):
out = aug(image, params=params)
assert aug._transform_matrix is None # construction remains lazy
matrix = aug.transform_matrix
- assert matrix.dtype == dtype and matrix.device == image.device
+ assert matrix.dtype == dtype
+ assert matrix.device == image.device
assert matrix.shape == (2, 3, 3)
assert aug.transform_matrix is matrix
src = params["src"].to(image)