diff --git a/scripts/tile/tests/tile_index_test.py b/scripts/tile/tests/tile_index_test.py index b597369a2..49bacefab 100644 --- a/scripts/tile/tests/tile_index_test.py +++ b/scripts/tile/tests/tile_index_test.py @@ -1,5 +1,5 @@ from scripts.tile.tests.tile_index_data import MAP_SHEET_DATA -from scripts.tile.tile_index import Point, get_tile_name +from scripts.tile.tile_index import Point, get_tile_name, round_to_correction def test_check_alignment_build_correct_sheet_code() -> None: @@ -15,3 +15,19 @@ def test_check_alignment_generate_correct_name() -> None: origin = Point(1236640, 4837560) tile_name = get_tile_name(origin, 500) assert tile_name + ".tiff" == file_name + + +def test_check_alignment_generate_correct_name_when_origin_drift() -> None: + file_name = "BP27_1000_4817.tiff" + origin = Point(1643679.999967818148434, 5444159.999954843893647) + tile_name = get_tile_name(origin, 1000) + assert tile_name + ".tiff" == file_name + + +def test_round_origin() -> None: + assert round_to_correction(1643679.999967818148434) == 1643680 + assert round_to_correction(1643679.99) == 1643680 + assert round_to_correction(1643680.01) == 1643680 + assert round_to_correction(1643680.05) == 1643680.05 + assert round_to_correction(1643679.969) == 1643679.97 + assert round_to_correction(5444160.051) == 5444160.05 diff --git a/scripts/tile/tile_index.py b/scripts/tile/tile_index.py index 4171c4088..b7b56ecb0 100644 --- a/scripts/tile/tile_index.py +++ b/scripts/tile/tile_index.py @@ -57,6 +57,7 @@ } GRID_SIZES = [10_000, 5_000, 2_000, 1_000, 500] GRID_SIZE_MAX = 50_000 +ROUND_CORRECTION = 0.01 class TileIndexException(Exception): @@ -70,6 +71,24 @@ class Point(NamedTuple): y: Union[int, float] +def round_to_correction(value: Union[int, float]) -> int | float: + if isinstance(value, int): + return value + + correction = rounded_value = round(value, 2) + + if not rounded_value.is_integer(): + if (rounded_value + ROUND_CORRECTION).is_integer(): + correction = rounded_value + ROUND_CORRECTION + elif (rounded_value - ROUND_CORRECTION).is_integer(): + correction = rounded_value - ROUND_CORRECTION + + if correction.is_integer(): + correction = int(correction) + + return correction + + def get_tile_name(origin: Point, grid_size: int) -> str: """Get the tile name from an origin point and the grid size (or scale). @@ -87,8 +106,8 @@ def get_tile_name(origin: Point, grid_size: int) -> str: if not grid_size in GRID_SIZES: raise TileIndexException(f"The scale has to be one of the following values: {GRID_SIZES}") - origin_x = origin[0] - origin_y = origin[1] + origin_x = round_to_correction(origin[0]) + origin_y = round_to_correction(origin[1]) scale = GRID_SIZE_MAX // grid_size tile_width = SHEET_WIDTH // scale tile_height = SHEET_HEIGHT // scale