-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathtest_rasterize.py
More file actions
1813 lines (1567 loc) · 74.3 KB
/
Copy pathtest_rasterize.py
File metadata and controls
1813 lines (1567 loc) · 74.3 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
"""Tests for xrspatial.rasterize (vector geometry rasterization)."""
import numpy as np
import pytest
import xarray as xr
try:
from shapely.geometry import (
box, Polygon, MultiPolygon, Point, MultiPoint,
LineString, MultiLineString,
)
has_shapely = True
except ImportError:
has_shapely = False
# Guard the rasterize import too -- it imports numba.cuda at module level
# which is fine, but the tests all need shapely anyway.
if has_shapely:
from xrspatial.rasterize import rasterize
pytestmark = pytest.mark.skipif(
not has_shapely, reason="shapely not installed"
)
# Try importing optional GPU dependencies
try:
import cupy
has_cupy = True
except ImportError:
has_cupy = False
try:
import geopandas as gpd
has_geopandas = True
except ImportError:
has_geopandas = False
try:
import dask.array as da
has_dask = True
except ImportError:
has_dask = False
try:
import dask_geopandas
has_dask_geopandas = True
except ImportError:
has_dask_geopandas = False
try:
from numba import cuda
has_cuda = has_cupy and cuda.is_available()
except Exception:
has_cuda = False
skip_no_geopandas = pytest.mark.skipif(
not has_geopandas, reason="geopandas not installed")
skip_no_cuda = pytest.mark.skipif(
not has_cuda, reason="CUDA / CuPy not available")
skip_no_dask = pytest.mark.skipif(
not has_dask, reason="dask not installed")
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def simple_gdf():
"""GeoDataFrame with a single square polygon."""
gdf = gpd.GeoDataFrame(
{'value': [5.0]},
geometry=[box(2, 2, 8, 8)],
)
return gdf
@pytest.fixture
def two_polygon_gdf():
"""GeoDataFrame with two non-overlapping rectangles."""
gdf = gpd.GeoDataFrame(
{'value': [1.0, 2.0]},
geometry=[box(0, 0, 4, 4), box(6, 6, 10, 10)],
)
return gdf
@pytest.fixture
def overlapping_gdf():
"""GeoDataFrame with two overlapping squares."""
gdf = gpd.GeoDataFrame(
{'value': [1.0, 2.0]},
geometry=[box(0, 0, 6, 6), box(4, 4, 10, 10)],
)
return gdf
# ---------------------------------------------------------------------------
# Basic correctness
# ---------------------------------------------------------------------------
@skip_no_geopandas
class TestBasic:
def test_output_shape(self, simple_gdf):
result = rasterize(simple_gdf, width=20, height=15, column='value')
assert result.shape == (15, 20)
assert result.dims == ('y', 'x')
def test_output_name(self, simple_gdf):
result = rasterize(simple_gdf, width=10, height=10, column='value',
name='burned')
assert result.name == 'burned'
def test_dtype(self, simple_gdf):
result = rasterize(simple_gdf, width=10, height=10, column='value',
dtype=np.float32)
assert result.dtype == np.float32
def test_fill_value(self, simple_gdf):
result = rasterize(simple_gdf, width=100, height=100,
bounds=(0, 0, 10, 10), column='value', fill=-999)
# Corners should be fill value (polygon is at 2-8, 2-8)
assert result.values[0, 0] == -999
def test_coords_match_bounds(self, simple_gdf):
result = rasterize(simple_gdf, width=10, height=10,
bounds=(0, 0, 10, 10), column='value')
# Pixel centers should be at 0.5, 1.5, ..., 9.5
np.testing.assert_allclose(result.x.values,
np.arange(0.5, 10, 1.0))
# y goes top to bottom: 9.5, 8.5, ..., 0.5
np.testing.assert_allclose(result.y.values,
np.arange(9.5, -0.5, -1.0))
def test_single_polygon_burns_interior(self, simple_gdf):
result = rasterize(simple_gdf, width=10, height=10,
bounds=(0, 0, 10, 10), column='value')
# Center pixel (row 5, col 5) is inside the polygon
# The polygon spans x=[2,8], y=[2,8] so pixel centers 2.5-7.5
# are inside in both dims
center = result.values[5, 5] # y=4.5, x=5.5
assert center == 5.0
def test_nan_fill_outside(self, simple_gdf):
result = rasterize(simple_gdf, width=10, height=10,
bounds=(0, 0, 10, 10), column='value')
# Corner pixel at (row=0, col=0) -> y=9.5, x=0.5 -> outside
assert np.isnan(result.values[0, 0])
# ---------------------------------------------------------------------------
# Multiple / overlapping polygons
# ---------------------------------------------------------------------------
@skip_no_geopandas
class TestMultiplePolygons:
def test_two_separate_polygons(self, two_polygon_gdf):
result = rasterize(two_polygon_gdf, width=10, height=10,
bounds=(0, 0, 10, 10), column='value')
# Bottom-left region (low x, low y -> high row index)
# box(0,0,4,4): pixel centers 0.5-3.5 in x, 0.5-3.5 in y
# y=0.5 is row 9, x=0.5 is col 0
assert result.values[9, 0] == 1.0 # inside first polygon
# Top-right region
# box(6,6,10,10): pixel centers 6.5-9.5 in x, 6.5-9.5 in y
# y=9.5 is row 0, x=9.5 is col 9
assert result.values[0, 9] == 2.0 # inside second polygon
def test_overlapping_last_writer_wins(self, overlapping_gdf):
result = rasterize(overlapping_gdf, width=10, height=10,
bounds=(0, 0, 10, 10), column='value')
# Overlap region: x=[4,6], y=[4,6] -> pixel centers 4.5, 5.5
# y=4.5 -> row 5, x=4.5 -> col 4
overlap_val = result.values[5, 4]
# Second polygon (value=2.0) should win in overlap zone
assert overlap_val == 2.0
# ---------------------------------------------------------------------------
# MultiPolygon support
# ---------------------------------------------------------------------------
@skip_no_geopandas
class TestMultiPolygon:
def test_multipolygon(self):
mp = MultiPolygon([box(0, 0, 3, 3), box(7, 7, 10, 10)])
gdf = gpd.GeoDataFrame(
{'value': [42.0]},
geometry=[mp],
)
result = rasterize(gdf, width=10, height=10,
bounds=(0, 0, 10, 10), column='value')
# Both sub-polygons should be filled
assert result.values[9, 0] == 42.0 # y=0.5, x=0.5 -> first box
assert result.values[0, 9] == 42.0 # y=9.5, x=9.5 -> second box
# ---------------------------------------------------------------------------
# List-of-pairs input
# ---------------------------------------------------------------------------
class TestListInput:
def test_list_of_pairs(self):
geom = box(1, 1, 4, 4)
result = rasterize([(geom, 7.0)], width=5, height=5,
bounds=(0, 0, 5, 5))
# Center pixel (row=2, col=2) -> y=2.5, x=2.5 -> inside
assert result.values[2, 2] == 7.0
def test_empty_list(self):
result = rasterize([], width=5, height=5, bounds=(0, 0, 5, 5))
assert result.shape == (5, 5)
assert np.all(np.isnan(result.values))
# ---------------------------------------------------------------------------
# Edge cases
# ---------------------------------------------------------------------------
@skip_no_geopandas
class TestEdgeCases:
def test_single_row_raster(self):
gdf = gpd.GeoDataFrame(
{'value': [1.0]},
geometry=[box(0, 0, 10, 2)],
)
result = rasterize(gdf, width=10, height=1,
bounds=(0, 0, 10, 2), column='value')
assert result.shape == (1, 10)
assert np.all(result.values == 1.0)
def test_single_column_raster(self):
gdf = gpd.GeoDataFrame(
{'value': [1.0]},
geometry=[box(0, 0, 2, 10)],
)
result = rasterize(gdf, width=1, height=10,
bounds=(0, 0, 2, 10), column='value')
assert result.shape == (10, 1)
assert np.all(result.values == 1.0)
def test_polygon_outside_bounds(self):
gdf = gpd.GeoDataFrame(
{'value': [1.0]},
geometry=[box(20, 20, 30, 30)],
)
result = rasterize(gdf, width=10, height=10,
bounds=(0, 0, 10, 10), column='value')
assert np.all(np.isnan(result.values))
def test_polygon_with_hole(self):
exterior = [(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)]
hole = [(3, 3), (3, 7), (7, 7), (7, 3), (3, 3)]
poly = Polygon(exterior, [hole])
result = rasterize([(poly, 1.0)], width=10, height=10,
bounds=(0, 0, 10, 10))
# Center (inside hole) should be NaN
assert np.isnan(result.values[5, 5])
# Corner (inside polygon) should be 1.0
assert result.values[9, 0] == 1.0
def test_empty_geometry_skipped(self):
from shapely.geometry import Point
empty = Point().buffer(0) # empty polygon
real = box(1, 1, 4, 4)
result = rasterize([(empty, 99.0), (real, 1.0)],
width=5, height=5, bounds=(0, 0, 5, 5))
assert result.values[2, 2] == 1.0
def test_unsupported_geom_type_skipped(self):
from shapely.geometry import GeometryCollection
gc = GeometryCollection()
result = rasterize([(gc, 99.0)], width=5, height=5,
bounds=(0, 0, 5, 5))
# Empty GeometryCollections are skipped
assert np.all(np.isnan(result.values))
# ---------------------------------------------------------------------------
# Validation
# ---------------------------------------------------------------------------
class TestValidation:
def test_invalid_dimensions(self):
with pytest.raises(ValueError, match="width and height must be >= 1"):
rasterize([], width=0, height=10, bounds=(0, 0, 10, 10))
def test_invalid_bounds(self):
with pytest.raises(ValueError, match="Invalid bounds"):
rasterize([(box(0, 0, 1, 1), 1.0)], width=10, height=10,
bounds=(10, 10, 0, 0))
def test_no_bounds_no_geom(self):
with pytest.raises(ValueError, match="bounds must be provided"):
rasterize([], width=10, height=10)
def test_oversize_explicit_dimensions_rejected(self):
# width * height = 4e18, far above the 1e9 default cap. Must
# raise before any np.full allocation runs.
with pytest.raises(ValueError, match="exceed the safety limit"):
rasterize([(box(0, 0, 1, 1), 1.0)],
width=2_000_000_000, height=2_000_000_000,
bounds=(0, 0, 1, 1))
def test_oversize_resolution_rejected(self):
# resolution=1e-6 with 10x10 bounds resolves to 10M x 10M =
# 1e14 pixels, well above the default cap.
with pytest.raises(ValueError, match="exceed the safety limit"):
rasterize([(box(0, 0, 1, 1), 1.0)],
resolution=1e-6, bounds=(0, 0, 10, 10))
def test_moderate_oversize_explicit_rejected(self):
# Realistic attack: ~2e9 pixels = ~16 GB float64 + 2 GB int8.
# Still above the default cap, still rejected.
with pytest.raises(ValueError, match="exceed the safety limit"):
rasterize([(box(0, 0, 1, 1), 1.0)],
width=50_000, height=50_000,
bounds=(0, 0, 1, 1))
def test_max_pixels_override_permits_larger(self):
# A caller who genuinely needs a >1e9-pixel raster can raise the
# cap explicitly. Use a moderate size that actually allocates.
result = rasterize(
[(box(0, 0, 1, 1), 1.0)],
width=2000, height=2000, bounds=(0, 0, 1, 1),
max_pixels=10_000_000,
)
assert result.shape == (2000, 2000)
def test_max_pixels_at_boundary_permitted(self):
# width * height == max_pixels must pass (strict >).
result = rasterize(
[(box(0, 0, 1, 1), 1.0)],
width=100, height=100, bounds=(0, 0, 1, 1),
max_pixels=10_000,
)
assert result.shape == (100, 100)
def test_max_pixels_one_over_rejected(self):
# width * height = 10_001, cap = 10_000 -> reject.
with pytest.raises(ValueError, match="exceed the safety limit"):
rasterize([(box(0, 0, 1, 1), 1.0)],
width=101, height=100, bounds=(0, 0, 1, 1),
max_pixels=10_000)
# ---------------------------------------------------------------------------
# all_touched mode
# ---------------------------------------------------------------------------
class TestAllTouched:
def test_all_touched_fills_more_pixels(self):
# Small polygon that might miss pixel centers
geom = box(2.1, 2.1, 2.9, 2.9)
normal = rasterize([(geom, 1.0)], width=5, height=5,
bounds=(0, 0, 5, 5), all_touched=False)
touched = rasterize([(geom, 1.0)], width=5, height=5,
bounds=(0, 0, 5, 5), all_touched=True)
# all_touched should have >= as many filled pixels
normal_count = np.count_nonzero(~np.isnan(normal.values))
touched_count = np.count_nonzero(~np.isnan(touched.values))
assert touched_count >= normal_count
# ---------------------------------------------------------------------------
# GeoDataFrame column selection
# ---------------------------------------------------------------------------
@skip_no_geopandas
class TestColumnSelection:
def test_explicit_column(self):
gdf = gpd.GeoDataFrame(
{'pop': [100.0], 'area': [50.0]},
geometry=[box(0, 0, 10, 10)],
)
result = rasterize(gdf, width=5, height=5, column='area')
assert np.nanmean(result.values) == 50.0
def test_default_first_numeric_column(self):
gdf = gpd.GeoDataFrame(
{'label': ['a'], 'score': [3.0]},
geometry=[box(0, 0, 10, 10)],
)
result = rasterize(gdf, width=5, height=5)
assert np.nanmean(result.values) == 3.0
def test_no_numeric_column_raises(self):
gdf = gpd.GeoDataFrame(
{'label': ['a']},
geometry=[box(0, 0, 10, 10)],
)
with pytest.raises(ValueError, match="no numeric columns"):
rasterize(gdf, width=5, height=5)
# ---------------------------------------------------------------------------
# Point rasterization
# ---------------------------------------------------------------------------
class TestPoints:
def test_single_point(self):
pt = Point(2.5, 2.5)
result = rasterize([(pt, 7.0)], width=5, height=5,
bounds=(0, 0, 5, 5), fill=0)
# y=2.5 -> row = floor((5 - 2.5) / 1.0) = 2, x=2.5 -> col = 2
assert result.values[2, 2] == 7.0
# Other pixels should be fill
assert result.values[0, 0] == 0
def test_multiple_points(self):
pairs = [
(Point(0.5, 0.5), 1.0),
(Point(4.5, 4.5), 2.0),
]
result = rasterize(pairs, width=5, height=5,
bounds=(0, 0, 5, 5), fill=0)
# Point at (0.5, 0.5): row=4, col=0
assert result.values[4, 0] == 1.0
# Point at (4.5, 4.5): row=0, col=4
assert result.values[0, 4] == 2.0
def test_multipoint(self):
mp = MultiPoint([(1.5, 1.5), (3.5, 3.5)])
result = rasterize([(mp, 5.0)], width=5, height=5,
bounds=(0, 0, 5, 5), fill=0)
# (1.5, 1.5): row=3, col=1
assert result.values[3, 1] == 5.0
# (3.5, 3.5): row=1, col=3
assert result.values[1, 3] == 5.0
def test_point_outside_bounds(self):
pt = Point(20, 20)
result = rasterize([(pt, 1.0)], width=5, height=5,
bounds=(0, 0, 5, 5), fill=0)
assert np.all(result.values == 0)
def test_point_on_boundary(self):
# Point exactly on the right edge (x=5.0) should be outside
# for a bounds of (0, 0, 5, 5) with width=5 (pixels at 0.5..4.5)
pt = Point(5.0, 2.5)
result = rasterize([(pt, 1.0)], width=5, height=5,
bounds=(0, 0, 5, 5), fill=0)
assert np.all(result.values == 0)
def test_overlapping_points_last_wins(self):
pairs = [
(Point(2.5, 2.5), 1.0),
(Point(2.5, 2.5), 9.0),
]
result = rasterize(pairs, width=5, height=5,
bounds=(0, 0, 5, 5), fill=0)
assert result.values[2, 2] == 9.0
# ---------------------------------------------------------------------------
# Line rasterization
# ---------------------------------------------------------------------------
class TestLines:
def test_horizontal_line(self):
line = LineString([(0.5, 2.5), (4.5, 2.5)])
result = rasterize([(line, 3.0)], width=5, height=5,
bounds=(0, 0, 5, 5), fill=0)
# Horizontal line at y=2.5 -> row=2
# Should burn across cols 0..4
for c in range(5):
assert result.values[2, c] == 3.0
def test_vertical_line(self):
line = LineString([(2.5, 0.5), (2.5, 4.5)])
result = rasterize([(line, 4.0)], width=5, height=5,
bounds=(0, 0, 5, 5), fill=0)
# Vertical line at x=2.5 -> col=2
# Should burn across rows 0..4
for r in range(5):
assert result.values[r, 2] == 4.0
def test_diagonal_line(self):
line = LineString([(0.5, 0.5), (4.5, 4.5)])
result = rasterize([(line, 1.0)], width=5, height=5,
bounds=(0, 0, 5, 5), fill=0)
# Diagonal: should hit approximately (row=4,col=0), (3,1), (2,2),
# (1,3), (0,4) via Bresenham
burned = np.sum(result.values == 1.0)
assert burned >= 5
def test_multilinestring(self):
ml = MultiLineString([
[(0.5, 2.5), (4.5, 2.5)], # horizontal
[(2.5, 0.5), (2.5, 4.5)], # vertical
])
result = rasterize([(ml, 1.0)], width=5, height=5,
bounds=(0, 0, 5, 5), fill=0)
# Cross pattern: row 2 all filled, col 2 all filled
for c in range(5):
assert result.values[2, c] == 1.0
for r in range(5):
assert result.values[r, 2] == 1.0
def test_line_outside_bounds(self):
line = LineString([(20, 20), (30, 30)])
result = rasterize([(line, 1.0)], width=5, height=5,
bounds=(0, 0, 5, 5), fill=0)
assert np.all(result.values == 0)
def test_single_point_line(self):
# Degenerate line with two identical endpoints
line = LineString([(2.5, 2.5), (2.5, 2.5)])
result = rasterize([(line, 1.0)], width=5, height=5,
bounds=(0, 0, 5, 5), fill=0)
# Should burn at least one pixel at (row=2, col=2)
assert result.values[2, 2] == 1.0
def test_multi_segment_line(self):
# L-shaped line: right then up
line = LineString([(0.5, 0.5), (4.5, 0.5), (4.5, 4.5)])
result = rasterize([(line, 2.0)], width=5, height=5,
bounds=(0, 0, 5, 5), fill=0)
# Bottom row (y=0.5, row=4) should be burned across
for c in range(5):
assert result.values[4, c] == 2.0
# Right column (x=4.5, col=4) should be burned down
for r in range(5):
assert result.values[r, 4] == 2.0
# ---------------------------------------------------------------------------
# Mixed geometry types
# ---------------------------------------------------------------------------
class TestMixedGeometries:
def test_polygon_and_point(self):
poly = box(0, 0, 3, 3)
pt = Point(4.5, 4.5)
result = rasterize([(poly, 1.0), (pt, 9.0)], width=5, height=5,
bounds=(0, 0, 5, 5), fill=0)
# Polygon should fill bottom-left area
assert result.values[4, 0] == 1.0 # y=0.5, x=0.5 -> inside poly
# Point should burn at top-right
assert result.values[0, 4] == 9.0
def test_polygon_and_line(self):
poly = box(0, 0, 5, 5)
line = LineString([(0.5, 2.5), (4.5, 2.5)])
result = rasterize([(poly, 1.0), (line, 5.0)], width=5, height=5,
bounds=(0, 0, 5, 5), fill=0)
# Polygon fills everything with 1.0
# Line overwrites row 2 with 5.0
assert result.values[0, 0] == 1.0 # polygon only
assert result.values[2, 2] == 5.0 # line overwrites
def test_point_overwrites_polygon(self):
poly = box(0, 0, 5, 5)
pt = Point(2.5, 2.5)
result = rasterize([(poly, 1.0), (pt, 99.0)], width=5, height=5,
bounds=(0, 0, 5, 5), fill=0)
# Point has highest priority
assert result.values[2, 2] == 99.0
# Rest is polygon
assert result.values[0, 0] == 1.0
def test_all_types_together(self):
poly = box(0, 0, 5, 5)
line = LineString([(0.5, 4.5), (4.5, 4.5)])
pt = Point(2.5, 2.5)
result = rasterize(
[(poly, 1.0), (line, 2.0), (pt, 3.0)],
width=5, height=5, bounds=(0, 0, 5, 5), fill=0)
# Polygon fills everything
assert result.values[4, 4] == 1.0
# Line overwrites top row
assert result.values[0, 2] == 2.0
# Point overwrites center
assert result.values[2, 2] == 3.0
# ---------------------------------------------------------------------------
# GeoDataFrame with mixed geometry types
# ---------------------------------------------------------------------------
@skip_no_geopandas
class TestGeoDataFrameMixed:
def test_gdf_with_points(self):
gdf = gpd.GeoDataFrame(
{'value': [1.0, 2.0, 3.0]},
geometry=[Point(1.5, 1.5), Point(3.5, 3.5), Point(2.5, 2.5)],
)
result = rasterize(gdf, width=5, height=5,
bounds=(0, 0, 5, 5), column='value', fill=0)
assert result.values[3, 1] == 1.0
assert result.values[1, 3] == 2.0
assert result.values[2, 2] == 3.0
def test_gdf_with_lines(self):
gdf = gpd.GeoDataFrame(
{'value': [1.0, 2.0]},
geometry=[
LineString([(0.5, 2.5), (4.5, 2.5)]),
LineString([(2.5, 0.5), (2.5, 4.5)]),
],
)
result = rasterize(gdf, width=5, height=5,
bounds=(0, 0, 5, 5), column='value', fill=0)
# Horizontal line at row 2
assert result.values[2, 0] == 1.0
# Vertical line at col 2 (overwrites at intersection)
assert result.values[0, 2] == 2.0
# ---------------------------------------------------------------------------
# GPU backend
# ---------------------------------------------------------------------------
@skip_no_cuda
class TestCuPy:
def test_cupy_output_type(self):
geom = box(1, 1, 4, 4)
result = rasterize([(geom, 1.0)], width=5, height=5,
bounds=(0, 0, 5, 5), use_cuda=True)
assert isinstance(result.data, cupy.ndarray)
def test_cupy_matches_numpy(self):
geom = box(1, 1, 8, 8)
np_result = rasterize([(geom, 3.0)], width=10, height=10,
bounds=(0, 0, 10, 10), use_cuda=False)
cp_result = rasterize([(geom, 3.0)], width=10, height=10,
bounds=(0, 0, 10, 10), use_cuda=True)
np.testing.assert_array_equal(
np_result.values, cupy.asnumpy(cp_result.data))
def test_cupy_multiple_polygons(self):
pairs = [(box(0, 0, 4, 4), 1.0), (box(6, 6, 10, 10), 2.0)]
np_result = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 10, 10), use_cuda=False)
cp_result = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 10, 10), use_cuda=True)
np.testing.assert_array_equal(
np_result.values, cupy.asnumpy(cp_result.data))
def test_cupy_with_hole(self):
exterior = [(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)]
hole = [(3, 3), (3, 7), (7, 7), (7, 3), (3, 3)]
poly = Polygon(exterior, [hole])
np_result = rasterize([(poly, 1.0)], width=10, height=10,
bounds=(0, 0, 10, 10), use_cuda=False)
cp_result = rasterize([(poly, 1.0)], width=10, height=10,
bounds=(0, 0, 10, 10), use_cuda=True)
np.testing.assert_array_equal(
np_result.values, cupy.asnumpy(cp_result.data))
def test_cupy_points_match_numpy(self):
pairs = [
(Point(1.5, 1.5), 1.0),
(Point(3.5, 3.5), 2.0),
(MultiPoint([(0.5, 0.5), (4.5, 4.5)]), 3.0),
]
np_result = rasterize(pairs, width=5, height=5,
bounds=(0, 0, 5, 5), fill=0, use_cuda=False)
cp_result = rasterize(pairs, width=5, height=5,
bounds=(0, 0, 5, 5), fill=0, use_cuda=True)
np.testing.assert_array_equal(
np_result.values, cupy.asnumpy(cp_result.data))
def test_cupy_lines_match_numpy(self):
# Use non-intersecting lines to avoid GPU race conditions
# at shared pixels
pairs = [
(LineString([(0.5, 0.5), (4.5, 0.5)]), 1.0),
(LineString([(0.5, 4.5), (4.5, 4.5)]), 2.0),
(MultiLineString([[(0.5, 2.5), (4.5, 2.5)]]), 3.0),
]
np_result = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 5, 5), fill=0, use_cuda=False)
cp_result = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 5, 5), fill=0, use_cuda=True)
np.testing.assert_array_equal(
np_result.values, cupy.asnumpy(cp_result.data))
def test_cupy_mixed_types_match_numpy(self):
pairs = [
(box(0, 0, 3, 3), 1.0),
(LineString([(0.5, 4.5), (4.5, 4.5)]), 2.0),
(Point(2.5, 2.5), 3.0),
]
np_result = rasterize(pairs, width=5, height=5,
bounds=(0, 0, 5, 5), fill=0, use_cuda=False)
cp_result = rasterize(pairs, width=5, height=5,
bounds=(0, 0, 5, 5), fill=0, use_cuda=True)
np.testing.assert_array_equal(
np_result.values, cupy.asnumpy(cp_result.data))
def test_cupy_no_cupy_raises(self):
"""use_cuda=True without cupy should raise ImportError."""
# This test only runs if cupy IS available, so we just verify
# the function works -- the ImportError path is tested by
# the fact that the guard exists.
pass
# ---------------------------------------------------------------------------
# Reference comparison: known rasterization
# ---------------------------------------------------------------------------
class TestKnownValues:
def test_unit_square_at_origin(self):
"""A 1x1 square at (0,0)-(1,1) in a 2x2 grid covering (0,0)-(2,2).
Pixel centers: (0.5, 1.5), (1.5, 1.5), (0.5, 0.5), (1.5, 0.5)
Row 0 (y=1.5) is above the polygon -- empty.
Row 1 (y=0.5) has scanline intersections at x=0 and x=1,
so both col 0 (x=0.5) and col 1 (x=1.5) fall outside the
strict interior, but col 0 lands on the boundary and gets
filled by ceil/floor rounding. The exact pixel set depends on
whether boundaries count, so we just check fill counts.
"""
geom = box(0, 0, 1, 1)
result = rasterize([(geom, 1.0)], width=2, height=2,
bounds=(0, 0, 2, 2), fill=0)
# Top row is outside
assert result.values[0, 0] == 0
assert result.values[0, 1] == 0
# Bottom-left pixel is inside
assert result.values[1, 0] == 1.0
def test_full_coverage_square(self):
"""Square covering the full raster extent fills every pixel."""
geom = box(0, 0, 10, 10)
result = rasterize([(geom, 7.0)], width=5, height=5,
bounds=(0, 0, 10, 10), fill=0)
assert np.all(result.values == 7.0)
def test_triangle(self):
"""Right triangle in bottom-left quadrant.
Triangle: (0,0), (4,0), (0,4) in a 4x4 grid covering (0,0)-(4,4).
Pixel centers at 0.5, 1.5, 2.5, 3.5.
"""
tri = Polygon([(0, 0), (4, 0), (0, 4), (0, 0)])
result = rasterize([(tri, 1.0)], width=4, height=4,
bounds=(0, 0, 4, 4), fill=0)
# Row 0: y=3.5 -> only x=0.5 is inside (x < 4 - 3.5 = 0.5 -> boundary)
# Row 1: y=2.5 -> x < 4-2.5=1.5 -> x=0.5 inside
# Row 2: y=1.5 -> x < 4-1.5=2.5 -> x=0.5, 1.5 inside
# Row 3: y=0.5 -> x < 4-0.5=3.5 -> x=0.5, 1.5, 2.5 inside
vals = result.values
# Check that filled pixels increase per row (top to bottom)
filled_per_row = [np.sum(vals[r] == 1.0) for r in range(4)]
assert filled_per_row[3] >= filled_per_row[2] >= filled_per_row[1]
# ---------------------------------------------------------------------------
# Custom merge functions
# ---------------------------------------------------------------------------
class TestCustomMerge:
"""Tests for user-supplied merge functions."""
def test_custom_merge_sum_matches_builtin(self):
"""Custom sum function produces same result as built-in 'sum'."""
from xrspatial.utils import ngjit
@ngjit
def my_sum(pixel, props, is_first):
if is_first:
return props[0]
return pixel + props[0]
pairs = [(box(0, 0, 6, 6), 1.0), (box(4, 4, 10, 10), 2.0)]
builtin = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 10, 10), fill=0, merge='sum')
custom = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 10, 10), fill=0, merge=my_sum)
np.testing.assert_array_equal(builtin.values, custom.values)
def test_custom_merge_max_matches_builtin(self):
"""Custom max function produces same result as built-in 'max'."""
from xrspatial.utils import ngjit
@ngjit
def my_max(pixel, props, is_first):
if is_first or props[0] > pixel:
return props[0]
return pixel
pairs = [(box(0, 0, 6, 6), 3.0), (box(4, 4, 10, 10), 7.0)]
builtin = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 10, 10), fill=0, merge='max')
custom = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 10, 10), fill=0, merge=my_max)
np.testing.assert_array_equal(builtin.values, custom.values)
def test_custom_merge_weighted_average(self):
"""Custom function computing running average."""
from xrspatial.utils import ngjit
@ngjit
def avg(pixel, props, is_first):
if is_first:
return props[0]
return (pixel + props[0]) / 2.0
pairs = [(box(0, 0, 10, 10), 4.0), (box(0, 0, 10, 10), 8.0)]
result = rasterize(pairs, width=2, height=2,
bounds=(0, 0, 10, 10), fill=0, merge=avg)
# (4.0 + 8.0) / 2 = 6.0
assert np.all(result.values == 6.0)
def test_custom_merge_with_lines(self):
"""Custom merge works with line geometries."""
from xrspatial.utils import ngjit
@ngjit
def my_sum(pixel, props, is_first):
if is_first:
return props[0]
return pixel + props[0]
pairs = [
(LineString([(0.5, 5), (9.5, 5)]), 1.0),
(LineString([(5, 0.5), (5, 9.5)]), 1.0),
]
result = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 10, 10), fill=0, merge=my_sum)
# Intersection pixel should be 2.0
assert result.values[5, 5] == 2.0
def test_custom_merge_with_points(self):
"""Custom merge works with point geometries."""
from xrspatial.utils import ngjit
@ngjit
def my_sum(pixel, props, is_first):
if is_first:
return props[0]
return pixel + props[0]
pairs = [(Point(5.5, 5.5), 3.0), (Point(5.5, 5.5), 7.0)]
result = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 10, 10), fill=0, merge=my_sum)
# Same pixel written twice: 3 + 7 = 10
assert result.values[4, 5] == 10.0
def test_custom_merge_invalid_type_raises(self):
"""Non-string, non-callable merge raises TypeError."""
with pytest.raises(TypeError):
rasterize([(box(0, 0, 5, 5), 1.0)], width=5, height=5,
bounds=(0, 0, 5, 5), merge=42)
def test_custom_merge_invalid_string_raises(self):
"""Unknown string merge mode raises ValueError."""
with pytest.raises(ValueError):
rasterize([(box(0, 0, 5, 5), 1.0)], width=5, height=5,
bounds=(0, 0, 5, 5), merge='bogus')
@skip_no_dask
class TestCustomMergeDask:
"""Custom merge functions with dask backends."""
def test_custom_merge_dask_matches_numpy(self):
"""Custom function via dask produces same result as numpy."""
from xrspatial.utils import ngjit
@ngjit
def my_sum(pixel, props, is_first):
if is_first:
return props[0]
return pixel + props[0]
pairs = [(box(0, 0, 6, 6), 1.0), (box(4, 4, 10, 10), 2.0)]
np_result = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 10, 10), fill=0, merge=my_sum)
dk_result = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 10, 10), fill=0,
merge=my_sum, chunks=(5, 5))
np.testing.assert_array_equal(np_result.values, dk_result.values)
def test_custom_merge_dask_weighted_average(self):
"""Custom averaging function works across tile boundaries."""
from xrspatial.utils import ngjit
@ngjit
def avg(pixel, props, is_first):
if is_first:
return props[0]
return (pixel + props[0]) / 2.0
pairs = [(box(0, 0, 10, 10), 4.0), (box(0, 0, 10, 10), 8.0)]
result = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 10, 10), fill=0,
merge=avg, chunks=(5, 5))
assert np.all(result.values == 6.0)
@skip_no_cuda
class TestCustomMergeGPU:
"""Custom merge functions with GPU backends."""
@staticmethod
def _to_numpy(da_result):
computed = da_result.compute() if hasattr(da_result, 'compute') \
else da_result
return cupy.asnumpy(computed.data)
def test_custom_gpu_merge_sum(self):
"""Custom GPU merge function matches built-in sum."""
from numba import cuda as _cuda
@_cuda.jit(device=True)
def my_sum_gpu(pixel, props, is_first):
if is_first:
return props[0]
return pixel + props[0]
pairs = [(box(0, 0, 6, 6), 1.0), (box(4, 4, 10, 10), 2.0)]
builtin = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 10, 10), fill=0, merge='sum')
custom = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 10, 10), fill=0,
merge=my_sum_gpu, use_cuda=True)
np.testing.assert_array_equal(
builtin.values, self._to_numpy(custom))
@skip_no_dask
def test_custom_gpu_merge_dask(self):
"""Custom GPU merge function works with dask+cupy."""
from numba import cuda as _cuda
@_cuda.jit(device=True)
def my_sum_gpu(pixel, props, is_first):
if is_first:
return props[0]
return pixel + props[0]
pairs = [(box(0, 0, 6, 6), 1.0), (box(4, 4, 10, 10), 2.0)]
builtin = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 10, 10), fill=0, merge='sum')
custom = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 10, 10), fill=0,
merge=my_sum_gpu, use_cuda=True,
chunks=(5, 5))
np.testing.assert_array_equal(
builtin.values, self._to_numpy(custom))
# ---------------------------------------------------------------------------
# Dask + NumPy backend
# ---------------------------------------------------------------------------
@skip_no_dask
class TestDaskNumpy:
"""Tile-based dask+numpy rasterization tests."""
@pytest.mark.parametrize("chunks", [(5, 5), (3, 7), (100, 100)])
def test_polygon_parity(self, chunks):
"""Dask output matches numpy for a simple polygon."""
geom = box(1, 1, 8, 8)
np_result = rasterize([(geom, 3.0)], width=10, height=10,
bounds=(0, 0, 10, 10))
dk_result = rasterize([(geom, 3.0)], width=10, height=10,
bounds=(0, 0, 10, 10), chunks=chunks)
assert isinstance(dk_result.data, da.Array)
np.testing.assert_array_equal(np_result.values, dk_result.values)
@pytest.mark.parametrize("chunks", [(5, 5), (3, 7)])
def test_multiple_polygons_parity(self, chunks):
pairs = [(box(0, 0, 4, 4), 1.0), (box(6, 6, 10, 10), 2.0)]
np_result = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 10, 10))
dk_result = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 10, 10), chunks=chunks)
np.testing.assert_array_equal(np_result.values, dk_result.values)
@pytest.mark.parametrize("chunks", [(5, 5), (3, 7)])
def test_line_parity(self, chunks):
line = LineString([(0.5, 0.5), (9.5, 9.5)])
np_result = rasterize([(line, 1.0)], width=10, height=10,
bounds=(0, 0, 10, 10), fill=0)
dk_result = rasterize([(line, 1.0)], width=10, height=10,
bounds=(0, 0, 10, 10), fill=0, chunks=chunks)
np.testing.assert_array_equal(np_result.values, dk_result.values)
@pytest.mark.parametrize("chunks", [(5, 5), (3, 7)])
def test_point_parity(self, chunks):
pairs = [(Point(1.5, 1.5), 1.0), (Point(8.5, 8.5), 2.0)]
np_result = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 10, 10), fill=0)
dk_result = rasterize(pairs, width=10, height=10,
bounds=(0, 0, 10, 10), fill=0, chunks=chunks)
np.testing.assert_array_equal(np_result.values, dk_result.values)
@pytest.mark.parametrize("chunks", [(5, 5), (3, 7)])
def test_mixed_types_parity(self, chunks):
pairs = [
(box(0, 0, 3, 3), 1.0),
(LineString([(0.5, 4.5), (4.5, 4.5)]), 2.0),
(Point(2.5, 2.5), 3.0),
]
np_result = rasterize(pairs, width=5, height=5,
bounds=(0, 0, 5, 5), fill=0)
dk_result = rasterize(pairs, width=5, height=5,