-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathsurface_distance.py
More file actions
1455 lines (1221 loc) · 49.4 KB
/
surface_distance.py
File metadata and controls
1455 lines (1221 loc) · 49.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Surface distance along 3D terrain via multi-source Dijkstra.
Computes the minimum accumulated distance along the terrain surface
from each pixel to the nearest target pixel, accounting for elevation
relief. A steep hillside has more surface distance than its flat
map projection.
Algorithm
---------
Multi-source Dijkstra with edge costs derived from elevation::
edge_cost = sqrt(horizontal_dist² + (elev_v − elev_u)²)
NaN elevation marks impassable pixels (barriers).
Dask strategy
-------------
For finite ``max_distance``, the maximum pixel radius any path can
reach is ``max_distance / min_cellsize`` (since surface distance >=
horizontal distance). This becomes the ``depth`` parameter to
``dask.array.map_overlap``, giving exact results.
If ``max_distance`` is infinite or the implied radius exceeds chunk
dimensions, an iterative boundary-only Dijkstra is used (same
tile-sweep pattern as ``cost_distance``).
"""
from __future__ import annotations
import math as _math
import warnings
from math import sqrt
import numpy as np
import xarray as xr
try:
import dask.array as da
except ImportError:
da = None
from numba import cuda
try:
import cupy
except ImportError:
class cupy: # type: ignore[no-redef]
ndarray = False
from xrspatial.cost_distance import _heap_push, _heap_pop
from xrspatial.proximity import _vectorized_calc_direction
from xrspatial.utils import (
_validate_raster,
cuda_args, get_dataarray_resolution, ngjit,
has_cuda_and_cupy, is_cupy_array, is_dask_cupy,
)
from xrspatial.dataset_support import supports_dataset
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
DISTANCE = 0
ALLOCATION = 1
DIRECTION = 2
# ---------------------------------------------------------------------------
# Numba kernels
# ---------------------------------------------------------------------------
@ngjit
def _seed_sources(source_data, elev_data, target_values,
dist, alloc, src_row, src_col):
"""Seed source pixels into pre-allocated output arrays.
Source pixels: dist=0, alloc=pixel_value, src_row/col=pixel position.
Only seeds if elevation is finite (passable).
"""
height, width = source_data.shape
n_values = len(target_values)
for r in range(height):
for c in range(width):
val = source_data[r, c]
is_target = False
if n_values == 0:
if val != 0.0 and np.isfinite(val):
is_target = True
else:
for k in range(n_values):
if val == target_values[k]:
is_target = True
break
if is_target:
if np.isfinite(elev_data[r, c]):
dist[r, c] = 0.0
alloc[r, c] = val
src_row[r, c] = r
src_col[r, c] = c
@ngjit
def _dijkstra(elev_data, height, width, max_distance,
dy, dx, dd, dist, alloc, src_row, src_col):
"""Planar multi-source Dijkstra. Modifies arrays in-place.
Pre-seeded pixels (dist < inf) are added to the heap.
Edge cost = sqrt(dd[i]^2 + dz^2).
"""
n_neighbors = len(dy)
max_heap = height * width
h_keys = np.empty(max_heap, dtype=np.float64)
h_rows = np.empty(max_heap, dtype=np.int64)
h_cols = np.empty(max_heap, dtype=np.int64)
h_size = 0
visited = np.zeros((height, width), dtype=np.int8)
# Add all pre-seeded pixels to the heap
for r in range(height):
for c in range(width):
if dist[r, c] < np.inf:
h_size = _heap_push(h_keys, h_rows, h_cols, h_size,
dist[r, c], r, c)
# Dijkstra main loop
while h_size > 0:
cost_u, ur, uc, h_size = _heap_pop(h_keys, h_rows, h_cols, h_size)
if visited[ur, uc]:
continue
visited[ur, uc] = 1
if cost_u > max_distance:
break
elev_u = elev_data[ur, uc]
for i in range(n_neighbors):
vr = ur + dy[i]
vc = uc + dx[i]
if vr < 0 or vr >= height or vc < 0 or vc >= width:
continue
if visited[vr, vc]:
continue
elev_v = elev_data[vr, vc]
if not np.isfinite(elev_v):
continue
dz = elev_v - elev_u
edge_cost = np.sqrt(dd[i] * dd[i] + dz * dz)
new_cost = cost_u + edge_cost
if new_cost < dist[vr, vc]:
dist[vr, vc] = new_cost
alloc[vr, vc] = alloc[ur, uc]
src_row[vr, vc] = src_row[ur, uc]
src_col[vr, vc] = src_col[ur, uc]
h_size = _heap_push(h_keys, h_rows, h_cols, h_size,
new_cost, vr, vc)
@ngjit
def _dijkstra_geodesic(elev_data, height, width, max_distance,
dy, dx, dd_grid, dist, alloc, src_row, src_col):
"""Geodesic variant with per-pixel horizontal distances.
dd_grid[i, r, c] = great-circle horizontal distance to neighbour i
from pixel (r, c).
"""
n_neighbors = len(dy)
max_heap = height * width
h_keys = np.empty(max_heap, dtype=np.float64)
h_rows = np.empty(max_heap, dtype=np.int64)
h_cols = np.empty(max_heap, dtype=np.int64)
h_size = 0
visited = np.zeros((height, width), dtype=np.int8)
for r in range(height):
for c in range(width):
if dist[r, c] < np.inf:
h_size = _heap_push(h_keys, h_rows, h_cols, h_size,
dist[r, c], r, c)
while h_size > 0:
cost_u, ur, uc, h_size = _heap_pop(h_keys, h_rows, h_cols, h_size)
if visited[ur, uc]:
continue
visited[ur, uc] = 1
if cost_u > max_distance:
break
elev_u = elev_data[ur, uc]
for i in range(n_neighbors):
vr = ur + dy[i]
vc = uc + dx[i]
if vr < 0 or vr >= height or vc < 0 or vc >= width:
continue
if visited[vr, vc]:
continue
elev_v = elev_data[vr, vc]
if not np.isfinite(elev_v):
continue
hdist = dd_grid[i, ur, uc]
dz = elev_v - elev_u
edge_cost = np.sqrt(hdist * hdist + dz * dz)
new_cost = cost_u + edge_cost
if new_cost < dist[vr, vc]:
dist[vr, vc] = new_cost
alloc[vr, vc] = alloc[ur, uc]
src_row[vr, vc] = src_row[ur, uc]
src_col[vr, vc] = src_col[ur, uc]
h_size = _heap_push(h_keys, h_rows, h_cols, h_size,
new_cost, vr, vc)
# ---------------------------------------------------------------------------
# Post-processing helpers
# ---------------------------------------------------------------------------
def _init_arrays(H, W):
"""Create and initialize output arrays for the Dijkstra kernel."""
dist = np.full((H, W), np.inf, dtype=np.float64)
alloc = np.full((H, W), np.nan, dtype=np.float64)
src_row = np.full((H, W), -1, dtype=np.int64)
src_col = np.full((H, W), -1, dtype=np.int64)
return dist, alloc, src_row, src_col
def _finalize_dist(dist, max_distance):
"""Convert float64 dist to float32; inf / over-budget -> NaN."""
out = np.where(
np.isinf(dist) | (dist > max_distance), np.nan, dist,
).astype(np.float32)
return out
def _finalize_alloc(alloc, dist, max_distance):
"""Float32 allocation; NaN where unreachable."""
out = np.where(
np.isinf(dist) | (dist > max_distance), np.nan, alloc,
).astype(np.float32)
return out
def _finalize_direction(src_row, src_col, dist, cellsize_x, cellsize_y,
max_distance):
"""Compute compass bearing from each pixel to its allocated source.
Uses pixel index differences scaled by cell size.
"""
H, W = dist.shape
row_idx, col_idx = np.meshgrid(np.arange(H), np.arange(W), indexing='ij')
# Coordinate differences (source - pixel)
dx = (src_col.astype(np.float64) - col_idx) * cellsize_x
dy = (src_row.astype(np.float64) - row_idx) * cellsize_y
result = _vectorized_calc_direction(
np.zeros((H, W), dtype=np.float64), dx,
np.zeros((H, W), dtype=np.float64), dy,
)
# Mask unreachable and no-source pixels
mask = np.isinf(dist) | (dist > max_distance) | (src_row < 0)
result[mask] = np.nan
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."""
if mode == DISTANCE:
return _finalize_dist(dist, max_distance)
elif mode == ALLOCATION:
return _finalize_alloc(alloc, dist, max_distance)
else:
return _finalize_direction(src_row, src_col, dist,
cellsize_x, cellsize_y, max_distance)
# ---------------------------------------------------------------------------
# Geodesic dd_grid precomputation
# ---------------------------------------------------------------------------
EARTH_RADIUS = 6378137.0 # meters
def _precompute_dd_grid(lat_2d, lon_2d, dy, dx):
"""Precompute per-pixel great-circle horizontal distances.
Returns dd_grid[n_neighbors, H, W] in meters.
"""
H, W = lat_2d.shape
n = len(dy)
# Memory guard: dd_grid is (n_neighbors, H, W) float64
estimated = n * H * W * 8
try:
from xrspatial.zonal import _available_memory_bytes
avail = _available_memory_bytes()
except ImportError:
avail = 2 * 1024**3
if estimated > 0.8 * avail:
raise MemoryError(
f"Geodesic dd_grid needs ~{estimated / 1e9:.1f} GB "
f"({n} neighbors x {H}x{W} x 8 bytes) but only "
f"~{avail / 1e9:.1f} GB available. Use planar mode "
f"or downsample the raster."
)
dd_grid = np.zeros((n, H, W), dtype=np.float64)
for i in range(n):
dr, dc = int(dy[i]), int(dx[i])
# Source region
r0 = max(0, -dr)
r1 = H - max(0, dr)
c0 = max(0, -dc)
c1 = W - max(0, dc)
# Neighbour region
nr0 = max(0, dr)
nr1 = H - max(0, -dr)
nc0 = max(0, dc)
nc1 = W - max(0, -dc)
lat1 = np.radians(lat_2d[r0:r1, c0:c1])
lon1 = np.radians(lon_2d[r0:r1, c0:c1])
lat2 = np.radians(lat_2d[nr0:nr1, nc0:nc1])
lon2 = np.radians(lon_2d[nr0:nr1, nc0:nc1])
dlat = lat2 - lat1
dlon = lon2 - lon1
a = (np.sin(dlat / 2) ** 2
+ np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2) ** 2)
dd_grid[i, r0:r1, c0:c1] = (
EARTH_RADIUS * 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a))
)
return dd_grid
# ---------------------------------------------------------------------------
# NumPy wrapper
# ---------------------------------------------------------------------------
def _surface_distance_numpy(source_data, elev_data, cellsize_x, cellsize_y,
max_distance, target_values, dy, dx, dd,
dd_grid, use_geodesic, mode):
"""NumPy backend: run Dijkstra and extract requested output."""
H, W = source_data.shape
dist, alloc, src_row, src_col = _init_arrays(H, W)
_seed_sources(source_data, elev_data, target_values,
dist, alloc, src_row, src_col)
if use_geodesic:
_dijkstra_geodesic(elev_data, H, W, max_distance,
dy, dx, dd_grid, dist, alloc, src_row, src_col)
else:
_dijkstra(elev_data, H, W, max_distance,
dy, dx, dd, dist, alloc, src_row, src_col)
return _extract_output(dist, alloc, src_row, src_col,
cellsize_x, cellsize_y, max_distance, mode)
# ---------------------------------------------------------------------------
# CuPy GPU backend — iterative parallel relaxation
# ---------------------------------------------------------------------------
@cuda.jit
def _sd_relax_kernel(elev, dist, alloc, src_row, src_col, changed,
height, width, dy, dx, dd, n_neighbors,
max_distance):
"""One relaxation pass for surface distance.
Each pixel checks all neighbours for shorter 3D paths.
Iterate until *changed* stays 0.
"""
iy, ix = cuda.grid(2)
if iy >= height or ix >= width:
return
elev_u = elev[iy, ix]
if not _math.isfinite(elev_u):
return
current = dist[iy, ix]
best = current
best_alloc = alloc[iy, ix]
best_srow = src_row[iy, ix]
best_scol = src_col[iy, ix]
for k in range(n_neighbors):
vy = iy + dy[k]
vx = ix + dx[k]
if vy < 0 or vy >= height or vx < 0 or vx >= width:
continue
d_v = dist[vy, vx]
if d_v >= best:
continue
elev_v = elev[vy, vx]
if not _math.isfinite(elev_v):
continue
dz = elev_u - elev_v
edge_cost = _math.sqrt(dd[k] * dd[k] + dz * dz)
new_cost = d_v + edge_cost
if new_cost < best:
best = new_cost
best_alloc = alloc[vy, vx]
best_srow = src_row[vy, vx]
best_scol = src_col[vy, vx]
if best < current and best <= max_distance:
dist[iy, ix] = best
alloc[iy, ix] = best_alloc
src_row[iy, ix] = best_srow
src_col[iy, ix] = best_scol
changed[0] = 1
def _surface_distance_cupy(source_data, elev_data, cellsize_x, cellsize_y,
max_distance, target_values, dy, dx, dd, mode):
"""GPU surface distance via iterative parallel relaxation."""
import cupy as cp
H, W = source_data.shape
src = source_data.astype(cp.float64)
elev = elev_data.astype(cp.float64)
dist = cp.full((H, W), cp.inf, dtype=cp.float64)
alloc_arr = cp.full((H, W), cp.nan, dtype=cp.float64)
srow = cp.full((H, W), -1, dtype=cp.int64)
scol = cp.full((H, W), -1, dtype=cp.int64)
# Seed sources
if len(target_values) == 0:
mask = cp.isfinite(src) & (src != 0) & cp.isfinite(elev)
else:
tv = cp.asarray(target_values, dtype=cp.float64)
mask = cp.isin(src, tv) & cp.isfinite(elev)
dist[mask] = 0.0
alloc_arr[mask] = src[mask]
rows_g, cols_g = cp.meshgrid(cp.arange(H, dtype=cp.int64),
cp.arange(W, dtype=cp.int64),
indexing='ij')
srow[mask] = rows_g[mask]
scol[mask] = cols_g[mask]
if not cp.any(mask):
out = cp.full((H, W), cp.nan, dtype=cp.float32)
return out
dy_d = cp.asarray(dy, dtype=cp.int64)
dx_d = cp.asarray(dx, dtype=cp.int64)
dd_d = cp.asarray(dd, dtype=cp.float64)
n_neighbors = len(dy)
changed = cp.zeros(1, dtype=cp.int32)
griddim, blockdim = cuda_args((H, W))
max_iterations = H + W
for _ in range(max_iterations):
changed[0] = 0
_sd_relax_kernel[griddim, blockdim](
elev, dist, alloc_arr, srow, scol, changed,
H, W,
dy_d, dx_d, dd_d, n_neighbors,
np.float64(max_distance),
)
if int(changed[0]) == 0:
break
# Extract output
if mode == DISTANCE:
out = cp.where(cp.isinf(dist) | (dist > max_distance),
cp.nan, dist).astype(cp.float32)
elif mode == ALLOCATION:
out = cp.where(cp.isinf(dist) | (dist > max_distance),
cp.nan, alloc_arr).astype(cp.float32)
else: # DIRECTION
row_idx, col_idx = cp.meshgrid(cp.arange(H, dtype=cp.float64),
cp.arange(W, dtype=cp.float64),
indexing='ij')
dx_coord = (scol.astype(cp.float64) - col_idx) * cellsize_x
dy_coord = (srow.astype(cp.float64) - row_idx) * cellsize_y
# Compute direction on CPU (uses numpy-based vectorized function)
dx_np = cp.asnumpy(dx_coord)
dy_np = cp.asnumpy(dy_coord)
zeros = np.zeros((H, W), dtype=np.float64)
result = _vectorized_calc_direction(zeros, dx_np, zeros, dy_np)
mask_np = cp.asnumpy(cp.isinf(dist) | (dist > max_distance)
| (srow < 0))
result[mask_np] = np.nan
out = cp.asarray(result)
return out
# ---------------------------------------------------------------------------
# Dask bounded — map_overlap
# ---------------------------------------------------------------------------
def _make_sd_chunk_func(cellsize_x, cellsize_y, max_distance,
target_values, dy, dx, dd, mode):
"""Return a function for ``da.map_overlap`` over source + elev."""
def _chunk(source_block, elev_block):
return _surface_distance_numpy(
source_block, elev_block,
cellsize_x, cellsize_y, max_distance,
target_values, dy, dx, dd,
None, False, mode,
)
return _chunk
def _surface_distance_dask_bounded(source_da, elev_da,
cellsize_x, cellsize_y,
max_distance, target_values,
dy, dx, dd, mode):
"""Dask bounded path via map_overlap."""
min_cellsize = min(abs(cellsize_x), abs(cellsize_y))
pad = int(max_distance / min_cellsize) + 1
chunk_func = _make_sd_chunk_func(
cellsize_x, cellsize_y, max_distance,
target_values, dy, dx, dd, mode,
)
return da.map_overlap(
chunk_func,
source_da, elev_da,
depth=(pad, pad),
boundary=np.nan,
dtype=np.float32,
meta=np.array((), dtype=np.float32),
)
# ---------------------------------------------------------------------------
# Iterative boundary-only Dijkstra for dask arrays
# ---------------------------------------------------------------------------
def _preprocess_tiles_sd(source_da, elev_da, chunks_y, chunks_x,
target_values):
"""Extract elevation boundary strips and identify source tiles."""
n_tile_y = len(chunks_y)
n_tile_x = len(chunks_x)
n_values = len(target_values)
elev_bdry = {
side: [[None] * n_tile_x for _ in range(n_tile_y)]
for side in ('top', 'bottom', 'left', 'right')
}
has_source = [[False] * n_tile_x for _ in range(n_tile_y)]
for iy in range(n_tile_y):
for ix in range(n_tile_x):
echunk = elev_da.blocks[iy, ix].compute()
elev_bdry['top'][iy][ix] = echunk[0, :].astype(np.float64)
elev_bdry['bottom'][iy][ix] = echunk[-1, :].astype(np.float64)
elev_bdry['left'][iy][ix] = echunk[:, 0].astype(np.float64)
elev_bdry['right'][iy][ix] = echunk[:, -1].astype(np.float64)
schunk = source_da.blocks[iy, ix].compute()
if n_values == 0:
has_source[iy][ix] = bool(
np.any((schunk != 0) & np.isfinite(schunk)
& np.isfinite(echunk))
)
else:
for tv in target_values:
if np.any((schunk == tv) & np.isfinite(echunk)):
has_source[iy][ix] = True
break
return elev_bdry, has_source
def _init_boundaries_sd(chunks_y, chunks_x):
"""Create boundary arrays: dist, alloc, src_row, src_col."""
n_y = len(chunks_y)
n_x = len(chunks_x)
def _make(side_sizes, fill, dtype):
return [[np.full(side_sizes(iy, ix), fill, dtype=dtype)
for ix in range(n_x)]
for iy in range(n_y)]
horiz = lambda iy, ix: chunks_x[ix] # noqa: E731
vert = lambda iy, ix: chunks_y[iy] # noqa: E731
boundaries = {}
for key, fill, dtype in [
('dist', np.inf, np.float64),
('alloc', np.nan, np.float64),
('src_row', np.inf, np.float64),
('src_col', np.inf, np.float64),
]:
boundaries[key] = {
'top': _make(horiz, fill, dtype),
'bottom': _make(horiz, fill, dtype),
'left': _make(vert, fill, dtype),
'right': _make(vert, fill, dtype),
}
return boundaries
def _compute_seeds_sd(iy, ix, boundaries, elev_bdry,
cellsize_x, cellsize_y, chunks_y, chunks_x,
n_tile_y, n_tile_x, connectivity):
"""Compute seed arrays for tile (iy, ix) from neighbour boundaries.
Returns dict with keys 'dist', 'alloc', 'src_row', 'src_col',
each containing (top, bottom, left, right, tl, tr, bl, br).
Cardinal seeds are 1-D float64 arrays; corner seeds are float64 scalars.
"""
tile_h = chunks_y[iy]
tile_w = chunks_x[ix]
diag_dist = sqrt(cellsize_x ** 2 + cellsize_y ** 2)
# Initialize seeds
seeds = {}
for key in ('dist', 'alloc', 'src_row', 'src_col'):
fill = np.inf if key == 'dist' else (np.nan if key == 'alloc'
else np.inf)
seeds[key] = {
'top': np.full(tile_w, fill),
'bottom': np.full(tile_w, fill),
'left': np.full(tile_h, fill),
'right': np.full(tile_h, fill),
'tl': fill, 'tr': fill, 'bl': fill, 'br': fill,
}
my_top = elev_bdry['top'][iy][ix]
my_bottom = elev_bdry['bottom'][iy][ix]
my_left = elev_bdry['left'][iy][ix]
my_right = elev_bdry['right'][iy][ix]
def _edge_seeds(nb_dist, nb_elev, my_elev,
nb_alloc, nb_srow, nb_scol,
cardinal_dist):
"""Compute min-cost seed per boundary pixel, tracking alloc/src."""
n = len(nb_dist)
# Cardinal: pixel c <- pixel c in neighbour
dz = my_elev - nb_elev
cost = nb_dist + np.sqrt(cardinal_dist ** 2 + dz ** 2)
valid = (np.isfinite(nb_dist) & np.isfinite(nb_elev)
& np.isfinite(my_elev))
s_dist = np.where(valid, cost, np.inf)
s_alloc = np.where(valid, nb_alloc, np.nan)
s_srow = np.where(valid, nb_srow, np.inf)
s_scol = np.where(valid, nb_scol, np.inf)
if connectivity == 8 and n > 1:
# Diagonal left: pixel c <- pixel c-1 in neighbour
dz_l = my_elev[1:] - nb_elev[:-1]
cost_l = nb_dist[:-1] + np.sqrt(diag_dist ** 2 + dz_l ** 2)
valid_l = (np.isfinite(nb_dist[:-1]) & np.isfinite(nb_elev[:-1])
& np.isfinite(my_elev[1:]))
cost_l = np.where(valid_l, cost_l, np.inf)
better = cost_l < s_dist[1:]
s_dist[1:] = np.where(better, cost_l, s_dist[1:])
s_alloc[1:] = np.where(better, nb_alloc[:-1], s_alloc[1:])
s_srow[1:] = np.where(better, nb_srow[:-1], s_srow[1:])
s_scol[1:] = np.where(better, nb_scol[:-1], s_scol[1:])
# Diagonal right: pixel c <- pixel c+1 in neighbour
dz_r = my_elev[:-1] - nb_elev[1:]
cost_r = nb_dist[1:] + np.sqrt(diag_dist ** 2 + dz_r ** 2)
valid_r = (np.isfinite(nb_dist[1:]) & np.isfinite(nb_elev[1:])
& np.isfinite(my_elev[:-1]))
cost_r = np.where(valid_r, cost_r, np.inf)
better_r = cost_r < s_dist[:-1]
s_dist[:-1] = np.where(better_r, cost_r, s_dist[:-1])
s_alloc[:-1] = np.where(better_r, nb_alloc[1:], s_alloc[:-1])
s_srow[:-1] = np.where(better_r, nb_srow[1:], s_srow[:-1])
s_scol[:-1] = np.where(better_r, nb_scol[1:], s_scol[:-1])
return s_dist, s_alloc, s_srow, s_scol
def _get_bdry(key, side, iy_, ix_):
return boundaries[key][side][iy_][ix_]
# Edge neighbours
if iy > 0:
result = _edge_seeds(
_get_bdry('dist', 'bottom', iy - 1, ix),
elev_bdry['bottom'][iy - 1][ix],
my_top,
_get_bdry('alloc', 'bottom', iy - 1, ix),
_get_bdry('src_row', 'bottom', iy - 1, ix),
_get_bdry('src_col', 'bottom', iy - 1, ix),
cellsize_y,
)
for i, key in enumerate(('dist', 'alloc', 'src_row', 'src_col')):
seeds[key]['top'] = result[i]
if iy < n_tile_y - 1:
result = _edge_seeds(
_get_bdry('dist', 'top', iy + 1, ix),
elev_bdry['top'][iy + 1][ix],
my_bottom,
_get_bdry('alloc', 'top', iy + 1, ix),
_get_bdry('src_row', 'top', iy + 1, ix),
_get_bdry('src_col', 'top', iy + 1, ix),
cellsize_y,
)
for i, key in enumerate(('dist', 'alloc', 'src_row', 'src_col')):
seeds[key]['bottom'] = result[i]
if ix > 0:
result = _edge_seeds(
_get_bdry('dist', 'right', iy, ix - 1),
elev_bdry['right'][iy][ix - 1],
my_left,
_get_bdry('alloc', 'right', iy, ix - 1),
_get_bdry('src_row', 'right', iy, ix - 1),
_get_bdry('src_col', 'right', iy, ix - 1),
cellsize_x,
)
for i, key in enumerate(('dist', 'alloc', 'src_row', 'src_col')):
seeds[key]['left'] = result[i]
if ix < n_tile_x - 1:
result = _edge_seeds(
_get_bdry('dist', 'left', iy, ix + 1),
elev_bdry['left'][iy][ix + 1],
my_right,
_get_bdry('alloc', 'left', iy, ix + 1),
_get_bdry('src_row', 'left', iy, ix + 1),
_get_bdry('src_col', 'left', iy, ix + 1),
cellsize_x,
)
for i, key in enumerate(('dist', 'alloc', 'src_row', 'src_col')):
seeds[key]['right'] = result[i]
# Diagonal corner seeds (8-connectivity only)
if connectivity == 8:
def _corner(nb_d, nb_e, my_e, nb_a, nb_sr, nb_sc):
nb_d = float(nb_d)
nb_e = float(nb_e)
my_e = float(my_e)
if (np.isfinite(nb_d) and np.isfinite(nb_e)
and np.isfinite(my_e)):
dz = my_e - nb_e
cost = nb_d + sqrt(diag_dist ** 2 + dz ** 2)
return cost, float(nb_a), float(nb_sr), float(nb_sc)
return np.inf, np.nan, np.inf, np.inf
corners = [
# (tile_offset_y, tile_offset_x, nb_side, nb_col_idx, my_elev_val,
# seed_key)
(iy - 1, ix - 1, 'bottom', -1, my_top[0], 'tl'),
(iy - 1, ix + 1, 'bottom', 0, my_top[-1], 'tr'),
(iy + 1, ix - 1, 'top', -1, my_bottom[0], 'bl'),
(iy + 1, ix + 1, 'top', 0, my_bottom[-1], 'br'),
]
for niy, nix, nb_side, nb_idx, my_e, skey in corners:
if 0 <= niy < n_tile_y and 0 <= nix < n_tile_x:
nb_d = boundaries['dist'][nb_side][niy][nix][nb_idx]
nb_e = elev_bdry[nb_side][niy][nix][nb_idx]
nb_a = boundaries['alloc'][nb_side][niy][nix][nb_idx]
nb_sr = boundaries['src_row'][nb_side][niy][nix][nb_idx]
nb_sc = boundaries['src_col'][nb_side][niy][nix][nb_idx]
cd, ca, csr, csc = _corner(nb_d, nb_e, my_e,
nb_a, nb_sr, nb_sc)
seeds['dist'][skey] = cd
seeds['alloc'][skey] = ca
seeds['src_row'][skey] = csr
seeds['src_col'][skey] = csc
return seeds
def _can_skip_sd(iy, ix, has_source, boundaries,
n_tile_y, n_tile_x, connectivity):
"""True when a tile cannot possibly receive any distance information."""
if has_source[iy][ix]:
return False
bdist = boundaries['dist']
if iy > 0 and np.any(np.isfinite(bdist['bottom'][iy - 1][ix])):
return False
if (iy < n_tile_y - 1
and np.any(np.isfinite(bdist['top'][iy + 1][ix]))):
return False
if ix > 0 and np.any(np.isfinite(bdist['right'][iy][ix - 1])):
return False
if (ix < n_tile_x - 1
and np.any(np.isfinite(bdist['left'][iy][ix + 1]))):
return False
if connectivity == 8:
if (iy > 0 and ix > 0
and np.isfinite(bdist['bottom'][iy - 1][ix - 1][-1])):
return False
if (iy > 0 and ix < n_tile_x - 1
and np.isfinite(bdist['bottom'][iy - 1][ix + 1][0])):
return False
if (iy < n_tile_y - 1 and ix > 0
and np.isfinite(bdist['top'][iy + 1][ix - 1][-1])):
return False
if (iy < n_tile_y - 1 and ix < n_tile_x - 1
and np.isfinite(bdist['top'][iy + 1][ix + 1][0])):
return False
return True
def _run_tile(source_chunk, elev_chunk, seeds, target_values,
max_distance, dy, dx, dd, row_offset, col_offset):
"""Run Dijkstra on one tile with boundary seeds.
Returns (dist, alloc, src_row, src_col) as raw float64/int64 arrays.
src_row/src_col are global indices.
"""
h, w = source_chunk.shape
dist, alloc, src_row, src_col = _init_arrays(h, w)
# Seed source pixels (using global coords for src)
n_values = len(target_values)
for r in range(h):
for c in range(w):
val = source_chunk[r, c]
is_target = False
if n_values == 0:
if val != 0.0 and np.isfinite(val):
is_target = True
else:
for k in range(n_values):
if val == target_values[k]:
is_target = True
break
if is_target and np.isfinite(elev_chunk[r, c]):
dist[r, c] = 0.0
alloc[r, c] = val
src_row[r, c] = r + row_offset
src_col[r, c] = c + col_offset
# Seed boundary pixels from neighbour tiles
sd = seeds['dist']
sa = seeds['alloc']
ssr = seeds['src_row']
ssc = seeds['src_col']
# Top edge
for c in range(w):
if sd['top'][c] < dist[0, c] and np.isfinite(elev_chunk[0, c]):
dist[0, c] = sd['top'][c]
alloc[0, c] = sa['top'][c]
src_row[0, c] = int(ssr['top'][c])
src_col[0, c] = int(ssc['top'][c])
# Bottom edge
for c in range(w):
if sd['bottom'][c] < dist[h - 1, c] and np.isfinite(
elev_chunk[h - 1, c]):
dist[h - 1, c] = sd['bottom'][c]
alloc[h - 1, c] = sa['bottom'][c]
src_row[h - 1, c] = int(ssr['bottom'][c])
src_col[h - 1, c] = int(ssc['bottom'][c])
# Left edge
for r in range(h):
if sd['left'][r] < dist[r, 0] and np.isfinite(elev_chunk[r, 0]):
dist[r, 0] = sd['left'][r]
alloc[r, 0] = sa['left'][r]
src_row[r, 0] = int(ssr['left'][r])
src_col[r, 0] = int(ssc['left'][r])
# Right edge
for r in range(h):
if sd['right'][r] < dist[r, w - 1] and np.isfinite(
elev_chunk[r, w - 1]):
dist[r, w - 1] = sd['right'][r]
alloc[r, w - 1] = sa['right'][r]
src_row[r, w - 1] = int(ssr['right'][r])
src_col[r, w - 1] = int(ssc['right'][r])
# Corner seeds
_corners = [
(0, 0, 'tl'),
(0, w - 1, 'tr'),
(h - 1, 0, 'bl'),
(h - 1, w - 1, 'br'),
]
for cr, cc, skey in _corners:
sv = sd[skey]
if sv < dist[cr, cc] and np.isfinite(elev_chunk[cr, cc]):
dist[cr, cc] = sv
alloc[cr, cc] = sa[skey]
src_row[cr, cc] = int(ssr[skey])
src_col[cr, cc] = int(ssc[skey])
# Run Dijkstra
_dijkstra(elev_chunk, h, w, max_distance,
dy, dx, dd, dist, alloc, src_row, src_col)
return dist, alloc, src_row, src_col
def _process_tile_sd(iy, ix, source_da, elev_da,
boundaries, elev_bdry,
cellsize_x, cellsize_y, max_distance, target_values,
dy, dx, dd, chunks_y, chunks_x,
n_tile_y, n_tile_x, connectivity,
cumul_rows, cumul_cols):
"""Run seeded Dijkstra on one tile; update boundaries in-place.
Returns the maximum absolute boundary distance change.
"""
source_chunk = source_da.blocks[iy, ix].compute()
elev_chunk = elev_da.blocks[iy, ix].compute()
h, w = source_chunk.shape
row_offset = cumul_rows[iy]
col_offset = cumul_cols[ix]
seeds = _compute_seeds_sd(
iy, ix, boundaries, elev_bdry,
cellsize_x, cellsize_y, chunks_y, chunks_x,
n_tile_y, n_tile_x, connectivity,
)
dist, alloc_arr, srow, scol = _run_tile(
source_chunk, elev_chunk, seeds, target_values,
max_distance, dy, dx, dd, row_offset, col_offset,
)
# Extract new boundary strips
change = 0.0
for side, sl in [
('top', (0, slice(None))),
('bottom', (-1, slice(None))),
('left', (slice(None), 0)),
('right', (slice(None), -1)),
]:
new_d = dist[sl]
old_d = boundaries['dist'][side][iy][ix]
with np.errstate(invalid='ignore'):
diff = np.abs(new_d - old_d)
diff = np.where(np.isnan(diff), 0.0, diff)
m = float(np.max(diff))
if m > change:
change = m
boundaries['dist'][side][iy][ix] = new_d.copy()
boundaries['alloc'][side][iy][ix] = alloc_arr[sl].copy()
boundaries['src_row'][side][iy][ix] = srow[sl].astype(
np.float64).copy()
boundaries['src_col'][side][iy][ix] = scol[sl].astype(
np.float64).copy()
return change
def _sd_dask_iterative(source_da, elev_da,
cellsize_x, cellsize_y,
max_distance, target_values,
dy, dx, dd, mode):
"""Iterative boundary-only Dijkstra for arbitrarily large dask arrays."""
connectivity = len(dy)
chunks_y = source_da.chunks[0]
chunks_x = source_da.chunks[1]
n_tile_y = len(chunks_y)
n_tile_x = len(chunks_x)
# Cumulative row/col offsets for global indexing
cumul_rows = [0]
for cy in chunks_y[:-1]:
cumul_rows.append(cumul_rows[-1] + cy)
cumul_cols = [0]
for cx in chunks_x[:-1]:
cumul_cols.append(cumul_cols[-1] + cx)
# Phase 0: pre-extract elevation boundaries & source flags
elev_bdry, has_source = _preprocess_tiles_sd(
source_da, elev_da, chunks_y, chunks_x, target_values,
)
# Phase 1: initialise boundaries