Skip to content

replace gdal_proximity with a  #15

Description

@hcwinsemius

I read into what gdal_proximity does. It calculates the nearest distance to masked areas. This requires iterating over each cell. In numpy this will be slow, but we implemented similar functionalities in the package pyflwdir that iterates many times, which is quite fast. A function signature like below is worth trying (not tested).

import numpy as np
import numba as nb

# create a njit (no-python just-in-time compiling) function below. This code will be converted to machine code
# and compiled on-the-fly making it much much faster. cache=True ensures the compilation is stored for the next
# time the function is used.

@nb.njit(cache=True)
def mv_proximity(mask):
    """Calculates nearest distance of missing values to non-missing values.

    Parameters
    ----------
    mask : np.ndarray [bool]
        2D array with True at locations with data, and False at locations without data
    Returns
    -------
    np.ndarray
        2D array containing distances to nearest non-missing value
    """
    distance = np.ones_like(data, dtype=np.float32) * np.inf  # start with infinite distances per grid cell

    rows, cols = distance.shape
    # it may be faster to first compute indexes of masked cells
    for row in range(rows):
        for col in range(cols):
            if mask[row, col]:
                # same here, it may be faster to first index logical values before running through them. Not yet carefully thought through...
                for k in range(rows):
                    for l in range(cols):
                        dist = np.sqrt((row - k) ** 2 + (col - l) ** 2)
                        if dist < distance[k, l]:
                            distance[k, l] = dist

    return distance

This should be tested for speed and compared against results of gdal_proximity.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions