import importlib.util from pathlib import Path import numpy as np import pytest p = Path(__file__).resolve().parents[1] / "simulation/semantic-learning/pixel_permutation.py" s = importlib.util.spec_from_file_location("pixel_permutation", p) m = importlib.util.module_from_spec(s) s.loader.exec_module(m) def pair(): target = np.full((5, 5), 255, np.uint8) target[0, :3] = [0, 1, 1] target[2, 1] = 0 # Encode the target and original coordinate in RGB to test alignment. rgb = np.stack([target, np.arange(25, dtype=np.uint8).reshape(5, 5), np.zeros((5, 5), np.uint8)], axis=-1) return rgb, target @pytest.mark.parametrize("element", range(8)) def test_inverse_alignment_counts_padding_and_no_input_mutation(element): rgb, target = pair() original = rgb.copy(), target.copy() image, labels = m.permute_training_pair(rgb, target, element) assert image.flags.c_contiguous and labels.flags.c_contiguous np.testing.assert_array_equal(image[:, :, 0], labels) np.testing.assert_array_equal(np.bincount(labels.ravel(), minlength=256), np.bincount(target.ravel(), minlength=256)) inverse = element if element >= 4 else (-element) % 4 restored = m.permute_training_pair(image, labels, inverse) np.testing.assert_array_equal(restored[0], rgb) np.testing.assert_array_equal(restored[1], target) image[:] = 0 labels[:] = 0 np.testing.assert_array_equal(rgb, original[0]) np.testing.assert_array_equal(target, original[1]) def test_all_eight_distinct_and_rng_unchanged(): rgb, target = pair() before = np.random.get_state() results = [m.permute_training_pair(rgb, target, k)[0].tobytes() for k in range(8)] after = np.random.get_state() assert len(set(results)) == 8 assert before[0] == after[0] and before[2:] == after[2:] np.testing.assert_array_equal(before[1], after[1]) @pytest.mark.parametrize("element", [-1, 8, True, 1.0, None]) def test_invalid_element(element): with pytest.raises(ValueError): m.permute_training_pair(*pair(), element) def test_invalid_shape_dtype_and_label_rejected(): rgb, target = pair() for image, labels in [(rgb[:3], target[:3]), (rgb, target.astype(float)), (rgb[:, :, :2], target), (rgb, np.full_like(target, 2))]: with pytest.raises(ValueError): m.permute_training_pair(image, labels, 0)