-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathtest_surface_distance.py
More file actions
923 lines (698 loc) · 32.4 KB
/
Copy pathtest_surface_distance.py
File metadata and controls
923 lines (698 loc) · 32.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
"""Tests for xrspatial.surface_distance."""
import inspect
import numpy as np
import pytest
import xarray as xr
from xrspatial.surface_distance import (
surface_distance, surface_allocation, surface_direction,
)
try:
import dask.array as da
except ImportError:
da = None
try:
import cupy
except ImportError:
cupy = None
from xrspatial.utils import has_cuda_and_cupy, is_cupy_array
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _make_raster(data, backend='numpy', chunks=(3, 3), name='raster',
res=1.0):
"""Build a DataArray with y/x coords, optionally dask/cupy-backed."""
h, w = data.shape
arr = xr.DataArray(
data.astype(np.float64),
dims=['y', 'x'],
coords={'y': np.arange(h, dtype=np.float64),
'x': np.arange(w, dtype=np.float64)},
attrs={'res': (float(res), float(res))},
name=name,
)
if backend == 'dask+numpy':
if da is None:
pytest.skip("dask not installed")
arr.data = da.from_array(arr.data, chunks=chunks)
elif backend == 'cupy':
if not has_cuda_and_cupy():
pytest.skip("cupy/cuda not available")
arr.data = cupy.asarray(arr.data)
elif backend == 'dask+cupy':
if da is None or not has_cuda_and_cupy():
pytest.skip("dask or cupy/cuda not available")
arr.data = da.from_array(cupy.asarray(arr.data), chunks=chunks)
return arr
def _compute(arr):
"""Extract numpy data from any backend."""
d = arr.data
if da is not None and isinstance(d, da.Array):
d = d.compute()
if has_cuda_and_cupy() and is_cupy_array(d):
d = d.get()
return np.asarray(d)
# ---------------------------------------------------------------------------
# Tests — flat terrain (must match Euclidean proximity)
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("backend", ['numpy', 'dask+numpy'])
def test_flat_terrain_matches_cost_distance(backend):
"""On zero-elevation, surface distance equals cost_distance with
friction=1 (both use grid-graph Dijkstra)."""
from xrspatial.cost_distance import cost_distance
source = np.zeros((7, 7), dtype=np.float64)
source[3, 3] = 1.0 # single target at centre
elev = np.zeros((7, 7), dtype=np.float64)
friction = np.ones((7, 7), dtype=np.float64)
raster = _make_raster(source, backend=backend, chunks=(4, 4))
elevation = _make_raster(elev, backend=backend, chunks=(4, 4))
friction_da = _make_raster(friction, backend=backend, chunks=(4, 4))
sd = surface_distance(raster, elevation)
cd = cost_distance(raster, friction_da)
sd_np = _compute(sd)
cd_np = _compute(cd)
np.testing.assert_allclose(sd_np, cd_np, rtol=1e-5, equal_nan=True)
@pytest.mark.parametrize("backend", ['numpy', 'dask+numpy'])
def test_flat_terrain_known_distances(backend):
"""On flat terrain, verify known grid-graph distances."""
source = np.zeros((5, 5), dtype=np.float64)
source[2, 2] = 1.0 # single target at centre
elev = np.zeros((5, 5), dtype=np.float64)
raster = _make_raster(source, backend=backend, chunks=(3, 3))
elevation = _make_raster(elev, backend=backend, chunks=(3, 3))
sd = _compute(surface_distance(raster, elevation))
# Source pixel
assert sd[2, 2] == 0.0
# Cardinal neighbours: distance = 1.0
assert sd[2, 3] == pytest.approx(1.0, abs=1e-5)
assert sd[2, 1] == pytest.approx(1.0, abs=1e-5)
assert sd[1, 2] == pytest.approx(1.0, abs=1e-5)
assert sd[3, 2] == pytest.approx(1.0, abs=1e-5)
# Diagonal neighbours: distance = sqrt(2)
assert sd[1, 1] == pytest.approx(np.sqrt(2), abs=1e-5)
assert sd[1, 3] == pytest.approx(np.sqrt(2), abs=1e-5)
assert sd[3, 1] == pytest.approx(np.sqrt(2), abs=1e-5)
assert sd[3, 3] == pytest.approx(np.sqrt(2), abs=1e-5)
# Two cardinal steps: distance = 2.0
assert sd[0, 2] == pytest.approx(2.0, abs=1e-5)
assert sd[4, 2] == pytest.approx(2.0, abs=1e-5)
assert sd[2, 0] == pytest.approx(2.0, abs=1e-5)
assert sd[2, 4] == pytest.approx(2.0, abs=1e-5)
# ---------------------------------------------------------------------------
# Tests — steep terrain
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("backend", ['numpy', 'dask+numpy'])
def test_steep_terrain_increases_distance(backend):
"""Steep terrain should give longer surface distances than flat."""
source = np.zeros((5, 5), dtype=np.float64)
source[2, 2] = 1.0
flat_elev = np.zeros((5, 5), dtype=np.float64)
steep_elev = np.zeros((5, 5), dtype=np.float64)
# Elevation ramp: 100m per cell in y direction
for r in range(5):
steep_elev[r, :] = r * 100.0
raster = _make_raster(source, backend=backend, chunks=(3, 3))
elev_flat = _make_raster(flat_elev, backend=backend, chunks=(3, 3))
elev_steep = _make_raster(steep_elev, backend=backend, chunks=(3, 3))
sd_flat = _compute(surface_distance(raster, elev_flat))
sd_steep = _compute(surface_distance(raster, elev_steep))
# All non-zero distances should be larger for steep terrain
mask = np.isfinite(sd_flat) & (sd_flat > 0)
assert np.all(sd_steep[mask] >= sd_flat[mask])
# At least some distances should be strictly larger
assert np.any(sd_steep[mask] > sd_flat[mask])
def test_45_degree_slope():
"""A 45-degree slope (dz = cellsize) gives sqrt(2)*cellsize per step."""
source = np.zeros((1, 5), dtype=np.float64)
source[0, 0] = 1.0
# Elevation ramp: 1.0 per cell (with cellsize=1.0, slope=45 deg)
elev = np.array([[0.0, 1.0, 2.0, 3.0, 4.0]])
raster = _make_raster(source, res=1.0)
elevation = _make_raster(elev, res=1.0)
sd = _compute(surface_distance(raster, elevation))
# Each cardinal step: sqrt(1^2 + 1^2) = sqrt(2)
expected = np.array([0.0, np.sqrt(2), 2 * np.sqrt(2),
3 * np.sqrt(2), 4 * np.sqrt(2)], dtype=np.float32)
np.testing.assert_allclose(sd[0], expected, rtol=1e-5)
# ---------------------------------------------------------------------------
# Tests — NaN barriers
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("backend", ['numpy', 'dask+numpy'])
def test_nan_barrier(backend):
"""NaN elevation should block pathfinding."""
source = np.zeros((3, 5), dtype=np.float64)
source[1, 0] = 1.0
elev = np.zeros((3, 5), dtype=np.float64)
# Wall of NaN in column 2
elev[:, 2] = np.nan
raster = _make_raster(source, backend=backend, chunks=(3, 3))
elevation = _make_raster(elev, backend=backend, chunks=(3, 3))
sd = _compute(surface_distance(raster, elevation))
# Columns 0-1 should be reachable
assert np.isfinite(sd[1, 0]) # source
assert np.isfinite(sd[1, 1]) # adjacent
# Column 2 (barrier) should be NaN
assert np.all(np.isnan(sd[:, 2]))
# Columns 3-4 (behind barrier) should be NaN
assert np.all(np.isnan(sd[:, 3:]))
def test_nan_elevation_source_ignored():
"""Source on NaN elevation should not be seeded."""
source = np.array([[1.0, 0.0, 0.0]], dtype=np.float64)
elev = np.array([[np.nan, 0.0, 0.0]], dtype=np.float64)
raster = _make_raster(source)
elevation = _make_raster(elev)
sd = _compute(surface_distance(raster, elevation))
# Source is on NaN elevation, so nothing is reachable
assert np.all(np.isnan(sd))
# ---------------------------------------------------------------------------
# Tests — allocation correctness
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("backend", ['numpy', 'dask+numpy'])
def test_allocation_consistency(backend):
"""Allocation must assign to the nearest target by surface distance."""
source = np.zeros((5, 5), dtype=np.float64)
source[0, 0] = 1.0
source[4, 4] = 2.0
elev = np.zeros((5, 5), dtype=np.float64)
raster = _make_raster(source, backend=backend, chunks=(3, 3))
elevation = _make_raster(elev, backend=backend, chunks=(3, 3))
sd = _compute(surface_distance(raster, elevation))
sa = _compute(surface_allocation(raster, elevation))
# Source pixels should have alloc = their own value
assert sa[0, 0] == 1.0
assert sa[4, 4] == 2.0
# The centre pixel should be allocated to whichever source is closer
# Both are equidistant on flat terrain, so either 1 or 2 is acceptable
assert sa[2, 2] in (1.0, 2.0)
# Near source 1 should be allocated to source 1
assert sa[0, 1] == 1.0
assert sa[1, 0] == 1.0
# Near source 2 should be allocated to source 2
assert sa[4, 3] == 2.0
assert sa[3, 4] == 2.0
# ---------------------------------------------------------------------------
# Tests — direction correctness
# ---------------------------------------------------------------------------
def test_direction_source_is_zero():
"""Source pixel direction should be 0."""
source = np.zeros((3, 3), dtype=np.float64)
source[1, 1] = 1.0
elev = np.zeros((3, 3), dtype=np.float64)
raster = _make_raster(source)
elevation = _make_raster(elev)
sd_dir = _compute(surface_direction(raster, elevation))
assert sd_dir[1, 1] == 0.0
def test_direction_cardinal_points():
"""Check compass directions for 4 cardinal neighbours of a source."""
source = np.zeros((3, 3), dtype=np.float64)
source[1, 1] = 1.0
elev = np.zeros((3, 3), dtype=np.float64)
raster = _make_raster(source)
elevation = _make_raster(elev)
sd_dir = _compute(surface_direction(raster, elevation))
# East of source (1, 2): direction should point west-ish (toward source)
# Source is at x=1, pixel is at x=2. Direction from pixel to source
# is toward west = 270
assert sd_dir[1, 2] == pytest.approx(270.0, abs=1.0)
# West of source (1, 0): direction should point east = 90
assert sd_dir[1, 0] == pytest.approx(90.0, abs=1.0)
# North of source (0, 1) with y increasing downward (row 0 = y=0):
# Source at row 1, pixel at row 0.
# dy = (src_row - pixel_row) * cellsize_y = (1 - 0) * 1 = 1 (south)
# Direction to source is south = 180
assert sd_dir[0, 1] == pytest.approx(180.0, abs=1.0)
# South of source (2, 1): direction to source is north = 360
assert sd_dir[2, 1] == pytest.approx(360.0, abs=1.0)
# ---------------------------------------------------------------------------
# Tests — max_distance clipping
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("backend", ['numpy', 'dask+numpy'])
def test_max_distance_clipping(backend):
"""Pixels beyond max_distance should be NaN."""
source = np.zeros((5, 5), dtype=np.float64)
source[2, 2] = 1.0
elev = np.zeros((5, 5), dtype=np.float64)
raster = _make_raster(source, backend=backend, chunks=(3, 3))
elevation = _make_raster(elev, backend=backend, chunks=(3, 3))
sd = _compute(surface_distance(raster, elevation, max_distance=1.5))
# Source and immediate cardinal neighbours should be within 1.5
assert sd[2, 2] == 0.0
assert np.isfinite(sd[2, 3]) # distance 1.0
assert np.isfinite(sd[2, 1]) # distance 1.0
assert np.isfinite(sd[1, 2]) # distance 1.0
assert np.isfinite(sd[3, 2]) # distance 1.0
# Diagonal neighbours are sqrt(2) ≈ 1.414, still within 1.5
assert np.isfinite(sd[1, 1])
# Two steps away (distance 2.0) should be clipped
assert np.isnan(sd[0, 2])
assert np.isnan(sd[2, 0])
assert np.isnan(sd[4, 2])
assert np.isnan(sd[2, 4])
# ---------------------------------------------------------------------------
# Tests — target_values filtering
# ---------------------------------------------------------------------------
def test_target_values():
"""Only specified target values should be used as sources."""
source = np.array([
[0.0, 1.0, 0.0, 2.0, 0.0],
], dtype=np.float64)
elev = np.zeros((1, 5), dtype=np.float64)
raster = _make_raster(source)
elevation = _make_raster(elev)
# Only use value 2 as target
sd = _compute(surface_distance(raster, elevation, target_values=[2]))
# Pixel at col 3 (value 2) should be 0
assert sd[0, 3] == 0.0
# Pixel at col 1 (value 1) should NOT be 0 (not a target)
assert sd[0, 1] > 0.0
# Distance from col 1 to col 3 = 2.0
assert sd[0, 1] == pytest.approx(2.0, abs=1e-5)
# ---------------------------------------------------------------------------
# Tests — connectivity
# ---------------------------------------------------------------------------
def test_connectivity_4_vs_8():
"""4-connectivity should give longer diagonal distances than 8."""
source = np.zeros((5, 5), dtype=np.float64)
source[0, 0] = 1.0
elev = np.zeros((5, 5), dtype=np.float64)
raster = _make_raster(source)
elevation = _make_raster(elev)
sd_8 = _compute(surface_distance(raster, elevation, connectivity=8))
sd_4 = _compute(surface_distance(raster, elevation, connectivity=4))
# With 4-conn, diagonal pixel (1,1) needs 2 steps = 2.0
# With 8-conn, diagonal pixel (1,1) needs 1 step = sqrt(2)
assert sd_4[1, 1] == pytest.approx(2.0, abs=1e-5)
assert sd_8[1, 1] == pytest.approx(np.sqrt(2), abs=1e-5)
# ---------------------------------------------------------------------------
# Tests — validation
# ---------------------------------------------------------------------------
def test_invalid_connectivity():
source = _make_raster(np.zeros((3, 3)))
elev = _make_raster(np.zeros((3, 3)))
with pytest.raises(ValueError, match="connectivity"):
surface_distance(source, elev, connectivity=6)
def test_shape_mismatch():
source = _make_raster(np.zeros((3, 3)))
elev = _make_raster(np.zeros((4, 4)))
with pytest.raises(ValueError, match="same shape"):
surface_distance(source, elev)
def test_invalid_method():
source = _make_raster(np.zeros((3, 3)))
elev = _make_raster(np.zeros((3, 3)))
with pytest.raises(ValueError, match="method"):
surface_distance(source, elev, method='fast')
# ---------------------------------------------------------------------------
# Tests — dask-specific
# ---------------------------------------------------------------------------
@pytest.mark.skipif(da is None, reason="dask not installed")
def test_dask_matches_numpy():
"""Dask+numpy result must match numpy baseline."""
source = np.zeros((8, 10), dtype=np.float64)
source[2, 3] = 1.0
source[6, 7] = 2.0
elev = np.random.default_rng(42).uniform(0, 100, (8, 10))
raster_np = _make_raster(source, backend='numpy')
elev_np = _make_raster(elev, backend='numpy')
raster_dask = _make_raster(source, backend='dask+numpy', chunks=(4, 5))
elev_dask = _make_raster(elev, backend='dask+numpy', chunks=(4, 5))
np_result = _compute(surface_distance(raster_np, elev_np,
max_distance=15.0))
dask_result = _compute(surface_distance(raster_dask, elev_dask,
max_distance=15.0))
np.testing.assert_allclose(dask_result, np_result, rtol=1e-5,
equal_nan=True)
@pytest.mark.skipif(da is None, reason="dask not installed")
def test_dask_allocation_matches_numpy():
"""Dask+numpy allocation must match numpy baseline."""
source = np.zeros((8, 10), dtype=np.float64)
source[2, 3] = 1.0
source[6, 7] = 2.0
elev = np.random.default_rng(42).uniform(0, 100, (8, 10))
raster_np = _make_raster(source, backend='numpy')
elev_np = _make_raster(elev, backend='numpy')
raster_dask = _make_raster(source, backend='dask+numpy', chunks=(4, 5))
elev_dask = _make_raster(elev, backend='dask+numpy', chunks=(4, 5))
np_result = _compute(surface_allocation(raster_np, elev_np,
max_distance=15.0))
dask_result = _compute(surface_allocation(raster_dask, elev_dask,
max_distance=15.0))
np.testing.assert_allclose(dask_result, np_result, rtol=1e-5,
equal_nan=True)
@pytest.mark.skipif(da is None, reason="dask not installed")
def test_iterative_matches_numpy():
"""Dask iterative (unbounded) result must match numpy."""
source = np.zeros((8, 10), dtype=np.float64)
source[2, 3] = 1.0
source[6, 7] = 2.0
rng = np.random.default_rng(42)
elev = rng.uniform(0, 50, (8, 10))
raster_np = _make_raster(source, backend='numpy')
elev_np = _make_raster(elev, backend='numpy')
raster_dask = _make_raster(source, backend='dask+numpy', chunks=(4, 5))
elev_dask = _make_raster(elev, backend='dask+numpy', chunks=(4, 5))
np_result = _compute(surface_distance(raster_np, elev_np))
with pytest.warns(UserWarning, match="iterative"):
dask_result = _compute(surface_distance(raster_dask, elev_dask))
np.testing.assert_allclose(dask_result, np_result, rtol=1e-4,
equal_nan=True)
@pytest.mark.skipif(da is None, reason="dask not installed")
def test_iterative_allocation_matches_numpy():
"""Dask iterative allocation must match numpy."""
source = np.zeros((8, 10), dtype=np.float64)
source[2, 3] = 1.0
source[6, 7] = 2.0
rng = np.random.default_rng(42)
elev = rng.uniform(0, 50, (8, 10))
raster_np = _make_raster(source, backend='numpy')
elev_np = _make_raster(elev, backend='numpy')
raster_dask = _make_raster(source, backend='dask+numpy', chunks=(4, 5))
elev_dask = _make_raster(elev, backend='dask+numpy', chunks=(4, 5))
np_result = _compute(surface_allocation(raster_np, elev_np))
with pytest.warns(UserWarning, match="iterative"):
dask_result = _compute(surface_allocation(raster_dask, elev_dask))
np.testing.assert_allclose(dask_result, np_result, rtol=1e-4,
equal_nan=True)
@pytest.mark.skipif(da is None, reason="dask not installed")
def test_dask_returns_dask_array():
"""Result should be a dask array when input is dask."""
source = np.zeros((5, 5), dtype=np.float64)
source[2, 2] = 1.0
elev = np.zeros((5, 5), dtype=np.float64)
raster = _make_raster(source, backend='dask+numpy', chunks=(3, 3))
elevation = _make_raster(elev, backend='dask+numpy', chunks=(3, 3))
sd = surface_distance(raster, elevation, max_distance=5.0)
assert isinstance(sd.data, da.Array)
# ---------------------------------------------------------------------------
# Tests — CuPy-specific (skipped if not available)
# ---------------------------------------------------------------------------
@pytest.mark.skipif(not has_cuda_and_cupy(), reason="cupy/cuda not available")
def test_cupy_matches_numpy():
"""CuPy result must match numpy baseline."""
source = np.zeros((8, 10), dtype=np.float64)
source[2, 3] = 1.0
source[6, 7] = 2.0
rng = np.random.default_rng(42)
elev = rng.uniform(0, 100, (8, 10))
raster_np = _make_raster(source, backend='numpy')
elev_np = _make_raster(elev, backend='numpy')
raster_cp = _make_raster(source, backend='cupy')
elev_cp = _make_raster(elev, backend='cupy')
np_result = _compute(surface_distance(raster_np, elev_np))
cp_result = _compute(surface_distance(raster_cp, elev_cp))
np.testing.assert_allclose(cp_result, np_result, rtol=1e-5,
equal_nan=True)
@pytest.mark.skipif(not has_cuda_and_cupy(), reason="cupy/cuda not available")
def test_cupy_returns_cupy_array():
"""CuPy input should produce CuPy output."""
source = np.zeros((5, 5), dtype=np.float64)
source[2, 2] = 1.0
elev = np.zeros((5, 5), dtype=np.float64)
raster = _make_raster(source, backend='cupy')
elevation = _make_raster(elev, backend='cupy')
sd = surface_distance(raster, elevation)
assert is_cupy_array(sd.data)
@pytest.mark.skipif(not has_cuda_and_cupy(), reason="cupy/cuda not available")
def test_cupy_allocation_matches_numpy():
"""CuPy allocation must match numpy baseline."""
source = np.zeros((8, 10), dtype=np.float64)
source[2, 3] = 1.0
source[6, 7] = 2.0
rng = np.random.default_rng(42)
elev = rng.uniform(0, 100, (8, 10))
raster_np = _make_raster(source, backend='numpy')
elev_np = _make_raster(elev, backend='numpy')
raster_cp = _make_raster(source, backend='cupy')
elev_cp = _make_raster(elev, backend='cupy')
np_result = _compute(surface_allocation(raster_np, elev_np))
cp_result = _compute(surface_allocation(raster_cp, elev_cp))
np.testing.assert_allclose(cp_result, np_result, rtol=1e-5,
equal_nan=True)
# ---------------------------------------------------------------------------
# Tests — multiple sources
# ---------------------------------------------------------------------------
def test_multiple_sources_nearest_wins():
"""Each pixel should be assigned to its nearest source."""
source = np.zeros((1, 7), dtype=np.float64)
source[0, 0] = 1.0
source[0, 6] = 2.0
elev = np.zeros((1, 7), dtype=np.float64)
raster = _make_raster(source)
elevation = _make_raster(elev)
sd = _compute(surface_distance(raster, elevation))
sa = _compute(surface_allocation(raster, elevation))
# Pixel 0: dist 0 from source 1
assert sd[0, 0] == 0.0
assert sa[0, 0] == 1.0
# Pixel 6: dist 0 from source 2
assert sd[0, 6] == 0.0
assert sa[0, 6] == 2.0
# Pixel 3: equidistant (dist 3 from both)
assert sd[0, 3] == pytest.approx(3.0, abs=1e-5)
# Pixels 1, 2 closer to source 1
assert sa[0, 1] == 1.0
assert sa[0, 2] == 1.0
# Pixels 4, 5 closer to source 2
assert sa[0, 4] == 2.0
assert sa[0, 5] == 2.0
# ---------------------------------------------------------------------------
# Tests — no sources
# ---------------------------------------------------------------------------
def test_no_sources_all_nan():
"""When there are no sources, all outputs should be NaN."""
source = np.zeros((3, 3), dtype=np.float64)
elev = np.zeros((3, 3), dtype=np.float64)
raster = _make_raster(source)
elevation = _make_raster(elev)
sd = _compute(surface_distance(raster, elevation))
sa = _compute(surface_allocation(raster, elevation))
sd_dir = _compute(surface_direction(raster, elevation))
assert np.all(np.isnan(sd))
assert np.all(np.isnan(sa))
assert np.all(np.isnan(sd_dir))
# ---------------------------------------------------------------------------
# Tests — geodesic mode (numpy only)
# ---------------------------------------------------------------------------
def test_geodesic_basic():
"""Basic geodesic test: horizontal distances should be in meters."""
# Small grid centred at equator
source = np.zeros((3, 3), dtype=np.float64)
source[1, 1] = 1.0
elev = np.zeros((3, 3), dtype=np.float64)
h, w = source.shape
lat = np.array([1.0, 0.0, -1.0]) # degrees
lon = np.array([-1.0, 0.0, 1.0])
raster = xr.DataArray(
source,
dims=['y', 'x'],
coords={'y': lat, 'x': lon},
)
elevation = xr.DataArray(
elev,
dims=['y', 'x'],
coords={'y': lat, 'x': lon},
)
sd = _compute(surface_distance(raster, elevation, method='geodesic'))
# Source pixel should be 0
assert sd[1, 1] == 0.0
# Cardinal neighbours should be ~111 km (1 degree at equator)
for pos in [(0, 1), (2, 1), (1, 0), (1, 2)]:
assert 100000 < sd[pos] < 130000 # roughly 100-130 km
# ---------------------------------------------------------------------------
# Memory guard
# ---------------------------------------------------------------------------
class TestMemoryGuard:
"""Memory guard on the eager numpy / cupy backends."""
def test_numpy_huge_raster_raises(self):
"""Numpy backend raises MemoryError when projected RAM exceeds budget."""
from unittest.mock import patch
source = np.zeros((4, 4), dtype=np.float64)
source[1, 1] = 1.0
elev = np.zeros((4, 4), dtype=np.float64)
raster = _make_raster(source)
elevation = _make_raster(elev)
# Mock available memory to 1 byte so even a 4x4 raster trips it.
with patch(
"xrspatial.surface_distance._available_memory_bytes",
return_value=1,
):
with pytest.raises(MemoryError, match="working memory"):
surface_distance(raster, elevation)
with pytest.raises(MemoryError, match="working memory"):
surface_allocation(raster, elevation)
with pytest.raises(MemoryError, match="working memory"):
surface_direction(raster, elevation)
def test_numpy_normal_input_succeeds(self):
"""Normal-size raster passes the guard with real memory."""
source = np.zeros((10, 10), dtype=np.float64)
source[5, 5] = 1.0
elev = np.zeros((10, 10), dtype=np.float64)
raster = _make_raster(source)
elevation = _make_raster(elev)
# Should not raise -- 10x10 needs ~8 KB.
result = surface_distance(raster, elevation)
assert result.shape == (10, 10)
def test_validation_error_takes_precedence(self):
"""Invalid args raise ValueError before the memory guard runs."""
from unittest.mock import patch
source = np.zeros((4, 4), dtype=np.float64)
elev_wrong = np.zeros((5, 5), dtype=np.float64)
raster = _make_raster(source)
elevation = xr.DataArray(
elev_wrong,
dims=['y', 'x'],
coords={'y': np.arange(5, dtype=np.float64),
'x': np.arange(5, dtype=np.float64)},
attrs={'res': (1.0, 1.0)},
)
with patch(
"xrspatial.surface_distance._available_memory_bytes",
return_value=1,
):
# Mismatched shapes raise ValueError before any allocation.
with pytest.raises(ValueError, match="same shape"):
surface_distance(raster, elevation)
# Invalid connectivity raises ValueError too.
elev_ok = _make_raster(np.zeros((4, 4), dtype=np.float64))
with pytest.raises(ValueError, match="connectivity"):
surface_distance(raster, elev_ok, connectivity=5)
def test_dask_path_bounded_per_chunk(self):
"""Dask backend inherits the guard per-chunk (not on the full shape).
A dask raster whose total footprint would trip the guard but whose
per-chunk footprint fits comfortably should compute successfully.
"""
if da is None:
pytest.skip("dask not installed")
from unittest.mock import patch
# 200x200 total (~6.4 MB at 80 B/pixel) chunked at 20x20
# (~32 KB per chunk). Mock available memory to 1 MB: the full
# array would exceed 50% of that, but each 20x20 chunk needs
# only ~32 KB so per-chunk allocation passes.
source = np.zeros((200, 200), dtype=np.float64)
source[100, 100] = 1.0
elev = np.zeros((200, 200), dtype=np.float64)
raster = _make_raster(source, backend='dask+numpy', chunks=(20, 20))
elevation = _make_raster(elev, backend='dask+numpy', chunks=(20, 20))
with patch(
"xrspatial.surface_distance._available_memory_bytes",
return_value=1024 * 1024, # 1 MB
):
# max_distance=5 keeps map_overlap depth small (< chunk size).
result = surface_distance(raster, elevation, max_distance=5.0)
# Force a small compute window to prove per-chunk passes.
_ = result.data[:4, :4].compute()
def test_error_message_mentions_grid_size(self):
"""The error message names the grid dimensions and the dask alternative."""
from unittest.mock import patch
source = np.zeros((7, 11), dtype=np.float64)
source[3, 5] = 1.0
elev = np.zeros((7, 11), dtype=np.float64)
raster = _make_raster(source)
elevation = _make_raster(elev)
with patch(
"xrspatial.surface_distance._available_memory_bytes",
return_value=1,
):
with pytest.raises(MemoryError, match="7x11"):
surface_distance(raster, elevation)
with pytest.raises(MemoryError, match="dask"):
surface_distance(raster, elevation)
# ---------------------------------------------------------------------------
# Tests — docstring contract
# ---------------------------------------------------------------------------
_PUBLIC = [surface_distance, surface_allocation, surface_direction]
def _flat_doc(func):
"""Docstring with line wrapping collapsed, so pinned phrases survive."""
return " ".join(inspect.getdoc(func).split())
@pytest.mark.parametrize("func", _PUBLIC)
def test_docstring_has_examples_section(func):
"""Every public surface-distance function ships a runnable example."""
doc = inspect.getdoc(func)
assert any(ln.strip() == "Examples" for ln in doc.splitlines()), (
f"{func.__name__} docstring has no Examples section"
)
assert ">>>" in doc, f"{func.__name__} Examples section has no code"
# Three dots renders as literal text instead of a code block.
assert "... sourcecode::" not in doc
@pytest.mark.parametrize("func", _PUBLIC)
def test_docstring_states_all_backends(func):
"""All three functions dispatch to numpy, cupy, dask+numpy, dask+cupy.
The docstrings named no backend at all, leaving users to guess. Pin the
phrases so the claim cannot silently disappear; reword the assertions,
not the docs, if the wording is revised while staying accurate.
"""
doc = _flat_doc(func)
assert "CuPy" in doc
assert "Dask with NumPy" in doc
assert "Dask with CuPy" in doc
@pytest.mark.parametrize("func", _PUBLIC)
def test_docstring_notes_geodesic_is_numpy_only(func):
"""geodesic raises NotImplementedError on every non-numpy backend."""
doc = _flat_doc(func)
assert "NumPy-backed input only" in doc or (
"requires a NumPy-backed DataArray" in doc
)
def test_geodesic_rejects_dask():
"""The documented geodesic limitation matches what the code does."""
if da is None:
pytest.skip("dask not installed")
source = np.zeros((4, 4), dtype=np.float64)
source[1, 1] = 1.0
elev = np.zeros((4, 4), dtype=np.float64)
raster = _make_raster(source, backend='dask+numpy', chunks=(2, 2))
elevation = _make_raster(elev, backend='dask+numpy', chunks=(2, 2))
with pytest.raises(NotImplementedError, match="geodesic"):
surface_distance(raster, elevation, method='geodesic')
def _docstring_example_rasters(source, elevation):
"""Build the y-descending DataArrays used by the Examples blocks."""
n, m = source.shape
raster = xr.DataArray(source, dims=['y', 'x'], name='raster')
raster['y'] = np.arange(n)[::-1]
raster['x'] = np.arange(m)
elev = xr.DataArray(elevation, dims=['y', 'x'], name='elevation')
elev['y'] = np.arange(n)[::-1]
elev['x'] = np.arange(m)
return raster, elev
_PEAK_ELEVATION = np.array([
[0., 0., 0.],
[0., 3., 0.],
[0., 0., 0.],
])
@pytest.mark.parametrize("func, source, expected", [
(
surface_distance,
np.array([[1., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]]),
np.array([[0., 1., 2.],
[1., 3.3166249, 2.4142137],
[2., 2.4142137, 3.4142137]], dtype=np.float32),
),
(
surface_allocation,
np.array([[1., 0., 0.],
[0., 0., 0.],
[0., 2., 0.]]),
np.array([[1., 1., 1.],
[1., 2., 2.],
[2., 2., 2.]], dtype=np.float32),
),
])
def test_docstring_example_matches_output(func, source, expected):
"""The pinned output in each Examples block is what the code returns."""
raster, elev = _docstring_example_rasters(source, _PEAK_ELEVATION)
result = func(raster, elev)
assert result.dtype == np.float32
np.testing.assert_allclose(result.values, expected, rtol=1e-6)
def test_direction_docstring_example_matches_output():
"""surface_direction()'s pinned Examples output, on the numpy backend."""
source = np.array([
[0., 0., 0.],
[0., 1., 0.],
[0., 0., 0.],
])
raster, elev = _docstring_example_rasters(source, np.zeros((3, 3)))
expected = np.array([[135., 180., 225.],
[90., 0., 270.],
[45., 360., 315.]], dtype=np.float32)
result = surface_direction(raster, elev)
assert result.dtype == np.float32
np.testing.assert_allclose(result.values, expected, rtol=1e-6)