import importlib.util from pathlib import Path import numpy as np import pytest p = Path(__file__).resolve().parents[1]/"simulation/semantic-learning/native_sliding.py" s = importlib.util.spec_from_file_location("native_sliding", p) m = importlib.util.module_from_spec(s) s.loader.exec_module(m) def test_native_placement_and_irregular_last_tiles(): rgb = np.zeros((5, 7, 3), np.uint8) rgb[:, :, 0] = np.arange(35).reshape(5, 7) out, meta = m.sliding_logits(rgb, lambda a: np.stack([a[:, :, 0], a[:, :, 0]]).astype(float), tile=4, stride=2) np.testing.assert_array_equal(out[0], rgb[:, :, 0]) assert meta["tiles"] == 6 and meta["minimum_overlap"] == 1 def test_logits_uniformly_average_overlaps_before_activation(): rgb = np.zeros((5, 7, 3), np.uint8) rgb[:, :, 0] = np.arange(7) out, _ = m.sliding_logits(rgb, lambda a: np.full((2, 4, 4), a[0, 0, 0], np.float32), tile=4, stride=2) np.testing.assert_allclose(out[0], np.tile([0, 0, 1, 5/3, 2.5, 2.5, 3], (5, 1))) def test_small_image_padding_does_not_change_native_extent(): rgb = np.full((2, 3, 3), 7, np.uint8) def predict(a): assert a.shape == (4, 4, 3) assert not a[2:].any() and not a[:, 3:].any() return np.stack([a[:, :, 0], a[:, :, 0]]).astype(np.float32) out, meta = m.sliding_logits(rgb, predict, tile=4, stride=2) assert out.shape == (2, 2, 3) and (out == 7).all() and meta["tiles"] == 1 @pytest.mark.parametrize("output", [np.full((2, 4, 4), np.nan), np.zeros((2, 3, 4))]) def test_bad_prediction_refused(output): with pytest.raises(ValueError, match="finite native"): m.sliding_logits(np.zeros((4, 4, 3), np.uint8), lambda _: output, tile=4, stride=2) def test_resource_or_stride_rejection_before_predictor(): def fail(_): raise AssertionError("Must reject before inference") a = np.zeros((5, 7, 3), np.uint8) for options in [dict(max_pixels=4), dict(tile=4, stride=2, max_tiles=1), dict(tile=4, stride=5)]: with pytest.raises(ValueError): m.sliding_logits(a, fail, **options) def test_declared_1024_recipe_has_nine_native_tiles(): assert m.starts(1024, 512, 256) == [0, 256, 512] def test_oversized_tile_and_grid_rejected_before_allocation(): def fail(_): raise AssertionError("Must not run predictor") with pytest.raises(ValueError, match="Tile working budget"): m.sliding_logits(np.zeros((2, 3, 3), np.uint8), fail, tile=100000, stride=256) with pytest.raises(ValueError, match="Tile grid budget"): m.starts(1000000, 2, 1, limit=256)