-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathstream_order_d8.py
More file actions
1550 lines (1342 loc) · 53.3 KB
/
stream_order_d8.py
File metadata and controls
1550 lines (1342 loc) · 53.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
"""Stream order extraction: Strahler and Shreve ordering of drainage networks.
Assigns hierarchical order values to stream cells derived from a D8
flow direction grid and a flow accumulation grid. Cells with
accumulation below a user-defined threshold are non-stream and receive
NaN. Two methods are supported:
* **Strahler**: headwaters = 1; when two streams of equal order meet
the downstream order increments by 1; otherwise the higher order
propagates.
* **Shreve**: headwaters = 1; at each confluence the downstream
magnitude equals the sum of all incoming magnitudes.
Algorithm
---------
CPU : Kahn's BFS topological sort among stream cells — O(N_stream).
GPU : iterative frontier peeling with pull-based kernels.
Dask: iterative tile sweep with boundary propagation, same pattern
as ``flow_accumulation.py``.
"""
from __future__ import annotations
import numpy as np
import xarray as xr
from numba import cuda
try:
import cupy
except ImportError:
class cupy: # type: ignore[no-redef]
ndarray = False
try:
import dask.array as da
except ImportError:
da = None
from xrspatial.utils import (
_validate_raster,
cuda_args,
has_cuda_and_cupy,
is_cupy_array,
is_dask_cupy,
ngjit,
)
from xrspatial.hydro._boundary_store import BoundaryStore
from xrspatial.dataset_support import supports_dataset
from xrspatial.hydro.flow_accumulation_d8 import _code_to_offset, _code_to_offset_py
def _to_numpy_f64(arr):
"""Convert *arr* to a contiguous numpy float64 array (handles CuPy)."""
if hasattr(arr, 'get'):
arr = arr.get()
return np.asarray(arr, dtype=np.float64)
# =====================================================================
# CPU kernels
# =====================================================================
@ngjit
def _strahler_cpu(flow_dir, stream_mask, height, width):
"""Kahn's BFS Strahler ordering among stream cells."""
order = np.empty((height, width), dtype=np.float64)
in_degree = np.zeros((height, width), dtype=np.int32)
max_in = np.zeros((height, width), dtype=np.float64)
cnt_max = np.zeros((height, width), dtype=np.int32)
# Initialise
for r in range(height):
for c in range(width):
if stream_mask[r, c] == 0:
order[r, c] = np.nan
else:
order[r, c] = 0.0
# Compute in-degrees (only among stream cells)
for r in range(height):
for c in range(width):
if stream_mask[r, c] == 0:
continue
v = flow_dir[r, c]
if v != v: # NaN
continue
dy, dx = _code_to_offset(v)
if dy == 0 and dx == 0:
continue
nr = r + dy
nc = c + dx
if 0 <= nr < height and 0 <= nc < width and stream_mask[nr, nc] == 1:
in_degree[nr, nc] += 1
# BFS queue
queue_r = np.empty(height * width, dtype=np.int64)
queue_c = np.empty(height * width, dtype=np.int64)
head = np.int64(0)
tail = np.int64(0)
# Enqueue headwaters (stream cells with in_degree == 0)
for r in range(height):
for c in range(width):
if stream_mask[r, c] == 1 and in_degree[r, c] == 0:
order[r, c] = 1.0
queue_r[tail] = r
queue_c[tail] = c
tail += 1
while head < tail:
r = queue_r[head]
c = queue_c[head]
head += 1
v = flow_dir[r, c]
if v != v:
continue
dy, dx = _code_to_offset(v)
if dy == 0 and dx == 0:
continue
nr = r + dy
nc = c + dx
if not (0 <= nr < height and 0 <= nc < width and stream_mask[nr, nc] == 1):
continue
cur_ord = order[r, c]
if cur_ord > max_in[nr, nc]:
max_in[nr, nc] = cur_ord
cnt_max[nr, nc] = 1
elif cur_ord == max_in[nr, nc]:
cnt_max[nr, nc] += 1
in_degree[nr, nc] -= 1
if in_degree[nr, nc] == 0:
if cnt_max[nr, nc] >= 2:
order[nr, nc] = max_in[nr, nc] + 1.0
else:
order[nr, nc] = max_in[nr, nc]
queue_r[tail] = nr
queue_c[tail] = nc
tail += 1
return order
@ngjit
def _shreve_cpu(flow_dir, stream_mask, height, width):
"""Kahn's BFS Shreve ordering among stream cells."""
order = np.empty((height, width), dtype=np.float64)
in_degree = np.zeros((height, width), dtype=np.int32)
for r in range(height):
for c in range(width):
if stream_mask[r, c] == 0:
order[r, c] = np.nan
else:
order[r, c] = 0.0
for r in range(height):
for c in range(width):
if stream_mask[r, c] == 0:
continue
v = flow_dir[r, c]
if v != v:
continue
dy, dx = _code_to_offset(v)
if dy == 0 and dx == 0:
continue
nr = r + dy
nc = c + dx
if 0 <= nr < height and 0 <= nc < width and stream_mask[nr, nc] == 1:
in_degree[nr, nc] += 1
queue_r = np.empty(height * width, dtype=np.int64)
queue_c = np.empty(height * width, dtype=np.int64)
head = np.int64(0)
tail = np.int64(0)
for r in range(height):
for c in range(width):
if stream_mask[r, c] == 1 and in_degree[r, c] == 0:
order[r, c] = 1.0
queue_r[tail] = r
queue_c[tail] = c
tail += 1
while head < tail:
r = queue_r[head]
c = queue_c[head]
head += 1
v = flow_dir[r, c]
if v != v:
continue
dy, dx = _code_to_offset(v)
if dy == 0 and dx == 0:
continue
nr = r + dy
nc = c + dx
if not (0 <= nr < height and 0 <= nc < width and stream_mask[nr, nc] == 1):
continue
order[nr, nc] += order[r, c]
in_degree[nr, nc] -= 1
if in_degree[nr, nc] == 0:
queue_r[tail] = nr
queue_c[tail] = nc
tail += 1
return order
# =====================================================================
# GPU kernels
# =====================================================================
@cuda.jit
def _stream_order_init_gpu(flow_dir, stream_mask, in_degree, state,
order, max_in, cnt_max, H, W):
"""Initialise GPU arrays for stream order computation."""
i, j = cuda.grid(2)
if i >= H or j >= W:
return
if stream_mask[i, j] == 0:
state[i, j] = 0
order[i, j] = 0.0
max_in[i, j] = 0.0
cnt_max[i, j] = 0
return
state[i, j] = 1
order[i, j] = 0.0
max_in[i, j] = 0.0
cnt_max[i, j] = 0
v = flow_dir[i, j]
if v != v:
return
code = int(v)
dy = 0
dx = 0
if code == 1:
dy, dx = 0, 1
elif code == 2:
dy, dx = 1, 1
elif code == 4:
dy, dx = 1, 0
elif code == 8:
dy, dx = 1, -1
elif code == 16:
dy, dx = 0, -1
elif code == 32:
dy, dx = -1, -1
elif code == 64:
dy, dx = -1, 0
elif code == 128:
dy, dx = -1, 1
if dy == 0 and dx == 0:
return
ni = i + dy
nj = j + dx
if 0 <= ni < H and 0 <= nj < W and stream_mask[ni, nj] == 1:
cuda.atomic.add(in_degree, (ni, nj), 1)
@cuda.jit
def _stream_order_find_ready(in_degree, state, order, changed, H, W):
"""Finalize previous frontier, mark new frontier cells."""
i, j = cuda.grid(2)
if i >= H or j >= W:
return
if state[i, j] == 2:
state[i, j] = 3
if state[i, j] == 1 and in_degree[i, j] == 0:
state[i, j] = 2
if order[i, j] == 0.0:
order[i, j] = 1.0 # headwater
cuda.atomic.add(changed, 0, 1)
@cuda.jit
def _stream_order_pull_strahler(flow_dir, stream_mask, in_degree, state,
order, max_in, cnt_max, H, W):
"""Active cells pull Strahler info from frontier neighbours."""
i, j = cuda.grid(2)
if i >= H or j >= W:
return
if state[i, j] != 1:
return
for k in range(8):
if k == 0:
dy, dx = 0, 1
elif k == 1:
dy, dx = 1, 1
elif k == 2:
dy, dx = 1, 0
elif k == 3:
dy, dx = 1, -1
elif k == 4:
dy, dx = 0, -1
elif k == 5:
dy, dx = -1, -1
elif k == 6:
dy, dx = -1, 0
else:
dy, dx = -1, 1
ni = i + dy
nj = j + dx
if ni < 0 or ni >= H or nj < 0 or nj >= W:
continue
if state[ni, nj] != 2:
continue
if stream_mask[ni, nj] == 0:
continue
nv = flow_dir[ni, nj]
ncode = int(nv)
ndy = 0
ndx = 0
if ncode == 1:
ndy, ndx = 0, 1
elif ncode == 2:
ndy, ndx = 1, 1
elif ncode == 4:
ndy, ndx = 1, 0
elif ncode == 8:
ndy, ndx = 1, -1
elif ncode == 16:
ndy, ndx = 0, -1
elif ncode == 32:
ndy, ndx = -1, -1
elif ncode == 64:
ndy, ndx = -1, 0
elif ncode == 128:
ndy, ndx = -1, 1
if ni + ndy == i and nj + ndx == j:
nb_ord = order[ni, nj]
if nb_ord > max_in[i, j]:
max_in[i, j] = nb_ord
cnt_max[i, j] = 1
elif nb_ord == max_in[i, j]:
cnt_max[i, j] += 1
in_degree[i, j] -= 1
if in_degree[i, j] == 0:
if cnt_max[i, j] >= 2:
order[i, j] = max_in[i, j] + 1.0
else:
order[i, j] = max_in[i, j]
@cuda.jit
def _stream_order_pull_shreve(flow_dir, stream_mask, in_degree, state,
order, H, W):
"""Active cells pull Shreve magnitudes from frontier neighbours."""
i, j = cuda.grid(2)
if i >= H or j >= W:
return
if state[i, j] != 1:
return
for k in range(8):
if k == 0:
dy, dx = 0, 1
elif k == 1:
dy, dx = 1, 1
elif k == 2:
dy, dx = 1, 0
elif k == 3:
dy, dx = 1, -1
elif k == 4:
dy, dx = 0, -1
elif k == 5:
dy, dx = -1, -1
elif k == 6:
dy, dx = -1, 0
else:
dy, dx = -1, 1
ni = i + dy
nj = j + dx
if ni < 0 or ni >= H or nj < 0 or nj >= W:
continue
if state[ni, nj] != 2:
continue
if stream_mask[ni, nj] == 0:
continue
nv = flow_dir[ni, nj]
ncode = int(nv)
ndy = 0
ndx = 0
if ncode == 1:
ndy, ndx = 0, 1
elif ncode == 2:
ndy, ndx = 1, 1
elif ncode == 4:
ndy, ndx = 1, 0
elif ncode == 8:
ndy, ndx = 1, -1
elif ncode == 16:
ndy, ndx = 0, -1
elif ncode == 32:
ndy, ndx = -1, -1
elif ncode == 64:
ndy, ndx = -1, 0
elif ncode == 128:
ndy, ndx = -1, 1
if ni + ndy == i and nj + ndx == j:
order[i, j] += order[ni, nj]
in_degree[i, j] -= 1
def _stream_order_cupy(flow_dir_data, stream_mask_data, method):
"""GPU driver for stream order computation."""
import cupy as cp
H, W = flow_dir_data.shape
flow_dir_f64 = flow_dir_data.astype(cp.float64)
stream_mask_i8 = stream_mask_data.astype(cp.int8)
in_degree = cp.zeros((H, W), dtype=cp.int32)
state = cp.zeros((H, W), dtype=cp.int32)
order = cp.zeros((H, W), dtype=cp.float64)
max_in = cp.zeros((H, W), dtype=cp.float64)
cnt_max = cp.zeros((H, W), dtype=cp.int32)
changed = cp.zeros(1, dtype=cp.int32)
griddim, blockdim = cuda_args((H, W))
_stream_order_init_gpu[griddim, blockdim](
flow_dir_f64, stream_mask_i8, in_degree, state,
order, max_in, cnt_max, H, W)
max_iter = H * W
for _ in range(max_iter):
changed[0] = 0
_stream_order_find_ready[griddim, blockdim](
in_degree, state, order, changed, H, W)
if int(changed[0]) == 0:
break
if method == 'strahler':
_stream_order_pull_strahler[griddim, blockdim](
flow_dir_f64, stream_mask_i8, in_degree, state,
order, max_in, cnt_max, H, W)
else:
_stream_order_pull_shreve[griddim, blockdim](
flow_dir_f64, stream_mask_i8, in_degree, state,
order, H, W)
order = cp.where(stream_mask_i8 == 0, cp.nan, order)
return order
# =====================================================================
# CPU tile kernels for dask
# =====================================================================
@ngjit
def _strahler_tile_kernel(flow_dir, stream_mask, h, w,
seed_max_top, seed_cnt_top,
seed_max_bottom, seed_cnt_bottom,
seed_max_left, seed_cnt_left,
seed_max_right, seed_cnt_right):
"""Seeded Strahler BFS for a single tile."""
order = np.empty((h, w), dtype=np.float64)
in_degree = np.zeros((h, w), dtype=np.int32)
max_in = np.zeros((h, w), dtype=np.float64)
cnt_max = np.zeros((h, w), dtype=np.int32)
for r in range(h):
for c in range(w):
if stream_mask[r, c] == 0:
order[r, c] = np.nan
else:
order[r, c] = 0.0
# Apply seeds: set max_in / cnt_max from boundary info
for c in range(w):
if stream_mask[0, c] == 1 and seed_max_top[c] > 0:
if seed_max_top[c] > max_in[0, c]:
max_in[0, c] = seed_max_top[c]
cnt_max[0, c] = int(seed_cnt_top[c])
elif seed_max_top[c] == max_in[0, c]:
cnt_max[0, c] += int(seed_cnt_top[c])
if stream_mask[h - 1, c] == 1 and seed_max_bottom[c] > 0:
if seed_max_bottom[c] > max_in[h - 1, c]:
max_in[h - 1, c] = seed_max_bottom[c]
cnt_max[h - 1, c] = int(seed_cnt_bottom[c])
elif seed_max_bottom[c] == max_in[h - 1, c]:
cnt_max[h - 1, c] += int(seed_cnt_bottom[c])
for r in range(h):
if stream_mask[r, 0] == 1 and seed_max_left[r] > 0:
if seed_max_left[r] > max_in[r, 0]:
max_in[r, 0] = seed_max_left[r]
cnt_max[r, 0] = int(seed_cnt_left[r])
elif seed_max_left[r] == max_in[r, 0]:
cnt_max[r, 0] += int(seed_cnt_left[r])
if stream_mask[r, w - 1] == 1 and seed_max_right[r] > 0:
if seed_max_right[r] > max_in[r, w - 1]:
max_in[r, w - 1] = seed_max_right[r]
cnt_max[r, w - 1] = int(seed_cnt_right[r])
elif seed_max_right[r] == max_in[r, w - 1]:
cnt_max[r, w - 1] += int(seed_cnt_right[r])
# Compute in-degrees among stream cells within tile
for r in range(h):
for c in range(w):
if stream_mask[r, c] == 0:
continue
v = flow_dir[r, c]
if v != v:
continue
dy, dx = _code_to_offset(v)
if dy == 0 and dx == 0:
continue
nr = r + dy
nc = c + dx
if 0 <= nr < h and 0 <= nc < w and stream_mask[nr, nc] == 1:
in_degree[nr, nc] += 1
# BFS
queue_r = np.empty(h * w, dtype=np.int64)
queue_c = np.empty(h * w, dtype=np.int64)
head = np.int64(0)
tail = np.int64(0)
for r in range(h):
for c in range(w):
if stream_mask[r, c] != 1:
continue
if in_degree[r, c] != 0:
continue
# Headwater or seeded cell
if max_in[r, c] > 0:
if cnt_max[r, c] >= 2:
order[r, c] = max_in[r, c] + 1.0
else:
order[r, c] = max_in[r, c]
else:
order[r, c] = 1.0
queue_r[tail] = r
queue_c[tail] = c
tail += 1
while head < tail:
r = queue_r[head]
c = queue_c[head]
head += 1
v = flow_dir[r, c]
if v != v:
continue
dy, dx = _code_to_offset(v)
if dy == 0 and dx == 0:
continue
nr = r + dy
nc = c + dx
if not (0 <= nr < h and 0 <= nc < w and stream_mask[nr, nc] == 1):
continue
cur_ord = order[r, c]
if cur_ord > max_in[nr, nc]:
max_in[nr, nc] = cur_ord
cnt_max[nr, nc] = 1
elif cur_ord == max_in[nr, nc]:
cnt_max[nr, nc] += 1
in_degree[nr, nc] -= 1
if in_degree[nr, nc] == 0:
if cnt_max[nr, nc] >= 2:
order[nr, nc] = max_in[nr, nc] + 1.0
else:
order[nr, nc] = max_in[nr, nc]
queue_r[tail] = nr
queue_c[tail] = nc
tail += 1
return order
@ngjit
def _shreve_tile_kernel(flow_dir, stream_mask, h, w,
seed_top, seed_bottom, seed_left, seed_right):
"""Seeded Shreve BFS for a single tile."""
order = np.empty((h, w), dtype=np.float64)
in_degree = np.zeros((h, w), dtype=np.int32)
for r in range(h):
for c in range(w):
if stream_mask[r, c] == 0:
order[r, c] = np.nan
else:
order[r, c] = 0.0
# Apply additive seeds
for c in range(w):
if stream_mask[0, c] == 1:
order[0, c] += seed_top[c]
if stream_mask[h - 1, c] == 1:
order[h - 1, c] += seed_bottom[c]
for r in range(h):
if stream_mask[r, 0] == 1:
order[r, 0] += seed_left[r]
if stream_mask[r, w - 1] == 1:
order[r, w - 1] += seed_right[r]
# In-degrees
for r in range(h):
for c in range(w):
if stream_mask[r, c] == 0:
continue
v = flow_dir[r, c]
if v != v:
continue
dy, dx = _code_to_offset(v)
if dy == 0 and dx == 0:
continue
nr = r + dy
nc = c + dx
if 0 <= nr < h and 0 <= nc < w and stream_mask[nr, nc] == 1:
in_degree[nr, nc] += 1
queue_r = np.empty(h * w, dtype=np.int64)
queue_c = np.empty(h * w, dtype=np.int64)
head = np.int64(0)
tail = np.int64(0)
for r in range(h):
for c in range(w):
if stream_mask[r, c] == 1 and in_degree[r, c] == 0:
if order[r, c] == 0.0:
order[r, c] = 1.0 # headwater
queue_r[tail] = r
queue_c[tail] = c
tail += 1
while head < tail:
r = queue_r[head]
c = queue_c[head]
head += 1
v = flow_dir[r, c]
if v != v:
continue
dy, dx = _code_to_offset(v)
if dy == 0 and dx == 0:
continue
nr = r + dy
nc = c + dx
if not (0 <= nr < h and 0 <= nc < w and stream_mask[nr, nc] == 1):
continue
order[nr, nc] += order[r, c]
in_degree[nr, nc] -= 1
if in_degree[nr, nc] == 0:
queue_r[tail] = nr
queue_c[tail] = nc
tail += 1
return order
# =====================================================================
# Dask iterative tile sweep
# =====================================================================
def _preprocess_stream_tiles(flow_dir_da, accum_da, threshold,
chunks_y, chunks_x):
"""Extract boundary strips for flow dir and stream mask."""
n_tile_y = len(chunks_y)
n_tile_x = len(chunks_x)
flow_bdry = BoundaryStore(chunks_y, chunks_x, fill_value=np.nan)
mask_bdry = BoundaryStore(chunks_y, chunks_x, fill_value=0.0)
for iy in range(n_tile_y):
for ix in range(n_tile_x):
fd_chunk = _to_numpy_f64(
flow_dir_da.blocks[iy, ix].compute())
ac_chunk = _to_numpy_f64(
accum_da.blocks[iy, ix].compute())
sm = np.where(ac_chunk >= threshold, 1.0, 0.0)
sm = np.where(np.isnan(ac_chunk), 0.0, sm)
sm = np.where(np.isnan(fd_chunk), 0.0, sm)
for side, row_data_fd, row_data_sm in [
('top', fd_chunk[0, :], sm[0, :]),
('bottom', fd_chunk[-1, :], sm[-1, :]),
('left', fd_chunk[:, 0], sm[:, 0]),
('right', fd_chunk[:, -1], sm[:, -1]),
]:
flow_bdry.set(side, iy, ix,
np.asarray(row_data_fd, dtype=np.float64))
mask_bdry.set(side, iy, ix,
np.asarray(row_data_sm, dtype=np.float64))
return flow_bdry, mask_bdry
def _compute_shreve_seeds(iy, ix, boundaries, flow_bdry, mask_bdry,
chunks_y, chunks_x, n_tile_y, n_tile_x):
"""Compute additive Shreve seeds from neighbours (same as flow_accum)."""
tile_h = chunks_y[iy]
tile_w = chunks_x[ix]
seed_top = np.zeros(tile_w, dtype=np.float64)
seed_bottom = np.zeros(tile_w, dtype=np.float64)
seed_left = np.zeros(tile_h, dtype=np.float64)
seed_right = np.zeros(tile_h, dtype=np.float64)
# Top edge: bottom of tile above
if iy > 0:
nb_fdir = flow_bdry.get('bottom', iy - 1, ix)
nb_mask = mask_bdry.get('bottom', iy - 1, ix)
nb_order = boundaries.get('bottom', iy - 1, ix)
w = len(nb_fdir)
for j in range(w):
if nb_mask[j] == 0:
continue
code = int(nb_fdir[j])
dy, dx = _code_to_offset_py(code)
if dy == 1 and dx == 0 and j < tile_w: # S
seed_top[j] += nb_order[j]
elif dy == 1 and dx == 1 and j + 1 < tile_w: # SE
seed_top[j + 1] += nb_order[j]
elif dy == 1 and dx == -1 and j - 1 >= 0: # SW
seed_top[j - 1] += nb_order[j]
# Bottom edge: top of tile below
if iy < n_tile_y - 1:
nb_fdir = flow_bdry.get('top', iy + 1, ix)
nb_mask = mask_bdry.get('top', iy + 1, ix)
nb_order = boundaries.get('top', iy + 1, ix)
w = len(nb_fdir)
for j in range(w):
if nb_mask[j] == 0:
continue
code = int(nb_fdir[j])
dy, dx = _code_to_offset_py(code)
if dy == -1 and dx == 0 and j < tile_w: # N
seed_bottom[j] += nb_order[j]
elif dy == -1 and dx == 1 and j + 1 < tile_w: # NE
seed_bottom[j + 1] += nb_order[j]
elif dy == -1 and dx == -1 and j - 1 >= 0: # NW
seed_bottom[j - 1] += nb_order[j]
# Left edge: right column of tile to the left
if ix > 0:
nb_fdir = flow_bdry.get('right', iy, ix - 1)
nb_mask = mask_bdry.get('right', iy, ix - 1)
nb_order = boundaries.get('right', iy, ix - 1)
h = len(nb_fdir)
for i in range(h):
if nb_mask[i] == 0:
continue
code = int(nb_fdir[i])
dy, dx = _code_to_offset_py(code)
if dx == 1 and dy == 0 and i < tile_h: # E
seed_left[i] += nb_order[i]
elif dx == 1 and dy == 1 and i + 1 < tile_h: # SE
seed_left[i + 1] += nb_order[i]
elif dx == 1 and dy == -1 and i - 1 >= 0: # NE
seed_left[i - 1] += nb_order[i]
# Right edge: left column of tile to the right
if ix < n_tile_x - 1:
nb_fdir = flow_bdry.get('left', iy, ix + 1)
nb_mask = mask_bdry.get('left', iy, ix + 1)
nb_order = boundaries.get('left', iy, ix + 1)
h = len(nb_fdir)
for i in range(h):
if nb_mask[i] == 0:
continue
code = int(nb_fdir[i])
dy, dx = _code_to_offset_py(code)
if dx == -1 and dy == 0 and i < tile_h: # W
seed_right[i] += nb_order[i]
elif dx == -1 and dy == 1 and i + 1 < tile_h: # SW
seed_right[i + 1] += nb_order[i]
elif dx == -1 and dy == -1 and i - 1 >= 0: # NW
seed_right[i - 1] += nb_order[i]
# Corner seeds from diagonal neighbours
if iy > 0 and ix > 0:
fdir = flow_bdry.get('bottom', iy - 1, ix - 1)[-1]
mask = mask_bdry.get('bottom', iy - 1, ix - 1)[-1]
if mask == 1 and int(fdir) == 2: # SE
seed_top[0] += boundaries.get('bottom', iy - 1, ix - 1)[-1]
if iy > 0 and ix < n_tile_x - 1:
fdir = flow_bdry.get('bottom', iy - 1, ix + 1)[0]
mask = mask_bdry.get('bottom', iy - 1, ix + 1)[0]
if mask == 1 and int(fdir) == 8: # SW
seed_top[tile_w - 1] += boundaries.get(
'bottom', iy - 1, ix + 1)[0]
if iy < n_tile_y - 1 and ix > 0:
fdir = flow_bdry.get('top', iy + 1, ix - 1)[-1]
mask = mask_bdry.get('top', iy + 1, ix - 1)[-1]
if mask == 1 and int(fdir) == 128: # NE
seed_bottom[0] += boundaries.get('top', iy + 1, ix - 1)[-1]
if iy < n_tile_y - 1 and ix < n_tile_x - 1:
fdir = flow_bdry.get('top', iy + 1, ix + 1)[0]
mask = mask_bdry.get('top', iy + 1, ix + 1)[0]
if mask == 1 and int(fdir) == 32: # NW
seed_bottom[tile_w - 1] += boundaries.get(
'top', iy + 1, ix + 1)[0]
return seed_top, seed_bottom, seed_left, seed_right
def _compute_strahler_seeds(iy, ix, bdry_max, bdry_cnt,
flow_bdry, mask_bdry,
chunks_y, chunks_x, n_tile_y, n_tile_x):
"""Compute Strahler (max, cnt) seeds from neighbours."""
tile_h = chunks_y[iy]
tile_w = chunks_x[ix]
smax_top = np.zeros(tile_w, dtype=np.float64)
scnt_top = np.zeros(tile_w, dtype=np.float64)
smax_bottom = np.zeros(tile_w, dtype=np.float64)
scnt_bottom = np.zeros(tile_w, dtype=np.float64)
smax_left = np.zeros(tile_h, dtype=np.float64)
scnt_left = np.zeros(tile_h, dtype=np.float64)
smax_right = np.zeros(tile_h, dtype=np.float64)
scnt_right = np.zeros(tile_h, dtype=np.float64)
def _update_max_cnt(cur_max, cur_cnt, new_val, idx):
if new_val > cur_max[idx]:
cur_max[idx] = new_val
cur_cnt[idx] = 1.0
elif new_val == cur_max[idx] and new_val > 0:
cur_cnt[idx] += 1.0
# Top edge
if iy > 0:
nb_fdir = flow_bdry.get('bottom', iy - 1, ix)
nb_mask = mask_bdry.get('bottom', iy - 1, ix)
nb_max = bdry_max.get('bottom', iy - 1, ix)
nb_cnt = bdry_cnt.get('bottom', iy - 1, ix)
w = len(nb_fdir)
for j in range(w):
if nb_mask[j] == 0 or nb_max[j] == 0:
continue
code = int(nb_fdir[j])
dy, dx = _code_to_offset_py(code)
target = -1
if dy == 1 and dx == 0:
target = j
elif dy == 1 and dx == 1:
target = j + 1
elif dy == 1 and dx == -1:
target = j - 1
if 0 <= target < tile_w:
# Reconstruct the order that this cell had
if nb_cnt[j] >= 2:
val = nb_max[j] + 1.0
else:
val = nb_max[j]
_update_max_cnt(smax_top, scnt_top, val, target)
# Bottom edge
if iy < n_tile_y - 1:
nb_fdir = flow_bdry.get('top', iy + 1, ix)
nb_mask = mask_bdry.get('top', iy + 1, ix)
nb_max = bdry_max.get('top', iy + 1, ix)
nb_cnt = bdry_cnt.get('top', iy + 1, ix)
w = len(nb_fdir)
for j in range(w):
if nb_mask[j] == 0 or nb_max[j] == 0:
continue
code = int(nb_fdir[j])
dy, dx = _code_to_offset_py(code)
target = -1
if dy == -1 and dx == 0:
target = j
elif dy == -1 and dx == 1:
target = j + 1
elif dy == -1 and dx == -1:
target = j - 1
if 0 <= target < tile_w:
if nb_cnt[j] >= 2:
val = nb_max[j] + 1.0
else:
val = nb_max[j]
_update_max_cnt(smax_bottom, scnt_bottom, val, target)
# Left edge
if ix > 0:
nb_fdir = flow_bdry.get('right', iy, ix - 1)
nb_mask = mask_bdry.get('right', iy, ix - 1)
nb_max = bdry_max.get('right', iy, ix - 1)
nb_cnt = bdry_cnt.get('right', iy, ix - 1)
h = len(nb_fdir)
for i in range(h):
if nb_mask[i] == 0 or nb_max[i] == 0:
continue
code = int(nb_fdir[i])
dy, dx = _code_to_offset_py(code)
target = -1
if dx == 1 and dy == 0:
target = i
elif dx == 1 and dy == 1:
target = i + 1
elif dx == 1 and dy == -1:
target = i - 1
if 0 <= target < tile_h:
if nb_cnt[i] >= 2:
val = nb_max[i] + 1.0
else:
val = nb_max[i]
_update_max_cnt(smax_left, scnt_left, val, target)
# Right edge
if ix < n_tile_x - 1:
nb_fdir = flow_bdry.get('left', iy, ix + 1)
nb_mask = mask_bdry.get('left', iy, ix + 1)
nb_max = bdry_max.get('left', iy, ix + 1)
nb_cnt = bdry_cnt.get('left', iy, ix + 1)
h = len(nb_fdir)
for i in range(h):
if nb_mask[i] == 0 or nb_max[i] == 0:
continue
code = int(nb_fdir[i])
dy, dx = _code_to_offset_py(code)
target = -1
if dx == -1 and dy == 0:
target = i
elif dx == -1 and dy == 1:
target = i + 1
elif dx == -1 and dy == -1:
target = i - 1
if 0 <= target < tile_h:
if nb_cnt[i] >= 2:
val = nb_max[i] + 1.0
else:
val = nb_max[i]
_update_max_cnt(smax_right, scnt_right, val, target)
# Corners
def _corner_seed(nb_side, nb_iy, nb_ix, nb_idx, code_expected,
s_max, s_cnt, target):
fdir = flow_bdry.get(nb_side, nb_iy, nb_ix)[nb_idx]
mask = mask_bdry.get(nb_side, nb_iy, nb_ix)[nb_idx]
if mask == 1 and int(fdir) == code_expected:
nm = bdry_max.get(nb_side, nb_iy, nb_ix)[nb_idx]
nc = bdry_cnt.get(nb_side, nb_iy, nb_ix)[nb_idx]
if nm > 0:
val = nm + 1.0 if nc >= 2 else nm
_update_max_cnt(s_max, s_cnt, val, target)
if iy > 0 and ix > 0:
_corner_seed('bottom', iy - 1, ix - 1, -1, 2,
smax_top, scnt_top, 0)
if iy > 0 and ix < n_tile_x - 1:
_corner_seed('bottom', iy - 1, ix + 1, 0, 8,
smax_top, scnt_top, tile_w - 1)
if iy < n_tile_y - 1 and ix > 0:
_corner_seed('top', iy + 1, ix - 1, -1, 128,
smax_bottom, scnt_bottom, 0)
if iy < n_tile_y - 1 and ix < n_tile_x - 1:
_corner_seed('top', iy + 1, ix + 1, 0, 32,
smax_bottom, scnt_bottom, tile_w - 1)
return (smax_top, scnt_top, smax_bottom, scnt_bottom,
smax_left, scnt_left, smax_right, scnt_right)
def _process_strahler_tile(iy, ix, flow_dir_da, accum_da, threshold,
bdry_max, bdry_cnt, flow_bdry, mask_bdry,
chunks_y, chunks_x, n_tile_y, n_tile_x):
"""Run seeded Strahler BFS on one tile; update boundary stores."""
fd_chunk = np.asarray(
flow_dir_da.blocks[iy, ix].compute(), dtype=np.float64)
ac_chunk = np.asarray(
accum_da.blocks[iy, ix].compute(), dtype=np.float64)
sm = np.where(ac_chunk >= threshold, 1, 0).astype(np.int8)
sm = np.where(np.isnan(ac_chunk), 0, sm).astype(np.int8)
sm = np.where(np.isnan(fd_chunk), 0, sm).astype(np.int8)
h, w = fd_chunk.shape
seeds = _compute_strahler_seeds(
iy, ix, bdry_max, bdry_cnt, flow_bdry, mask_bdry,
chunks_y, chunks_x, n_tile_y, n_tile_x)
order = _strahler_tile_kernel(fd_chunk, sm, h, w, *seeds)
# Extract boundary order values and recompute max/cnt for boundaries
change = 0.0