xrspatial.cost_distance.cost_distance#
- xrspatial.cost_distance.cost_distance(raster: DataArray, friction: DataArray, x: str = 'x', y: str = 'y', target_values: list = None, max_cost: float = inf, connectivity: int = 8) DataArray[source]#
Compute accumulated cost-distance through a friction surface.
For every pixel, computes the minimum accumulated traversal cost to reach the nearest target pixel, where traversal cost along each edge equals
geometric_distance * mean_friction_of_endpoints.Cost-distance supports NumPy, CuPy, Dask with NumPy, and Dask with CuPy backed xarray DataArray. The return values of cost_distance are of the same type as the input type: a NumPy-backed input gives a NumPy-backed result, a CuPy-backed input gives a CuPy-backed result, and a Dask-backed input gives a Dask-backed result.
- Parameters:
raster (xr.DataArray or xr.Dataset) – 2-D source raster. Target pixels are identified by non-zero finite values (or values in target_values).
friction (xr.DataArray) – 2-D friction (cost) surface. Must have the same shape and coordinates as raster. Values must be positive and finite for passable cells; NaN or
<= 0marks impassable barriers.x (str, default='x') – Name of the x coordinate.
y (str, default='y') – Name of the y coordinate.
target_values (list, optional) – Specific pixel values in raster to treat as sources. If not provided, all non-zero finite pixels are sources.
max_cost (float, default=np.inf) – Maximum accumulated cost. Pixels whose least-cost path exceeds this budget are set to NaN. A finite value enables efficient Dask parallelisation via
map_overlap.connectivity (int, default=8) – Pixel connectivity: 4 (cardinal only) or 8 (cardinal + diagonal).
- Returns:
2-D array of accumulated cost-distance values (float32). Source pixels have cost 0. Unreachable pixels are NaN.
- Return type:
xr.DataArray or xr.Dataset
Examples
>>> import numpy as np >>> import xarray as xr >>> source = np.array([ ... [0., 0., 0.], ... [0., 1., 0.], ... [0., 0., 0.], ... ]) >>> friction = np.ones((3, 3)) >>> n, m = source.shape >>> raster = xr.DataArray(source, dims=['y', 'x'], name='raster') >>> raster['y'] = np.arange(n)[::-1] >>> raster['x'] = np.arange(m) >>> friction_da = xr.DataArray( ... friction, dims=['y', 'x'], name='friction') >>> friction_da['y'] = np.arange(n)[::-1] >>> friction_da['x'] = np.arange(m) >>> from xrspatial import cost_distance >>> result = cost_distance(raster, friction_da) >>> result <xarray.DataArray (y: 3, x: 3)> array([[1.4142135, 1. , 1.4142135], [1. , 0. , 1. ], [1.4142135, 1. , 1.4142135]], dtype=float32) Coordinates: * y (y) int64 2 1 0 * x (x) int64 0 1 2