Repository navigation
Expand file tree
/
Copy pathproximity.py
More file actions
2275 lines (1942 loc) · 87.1 KB
/
Copy pathproximity.py
File metadata and controls
2275 lines (1942 loc) · 87.1 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
import threading
import warnings
from functools import partial
try:
import dask.array as da
except ImportError:
da = None
try:
from scipy.spatial import cKDTree
except ImportError:
cKDTree = None
import math as _math
import numpy as np
import xarray as xr
from numba import cuda, jit, prange
try:
import cupy
except ImportError:
class cupy(object):
ndarray = False
from xrspatial.dataset_support import supports_dataset
from xrspatial.pathfinding import _available_memory_bytes
from xrspatial.utils import (_dask_task_name_kwargs, _validate_raster, cuda_args, has_cuda_and_cupy,
is_cupy_array, is_dask_cupy, ngjit)
EUCLIDEAN = 0
GREAT_CIRCLE = 1
MANHATTAN = 2
PROXIMITY = 0
ALLOCATION = 1
DIRECTION = 2
# Map the runtime process_mode to the public function name so the shared
# _process compute layers label their dask tasks under the op that called them.
_PROCESS_MODE_TASK_NAMES = {
PROXIMITY: 'xrspatial.proximity',
ALLOCATION: 'xrspatial.allocation',
DIRECTION: 'xrspatial.direction',
}
def _distance_metric_mapping():
DISTANCE_METRICS = {}
DISTANCE_METRICS["EUCLIDEAN"] = EUCLIDEAN
DISTANCE_METRICS["GREAT_CIRCLE"] = GREAT_CIRCLE
DISTANCE_METRICS["MANHATTAN"] = MANHATTAN
return DISTANCE_METRICS
# create dictionary to map distance metric presented by string and the
# corresponding metric presented by integer.
DISTANCE_METRICS = _distance_metric_mapping()
@ngjit
def euclidean_distance(x1: float, x2: float, y1: float, y2: float) -> float:
"""
Calculates Euclidean (straight line) distance between (x1, y1) and
(x2, y2).
Parameters
----------
x1 : float
x-coordinate of the first point.
x2 : float
x-coordinate of the second point.
y1 : float
y-coordinate of the first point.
y2 : float
y-coordinate of the second point.
Returns
-------
distance : float
Euclidean distance between two points.
References
----------
- Wikipedia: https://en.wikipedia.org/wiki/Euclidean_distance#:~:text=In%20mathematics%2C%20the%20Euclidean%20distance,being%20called%20the%20Pythagorean%20distance. # noqa
Examples
--------
.. sourcecode:: python
>>> # Imports
>>> from xrspatial import euclidean_distance
>>> point_a = (142.32, 23.23)
>>> point_b = (312.54, 432.01)
>>> # Calculate Euclidean Distance
>>> dist = euclidean_distance(
... point_a[0],
... point_b[0],
... point_a[1],
... point_b[1])
>>> print(dist)
442.80462599209596
"""
x = x1 - x2
y = y1 - y2
return np.sqrt(x * x + y * y)
@ngjit
def manhattan_distance(x1: float, x2: float, y1: float, y2: float) -> float:
"""
Calculates Manhattan distance (sum of distance in x and y directions)
between (x1, y1) and (x2, y2).
Parameters
----------
x1 : float
x-coordinate of the first point.
x2 : float
x-coordinate of the second point.
y1 : float
y-coordinate of the first point.
y2 : float
y-coordinate of the second point.
Returns
-------
distance : float
Manhattan distance between two points.
References
----------
- Wikipedia: https://en.wikipedia.org/wiki/Taxicab_geometry
Examples
--------
.. sourcecode:: python
>>> from xrspatial import manhattan_distance
>>> point_a = (142.32, 23.23)
>>> point_b = (312.54, 432.01)
>>> # Calculate Manhattan Distance
>>> dist = manhattan_distance(
... point_a[0],
... point_b[0],
... point_a[1],
... point_b[1])
>>> print(dist)
579.0
"""
x = x1 - x2
y = y1 - y2
return abs(x) + abs(y)
@ngjit
def great_circle_distance(
x1: float, x2: float, y1: float, y2: float, radius: float = 6378137
) -> float:
"""
Calculates great-circle (orthodromic/spherical) distance between
(x1, y1) and (x2, y2), assuming each point is a longitude,
latitude pair.
Parameters
----------
x1 : float
x-coordinate (longitude) between -180 and 180 of the first point.
x2: float
x-coordinate (longitude) between -180 and 180 of the second point.
y1: float
y-coordinate (latitude) between -90 and 90 of the first point.
y2: float
y-coordinate (latitude) between -90 and 90 of the second point.
radius: float, default=6378137
Radius of sphere (earth), in meters. The default is the WGS84
equatorial radius, so the returned distance is in meters.
Returns
-------
distance : float
Great-Circle distance between two points, in the same unit as
``radius`` (meters by default).
References
----------
- Wikipedia: https://en.wikipedia.org/wiki/Great-circle_distance#:~:text=The%20great%2Dcircle%20distance%2C%20orthodromic,line%20through%20the%20sphere's%20interior). # noqa
Examples
--------
.. sourcecode:: python
>>> from xrspatial import great_circle_distance
>>> point_a = (123.2, 82.32)
>>> point_b = (178.0, 65.09)
>>> # Calculate Great Circle Distance
>>> dist = great_circle_distance(
... point_a[0],
... point_b[0],
... point_a[1],
... point_b[1])
>>> print(dist)
2378290.489801402
"""
if x1 > 180 or x1 < -180:
raise ValueError(
"Invalid x-coordinate of the first point."
"Must be in the range [-180, 180]"
)
if x2 > 180 or x2 < -180:
raise ValueError(
"Invalid x-coordinate of the second point."
"Must be in the range [-180, 180]"
)
if y1 > 90 or y1 < -90:
raise ValueError(
"Invalid y-coordinate of the first point."
"Must be in the range [-90, 90]"
)
if y2 > 90 or y2 < -90:
raise ValueError(
"Invalid y-coordinate of the second point."
"Must be in the range [-90, 90]"
)
lat1, lon1, lat2, lon2 = (
np.radians(y1),
np.radians(x1),
np.radians(y2),
np.radians(x2),
)
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat / 2.0) ** 2 + \
np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2.0) ** 2
# earth radius: 6378137
return radius * 2 * np.arcsin(np.sqrt(a))
@ngjit
def _distance(x1, x2, y1, y2, metric):
if metric == EUCLIDEAN:
d = euclidean_distance(x1, x2, y1, y2)
elif metric == GREAT_CIRCLE:
d = great_circle_distance(x1, x2, y1, y2)
else:
# metric == MANHATTAN:
d = manhattan_distance(x1, x2, y1, y2)
return np.float32(d)
def _check_monotonic_coords(x_coords, y_coords, x, y):
"""Reject non-monotonic 1D coordinates.
Every backend in this module assumes the 1D axis coordinates are
monotonic: ``max_possible_distance`` is taken from the endpoints, the
dask halo treats array adjacency as spatial adjacency, and the tiled
KDTree convergence check lower-bounds the
out-of-region distance with chunk-boundary coordinate gaps. None of
those hold when a coordinate axis is not monotonic, so a non-monotonic
axis silently yields wrong proximity/allocation/direction. Reject it up
front with a clear message instead.
A single-element axis has no order to violate and is allowed.
"""
for coords, name in ((x_coords, x), (y_coords, y)):
if len(coords) < 2:
continue
diffs = np.diff(coords)
ascending = np.all(diffs > 0)
descending = np.all(diffs < 0)
if not (ascending or descending):
raise ValueError(
"proximity/allocation/direction require strictly monotonic "
"(strictly increasing or strictly decreasing, no duplicate or "
"NaN values) 1D coordinates, but the {0!r} axis does not "
"qualify. Sort the raster along {0!r} before calling.".format(
name)
)
def _great_circle_col_halo(x_coords, y_coords, max_distance):
"""Column halo depth (in pixels) for the GREAT_CIRCLE metric.
Great-circle distance is periodic in longitude (haversine takes the
short way around the sphere) and its chords shorten toward the poles,
so a linear sum of per-column step distances is not a lower bound on
the spherical distance between two grid points. Use the chord bound
dist(p, t) >= 2 * R * asin(cos(lat_max) * |sin(dlon / 2)|)
which holds for every pair of grid points (``lat_max`` is the largest
absolute latitude on the raster). Inverting it for ``max_distance``
gives ``dlon_max``: any pair separated by more than ``dlon_max``
degrees of longitude (the short way around) is farther apart than
``max_distance`` no matter the latitudes.
When the bound cannot exclude anything -- ``max_distance`` reaches the
180-degree chord at ``lat_max``, or targets across the +/-180 seam are
within reach (seam gap <= ``dlon_max``) -- no array-space halo can
cover the wrap. Return a depth one larger than the axis so
``_fit_halo_to_chunks`` folds the x axis into a single chunk and every
chunk sees all columns.
"""
width = len(x_coords)
if width < 2:
return 0
fold = width + 1
radius = 6378137.0
half_angle = max_distance / (2.0 * radius)
if half_angle >= np.pi / 2.0:
# max_distance spans half the circumference: everything is in reach.
return fold
cos_lat_max = np.cos(np.radians(np.abs(np.asarray(y_coords)).max()))
sin_half = np.sin(half_angle)
if sin_half >= cos_lat_max:
# Even a 180-degree longitude gap at the worst-case latitude stays
# within max_distance, so no longitude separation excludes a target.
return fold
dlon_max = np.degrees(2.0 * np.arcsin(sin_half / cos_lat_max))
# Wrap check: the smallest longitude separation through the +/-180 seam
# is between the first and last columns. If that is within dlon_max, a
# target near one edge of the array can be the nearest target of a pixel
# near the opposite edge, which no per-chunk halo can express.
span = abs(float(x_coords[-1]) - float(x_coords[0]))
seam_gap = 360.0 - span
if seam_gap <= dlon_max:
return fold
# No wrap in reach: a target k columns away is at least k * min_step
# degrees of longitude away (monotonic coords), so columns beyond
# dlon_max / min_step are excluded by the chord bound.
min_step = np.abs(np.diff(np.asarray(x_coords, dtype=np.float64))).min()
return int(np.ceil(dlon_max / min_step))
def _halo_depth(x_coords, y_coords, max_distance, distance_metric):
"""Overlap depth in pixels for the bounded dask map_overlap call.
``max_distance`` is expressed in the same unit as the chosen
distance_metric, so the pixel pitch is measured with that same metric.
Using the raw degree cellsize for GREAT_CIRCLE (where max_distance is in
metres) would yield a meaningless depth.
The depth is sized from the *densest* (smallest positive) spacing along
each axis rather than only the first coordinate pair. On irregular
coordinates the first gap can be much larger than later gaps; sizing the
halo from the first gap alone leaves it too thin and chunks then miss
valid targets just past the boundary.
An axis with a single coordinate has no spacing and therefore contributes
no halo along that axis (depth 0), so (1, N) and (N, 1) rasters do not
crash on the missing second coordinate.
For GREAT_CIRCLE the column depth comes from the spherical chord bound
in ``_great_circle_col_halo``: longitude is periodic and chords shorten
toward the poles, so a per-column linear step sum is not a valid lower
bound there. When targets across the +/-180 seam are within
``max_distance``, the returned column depth exceeds the axis length so
``_fit_halo_to_chunks`` folds the axis. The row depth stays linear: the
great-circle distance between two points is never smaller than their
meridian (north-south) separation, so the per-row step sum is a valid
lower bound for every metric.
"""
def _min_step_distance(coords, x_ref, y_ref, along):
if len(coords) < 2:
return None
smallest = None
for i in range(len(coords) - 1):
if along == "row":
d = _distance(
x_ref, x_ref, coords[i], coords[i + 1], distance_metric)
else:
d = _distance(
coords[i], coords[i + 1], y_ref, y_ref, distance_metric)
if d > 0 and (smallest is None or d < smallest):
smallest = d
return smallest
dist_per_row = _min_step_distance(y_coords, x_coords[0], None, "row")
pad_y = 0 if dist_per_row is None else int(max_distance / dist_per_row + 0.5)
if distance_metric == GREAT_CIRCLE:
pad_x = _great_circle_col_halo(x_coords, y_coords, max_distance)
else:
dist_per_col = _min_step_distance(x_coords, None, y_coords[0], "col")
pad_x = 0 if dist_per_col is None else int(
max_distance / dist_per_col + 0.5)
return pad_y, pad_x
def _fit_halo_to_chunks(pad_y, pad_x, *arrays):
"""Make a bounded halo depth that ``da.map_overlap`` will accept.
``map_overlap`` rejects a depth that is larger than the smallest chunk
along that axis. The pixel halo from ``_halo_depth`` can exceed that on
skinny rasters (e.g. a 3-row raster with a 10-pixel halo), or on
great-circle rasters where the pixel pitch shrinks toward the poles. When
a halo is too deep for the chunking, fold that whole axis into a single
chunk and drop its depth to zero: every chunk then sees the full axis, so
no target within ``max_distance`` is missed and the result still matches
the NumPy backend. The fold deliberately trades chunking on that axis for
correctness; clamping the depth while keeping multiple chunks would
silently drop targets that fall in a non-adjacent chunk, so do not replace
it with a bare depth clamp.
``arrays`` are the dask arrays passed to the same ``map_overlap`` call
(the raster and the coordinate grids); they all share the raster's
chunking and are rechunked together so the call stays aligned.
Returns the adjusted ``(pad_y, pad_x)`` and the (possibly rechunked)
arrays in the same order they were given.
"""
arrays = list(arrays)
height, width = arrays[0].shape
chunks_y, chunks_x = arrays[0].chunks
rechunk = {}
if pad_y > min(chunks_y):
rechunk[0] = height
pad_y = 0
if pad_x > min(chunks_x):
rechunk[1] = width
pad_x = 0
if rechunk:
arrays = [a.rechunk(rechunk) for a in arrays]
return pad_y, pad_x, arrays
@ngjit
def _calc_direction(x1, x2, y1, y2):
# Calculate direction from (x1, y1) to a source cell (x2, y2).
# The output values are based on compass directions,
# 90 to the east, 180 to the south, 270 to the west, and 360 to the north,
# with 0 reserved for the source cell itself
if x1 == x2 and y1 == y2:
return 0
x = x2 - x1
y = y2 - y1
d = np.arctan2(-y, x) * 57.29578
if d < 0:
d = 90.0 - d
elif d > 90.0:
d = 360.0 - d + 90.0
else:
d = 90.0 - d
return np.float32(d)
def _vectorized_calc_direction(x1, x2, y1, y2):
"""Array-based compass direction from (x1, y1) to (x2, y2).
Uses the same conversion constant (57.29578) as _calc_direction
to ensure identical floating-point behaviour.
"""
dx = x2 - x1
dy = y2 - y1
d = np.arctan2(-dy, dx) * 57.29578
result = np.where(d < 0, 90.0 - d,
np.where(d > 90.0, 360.0 - d + 90.0, 90.0 - d))
result[(x1 == x2) & (y1 == y2)] = 0.0
return result.astype(np.float32)
@ngjit
def _is_target_value(v, target_values):
# A pixel is a target if it matches one of target_values, or (when no
# target_values are given) if it is non-zero and finite. NaN padding from
# dask's boundary=np.nan is excluded either way.
if len(target_values) == 0:
return v != 0 and np.isfinite(v)
for k in range(len(target_values)):
if v == target_values[k]:
return True
return False
# Numba parallel=True kernels must not be launched concurrently from multiple
# Python threads: the default 'workqueue' threading layer is not threadsafe and
# aborts the process (SIGABRT on macOS) when two host threads enter a parallel
# region at once. _process_dask maps _process_numpy over chunks under dask's
# threaded scheduler, and that reaches the brute-force kernel for GREAT_CIRCLE,
# ALLOCATION, DIRECTION and the no-scipy PROXIMITY fallback, so the kernel
# launch is serialized behind this lock. Same hazard and fix as the
# convolution, terrain and reproject kernels (#3141).
_PARALLEL_KERNEL_LOCK = threading.Lock()
@ngjit
def _collect_targets(img, target_values):
"""Row/col indices of every target pixel, in flat (row-major) order."""
height, width = img.shape
n_targets = 0
for line in range(height):
for col in range(width):
if _is_target_value(img[line, col], target_values):
n_targets += 1
target_rows = np.empty(n_targets, dtype=np.int64)
target_cols = np.empty(n_targets, dtype=np.int64)
t = 0
for line in range(height):
for col in range(width):
if _is_target_value(img[line, col], target_values):
target_rows[t] = line
target_cols[t] = col
t += 1
return target_rows, target_cols
# The three inner loops below each scan every target for one pixel and return
# (index, float32 distance) of the nearest one, or (-1, inf) with no targets.
#
# They compare a cheap proxy that is monotone in the distance (squared
# distance, |dx| + |dy|, the haversine term) and only evaluate the sqrt /
# arcsin and the float32 rounding when the proxy beats the running best. The
# strict ``<`` that decides the winner still runs on the float32 distance, the
# same value ``_distance`` returns, so the documented tie-break is unchanged:
# two targets whose float64 distances differ only past the float32 mantissa
# are a tie and the lowest flat index wins (issue #3689, and the matching
# comment in ``_proximity_cuda_kernel``). A candidate whose proxy does not
# beat the running best has a float32 distance >= the running best and could
# never have won under that rule, so skipping it changes nothing.
# The running best is updated with a select rather than a branch, and only
# when the candidate wins, so a NaN distance (say a haversine term rounded a
# hair past 1.0) is skipped instead of poisoning every later comparison.
@ngjit
def _nearest_euclidean(px, py, txs, tys):
best_proxy = np.inf
best_dist = np.float32(np.inf)
best_idx = -1
for k in range(len(txs)):
dx = px - txs[k]
dy = py - tys[k]
proxy = dx * dx + dy * dy
if proxy < best_proxy:
d = np.float32(np.sqrt(proxy))
better = d < best_dist
best_idx = k if better else best_idx
best_dist = d if better else best_dist
best_proxy = proxy
return best_idx, best_dist
@ngjit
def _nearest_manhattan(px, py, txs, tys):
best_proxy = np.inf
best_dist = np.float32(np.inf)
best_idx = -1
for k in range(len(txs)):
dx = px - txs[k]
dy = py - tys[k]
proxy = abs(dx) + abs(dy)
if proxy < best_proxy:
d = np.float32(proxy)
better = d < best_dist
best_idx = k if better else best_idx
best_dist = d if better else best_dist
best_proxy = proxy
return best_idx, best_dist
@ngjit
def _nearest_great_circle(px, py, tlons, tlats, tcoslats):
# Same arithmetic, in the same order, as great_circle_distance with the
# default radius, so the float32 distance is bit-identical to _distance.
lat1 = np.radians(py)
lon1 = np.radians(px)
coslat1 = np.cos(lat1)
best_proxy = np.inf
best_dist = np.float32(np.inf)
best_idx = -1
for k in range(len(tlons)):
dlon = tlons[k] - lon1
dlat = tlats[k] - lat1
proxy = np.sin(dlat / 2.0) ** 2 + \
coslat1 * tcoslats[k] * np.sin(dlon / 2.0) ** 2
if proxy < best_proxy:
d = np.float32(6378137 * 2 * np.arcsin(np.sqrt(proxy)))
better = d < best_dist
best_idx = k if better else best_idx
best_dist = d if better else best_dist
best_proxy = proxy
return best_idx, best_dist
@ngjit
def _great_circle_target_terms(txs, tys):
# Precompute the per-target radians and cos(lat) with numba's np.radians /
# np.cos rather than numpy's, so they match what the per-pixel side of
# _nearest_great_circle (and great_circle_distance) computes bit for bit.
n = len(txs)
tlons = np.empty(n, dtype=np.float64)
tlats = np.empty(n, dtype=np.float64)
tcoslats = np.empty(n, dtype=np.float64)
for k in range(n):
tlons[k] = np.radians(txs[k])
tlats[k] = np.radians(tys[k])
tcoslats[k] = np.cos(tlats[k])
return tlons, tlats, tcoslats
@ngjit
def _great_circle_range_violation(xs, ys, txs, tys):
# Report the first out-of-range coordinate in the order the per-pair
# guards in great_circle_distance would have hit it when the pixel loop
# called it pair by pair: pixel (0, 0) against every target, then the
# remaining pixels. 0 = no violation, otherwise the guard number (1: x of
# the first point, 2: x of the second, 3: y of the first, 4: y of the
# second). NaN coordinates (dask halo padding) fail no comparison, as
# before.
px = xs[0, 0]
py = ys[0, 0]
if px > 180 or px < -180:
return 1
if txs[0] > 180 or txs[0] < -180:
return 2
if py > 90 or py < -90:
return 3
if tys[0] > 90 or tys[0] < -90:
return 4
for k in range(1, len(txs)):
if txs[k] > 180 or txs[k] < -180:
return 2
if tys[k] > 90 or tys[k] < -90:
return 4
height, width = xs.shape
for line in range(height):
for col in range(width):
if xs[line, col] > 180 or xs[line, col] < -180:
return 1
if ys[line, col] > 90 or ys[line, col] < -90:
return 3
return 0
_GREAT_CIRCLE_RANGE_MESSAGES = {
1: "Invalid x-coordinate of the first point."
"Must be in the range [-180, 180]",
2: "Invalid x-coordinate of the second point."
"Must be in the range [-180, 180]",
3: "Invalid y-coordinate of the first point."
"Must be in the range [-90, 90]",
4: "Invalid y-coordinate of the second point."
"Must be in the range [-90, 90]",
}
@jit(nopython=True, nogil=True, parallel=True)
def _bruteforce_kernel(
img, xs, ys, target_rows, target_cols, txs, tys, tlons, tlats, tcoslats,
max_distance, distance_metric, process_mode, output
):
# The metric branch sits per pixel, outside the target loop, and the
# metric stays a runtime value so one compiled specialization serves all
# three. Rows are independent, so prange over them.
height, width = img.shape
for line in prange(height):
for col in range(width):
px = xs[line, col]
py = ys[line, col]
if distance_metric == EUCLIDEAN:
best_idx, best_dist = _nearest_euclidean(px, py, txs, tys)
elif distance_metric == GREAT_CIRCLE:
best_idx, best_dist = _nearest_great_circle(
px, py, tlons, tlats, tcoslats)
else:
best_idx, best_dist = _nearest_manhattan(px, py, txs, tys)
if best_idx >= 0 and best_dist <= max_distance:
if process_mode == PROXIMITY:
output[line, col] = best_dist
elif process_mode == ALLOCATION:
output[line, col] = img[
target_rows[best_idx], target_cols[best_idx]]
else:
output[line, col] = _calc_direction(
px, txs[best_idx], py, tys[best_idx])
def _process_numpy_bruteforce(
img, xs, ys, target_values, max_distance, distance_metric, process_mode
):
"""Exact nearest-target proximity / allocation / direction on the CPU.
For every pixel, scan all target pixels and keep the closest one under the
chosen distance metric. This is the same brute-force search the CUDA kernel
runs (see ``_proximity_cuda_kernel``). It covers what the cKDTree path
cannot: GREAT_CIRCLE (not a Minkowski metric), the tie-break-sensitive
ALLOCATION/DIRECTION modes, and PROXIMITY when scipy is missing.
``xs`` and ``ys`` are the per-pixel 2D coordinate grids built by the caller.
The target coordinates are gathered into flat arrays once, the per-metric
inner loops live in ``_nearest_*`` and the pixel loop runs in parallel over
rows in ``_bruteforce_kernel``, serialized behind ``_PARALLEL_KERNEL_LOCK``
because the dask path calls this per chunk from worker threads.
"""
target_rows, target_cols = _collect_targets(img, target_values)
output = np.full(img.shape, np.nan, dtype=np.float32)
if len(target_rows) == 0:
return output
txs = xs[target_rows, target_cols]
tys = ys[target_rows, target_cols]
if distance_metric == GREAT_CIRCLE:
# The per-pair guards in great_circle_distance no longer run inside
# the loop; check the grids once up front and raise the same message.
violation = _great_circle_range_violation(xs, ys, txs, tys)
if violation:
raise ValueError(_GREAT_CIRCLE_RANGE_MESSAGES[violation])
tlons, tlats, tcoslats = _great_circle_target_terms(txs, tys)
else:
# Placeholders: the kernel only reads these under GREAT_CIRCLE.
tlons = tlats = tcoslats = np.empty(0, dtype=np.float64)
with _PARALLEL_KERNEL_LOCK:
_bruteforce_kernel(
img, xs, ys, target_rows, target_cols, txs, tys,
tlons, tlats, tcoslats,
max_distance, distance_metric, process_mode, output,
)
return output
# =====================================================================
# GPU (CuPy / CUDA) backend
# =====================================================================
@cuda.jit(device=True)
def _gpu_euclidean_distance(x1, x2, y1, y2):
dx = x1 - x2
dy = y1 - y2
return _math.sqrt(dx * dx + dy * dy)
@cuda.jit(device=True)
def _gpu_manhattan_distance(x1, x2, y1, y2):
return abs(x1 - x2) + abs(y1 - y2)
@cuda.jit(device=True)
def _gpu_great_circle_distance(x1, x2, y1, y2):
if x1 == x2 and y1 == y2:
return 0.0
lat1 = y1 * 0.017453292519943295
lon1 = x1 * 0.017453292519943295
lat2 = y2 * 0.017453292519943295
lon2 = x2 * 0.017453292519943295
dlon = lon2 - lon1
dlat = lat2 - lat1
a = (_math.sin(dlat / 2.0) ** 2
+ _math.cos(lat1) * _math.cos(lat2)
* _math.sin(dlon / 2.0) ** 2)
return 6378137.0 * 2.0 * _math.asin(_math.sqrt(a))
@cuda.jit(device=True)
def _gpu_distance(x1, x2, y1, y2, metric):
if metric == EUCLIDEAN:
return _gpu_euclidean_distance(x1, x2, y1, y2)
elif metric == GREAT_CIRCLE:
return _gpu_great_circle_distance(x1, x2, y1, y2)
else:
return _gpu_manhattan_distance(x1, x2, y1, y2)
@cuda.jit(device=True)
def _gpu_calc_direction(x1, x2, y1, y2):
if x1 == x2 and y1 == y2:
return 0.0
dx = x2 - x1
dy = y2 - y1
d = _math.atan2(-dy, dx) * 57.29578
if d < 0.0:
d = 90.0 - d
elif d > 90.0:
d = 360.0 - d + 90.0
else:
d = 90.0 - d
return d
@cuda.jit
def _proximity_cuda_kernel(target_xs, target_ys, target_vals, n_targets,
y_coords, x_coords, max_distance,
distance_metric, process_mode, out):
iy, ix = cuda.grid(2)
if iy >= out.shape[0] or ix >= out.shape[1]:
return
px = x_coords[ix]
py = y_coords[iy]
best_dist = 1.0e38
best_idx = -1
# Round each candidate distance to float32 before comparing, matching the
# CPU brute-force path where _distance returns np.float32(d). This makes
# both the argmin and the max_distance range test float32 on every
# backend: two targets whose float64 distances differ only past the
# float32 mantissa are a tie, and the strict < keeps the first (lowest
# flat-index) target, the tie-break documented on allocation/direction.
# Comparing float64 here instead let the float64-closer target win on the
# GPU while the CPU called it a tie and picked the lowest index.
for k in range(n_targets):
d = np.float32(_gpu_distance(
px, target_xs[k], py, target_ys[k], distance_metric))
if d < best_dist:
best_dist = d
best_idx = k
if best_idx >= 0 and best_dist <= max_distance:
if process_mode == PROXIMITY:
out[iy, ix] = best_dist
elif process_mode == ALLOCATION:
out[iy, ix] = target_vals[best_idx]
else:
out[iy, ix] = _gpu_calc_direction(
px, target_xs[best_idx], py, target_ys[best_idx])
def _process_cupy(raster_data, x_coords, y_coords, target_values,
max_distance, distance_metric, process_mode):
"""GPU proximity using CUDA brute-force nearest-target kernel."""
import cupy as cp
# Find target pixels on GPU
if len(target_values) == 0:
mask = cp.isfinite(raster_data) & (raster_data != 0)
else:
mask = cp.isin(raster_data, cp.asarray(target_values))
mask &= cp.isfinite(raster_data)
target_rows, target_cols = cp.where(mask)
n_targets = int(target_rows.shape[0])
if n_targets == 0:
return cp.full(raster_data.shape, cp.nan, dtype=cp.float32)
# Collect target world-coordinates and values
y_dev = cp.asarray(y_coords, dtype=cp.float64)
x_dev = cp.asarray(x_coords, dtype=cp.float64)
target_ys = y_dev[target_rows]
target_xs = x_dev[target_cols]
target_vals = raster_data[target_rows, target_cols].astype(cp.float32)
# Pre-fill output with NaN (pixels with no target within range stay NaN)
out = cp.full(raster_data.shape, cp.nan, dtype=cp.float32)
griddim, blockdim = cuda_args(raster_data.shape)
_proximity_cuda_kernel[griddim, blockdim](
target_xs, target_ys, target_vals, n_targets,
y_dev, x_dev,
np.float64(max_distance),
np.int32(distance_metric),
np.int32(process_mode),
out,
)
return out
def _process_dask_cupy(raster, x_coords, y_coords, target_values,
max_distance, distance_metric, process_mode):
"""Dask+CuPy bounded proximity via map_overlap with per-chunk GPU kernel.
Each chunk (plus an overlap padding of ``max_distance`` converted to
pixels using the active distance metric) is processed on GPU
independently. Only valid for finite max_distance
where the padding guarantees all relevant targets are visible within
each overlapped chunk.
"""
import cupy as cp
# Overlap depth in pixels, sized from the densest coordinate spacing and
# measured with the active distance_metric. See _halo_depth.
pad_y, pad_x = _halo_depth(
x_coords, y_coords, max_distance, distance_metric)
# Build 2D coordinate grids as dask+cupy arrays matching raster chunks.
# Each chunk is small (chunk_h x chunk_w x 8 bytes); the full grid is
# never materialised. Chunk the 1D coords to the raster's chunking and
# broadcast: tile/repeat + rechunk built the same grids but cost ~100
# graph tasks per chunk (the repeat term scales with raster height),
# while a chunk-aligned broadcast is ~1 task per chunk (issue #3132).
x_cp = cp.asarray(x_coords, dtype=cp.float64)
y_cp = cp.asarray(y_coords, dtype=cp.float64)
x_da = da.from_array(x_cp, chunks=(raster.data.chunks[1],))
y_da = da.from_array(y_cp, chunks=(raster.data.chunks[0],))
xs = da.broadcast_to(
x_da[None, :], raster.shape, chunks=raster.data.chunks)
ys = da.broadcast_to(
y_da[:, None], raster.shape, chunks=raster.data.chunks)
# Keep the overlap depth within what map_overlap accepts on skinny rasters.
pad_y, pad_x, (raster_data, xs, ys) = _fit_halo_to_chunks(
pad_y, pad_x, raster.data, xs, ys)
# Capture closure vars for the chunk function
tv = target_values
md = max_distance
dm = distance_metric
pm = process_mode
def _chunk_func(data_chunk, xs_chunk, ys_chunk):
# Use middle row/col to avoid NaN from boundary padding
x_1d = xs_chunk[xs_chunk.shape[0] // 2, :]
y_1d = ys_chunk[:, ys_chunk.shape[1] // 2]
return _process_cupy(data_chunk, x_1d, y_1d, tv, md, dm, pm)
return da.map_overlap(
_chunk_func,
raster_data, xs, ys,
depth=(pad_y, pad_x),
boundary=np.nan,
meta=cp.array((), dtype=cp.float32),
**_dask_task_name_kwargs(_PROCESS_MODE_TASK_NAMES[process_mode]),
)
def _inclusive_upper_bound(max_distance):
"""Exclusive cKDTree ``distance_upper_bound`` matching the float32 keep test.
The brute-force and CUDA kernels round each candidate distance to float32
and keep it when ``np.float32(dist) <= max_distance`` (see
``_process_numpy_bruteforce`` and ``_proximity_cuda_kernel``). cKDTree
instead compares *float64* distances against an *exclusive* bound, so to
reproduce the kernels' keep decision the bound has to account for both
differences.
* Float32 rounding: a target whose true float64 distance rounds *down*
across a float32 step to a value ``<= max_distance`` is kept by the
kernels but, against a float64-exact bound, dropped by cKDTree to NaN.
This surfaces when ``max_distance`` sits in the float32 ulp gap just
below a target's distance (issue #3392). The bound is therefore widened
to the midpoint between the largest float32 ``<= max_distance`` and the
next float32 up: the supremum of float64 distances that still round to a
float32 value ``<= max_distance``. Nothing beyond that midpoint is pulled
in, so no target the kernels exclude is admitted.
* Inclusive boundary for ``p=2``: cKDTree compares *squared* distances
internally, and the square of ``nextafter(0.0, inf)`` (the smallest
subnormal) underflows back to 0.0, collapsing the bound to exactly
``max_distance`` and dropping a target sitting on the bound -- most
visibly a target pixel itself at ``max_distance=0``. A relative bump with
an absolute floor stays large enough to survive squaring for ``p=2`` (and
is harmless for ``p=1``). At small ``max_distance`` the float32 midpoint
underflows toward 0, so this floor is what keeps the boundary inclusive.
"""
if not np.isfinite(max_distance):
return np.inf
# Largest float32 value <= max_distance (np.float32 rounds to nearest, so it
# can land just above; step down one float32 ulp when it does).
f = np.float32(max_distance)
if f > max_distance:
f = np.nextafter(f, np.float32(-np.inf))
nf = np.nextafter(f, np.float32(np.inf))
f32_bound = (float(f) + float(nf)) / 2.0
bump = 4.0 * np.finfo(np.float64).eps * max(abs(max_distance), 1.0)
return max(f32_bound, max_distance + bump)
def _process_numpy_kdtree(img, xs, ys, target_values, max_distance, p,
workers=1):
"""Exact nearest-target PROXIMITY on the CPU via scipy's cKDTree.
``workers`` is forwarded to ``cKDTree.query``. The eager numpy backend
passes -1 (all cores) because it runs a single query over the whole
raster; the dask chunk path keeps the default 1 because concurrent
chunks already fill the cores and -1 would oversubscribe them.
Replaces the GDAL-ported 4-pass line-sweep for EUCLIDEAN/MANHATTAN: the
sweep propagated one nearest-target candidate between adjacent pixels,
and on some target layouts that chain never delivers the true nearest
target, overstating the distance by a fraction of a pixel (issue #3121).
This function is also the bounded-dask chunk function. map_overlap pads
edge chunks with NaN (boundary=np.nan) in both the data and the