-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathrasterize.py
More file actions
1429 lines (1204 loc) · 48.4 KB
/
rasterize.py
File metadata and controls
1429 lines (1204 loc) · 48.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Vector geometry rasterization (polygons, lines, points).
Converts vector geometries (GeoDataFrame or list of (geometry, value) pairs)
to a 2D xr.DataArray. No GDAL dependency.
- Polygons/MultiPolygons: scanline fill
- Lines/MultiLineStrings: Bresenham line rasterization
- Points/MultiPoints: direct pixel burn
Supports numpy and cupy backends.
"""
from __future__ import annotations
from typing import Optional, Tuple, Union
import numpy as np
import xarray as xr
from xrspatial.utils import ngjit
try:
import cupy
except ImportError:
cupy = None
# Detect shapely 2.0+ for vectorized extraction
try:
import shapely as _shapely_mod
_HAS_SHAPELY2 = hasattr(_shapely_mod, 'get_parts')
except ImportError:
_HAS_SHAPELY2 = False
# ---------------------------------------------------------------------------
# Merge mode constants
# ---------------------------------------------------------------------------
_MERGE_LAST = 0
_MERGE_FIRST = 1
_MERGE_MAX = 2
_MERGE_MIN = 3
_MERGE_SUM = 4
_MERGE_COUNT = 5
_MERGE_MODES = {
'last': _MERGE_LAST, 'first': _MERGE_FIRST,
'max': _MERGE_MAX, 'min': _MERGE_MIN,
'sum': _MERGE_SUM, 'count': _MERGE_COUNT,
}
# ---------------------------------------------------------------------------
# Merge pixel helper (CPU)
# ---------------------------------------------------------------------------
@ngjit
def _merge_pixel(out, written, r, c, val, mode):
"""Write *val* into ``out[r, c]`` using the given merge strategy.
A separate ``written`` array (int8) tracks which pixels have been
touched, replacing the previous NaN-sentinel approach which failed
when the caller intentionally burned NaN values.
"""
if mode == 0: # last -- unconditional overwrite, written not read
out[r, c] = val
elif mode == 1: # first
if written[r, c] == 0:
out[r, c] = val
written[r, c] = 1
elif mode == 2: # max
if written[r, c] == 0 or val > out[r, c]:
out[r, c] = val
written[r, c] = 1
elif mode == 3: # min
if written[r, c] == 0 or val < out[r, c]:
out[r, c] = val
written[r, c] = 1
elif mode == 4: # sum
if written[r, c] == 0:
out[r, c] = val
written[r, c] = 1
else:
out[r, c] = out[r, c] + val
else: # count
if written[r, c] == 0:
out[r, c] = 1.0
written[r, c] = 1
else:
out[r, c] = out[r, c] + 1.0
# ---------------------------------------------------------------------------
# Geometry classification (single pass)
# ---------------------------------------------------------------------------
def _classify_geometries(geometries, values):
"""Classify geometries by type in a single pass.
Also tracks each polygon's input index so the scanline fill can
process geometries in input order (needed for first/last merge).
GeometryCollections are recursively unpacked so their contents are
rasterized rather than silently dropped.
Returns
-------
(poly_geoms, poly_vals, poly_ids),
(line_geoms, line_vals),
(point_geoms, point_vals)
"""
poly_geoms, poly_vals, poly_ids = [], [], []
line_geoms, line_vals = [], []
point_geoms, point_vals = [], []
def _classify_one(geom, val, idx):
if geom is None or geom.is_empty:
return
gt = geom.geom_type
if gt in ('Polygon', 'MultiPolygon'):
poly_geoms.append(geom)
poly_vals.append(val)
poly_ids.append(idx)
elif gt in ('LineString', 'MultiLineString'):
line_geoms.append(geom)
line_vals.append(val)
elif gt in ('Point', 'MultiPoint'):
point_geoms.append(geom)
point_vals.append(val)
elif gt == 'GeometryCollection':
for sub in geom.geoms:
_classify_one(sub, val, idx)
for idx, (geom, val) in enumerate(zip(geometries, values)):
_classify_one(geom, val, idx)
return ((poly_geoms, poly_vals, poly_ids),
(line_geoms, line_vals),
(point_geoms, point_vals))
# ---------------------------------------------------------------------------
# Edge table construction
# ---------------------------------------------------------------------------
_EMPTY_EDGES = (np.empty(0, np.int32), np.empty(0, np.int32),
np.empty(0, np.float64), np.empty(0, np.float64),
np.empty(0, np.float64), np.empty(0, np.int32))
def _extract_edges(geometries, values, geom_ids, bounds, height, width,
all_touched=False):
"""Build the edge table for polygon scanline fill.
Returns
-------
edge_y_min, edge_y_max : int32 arrays
edge_x_at_ymin, edge_inv_slope, edge_value : float64 arrays
edge_geom_id : int32 array -- input geometry index for ordering
"""
if not geometries:
return _EMPTY_EDGES
if _HAS_SHAPELY2:
return _extract_edges_vectorized(
geometries, values, geom_ids, bounds, height, width, all_touched)
return _extract_edges_loop(
geometries, values, geom_ids, bounds, height, width, all_touched)
def _extract_edges_vectorized(geometries, values, geom_ids, bounds,
height, width, all_touched):
"""Vectorized edge extraction using shapely 2.0 array ops."""
import shapely
xmin, ymin, xmax, ymax = bounds
px = (xmax - xmin) / width
py = (ymax - ymin) / height
geom_arr = np.array(geometries, dtype=object)
val_arr = np.array(values, dtype=np.float64)
id_arr = np.array(geom_ids, dtype=np.int32)
# Explode MultiPolygons to individual Polygons
parts, part_idx = shapely.get_parts(geom_arr, return_index=True)
part_vals = val_arr[part_idx]
part_ids = id_arr[part_idx]
# Get all rings (exterior + interior)
rings, ring_idx = shapely.get_rings(parts, return_index=True)
ring_vals = part_vals[ring_idx]
ring_ids = part_ids[ring_idx]
if len(rings) == 0:
return _EMPTY_EDGES
# Get all vertex coordinates with ring membership
coords, coord_ring_idx = shapely.get_coordinates(
rings, return_index=True)
n_coords = len(coords)
if n_coords < 2:
return _EMPTY_EDGES
# Mark last coordinate of each ring (don't form cross-ring edges)
is_last = np.zeros(n_coords, dtype=bool)
changes = np.nonzero(np.diff(coord_ring_idx))[0]
is_last[changes] = True
is_last[-1] = True
# Edges: from each non-last coordinate to its successor
start_idx = np.nonzero(~is_last)[0]
end_idx = start_idx + 1
# Burn value and geometry id for each edge
edge_vals = ring_vals[coord_ring_idx[start_idx]]
edge_ids = ring_ids[coord_ring_idx[start_idx]]
# Convert to pixel space
start_row = (ymax - coords[start_idx, 1]) / py
start_col = (coords[start_idx, 0] - xmin) / px
end_row = (ymax - coords[end_idx, 1]) / py
end_col = (coords[end_idx, 0] - xmin) / px
# Drop horizontal edges
not_horiz = start_row != end_row
start_row = start_row[not_horiz]
start_col = start_col[not_horiz]
end_row = end_row[not_horiz]
end_col = end_col[not_horiz]
edge_vals = edge_vals[not_horiz]
edge_ids = edge_ids[not_horiz]
if len(start_row) == 0:
return _EMPTY_EDGES
# Orient edges so top_r < bot_r
swap = start_row > end_row
top_r = np.where(swap, end_row, start_row)
top_c = np.where(swap, end_col, start_col)
bot_r = np.where(swap, start_row, end_row)
bot_c = np.where(swap, start_col, end_col)
# Clamp to raster rows
if all_touched:
ry_min = np.maximum(np.floor(top_r - 0.5).astype(np.int32), 0)
ry_max = np.minimum(
np.ceil(bot_r + 0.5).astype(np.int32) - 1, height - 1)
else:
ry_min = np.maximum(np.ceil(top_r).astype(np.int32), 0)
ry_max = np.minimum(
np.ceil(bot_r).astype(np.int32) - 1, height - 1)
# Only keep edges that span at least one row
valid = ry_min <= ry_max
# Inverse slope and x at first active row
dr = bot_r - top_r # guaranteed != 0
inv_slope = (bot_c - top_c) / dr
x_at_ymin = top_c + (ry_min.astype(np.float64) - top_r) * inv_slope
return (ry_min[valid],
ry_max[valid],
x_at_ymin[valid],
inv_slope[valid],
edge_vals[valid],
edge_ids[valid])
def _extract_edges_loop(geometries, values, geom_ids, bounds, height, width,
all_touched):
"""Loop-based edge extraction (shapely < 2.0 fallback)."""
xmin, ymin, xmax, ymax = bounds
px = (xmax - xmin) / width
py = (ymax - ymin) / height
all_y_min = []
all_y_max = []
all_x_at_ymin = []
all_inv_slope = []
all_value = []
all_geom_id = []
for geom, val, gid in zip(geometries, values, geom_ids):
if geom is None or geom.is_empty:
continue
if geom.geom_type == 'Polygon':
parts = [geom]
elif geom.geom_type == 'MultiPolygon':
parts = list(geom.geoms)
else:
continue
for poly in parts:
rings = [poly.exterior] + list(poly.interiors)
for ring in rings:
coords = np.asarray(ring.coords)
row = (ymax - coords[:, 1]) / py
col = (coords[:, 0] - xmin) / px
n = len(row) - 1
for i in range(n):
r0, c0 = row[i], col[i]
r1, c1 = row[i + 1], col[i + 1]
if r0 == r1:
continue
if r0 > r1:
r0, c0, r1, c1 = r1, c1, r0, c0
if all_touched:
ry_min = max(int(np.floor(r0 - 0.5)), 0)
ry_max = min(
int(np.ceil(r1 + 0.5)) - 1, height - 1)
else:
ry_min = max(int(np.ceil(r0)), 0)
ry_max = min(
int(np.ceil(r1)) - 1, height - 1)
if ry_min > ry_max:
continue
inv_slope = (c1 - c0) / (r1 - r0)
x_at_ymin = c0 + (ry_min - r0) * inv_slope
all_y_min.append(np.int32(ry_min))
all_y_max.append(np.int32(ry_max))
all_x_at_ymin.append(x_at_ymin)
all_inv_slope.append(inv_slope)
all_value.append(np.float64(val))
all_geom_id.append(np.int32(gid))
if not all_y_min:
return _EMPTY_EDGES
return (np.array(all_y_min, np.int32),
np.array(all_y_max, np.int32),
np.array(all_x_at_ymin, np.float64),
np.array(all_inv_slope, np.float64),
np.array(all_value, np.float64),
np.array(all_geom_id, np.int32))
def _sort_edges(edge_arrays):
"""Sort edge table by y_min for scanline early termination."""
if len(edge_arrays[0]) == 0:
return edge_arrays
order = np.argsort(edge_arrays[0], kind='stable')
return tuple(arr[order] for arr in edge_arrays)
# ---------------------------------------------------------------------------
# Point extraction (always on host)
# ---------------------------------------------------------------------------
def _extract_points(geometries, values, bounds, height, width):
"""Parse Point/MultiPoint geometries into pixel coordinate arrays."""
if not geometries:
return (np.empty(0, np.int32), np.empty(0, np.int32),
np.empty(0, np.float64))
if _HAS_SHAPELY2:
return _extract_points_vectorized(
geometries, values, bounds, height, width)
return _extract_points_loop(
geometries, values, bounds, height, width)
def _extract_points_vectorized(geometries, values, bounds, height, width):
"""Vectorized point extraction using shapely 2.0 array ops."""
import shapely
xmin, ymin, xmax, ymax = bounds
px = (xmax - xmin) / width
py = (ymax - ymin) / height
geom_arr = np.array(geometries, dtype=object)
val_arr = np.array(values, dtype=np.float64)
# Explode MultiPoints to individual Points
parts, part_idx = shapely.get_parts(geom_arr, return_index=True)
part_vals = val_arr[part_idx]
if len(parts) == 0:
return (np.empty(0, np.int32), np.empty(0, np.int32),
np.empty(0, np.float64))
# Extract coordinates with index back to each point
coords, coord_idx = shapely.get_coordinates(
parts, return_index=True)
pt_vals = part_vals[coord_idx]
cols = np.floor((coords[:, 0] - xmin) / px).astype(np.int32)
rows = np.floor((ymax - coords[:, 1]) / py).astype(np.int32)
valid = (rows >= 0) & (rows < height) & (cols >= 0) & (cols < width)
return (rows[valid], cols[valid], pt_vals[valid])
def _extract_points_loop(geometries, values, bounds, height, width):
"""Loop-based point extraction (shapely < 2.0 fallback)."""
xmin, ymin, xmax, ymax = bounds
px = (xmax - xmin) / width
py = (ymax - ymin) / height
all_rows, all_cols, all_vals = [], [], []
for geom, val in zip(geometries, values):
if geom is None or geom.is_empty:
continue
if geom.geom_type == 'Point':
pts = [geom]
elif geom.geom_type == 'MultiPoint':
pts = list(geom.geoms)
else:
continue
for pt in pts:
col = int(np.floor((pt.x - xmin) / px))
row = int(np.floor((ymax - pt.y) / py))
if 0 <= row < height and 0 <= col < width:
all_rows.append(np.int32(row))
all_cols.append(np.int32(col))
all_vals.append(np.float64(val))
if not all_rows:
return (np.empty(0, np.int32), np.empty(0, np.int32),
np.empty(0, np.float64))
return (np.array(all_rows, np.int32),
np.array(all_cols, np.int32),
np.array(all_vals, np.float64))
# ---------------------------------------------------------------------------
# Line segment extraction (always on host)
# ---------------------------------------------------------------------------
_EMPTY_LINES = (np.empty(0, np.int32), np.empty(0, np.int32),
np.empty(0, np.int32), np.empty(0, np.int32),
np.empty(0, np.float64))
def _extract_line_segments(geometries, values, bounds, height, width):
"""Parse LineString/MultiLineString geometries into pixel-space segments.
Segments are clipped to the raster extent before conversion to pixel
coordinates, so Bresenham never iterates over out-of-bounds pixels.
"""
if not geometries:
return _EMPTY_LINES
if _HAS_SHAPELY2:
return _extract_lines_vectorized(
geometries, values, bounds, height, width)
return _extract_lines_loop(
geometries, values, bounds, height, width)
def _liang_barsky_clip(x0, y0, x1, y1, xmin, ymin, xmax, ymax):
"""Liang-Barsky line clipping. Returns clipped (x0,y0,x1,y1) or None."""
dx = x1 - x0
dy = y1 - y0
p = np.array([-dx, dx, -dy, dy])
q = np.array([x0 - xmin, xmax - x0, y0 - ymin, ymax - y0])
t0, t1 = 0.0, 1.0
for i in range(4):
if p[i] == 0.0:
if q[i] < 0.0:
return None
elif p[i] < 0.0:
t = q[i] / p[i]
if t > t1:
return None
if t > t0:
t0 = t
else:
t = q[i] / p[i]
if t < t0:
return None
if t < t1:
t1 = t
cx0 = x0 + t0 * dx
cy0 = y0 + t0 * dy
cx1 = x0 + t1 * dx
cy1 = y0 + t1 * dy
return cx0, cy0, cx1, cy1
def _extract_lines_vectorized(geometries, values, bounds, height, width):
"""Vectorized line extraction with Liang-Barsky clipping."""
import shapely
xmin, ymin, xmax, ymax = bounds
px = (xmax - xmin) / width
py = (ymax - ymin) / height
geom_arr = np.array(geometries, dtype=object)
val_arr = np.array(values, dtype=np.float64)
# Explode MultiLineStrings to individual LineStrings
parts, part_idx = shapely.get_parts(geom_arr, return_index=True)
part_vals = val_arr[part_idx]
if len(parts) == 0:
return _EMPTY_LINES
# Get all vertex coordinates with line membership
coords, coord_line_idx = shapely.get_coordinates(
parts, return_index=True)
n_coords = len(coords)
if n_coords < 2:
return _EMPTY_LINES
# Mark last coordinate of each line (don't form cross-line segments)
is_last = np.zeros(n_coords, dtype=bool)
changes = np.nonzero(np.diff(coord_line_idx))[0]
is_last[changes] = True
is_last[-1] = True
# Segments: from each non-last coordinate to its successor
start_idx = np.nonzero(~is_last)[0]
end_idx = start_idx + 1
seg_vals = part_vals[coord_line_idx[start_idx]]
# World-space segment endpoints
x0 = coords[start_idx, 0]
y0 = coords[start_idx, 1]
x1 = coords[end_idx, 0]
y1 = coords[end_idx, 1]
# Vectorized Liang-Barsky clip to raster bounds
dx = x1 - x0
dy = y1 - y0
# p and q arrays: shape (4, n_segments)
p = np.array([-dx, dx, -dy, dy])
q = np.array([x0 - xmin, xmax - x0, y0 - ymin, ymax - y0])
t0 = np.zeros(len(x0))
t1 = np.ones(len(x0))
valid = np.ones(len(x0), dtype=bool)
for i in range(4):
parallel = p[i] == 0.0
outside = parallel & (q[i] < 0.0)
valid &= ~outside
neg = (~parallel) & (p[i] < 0.0)
pos = (~parallel) & (p[i] > 0.0)
with np.errstate(divide='ignore', invalid='ignore'):
t_neg = np.where(neg, q[i] / p[i], 0.0)
t_pos = np.where(pos, q[i] / p[i], 1.0)
t0 = np.where(neg, np.maximum(t0, t_neg), t0)
t1 = np.where(pos, np.minimum(t1, t_pos), t1)
valid &= (t0 <= t1)
# Apply clipping
cx0 = x0 + t0 * dx
cy0 = y0 + t0 * dy
cx1 = x0 + t1 * dx
cy1 = y0 + t1 * dy
# Convert to pixel space and floor to int32
r0 = np.floor((ymax - cy0) / py).astype(np.int32)
c0 = np.floor((cx0 - xmin) / px).astype(np.int32)
r1 = np.floor((ymax - cy1) / py).astype(np.int32)
c1 = np.floor((cx1 - xmin) / px).astype(np.int32)
# Clamp edge cases (clipping guarantees in-bounds but float rounding
# at exact boundaries can produce height or width)
np.clip(r0, 0, height - 1, out=r0)
np.clip(c0, 0, width - 1, out=c0)
np.clip(r1, 0, height - 1, out=r1)
np.clip(c1, 0, width - 1, out=c1)
v = valid
return (r0[v], c0[v], r1[v], c1[v], seg_vals[v])
def _extract_lines_loop(geometries, values, bounds, height, width):
"""Loop-based line extraction with Liang-Barsky clipping (fallback)."""
xmin, ymin, xmax, ymax = bounds
px = (xmax - xmin) / width
py = (ymax - ymin) / height
all_r0, all_c0, all_r1, all_c1, all_vals = [], [], [], [], []
for geom, val in zip(geometries, values):
if geom is None or geom.is_empty:
continue
if geom.geom_type == 'LineString':
lines = [geom]
elif geom.geom_type == 'MultiLineString':
lines = list(geom.geoms)
else:
continue
for line in lines:
coords = np.asarray(line.coords)
for i in range(len(coords) - 1):
clipped = _liang_barsky_clip(
coords[i, 0], coords[i, 1],
coords[i + 1, 0], coords[i + 1, 1],
xmin, ymin, xmax, ymax)
if clipped is None:
continue
cx0, cy0, cx1, cy1 = clipped
r0 = min(max(int(np.floor((ymax - cy0) / py)), 0), height - 1)
c0 = min(max(int(np.floor((cx0 - xmin) / px)), 0), width - 1)
r1 = min(max(int(np.floor((ymax - cy1) / py)), 0), height - 1)
c1 = min(max(int(np.floor((cx1 - xmin) / px)), 0), width - 1)
all_r0.append(np.int32(r0))
all_c0.append(np.int32(c0))
all_r1.append(np.int32(r1))
all_c1.append(np.int32(c1))
all_vals.append(np.float64(val))
if not all_r0:
return _EMPTY_LINES
return (np.array(all_r0, np.int32), np.array(all_c0, np.int32),
np.array(all_r1, np.int32), np.array(all_c1, np.int32),
np.array(all_vals, np.float64))
# ---------------------------------------------------------------------------
# Polygon boundary segments (for all_touched mode)
# ---------------------------------------------------------------------------
def _extract_polygon_boundary_segments(geometries, values, bounds,
height, width):
"""Extract polygon ring edges as line segments for Bresenham drawing.
Used by all_touched mode: drawing the boundary ensures every pixel
the polygon touches is burned, without expanding scanline edge
y-ranges (which breaks edge pairing).
"""
from shapely.geometry import LineString as _LS
boundary_lines = []
boundary_vals = []
for geom, val in zip(geometries, values):
if geom is None or geom.is_empty:
continue
if geom.geom_type == 'Polygon':
parts = [geom]
elif geom.geom_type == 'MultiPolygon':
parts = list(geom.geoms)
else:
continue
for poly in parts:
boundary_lines.append(_LS(poly.exterior.coords))
boundary_vals.append(val)
for interior in poly.interiors:
boundary_lines.append(_LS(interior.coords))
boundary_vals.append(val)
if not boundary_lines:
return _EMPTY_LINES
return _extract_line_segments(boundary_lines, boundary_vals,
bounds, height, width)
# ---------------------------------------------------------------------------
# CPU burn kernels (numba)
# ---------------------------------------------------------------------------
@ngjit
def _burn_points_cpu(out, written, rows, cols, vals, mode):
for i in range(len(rows)):
r = rows[i]
c = cols[i]
if 0 <= r < out.shape[0] and 0 <= c < out.shape[1]:
_merge_pixel(out, written, r, c, vals[i], mode)
@ngjit
def _burn_lines_cpu(out, written, r0_arr, c0_arr, r1_arr, c1_arr, vals,
height, width, mode):
for i in range(len(r0_arr)):
r0 = r0_arr[i]
c0 = c0_arr[i]
r1 = r1_arr[i]
c1 = c1_arr[i]
val = vals[i]
dr = r1 - r0
dc = c1 - c0
sr = 1 if dr >= 0 else -1
sc = 1 if dc >= 0 else -1
dr = dr * sr
dc = dc * sc
if dr >= dc:
err = dc - dr
r, c = r0, c0
for _ in range(dr + 1):
if 0 <= r < height and 0 <= c < width:
_merge_pixel(out, written, r, c, val, mode)
if err >= 0:
c += sc
err -= dr
r += sr
err += dc
else:
err = dr - dc
r, c = r0, c0
for _ in range(dc + 1):
if 0 <= r < height and 0 <= c < width:
_merge_pixel(out, written, r, c, val, mode)
if err >= 0:
r += sr
err -= dc
c += sc
err += dr
# ---------------------------------------------------------------------------
# CPU scanline fill (numba) -- edges must be sorted by y_min
# ---------------------------------------------------------------------------
@ngjit
def _scanline_fill_cpu(out, written, edge_y_min, edge_y_max, edge_x_at_ymin,
edge_inv_slope, edge_value, edge_geom_id,
height, width, mode):
"""Scanline fill with active-edge-list for O(active) work per row.
Instead of scanning all edges up to the binary-search cutoff (which
wastes >99% of checks on dead edges for many-polygon inputs), this
maintains a compact list of currently-active edge indices. For each
row we remove expired edges and add newly-active ones, keeping total
work proportional to the sum of active-edge counts across rows.
"""
n_edges = len(edge_y_min)
# Active edge list: indices into the edge arrays
active = np.empty(n_edges, dtype=np.int32)
n_active = 0
add_ptr = 0 # next edge to consider adding (y_min sorted)
# Scratch arrays for intersections
xs = np.empty(n_edges, dtype=np.float64)
vs = np.empty(n_edges, dtype=np.float64)
gs = np.empty(n_edges, dtype=np.int32)
for row in range(height):
# 1. Remove expired edges (y_max < row)
write_pos = 0
for i in range(n_active):
if edge_y_max[active[i]] >= row:
active[write_pos] = active[i]
write_pos += 1
n_active = write_pos
# 2. Add newly-active edges whose y_min <= row
while add_ptr < n_edges and edge_y_min[add_ptr] <= row:
active[n_active] = add_ptr
n_active += 1
add_ptr += 1
if n_active == 0:
continue
# 3. Compute x-intersections for active edges only
for i in range(n_active):
e = active[i]
xs[i] = (edge_x_at_ymin[e]
+ (row - edge_y_min[e]) * edge_inv_slope[e])
vs[i] = edge_value[e]
gs[i] = edge_geom_id[e]
# 4. Insertion sort by (geom_id, x) so each geometry's edges pair
# correctly and geometries are processed in input order.
for i in range(1, n_active):
kx = xs[i]
kv = vs[i]
kg = gs[i]
j = i - 1
while j >= 0 and (gs[j] > kg or (gs[j] == kg and xs[j] > kx)):
xs[j + 1] = xs[j]
vs[j + 1] = vs[j]
gs[j + 1] = gs[j]
j -= 1
xs[j + 1] = kx
vs[j + 1] = kv
gs[j + 1] = kg
# 5. Fill between edge pairs per geometry
i = 0
while i < n_active - 1:
gid = gs[i]
val = vs[i]
j = i
while j < n_active and gs[j] == gid:
j += 1
k = i
while k + 1 < j:
x_start = xs[k]
x_end = xs[k + 1]
col_start = max(int(np.ceil(x_start)), 0)
col_end = min(int(np.ceil(x_end)) - 1, width - 1)
for c in range(col_start, col_end + 1):
_merge_pixel(out, written, row, c, val, mode)
k += 2
i = j
def _run_numpy(geometries, values, bounds, height, width, fill, dtype,
all_touched, merge_mode):
"""NumPy backend for rasterize."""
out = np.full((height, width), fill, dtype=np.float64)
# For non-'last' modes we need a written mask to track which pixels
# have been touched (replacing the old NaN-sentinel approach).
if merge_mode != _MERGE_LAST:
written = np.zeros((height, width), dtype=np.int8)
else:
# Dummy -- never indexed, but numba needs a typed array argument
written = np.empty((0, 0), dtype=np.int8)
(poly_geoms, poly_vals, poly_ids), (line_geoms, line_vals), \
(point_geoms, point_vals) = _classify_geometries(geometries, values)
# 1. Polygons -- always use normal edge ranges for scanline fill
# (all_touched y-expansion breaks edge pairing, so we handle
# all_touched by drawing polygon boundaries separately below).
edge_arrays = _extract_edges(
poly_geoms, poly_vals, poly_ids, bounds, height, width,
all_touched=False)
edge_arrays = _sort_edges(edge_arrays)
if len(edge_arrays[0]) > 0:
_scanline_fill_cpu(out, written, *edge_arrays, height, width,
merge_mode)
# 1b. all_touched: draw polygon boundaries via Bresenham so every
# pixel the boundary passes through is burned. This guarantees
# all_touched is a superset of the normal fill.
if all_touched and poly_geoms:
br0, bc0, br1, bc1, bvals = _extract_polygon_boundary_segments(
poly_geoms, poly_vals, bounds, height, width)
if len(br0) > 0:
_burn_lines_cpu(out, written, br0, bc0, br1, bc1, bvals,
height, width, merge_mode)
# 2. Lines
r0, c0, r1, c1, lvals = _extract_line_segments(
line_geoms, line_vals, bounds, height, width)
if len(r0) > 0:
_burn_lines_cpu(out, written, r0, c0, r1, c1, lvals, height, width,
merge_mode)
# 3. Points
prows, pcols, pvals = _extract_points(
point_geoms, point_vals, bounds, height, width)
if len(prows) > 0:
_burn_points_cpu(out, written, prows, pcols, pvals, merge_mode)
return out.astype(dtype)
# ---------------------------------------------------------------------------
# GPU kernels -- compiled lazily to avoid importing numba.cuda at module
# level (~160ms + CUDA driver init even when not using GPU).
# ---------------------------------------------------------------------------
_gpu_kernels = None
def _ensure_gpu_kernels():
"""Compile CUDA kernels on first use and cache them."""
global _gpu_kernels
if _gpu_kernels is not None:
return _gpu_kernels
from numba import cuda
@cuda.jit(device=True)
def _merge_pixel_gpu(out, written, r, c, val, mode):
if mode == 0: # last
out[r, c] = val
elif mode == 1: # first
if written[r, c] == 0:
out[r, c] = val
written[r, c] = 1
elif mode == 2: # max
if written[r, c] == 0 or val > out[r, c]:
out[r, c] = val
written[r, c] = 1
elif mode == 3: # min
if written[r, c] == 0 or val < out[r, c]:
out[r, c] = val
written[r, c] = 1
elif mode == 4: # sum
if written[r, c] == 0:
out[r, c] = val
written[r, c] = 1
else:
out[r, c] = out[r, c] + val
else: # count
if written[r, c] == 0:
out[r, c] = 1.0
written[r, c] = 1
else:
out[r, c] = out[r, c] + 1.0
@cuda.jit
def _scanline_fill_gpu(out, written, edge_y_min, edge_x_at_ymin,
edge_inv_slope, edge_value, edge_geom_id,
row_ptr, col_idx, width, mode):
"""CUDA kernel: one thread per raster row, CSR-indexed active edges.
Instead of binary-searching the sorted edge table and scanning
through dead edges, each thread reads its active edge list
directly from the precomputed CSR structure (row_ptr, col_idx).
"""
row = cuda.grid(1)
if row >= out.shape[0]:
return
start = row_ptr[row]
end = row_ptr[row + 1]
count = end - start
if count == 0:
return
MAX_ISECT = 512
if count > MAX_ISECT:
count = MAX_ISECT
xs = cuda.local.array(512, dtype=np.float64)
vs = cuda.local.array(512, dtype=np.float64)
gs = cuda.local.array(512, dtype=np.int32)
actual = 0
for k in range(start, end):
if actual >= MAX_ISECT:
break
e = col_idx[k]
xs[actual] = (edge_x_at_ymin[e]
+ (row - edge_y_min[e]) * edge_inv_slope[e])
vs[actual] = edge_value[e]
gs[actual] = edge_geom_id[e]
actual += 1
# Insertion sort by (geom_id, x)
for i in range(1, actual):
kx = xs[i]
kv = vs[i]
kg = gs[i]
j = i - 1
while j >= 0 and (gs[j] > kg or (gs[j] == kg and xs[j] > kx)):
xs[j + 1] = xs[j]
vs[j + 1] = vs[j]
gs[j + 1] = gs[j]
j -= 1
xs[j + 1] = kx
vs[j + 1] = kv
gs[j + 1] = kg
# Fill between pairs per geometry
i = 0
while i < actual - 1:
gid = gs[i]
val = vs[i]
j = i
while j < actual and gs[j] == gid:
j += 1
k = i
while k + 1 < j:
x_start = xs[k]
x_end = xs[k + 1]
# Proper ceil: int() truncates toward zero, so for
# positive fractions we add 1; for exact ints and
# negative fractions int() already rounds up.
ix = int(x_start)
col_start = ix + 1 if x_start > ix else ix
if col_start < 0:
col_start = 0
# Half-open interval: ceil(x_end) - 1 excludes
# boundary pixels whose centers are outside.
ix_end = int(x_end)
col_end = ix_end if x_end > ix_end else ix_end - 1
if col_end >= width:
col_end = width - 1
for c in range(col_start, col_end + 1):
_merge_pixel_gpu(out, written, row, c, val, mode)
k += 2
i = j
@cuda.jit
def _burn_points_gpu(out, written, rows, cols, vals, n_points, mode):
i = cuda.grid(1)
if i >= n_points:
return
r = rows[i]
c = cols[i]
if 0 <= r < out.shape[0] and 0 <= c < out.shape[1]:
_merge_pixel_gpu(out, written, r, c, vals[i], mode)
@cuda.jit
def _burn_lines_gpu(out, written, r0_arr, c0_arr, r1_arr, c1_arr, vals,
n_segs, height, width, mode):
i = cuda.grid(1)
if i >= n_segs:
return
r0 = r0_arr[i]
c0 = c0_arr[i]