From 0a8a2fda923fb32c7c083d24bb839ae4fa86ff92 Mon Sep 17 00:00:00 2001 From: Niko Aarnio Date: Mon, 29 Apr 2024 09:55:54 +0300 Subject: [PATCH] feat(distance_computation): add max distance parameter to distance computation and distance to anomaly --- .../vector_processing/distance_computation.py | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/eis_toolkit/vector_processing/distance_computation.py b/eis_toolkit/vector_processing/distance_computation.py index 1f128905..c18722d4 100644 --- a/eis_toolkit/vector_processing/distance_computation.py +++ b/eis_toolkit/vector_processing/distance_computation.py @@ -1,23 +1,28 @@ +from numbers import Number + import geopandas as gpd import numpy as np from beartype import beartype -from beartype.typing import Union +from beartype.typing import Optional, Union from rasterio import profiles, transform from shapely.geometry.base import BaseGeometry, BaseMultipartGeometry -from eis_toolkit.exceptions import EmptyDataFrameException, NonMatchingCrsException +from eis_toolkit.exceptions import EmptyDataFrameException, NonMatchingCrsException, NumericValueSignException from eis_toolkit.utilities.checks.raster import check_raster_profile from eis_toolkit.utilities.miscellaneous import row_points @beartype -def distance_computation(geodataframe: gpd.GeoDataFrame, raster_profile: Union[profiles.Profile, dict]) -> np.ndarray: +def distance_computation( + geodataframe: gpd.GeoDataFrame, raster_profile: Union[profiles.Profile, dict], max_distance: Optional[Number] = None +) -> np.ndarray: """Calculate distance from raster cell to nearest geometry. Args: geodataframe: The GeoDataFrame with geometries to determine distance to. raster_profile: The raster profile of the raster in which the distances to the nearest geometry are determined. + max_distance: The maximum distance in the output array. Returns: A 2D numpy array with the distances computed. @@ -30,6 +35,8 @@ def distance_computation(geodataframe: gpd.GeoDataFrame, raster_profile: Union[p raise NonMatchingCrsException("Expected coordinate systems to match between raster and GeoDataFrame.") if geodataframe.shape[0] == 0: raise EmptyDataFrameException("Expected GeoDataFrame to not be empty.") + if max_distance is not None and max_distance <= 0: + raise NumericValueSignException("Expected max distance to be a positive number.") check_raster_profile(raster_profile=raster_profile) @@ -37,12 +44,16 @@ def distance_computation(geodataframe: gpd.GeoDataFrame, raster_profile: Union[p raster_height = raster_profile.get("height") raster_transform = raster_profile.get("transform") - return _distance_computation( + distance_matrix = _distance_computation( raster_width=raster_width, raster_height=raster_height, raster_transform=raster_transform, geodataframe=geodataframe, ) + if max_distance is not None: + distance_matrix[distance_matrix > max_distance] = max_distance + + return distance_matrix def _calculate_row_distances(