Skip to content

Distance computation

distance_computation(geodataframe, raster_profile, max_distance=None)

Calculate distance from raster cell to nearest geometry.

Parameters:

Name Type Description Default
geodataframe GeoDataFrame

The GeoDataFrame with geometries to determine distance to.

required
raster_profile Union[Profile, dict]

The raster profile of the raster in which the distances to the nearest geometry are determined.

required
max_distance Optional[Number]

The maximum distance in the output array.

None

Returns:

Type Description
ndarray

A 2D numpy array with the distances computed.

Raises:

Type Description
NonMatchingCrsException

The input raster profile and geodataframe have mismatching CRS.

EmptyDataFrameException

The input geodataframe is empty.

Source code in eis_toolkit/vector_processing/distance_computation.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
@beartype
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.

    Raises:
        NonMatchingCrsException: The input raster profile and geodataframe have mismatching CRS.
        EmptyDataFrameException: The input geodataframe is empty.
    """
    if raster_profile.get("crs") != geodataframe.crs:
        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)

    raster_width = raster_profile.get("width")
    raster_height = raster_profile.get("height")
    raster_transform = raster_profile.get("transform")

    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