-
Notifications
You must be signed in to change notification settings - Fork 13
/
dijkstra3d.pyx
1937 lines (1726 loc) · 55.7 KB
/
dijkstra3d.pyx
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
# cython: language_level=3
"""
Cython binding for C++ dijkstra's shortest path algorithm
applied to 3D images.
Contains:
dijkstra - Find the shortest 26-connected path from source
to target using the values of each voxel as edge weights.\
distance_field - Compute the distance field from a source
voxel in an image using image voxel values as edge weights.
euclidean_distance_field - Compute the euclidean distance
to each voxel in a binary image from a source point.
parental_field / path_from_parents - Same as dijkstra,
but if you're computing dijkstra multiple times on
the same image, this can be much much faster.
Authors: William Silversmith, Izzy Turtle (@turtleizzy on Github)
Affiliation: Seung Lab, Princeton Neuroscience Institute
Date: August 2018 - May 2023
"""
from libc.stdlib cimport calloc, free
from libc.stdint cimport (
int8_t, int16_t, int32_t, int64_t,
uint8_t, uint16_t, uint32_t, uint64_t
)
from cpython cimport array
import array
import sys
import cython
from libcpp.vector cimport vector
cimport numpy as cnp
import numpy as np
cnp.import_array()
import warnings
__VERSION__ = '1.14.0'
ctypedef fused UINT:
uint8_t
uint16_t
uint32_t
uint64_t
class DimensionError(Exception):
pass
cdef extern from "dijkstra3d.hpp" namespace "dijkstra":
cdef vector[OUT] dijkstra3d[T,OUT](
T* field,
size_t sx, size_t sy, size_t sz,
size_t source, size_t target,
int connectivity, uint32_t* voxel_graph
)
cdef vector[OUT] dijkstra3d_anisotropy[T,OUT](
T* field,
size_t sx, size_t sy, size_t sz,
size_t source, size_t target,
int connectivity,
float wx, float wy, float wz,
uint32_t* voxel_graph
)
cdef vector[OUT] binary_dijkstra3d[OUT](
uint8_t* field,
size_t sx, size_t sy, size_t sz,
size_t source, size_t target,
int connectivity,
float wx, float wy, float wz,
uint8_t euclidean_metric,
uint32_t* voxel_graph,
int background_color
)
cdef vector[OUT] bidirectional_dijkstra3d[T,OUT](
T* field,
size_t sx, size_t sy, size_t sz,
size_t source, size_t target,
int connectivity, uint32_t* voxel_graph
)
cdef vector[OUT] value_target_dijkstra3d[T,OUT](
T* field,
size_t sx, size_t sy, size_t sz,
size_t source, T target,
int connectivity,
uint32_t* voxel_connectivity_graph
)
cdef vector[OUT] compass_guided_dijkstra3d[T,OUT](
T* field,
size_t sx, size_t sy, size_t sz,
size_t source, size_t target,
int connectivity, float normalizer,
uint32_t* voxel_graph
)
cdef vector[OUT] compass_guided_dijkstra3d_anisotropy_line_preference[T,OUT](
T* field,
size_t sx, size_t sy, size_t sz,
size_t source, size_t target,
int connectivity, float normalizer, float line_preference_weight,
float wx, float wy, float wz,
uint32_t* voxel_graph
)
cdef float* distance_field3d[T](
T* field,
size_t sx, size_t sy, size_t sz,
vector[size_t] source, size_t connectivity,
uint32_t* voxel_graph, size_t &max_loc
)
cdef OUT* parental_field3d[T,OUT](
T* field,
size_t sx, size_t sy, size_t sz,
size_t source, OUT* parents,
int connectivity, uint32_t* voxel_graph
)
cdef float* euclidean_distance_field3d(
uint8_t* field,
size_t sx, size_t sy, size_t sz,
float wx, float wy, float wz,
vector[size_t] source,
float free_space_radius,
float* dist,
uint32_t* voxel_graph,
size_t &max_loc
)
cdef OUT* edf_with_feature_map[OUT](
uint8_t* field,
uint64_t sx, uint64_t sy, uint64_t sz,
float wx, float wy, float wz,
vector[uint64_t] &sources,
float* dist, OUT* feature_map,
size_t &max_loc
)
cdef vector[T] query_shortest_path[T](
T* parents, T target
)
def format_voxel_graph(voxel_graph):
while voxel_graph.ndim < 3:
voxel_graph = voxel_graph[..., np.newaxis]
if not np.issubdtype(voxel_graph.dtype, np.uint32):
voxel_graph = voxel_graph.astype(np.uint32, order="F")
return np.asfortranarray(voxel_graph)
@cython.binding(True)
def dijkstra(
data, source, target,
bidirectional=False, connectivity=26,
compass=False, compass_norm=-1, line_preference_weight=0,
voxel_graph=None,
anisotropy=None
):
"""
Perform dijkstra's shortest path algorithm
on a 3D image grid. Vertices are voxels and
edges are the 26 nearest neighbors (except
for the edges of the image where the number
of edges is reduced).
For given input voxels A and B, the edge
weight from A to B is B and from B to A is
A. All weights must be non-negative (incl.
negative zero).
If anisotropy is provided, the edge weight is
multiplied by the euclidean distance from the
center of the voxel to the face, edge, or corner
depending on the direction.
Parameters:
Data: Input weights in a 2D or 3D numpy array.
source: (x,y,z) coordinate of starting voxel
target: (x,y,z) coordinate of target voxel
bidirectional: If True, use more memory but conduct
a bidirectional search, which has the potential to be
much faster.
connectivity: 6 (faces), 18 (faces + edges), and
26 (faces + edges + corners) voxel graph connectivities
are supported. For 2D images, 4 gets translated to 6,
8 gets translated to 18.
compass: If True, A* search using the chessboard
distance to target as the heuristic. This has the
effect of guiding the search like using a compass.
This option has no effect when bidirectional search
is enabled as it is not supported yet.
compass_norm: Allows you to manipulate the relative
greed of the A* search. By default set to -1, which
means the norm will be the field minimum, but you
can choose whatever you want if you know what you're
doing.
voxel_graph: a bitwise representation of the premitted
directions of travel between voxels. Generated from
cc3d.voxel_connectivity_graph.
(See https://github.com/seung-lab/connected-components-3d)
anisotropy: If provided, [x,y,z] relative dimensions of each voxel
in the x,y, and z dimensions. This changes the weighting
calculation in the search by multiplying by the appropriate
euclidean weight for faces, edges, and corners.
Returns: 1D numpy array containing indices of the path from
source to target including source and target.
"""
dims = len(data.shape)
if dims not in (2,3):
raise DimensionError("Only 2D and 3D image sources are supported. Got: " + str(dims))
if dims == 2:
if connectivity == 4:
connectivity = 6
elif connectivity == 8:
connectivity = 18 # or 26 but 18 might be faster
if connectivity not in (6, 18, 26):
raise ValueError(
"Only 6, 18, and 26 connectivities are supported. Got: " + str(connectivity)
)
if data.size == 0:
return np.zeros(shape=(0,), dtype=np.uint32, order='F')
_validate_coord(data, source)
_validate_coord(data, target)
if dims == 2:
data = data[:, :, np.newaxis]
source = list(source) + [ 0 ]
target = list(target) + [ 0 ]
if voxel_graph is not None:
voxel_graph = format_voxel_graph(voxel_graph)
data = np.asfortranarray(data)
cdef size_t cols = data.shape[0]
cdef size_t rows = data.shape[1]
cdef size_t depth = data.shape[2]
if anisotropy is None:
path = _execute_dijkstra(
data, source, target, connectivity,
bidirectional, compass, compass_norm,
voxel_graph
)
else:
anisotropy = list(anisotropy)
while len(anisotropy) < 3:
anisotropy.append(float(1))
if bidirectional:
warnings.warn("bidirectional = True is not currently supported by \
anisotropy dijkstra3d. Fall back to vanilla dijkstra algorithm.")
path = _execute_dijkstra_anisotropy(
data, source, target, connectivity,
anisotropy, compass, compass_norm, voxel_graph, line_preference_weight
)
return _path_to_point_cloud(path, dims, rows, cols)
@cython.binding(True)
def railroad(
data, source,
connectivity=26, voxel_graph=None
):
"""
A "rail road" (a term defined by us) is the shortest
last-mile path (the "road") from a target point to a
"rail network" that includes the source point. A "rail"
is a zero weighted path that acts as a strong attractor
for the search algorithm. In the context of the
skeletonization problem, such networks are assembled
as a matter of course. It becomes more and more efficient
to search for the rail network than for the target point.
For given input voxels A and B, the edge
weight from A to B is B and from B to A is
A. All weights must be non-negative (incl.
negative zero).
Parameters:
Data: Input weights in a 2D or 3D numpy array.
source: (x,y,z) coordinate of starting voxel
connectivity: 6 (faces), 18 (faces + edges), and
26 (faces + edges + corners) voxel graph connectivities
are supported. For 2D images, 4 gets translated to 6,
8 gets translated to 18.
voxel_graph: a bitwise representation of the premitted
directions of travel between voxels. Generated from
cc3d.voxel_connectivity_graph.
(See https://github.com/seung-lab/connected-components-3d)
Returns: 1D numpy array containing indices of the path from
source to target including source and destination.
"""
dims = len(data.shape)
if dims not in (2,3):
raise DimensionError("Only 2D and 3D image sources are supported. Got: " + str(dims))
if dims == 2:
if connectivity == 4:
connectivity = 6
elif connectivity == 8:
connectivity = 18 # or 26 but 18 might be faster
if connectivity not in (6, 18, 26):
raise ValueError(
"Only 6, 18, and 26 connectivities are supported. Got: " + str(connectivity)
)
if data.size == 0:
return np.zeros(shape=(0,), dtype=np.uint32, order='F')
_validate_coord(data, source)
if dims == 2:
data = data[:, :, np.newaxis]
source = list(source) + [ 0 ]
if voxel_graph is not None:
voxel_graph = format_voxel_graph(voxel_graph)
data = np.asfortranarray(data)
cdef size_t cols = data.shape[0]
cdef size_t rows = data.shape[1]
path = _execute_value_target_dijkstra(
data, source,
connectivity, voxel_graph
)
return _path_to_point_cloud(path, dims, rows, cols)
@cython.binding(True)
def binary_dijkstra(
data, source, target,
connectivity=26,
background_color=0,
anisotropy=(1.0, 1.0, 1.0),
euclidean_metric=True,
voxel_graph=None
):
"""
Perform dijkstra's shortest path algorithm
on a 3D image grid. Vertices are voxels and
edges are the 26 nearest neighbors (except
for the edges of the image where the number
of edges is reduced).
This version treats the data as a binary image
with the background color set to 0 or 1. Background
voxels will not be considered.
Parameters:
Data: Input weights in a 2D or 3D numpy array.
source: (x,y,z) coordinate of starting voxel
target: (x,y,z) coordinate of target voxel
anisotropy: (wx,wy,wz) weights for each axial direction.
background_color: 1 or 0, pick which color in a binary image
will be considered background.
connectivity: 6 (faces), 18 (faces + edges), and
26 (faces + edges + corners) voxel graph connectivities
are supported. For 2D images, 4 gets translated to 6,
8 gets translated to 18.
euclidean_metric: if True, treat the image as a euclidean
space weighted by the anisotropy on x, y, and z. Otherwise,
each movement in any direction, including diagonals,
are evenly weighted.
voxel_graph: a bitwise representation of the premitted
directions of travel between voxels. Generated from
cc3d.voxel_connectivity_graph.
(See https://github.com/seung-lab/connected-components-3d)
Returns: 1D numpy array containing indices of the path from
source to target including source and target.
"""
dims = len(data.shape)
if dims not in (2,3):
raise DimensionError("Only 2D and 3D image sources are supported. Got: " + str(dims))
if dims == 2:
if connectivity == 4:
connectivity = 6
elif connectivity == 8:
connectivity = 18 # or 26 but 18 might be faster
if connectivity not in (6, 18, 26):
raise ValueError(
"Only 6, 18, and 26 connectivities are supported. Got: " + str(connectivity)
)
if not np.issubdtype(data.dtype, bool):
raise ValueError(f"This function only accepts boolean type images. Got: {data.dtype}")
if data.size == 0:
return np.zeros(shape=(0,), dtype=np.uint32, order='F')
_validate_coord(data, source)
_validate_coord(data, target)
if dims == 2:
data = data[:, :, np.newaxis]
source = list(source) + [ 0 ]
target = list(target) + [ 0 ]
if voxel_graph is not None:
voxel_graph = format_voxel_graph(voxel_graph)
data = np.asfortranarray(data)
cdef size_t cols = data.shape[0]
cdef size_t rows = data.shape[1]
cdef size_t depth = data.shape[2]
path = _execute_binary_dijkstra(
data, source, target, connectivity,
anisotropy[0], anisotropy[1], anisotropy[2],
euclidean_metric,
voxel_graph, background_color
)
return _path_to_point_cloud(path, dims, rows, cols)
@cython.binding(True)
def distance_field(
data, source, connectivity=26,
voxel_graph=None, return_max_location=False
):
"""
Use dijkstra's shortest path algorithm
on a 3D image grid to generate a weighted
distance field from one or more source voxels. Vertices are
voxels and edges are the 26 nearest neighbors
(except for the edges of the image where
the number of edges is reduced).
For given input voxels A and B, the edge
weight from A to B is B and from B to A is
A. All weights must be non-negative (incl.
negative zero).
Parameters:
data: Input weights in a 2D or 3D numpy array.
source: (x,y,z) coordinate or list of coordinates
of starting voxels.
connectivity: 26, 18, or 6 connected.
return_max_location: returns the coordinates of one
of the possibly multiple maxima.
Returns:
let field = 2D or 3D numpy array with each index
containing its distance from the source voxel.
if return_max_location:
return (field, (x,y,z) of max distance)
else:
return field
"""
dims = len(data.shape)
if dims not in (2,3):
raise DimensionError("Only 2D and 3D image sources are supported. Got: " + str(dims))
if dims == 2:
if connectivity == 4:
connectivity = 6
elif connectivity == 8:
connectivity = 18 # or 26 but 18 might be faster
if connectivity not in (6, 18, 26):
raise ValueError(
"Only 6, 18, and 26 connectivities are supported. Got: " + str(connectivity)
)
if data.size == 0:
return np.zeros(shape=(0,), dtype=np.float32)
source = np.array(source, dtype=np.uint64)
if source.ndim == 1:
source = source[np.newaxis, :]
for src in source:
_validate_coord(data, src)
if source.shape[1] < 3:
tmp = np.zeros((source.shape[0], 3), dtype=np.uint64)
tmp[:, :source.shape[1]] = source[:,:]
source = tmp
while data.ndim < 3:
data = data[..., np.newaxis]
if voxel_graph is not None:
voxel_graph = format_voxel_graph(voxel_graph)
data = np.asfortranarray(data)
field, max_loc = _execute_distance_field(data, source, connectivity, voxel_graph)
if dims < 3:
field = np.squeeze(field, axis=2)
if dims < 2:
field = np.squeeze(field, axis=1)
if return_max_location:
return field, np.unravel_index(max_loc, data.shape, order="F")[:dims]
else:
return field
# parents is either uint32 or uint64
def _path_from_parents_helper(cnp.ndarray[UINT, ndim=3] parents, target):
cdef UINT[:,:,:] arr_memview
cdef vector[UINT] path
cdef UINT* path_ptr
cdef UINT[:] vec_view
cdef size_t sx = parents.shape[0]
cdef size_t sy = parents.shape[1]
cdef size_t sz = parents.shape[2]
cdef UINT targ = target[0] + sx * (target[1] + sy * target[2])
arr_memview = parents
path = query_shortest_path(&arr_memview[0,0,0], targ)
path_ptr = <UINT*>&path[0]
vec_view = <UINT[:path.size()]>path_ptr
buf = bytearray(vec_view[:])
return np.frombuffer(buf, dtype=parents.dtype)[::-1]
def path_from_parents(parents, target):
ndim = parents.ndim
while parents.ndim < 3:
parents = parents[..., np.newaxis]
while len(target) < 3:
target += (0,)
cdef size_t sx = parents.shape[0]
cdef size_t sy = parents.shape[1]
numpy_path = _path_from_parents_helper(parents, target)
ptlist = _path_to_point_cloud(numpy_path, 3, sy, sx)
return ptlist[:, :ndim]
@cython.binding(True)
def parental_field(data, source, connectivity=26, voxel_graph=None):
"""
Use dijkstra's shortest path algorithm
on a 3D image grid to generate field of
voxels that point to their parent voxel.
This is used to execute dijkstra's algorithm
once, and then query different targets for
the path they represent.
Parameters:
data: Input weights in a 2D or 3D numpy array.
source: (x,y,z) coordinate of starting voxel
connectivity: 6 (faces), 18 (faces + edges), and
26 (faces + edges + corners) voxel graph connectivities
are supported. For 2D images, 4 gets translated to 6,
8 gets translated to 18.
Returns: 2D or 3D numpy array with each index
containing the index of its parent. The root
of a path has index 0.
"""
dims = len(data.shape)
if dims not in (2,3):
raise DimensionError("Only 2D and 3D image sources are supported. Got: " + str(dims))
if dims == 2:
if connectivity == 4:
connectivity = 6
elif connectivity == 8:
connectivity = 18 # or 26 but 18 might be faster
if connectivity not in (6,18,26):
raise ValueError(
"Only 6, 18, and 26 connectivities are supported. Got: " + str(connectivity)
)
if data.size == 0:
return np.zeros(shape=(0,), dtype=np.float32)
if dims == 1:
data = data[:, np.newaxis, np.newaxis]
source = ( source[0], 0, 0 )
if dims == 2:
data = data[:, :, np.newaxis]
source = ( source[0], source[1], 0 )
if voxel_graph is not None:
voxel_graph = format_voxel_graph(voxel_graph)
_validate_coord(data, source)
data = np.asfortranarray(data)
field = _execute_parental_field(data, source, connectivity, voxel_graph)
if dims < 3:
field = np.squeeze(field, axis=2)
if dims < 2:
field = np.squeeze(field, axis=1)
return field
@cython.binding(True)
def euclidean_distance_field(
data, source, anisotropy=(1,1,1),
free_space_radius=0, voxel_graph=None,
return_max_location=False,
return_feature_map=False,
):
"""
Use dijkstra's shortest path algorithm
on a 3D image grid to generate a weighted
euclidean distance field from a source voxel
from a binary image. Vertices are
voxels and edges are the 26 nearest neighbors
(except for the edges of the image where
the number of edges is reduced).
For given input voxels A and B, the edge
weight from A to B is B and from B to A is
A. All weights must be non-negative (incl.
negative zero).
Parameters:
data: binary image represented as a 2D or 3D numpy array.
source: (x,y,z) coordinate or list of coordinates
of starting voxels
anisotropy: (wx,wy,wz) weights for each axial direction.
free_space_radius: (float, optional) if you know that the
region surrounding the source is free space, we can use
a much faster algorithm to fill in that volume. Value
is physical radius (can get this from the EDT).
voxel_graph: a bitwise representation of the premitted
directions of travel between voxels. Generated from
cc3d.voxel_connectivity_graph.
(See https://github.com/seung-lab/connected-components-3d)
return_max_location: returns the coordinates of one
of the possibly multiple maxima.
return_feature_map: return labeling of the image such
that all the voxels nearest a given source point are
a single label. At locations where two labels are
equidistant, the numerically larger label wins (to
differences in behavior on different platforms).
Returns:
let field = 2D or 3D numpy array with each index
containing its distance from the source voxel.
if return_max_location and return_feature_map:
return (field, (x,y,z) of max distance, feature_map)
elif return_max_location:
return (field, (x,y,z) of max distance)
elif return_feature_map:
return (field, feature_map)
else:
return field
"""
dims = len(data.shape)
if dims > 3:
raise DimensionError(f"Only 2D and 3D image sources are supported. Got: {dims}")
if data.size == 0:
return np.zeros(shape=(0,), dtype=np.float32)
source = np.array(source, dtype=np.uint64)
if source.ndim == 1:
source = source[np.newaxis, :]
if source.shape[1] < 3:
tmp = np.zeros((source.shape[0], 3), dtype=np.uint64)
tmp[:, :source.shape[1]] = source[:,:]
source = tmp
while data.ndim < 3:
data = data[..., np.newaxis]
for src in source:
_validate_coord(data, src)
if voxel_graph is not None:
voxel_graph = format_voxel_graph(voxel_graph)
data = np.asfortranarray(data)
if return_feature_map:
field, feature_map, max_loc = _execute_euclidean_distance_field_w_feature_map(
data, source, anisotropy,
)
else:
feature_map = None
field, max_loc = _execute_euclidean_distance_field(
data, source, anisotropy,
free_space_radius, voxel_graph
)
if dims < 3:
field = np.squeeze(field, axis=2)
if feature_map:
feature_map = np.squeeze(feature_map, axis=2)
if dims < 2:
field = np.squeeze(field, axis=1)
if feature_map:
feature_map = np.squeeze(feature_map, axis=1)
ret = [ field ]
if return_max_location:
ret.append(
np.unravel_index(max_loc, data.shape, order="F")[:dims]
)
if return_feature_map:
ret.append(feature_map)
if len(ret) == 1:
return ret[0]
return tuple(ret)
def _validate_coord(data, coord):
dims = len(data.shape)
if len(coord) != dims:
raise IndexError(
"Coordinates must have the same dimension as the data. coord: {}, data shape: {}"
.format(coord, data.shape)
)
for i, size in enumerate(data.shape):
if coord[i] < 0 or coord[i] >= size:
raise IndexError("Selected voxel {} was not located inside the array.".format(coord))
def _path_to_point_cloud(path, dims, rows, cols):
ptlist = np.zeros((path.shape[0], dims), dtype=np.uint32)
cdef size_t sxy = rows * cols
cdef size_t i = 0
if dims == 3:
for i, pt in enumerate(path):
ptlist[ i, 0 ] = pt % cols
ptlist[ i, 1 ] = (pt % sxy) / cols
ptlist[ i, 2 ] = pt / sxy
else:
for i, pt in enumerate(path):
ptlist[ i, 0 ] = pt % cols
ptlist[ i, 1 ] = (pt % sxy) / cols
return ptlist
def _execute_value_target_dijkstra(
data, source,
int connectivity, voxel_graph=None
):
cdef uint8_t[:,:,:] arr_memview8
cdef uint16_t[:,:,:] arr_memview16
cdef uint32_t[:,:,:] arr_memview32
cdef uint64_t[:,:,:] arr_memview64
cdef float[:,:,:] arr_memviewfloat
cdef double[:,:,:] arr_memviewdouble
cdef uint32_t[:,:,:] voxel_graph_memview
cdef uint32_t* voxel_graph_ptr = NULL
if voxel_graph is not None:
voxel_graph_memview = voxel_graph
voxel_graph_ptr = <uint32_t*>&voxel_graph_memview[0,0,0]
cdef size_t sx = data.shape[0]
cdef size_t sy = data.shape[1]
cdef size_t sz = data.shape[2]
cdef size_t src = source[0] + sx * (source[1] + sy * source[2])
cdef vector[uint32_t] output32
cdef vector[uint64_t] output64
sixtyfourbit = data.size > np.iinfo(np.uint32).max
dtype = data.dtype
if dtype == np.float32:
arr_memviewfloat = data
if sixtyfourbit:
output64 = value_target_dijkstra3d[float, uint64_t](
&arr_memviewfloat[0,0,0],
sx, sy, sz,
src, 0, connectivity,
voxel_graph_ptr
)
else:
output32 = value_target_dijkstra3d[float, uint32_t](
&arr_memviewfloat[0,0,0],
sx, sy, sz,
src, 0, connectivity,
voxel_graph_ptr
)
elif dtype == np.float64:
arr_memviewdouble = data
if sixtyfourbit:
output64 = value_target_dijkstra3d[double, uint64_t](
&arr_memviewdouble[0,0,0],
sx, sy, sz,
src, 0, connectivity,
voxel_graph_ptr
)
else:
output32 = value_target_dijkstra3d[double, uint32_t](
&arr_memviewdouble[0,0,0],
sx, sy, sz,
src, 0, connectivity,
voxel_graph_ptr
)
elif dtype in (np.int64, np.uint64):
arr_memview64 = data.view(np.uint64)
if sixtyfourbit:
output64 = value_target_dijkstra3d[uint64_t, uint64_t](
&arr_memview64[0,0,0],
sx, sy, sz,
src, 0, connectivity,
voxel_graph_ptr
)
else:
output32 = value_target_dijkstra3d[uint64_t, uint32_t](
&arr_memview64[0,0,0],
sx, sy, sz,
src, 0, connectivity,
voxel_graph_ptr
)
elif dtype in (np.int32, np.uint32):
arr_memview32 = data.view(np.uint32)
if sixtyfourbit:
output64 = value_target_dijkstra3d[uint32_t, uint64_t](
&arr_memview32[0,0,0],
sx, sy, sz,
src, 0, connectivity,
voxel_graph_ptr
)
else:
output32 = value_target_dijkstra3d[uint32_t, uint32_t](
&arr_memview32[0,0,0],
sx, sy, sz,
src, 0, connectivity,
voxel_graph_ptr
)
elif dtype in (np.int16, np.uint16):
arr_memview16 = data.view(np.uint16)
if sixtyfourbit:
output64 = value_target_dijkstra3d[uint16_t, uint64_t](
&arr_memview16[0,0,0],
sx, sy, sz,
src, 0, connectivity,
voxel_graph_ptr
)
else:
output32 = value_target_dijkstra3d[uint16_t, uint32_t](
&arr_memview16[0,0,0],
sx, sy, sz,
src, 0, connectivity,
voxel_graph_ptr
)
elif dtype in (np.int8, np.uint8, bool):
arr_memview8 = data.view(np.uint8)
if sixtyfourbit:
output64 = value_target_dijkstra3d[uint8_t, uint64_t](
&arr_memview8[0,0,0],
sx, sy, sz,
src, 0, connectivity,
voxel_graph_ptr
)
else:
output32 = value_target_dijkstra3d[uint8_t, uint32_t](
&arr_memview8[0,0,0],
sx, sy, sz,
src, 0, connectivity,
voxel_graph_ptr
)
cdef uint32_t* output_ptr32
cdef uint64_t* output_ptr64
cdef uint32_t[:] vec_view32
cdef uint64_t[:] vec_view64
if sixtyfourbit:
output_ptr64 = <uint64_t*>&output64[0]
if output64.size() == 0:
return np.zeros((0,), dtype=np.uint64)
vec_view64 = <uint64_t[:output64.size()]>output_ptr64
buf = bytearray(vec_view64[:])
output = np.frombuffer(buf, dtype=np.uint64)
else:
output_ptr32 = <uint32_t*>&output32[0]
if output32.size() == 0:
return np.zeros((0,), dtype=np.uint32)
vec_view32 = <uint32_t[:output32.size()]>output_ptr32
buf = bytearray(vec_view32[:])
output = np.frombuffer(buf, dtype=np.uint32)
return output[::-1]
def _execute_dijkstra(
data, source, target, int connectivity,
bidirectional, compass, float compass_norm=-1,
voxel_graph=None
):
cdef uint8_t[:,:,:] arr_memview8
cdef uint16_t[:,:,:] arr_memview16
cdef uint32_t[:,:,:] arr_memview32
cdef uint64_t[:,:,:] arr_memview64
cdef float[:,:,:] arr_memviewfloat
cdef double[:,:,:] arr_memviewdouble
cdef uint32_t[:,:,:] voxel_graph_memview
cdef uint32_t* voxel_graph_ptr = NULL
if voxel_graph is not None:
voxel_graph_memview = voxel_graph
voxel_graph_ptr = <uint32_t*>&voxel_graph_memview[0,0,0]
cdef size_t sx = data.shape[0]
cdef size_t sy = data.shape[1]
cdef size_t sz = data.shape[2]
cdef size_t src = source[0] + sx * (source[1] + sy * source[2])
cdef size_t sink = target[0] + sx * (target[1] + sy * target[2])
cdef vector[uint32_t] output32
cdef vector[uint64_t] output64
sixtyfourbit = data.size > np.iinfo(np.uint32).max
dtype = data.dtype
if dtype == np.float32:
arr_memviewfloat = data
if bidirectional:
if sixtyfourbit:
output64 = bidirectional_dijkstra3d[float, uint64_t](
&arr_memviewfloat[0,0,0],
sx, sy, sz,
src, sink, connectivity,
voxel_graph_ptr
)
else:
output32 = bidirectional_dijkstra3d[float, uint32_t](
&arr_memviewfloat[0,0,0],
sx, sy, sz,
src, sink, connectivity,
voxel_graph_ptr
)
elif compass:
if sixtyfourbit:
output64 = compass_guided_dijkstra3d[float, uint64_t](
&arr_memviewfloat[0,0,0],
sx, sy, sz,
src, sink,
connectivity, compass_norm,
voxel_graph_ptr
)
else:
output32 = compass_guided_dijkstra3d[float, uint32_t](
&arr_memviewfloat[0,0,0],
sx, sy, sz,
src, sink,
connectivity, compass_norm,
voxel_graph_ptr
)
else:
if sixtyfourbit:
output64 = dijkstra3d[float, uint64_t](
&arr_memviewfloat[0,0,0],
sx, sy, sz,
src, sink, connectivity,
voxel_graph_ptr
)
else:
output32 = dijkstra3d[float, uint32_t](
&arr_memviewfloat[0,0,0],
sx, sy, sz,
src, sink, connectivity,
voxel_graph_ptr
)
elif dtype == np.float64:
arr_memviewdouble = data
if bidirectional:
if sixtyfourbit:
output64 = bidirectional_dijkstra3d[double, uint64_t](
&arr_memviewdouble[0,0,0],
sx, sy, sz,
src, sink, connectivity,
voxel_graph_ptr
)
else:
output32 = bidirectional_dijkstra3d[double, uint32_t](
&arr_memviewdouble[0,0,0],
sx, sy, sz,