Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 43 additions & 6 deletions xrspatial/surface_distance.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,32 @@ def _finalize_direction(src_row, src_col, dist, cellsize_x, cellsize_y,
return result


@ngjit
def _finalize_geodesic_direction(src_row, src_col, dist, lat, lon, max_distance):
"""Compute initial spherical bearings to the targets selected by Dijkstra."""
height, width = dist.shape
result = np.full((height, width), np.nan, dtype=np.float32)
for row in range(height):
for col in range(width):
if not np.isfinite(dist[row, col]) or dist[row, col] > max_distance:
continue
target_row, target_col = src_row[row, col], src_col[row, col]
if row == target_row and col == target_col:
result[row, col] = 0
continue

start_lat = _math.radians(lat[row, col])
target_lat = _math.radians(lat[target_row, target_col])
delta_lon = _math.radians(lon[target_row, target_col] - lon[row, col])
east = _math.sin(delta_lon) * _math.cos(target_lat)
north = (_math.cos(start_lat) * _math.sin(target_lat)
- _math.sin(start_lat) * _math.cos(target_lat)
* _math.cos(delta_lon))
bearing = _math.degrees(_math.atan2(east, north)) % 360
result[row, col] = 360 if bearing == 0 else bearing
return result


def _extract_output(dist, alloc, src_row, src_col,
cellsize_x, cellsize_y, max_distance, mode):
"""Select and finalize the requested output from raw Dijkstra arrays."""
Expand Down Expand Up @@ -524,7 +550,7 @@ def _precompute_dd_grid(lat_2d, lon_2d, dy, dx):

def _surface_distance_numpy(source_data, elev_data, cellsize_x, cellsize_y,
max_distance, target_values, dy, dx, dd,
dd_grid, use_geodesic, mode):
dd_grid, geodesic_coords, mode):
"""NumPy backend: run Dijkstra and extract requested output."""
H, W = source_data.shape
_check_memory(H, W)
Expand All @@ -533,9 +559,14 @@ def _surface_distance_numpy(source_data, elev_data, cellsize_x, cellsize_y,
_seed_sources(source_data, elev_data, target_values,
dist, alloc, src_row, src_col)

if use_geodesic:
if geodesic_coords is not None:
_dijkstra_geodesic(elev_data, H, W, max_distance,
dy, dx, dd_grid, dist, alloc, src_row, src_col)
if mode == DIRECTION:
lat, lon = geodesic_coords
return _finalize_geodesic_direction(
src_row, src_col, dist, lat, lon, max_distance,
)
else:
_dijkstra(elev_data, H, W, max_distance,
dy, dx, dd, dist, alloc, src_row, src_col)
Expand Down Expand Up @@ -719,7 +750,7 @@ def _chunk(source_block, elev_block):
source_block, elev_block,
cellsize_x, cellsize_y, max_distance,
target_values, dy, dx, dd,
None, False, mode,
None, None, mode,
)

return _chunk
Expand Down Expand Up @@ -1465,9 +1496,11 @@ def _compute(raster, elevation, x, y, target_values, max_distance,
# Geodesic dd_grid precomputation (numpy only for now)
use_geodesic = (method == 'geodesic')
dd_grid = None
geodesic_coords = None
if use_geodesic:
from xrspatial.utils import _extract_latlon_coords
lat_2d, lon_2d = _extract_latlon_coords(raster)
geodesic_coords = _extract_latlon_coords(raster)
lat_2d, lon_2d = geodesic_coords
dd_grid = _precompute_dd_grid(lat_2d, lon_2d, dy_arr, dx_arr)

source_data = raster.data
Expand Down Expand Up @@ -1510,14 +1543,14 @@ def _compute(raster, elevation, x, y, target_values, max_distance,
result_data = _surface_distance_numpy(
source_data, elev_data, signed_cellsize_x, signed_cellsize_y,
max_distance_f, target_values, dy_arr, dx_arr, dd_arr,
dd_grid, use_geodesic, mode,
dd_grid, geodesic_coords, mode,
)
else:
elev_np = np.asarray(elev_data)
result_data = _surface_distance_numpy(
source_data, elev_np, signed_cellsize_x, signed_cellsize_y,
max_distance_f, target_values, dy_arr, dx_arr, dd_arr,
dd_grid, use_geodesic, mode,
dd_grid, geodesic_coords, mode,
)
elif _is_dask:
if use_geodesic:
Expand Down Expand Up @@ -1667,6 +1700,10 @@ def surface_direction(
nearest target pixel by surface distance. 0 = source pixel,
90 = east, 180 = south, 270 = west, 360 = north.

With ``method='geodesic'``, the result is the initial great-circle
bearing from the pixel to its target, based on their latitude and
longitude. It is available for NumPy-backed rasters.

Parameters
----------
raster : xr.DataArray or xr.Dataset
Expand Down
38 changes: 38 additions & 0 deletions xrspatial/tests/test_surface_distance.py
Original file line number Diff line number Diff line change
Expand Up @@ -921,6 +921,44 @@ def test_geodesic_basic():
assert 100000 < sd[pos] < 130000 # roughly 100-130 km


def test_geodesic_direction_initial_bearing_at_high_latitude():
"""Compare the direction to the initial bearing on a sphere."""
source = np.zeros((3, 3))
source[0, 2] = 1
raster = xr.DataArray(
source, dims=['y', 'x'],
coords={'y': [61., 60., 59.], 'x': [-1., 0., 1.]},
)
elevation = xr.zeros_like(raster)

result = surface_direction(raster, elevation, method='geodesic')

# Initial spherical bearing from (0 E, 60 N) to (1 E, 61 N).
assert result.values[1, 1] == pytest.approx(25.78, abs=0.01)
assert result.values[1, 2] == 360 # due north
assert result.values[0, 2] == 0 # the target itself


def test_geodesic_direction_uses_curvilinear_coordinates():
"""Use geographic coordinates even when they disagree with grid indices."""
raster = xr.DataArray(
[[0, 0], [0, 1]], dims=['y', 'x'],
coords={
'y': [0, 1], 'x': [0, 1],
'latitude': (('y', 'x'), [[1., 2.], [0., 0.]]),
'longitude': (('y', 'x'), [[179., -179.], [-179., 179.]]),
},
)
elevation = xr.zeros_like(raster)
result = surface_direction(
raster, elevation, method='geodesic', max_distance=250_000,
)

# The target is to the west across the antimeridian, despite its column.
assert result.values[1, 0] == pytest.approx(270)
assert np.isnan(result.values[0, 1]) # beyond the distance cutoff


# ---------------------------------------------------------------------------
# Metadata propagation (issue #3708)
# ---------------------------------------------------------------------------
Expand Down
Loading