-
Notifications
You must be signed in to change notification settings - Fork 4
/
CMap2D.pyx
2248 lines (2136 loc) · 99.8 KB
/
CMap2D.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
# distutils: language=c++
from libcpp cimport bool
from libcpp.queue cimport priority_queue as cpp_priority_queue
from libcpp.pair cimport pair as cpp_pair
import numpy as np
cimport numpy as np
from cython.operator cimport dereference as deref
cimport cython
from math import sqrt
from libc.math cimport cos as ccos
from libc.math cimport sin as csin
from libc.math cimport acos as cacos
from libc.math cimport sqrt as csqrt
from libc.math cimport floor as cfloor
import os
from yaml import load, SafeLoader
from matplotlib.pyplot import imread
def gridshow(*args, **kwargs):
""" utility function for showing 2d grids in matplotlib,
wrapper around pyplot.imshow
use 'extent' = [-1, 1, -1, 1] to change the axis values """
from matplotlib import pyplot as plt
if not 'origin' in kwargs:
kwargs['origin'] = 'lower'
if not 'cmap' in kwargs:
kwargs['cmap'] = plt.cm.Greys
return plt.imshow(*(arg.T if i == 0 else arg for i, arg in enumerate(args)), **kwargs)
cdef class CMap2D:
# these names are inconsistent, but kept for legacy reasons
cdef public np.float32_t[:,::1] _occupancy # (0 to 1) 1 means 100% certain occupied # [:, ::1] means 2d c-contiguous
cdef int occupancy_shape0
cdef int occupancy_shape1
cdef float resolution_ # [meters] side of 1 grid square
cdef float _thresh_occupied
cdef float thresh_free
cdef float HUGE_ # bigger than any possible distance in the map
cdef public np.float32_t[:] origin # [meters] x y coordinates of point at i = j = 0
def __init__(self, folder=None, name=None, silent=False):
self._occupancy = np.ones((100, 100), dtype=np.float32) * 0.5
self.occupancy_shape0 = 100
self.occupancy_shape1 = 100
self.resolution_ = 0.01
self.origin = np.array([0., 0.], dtype=np.float32)
self._thresh_occupied = 0.9
self.thresh_free = 0.1
self.HUGE_ = 1e10
if folder is None or name is None:
return
# Load map from file
folder = os.path.expanduser(folder)
yaml_file = os.path.join(folder, name + ".yaml")
if not silent:
print("Loading map definition from {}".format(yaml_file))
with open(yaml_file) as stream:
mapparams = load(stream, Loader=SafeLoader)
map_file = os.path.join(folder, mapparams["image"])
if not silent:
print("Map definition found. Loading map from {}".format(map_file))
mapimage = imread(map_file)
temp = (1. - mapimage.T[:, ::-1] / 254.).astype(np.float32)
mapimage = np.ascontiguousarray(temp)
self._occupancy = mapimage
self.occupancy_shape0 = mapimage.shape[0]
self.occupancy_shape1 = mapimage.shape[1]
self.resolution_ = mapparams["resolution"]
self.origin = np.array(mapparams["origin"][:2]).astype(np.float32)
if mapparams["origin"][2] != 0:
raise ValueError(
"Map files with a rotated frame (origin.theta != 0) are not"
" supported. Setting the value to 0 in the MAP_NAME.yaml file is one way to"
" resolve this."
)
self._thresh_occupied = mapparams["occupied_thresh"]
self.thresh_free = mapparams["free_thresh"]
self.HUGE_ = 100 * self.occupancy_shape0 * self.occupancy_shape1
if self.resolution_ == 0:
raise ValueError("resolution can not be 0")
def from_array(self, occupancy, origin, resolution, thresh_free=0.1, thresh_occupied=0.9):
""" Ideally this would be the default constructor (for legacy reasons loading from file is kept)
as convention, the x y coordinates correspond to the first and second index (i and j), respectively
map[i, j]
i <-> x
j <-> y
arguments:
occupancy (ndarray): 2D array with occupancy values (0-1 if thresholds are not set)
origin (tuple of size 2): x, y coordinates [m] of bottom left grid cell (i=0, j=0)
resolution (float): cell size [m]
thresh_free (float): values less than this are considered not occupied
thresh_occupied (float): values more than this are considered occupied
"""
data = np.ascontiguousarray(occupancy.astype(np.float32))
self._occupancy = data
self.occupancy_shape0 = data.shape[0]
self.occupancy_shape1 = data.shape[1]
self.resolution_ = float(resolution)
self.origin = np.array(origin).astype(np.float32)
self._thresh_occupied = float(thresh_occupied)
self.thresh_free = float(thresh_free)
self.HUGE_ = 100 * self.occupancy_shape0 * self.occupancy_shape1
if self.resolution_ == 0:
raise ValueError("resolution can not be 0")
def empty_like(self):
width_i = self._occupancy.shape[0]
height_j = self._occupancy.shape[1]
newmap = CMap2D()
newmap._occupancy = np.zeros((width_i, height_j), dtype=np.float32)
newmap.occupancy_shape0 = width_i
newmap.occupancy_shape1 = height_j
newmap.resolution_ = self.resolution_
newmap.origin[0] = self.origin[0]
newmap.origin[1] = self.origin[1]
newmap._thresh_occupied = self._thresh_occupied
newmap.thresh_free = self.thresh_free
newmap.HUGE_ = self.HUGE_
return newmap
def from_msg(self, msg):
self.origin[0] = msg.info.origin.position.x
self.origin[1] = msg.info.origin.position.y
self.set_resolution(msg.info.resolution)
self.cset_occupancy(
np.ascontiguousarray(np.array(msg.data).reshape(
(msg.info.height, msg.info.width)
).T * 0.01).astype(np.float32)
)
self.HUGE_ = 100 * np.prod(
self._occupancy.shape
) # bigger than any possible distance in the map
# self._thresh_occupied # TODO
# self.thresh_free
def from_scan(self, scan, resolution=0.05, limits=None, inscribed_radius=None, legacy=True):
""" Creating a map from a scan places the x y origin in the center of the grid,
and generates the occupancy field from the laser data.
limits are in lidar frame (meters) [[xmin, xmax], [ymin, ymax]]
"""
angles = np.arange(scan.angle_min,
scan.angle_max + scan.angle_increment,
scan.angle_increment, dtype=np.float32)[:len(scan.ranges)]
ranges = np.array(scan.ranges, dtype=np.float32)
if inscribed_radius is not None:
ranges[ranges < inscribed_radius] = np.inf
xy_hits = (ranges * np.array([np.cos(angles), np.sin(angles)])).T
xy_hits = xy_hits[ranges != 0]
xy_hits = np.ascontiguousarray(xy_hits.astype(np.float32))
if limits is None:
limits = np.array([[np.min(xy_hits[:,0]), np.max(xy_hits[:,0])],
[np.min(xy_hits[:,1]), np.max(xy_hits[:,1])]],
dtype=np.float32)
# fill map
self.origin = limits[:, 0]
width = int((limits[0, 1] - limits[0, 0]) / resolution)
height = int((limits[1, 1] - limits[1, 0]) / resolution)
self.occupancy_shape0 = width
self.occupancy_shape1 = height
self.resolution_ = resolution
self._thresh_occupied = 0.9
self.thresh_free = 0.1
if legacy:
ij_hits = self.xy_to_ij(xy_hits, clip_if_outside=False)
is_inside = self.is_inside_ij(ij_hits.astype(np.float32))
ij_hits = ij_hits[np.where(is_inside)]
occupancy = 0.05 * np.ones((width, height), dtype=np.float32)
occupancy[tuple(ij_hits.T)] = 0.95
self._occupancy = occupancy
else:
observer_ij = self.xy_to_ij(np.array([[0, 0]]))[0]
occupancy = np.ones((width, height), dtype=np.float32) * 0.5
self.creverse_raytrace_lidar(np.array(observer_ij).astype(np.int64), angles, ranges, occupancy)
self._occupancy = occupancy
# ij_laser_orig = (-self.origin / self.resolution_).astype(int)
# compiled_reverse_raytrace(ij_hits, ij_laser_orig, self.occupancy_) # TODO
def from_closed_obst_vertices(self, contours, resolution=0.05, pad_ij=2.):
""" contours is a list of lists of vertices, in clockwise order (counterclockwise for bounding obstacles)
"""
unsorted_vertices = np.array([vert for c in contours for vert in c])
PAD = resolution * pad_ij
limits = np.array([[np.min(unsorted_vertices[:,0])-PAD, np.max(unsorted_vertices[:,0])+PAD],
[np.min(unsorted_vertices[:,1])-PAD, np.max(unsorted_vertices[:,1])+PAD]],
dtype=np.float32)
# fill map
self.origin = limits[:, 0]
width = int((limits[0, 1] - limits[0, 0]) / resolution)
height = int((limits[1, 1] - limits[1, 0]) / resolution)
self.occupancy_shape0 = width
self.occupancy_shape1 = height
self.resolution_ = resolution
self._thresh_occupied = 0.9
self.thresh_free = 0.1
occupancy = 0.05 * np.ones((width, height), dtype=np.float32)
self._occupancy = occupancy
self.fill_polygon_obstacles(contours)
def fill_polygon_obstacles(self, contours):
# stencil occupancy by walking along polygon edges (at half resolution step)
occupancy = np.array(self._occupancy)
for c in contours:
verts = np.concatenate((c, [c[0]]), axis=0) # convert to array and connect first/last vert
for va, vb in zip(verts[:-1], verts[1:]):
delta = vb - va
edgelength = np.linalg.norm(delta)
nsteps = int(np.ceil(edgelength * 2. / self.resolution_))
t = np.linspace(0., 1., nsteps)
steps = va[None, :] + t[:, None] * delta[None, :]
steps_ij = self.xy_to_ij(steps)
occupancy[tuple(steps_ij.T)] = 0.95
self._occupancy = occupancy
def serialize(self):
return {
"occupancy": np.array(self._occupancy),
"occupancy_shape0": int(self.occupancy_shape0),
"occupancy_shape1": int(self.occupancy_shape1),
"resolution_": float(self.resolution_),
"_thresh_occupied": float(self._thresh_occupied),
"thresh_free": float(self.thresh_free),
"HUGE_": float(self.HUGE_),
"origin": np.array(self.origin),
}
def unserialize(self, dict_):
# WARNING: changing the dict strings will break compatiblity with previously saved maps!
# (for example, IAN ros node saves maps as part of fixed state in log)
self._occupancy = dict_["occupancy"]
self.occupancy_shape0 = dict_["occupancy_shape0"]
self.occupancy_shape1 = dict_["occupancy_shape1"]
self.resolution_ = dict_["resolution_"]
self._thresh_occupied = dict_["_thresh_occupied"]
self.thresh_free = dict_["thresh_free"]
self.HUGE_ = dict_["HUGE_"]
self.origin = dict_["origin"]
def cset_occupancy(self, np.float32_t[:,::1] occupancy):
self._occupancy = occupancy.copy()
self.occupancy_shape0 = occupancy.shape[0]
self.occupancy_shape1 = occupancy.shape[1]
def cset_resolution(self, float res):
self.resolution_ = res
def set_resolution(self, res):
self.cset_resolution(res)
def resolution(self):
res = float(self.resolution_)
return res
def thresh_occupied(self):
res = float(self._thresh_occupied)
return res
def as_occupied_points_ij(self):
return np.ascontiguousarray(np.array(np.where(self.occupancy() > self.thresh_occupied())).T)
def as_closed_obst_vertices(self):
""" Converts map into list of contours of obstacles, in xy
returns list of obstacles, for each obstacle a list of xy vertices constituing its contour
based on the opencv2 findContours function
contours = [ [[x1, y1], [x2, y2], ...], [...] ]
"""
cont = self.as_closed_obst_vertices_ij()
# switch i j
contours = [self.ij_to_xy(c) for c in cont]
return contours
def as_closed_obst_vertices_ij(self):
""" Converts map into list of contours of obstacles, in ij
returns list of obstacles, for each obstacle a list of ij vertices constituing its contour
based on the opencv2 findContours function
"""
import cv2
gray = self.occupancy()
ret, thresh = cv2.threshold(gray, self.thresh_occupied(), 1, cv2.THRESH_BINARY)
thresh = thresh.astype(np.uint8)
kernel = np.ones((3,3),np.uint8)
thresh = cv2.dilate(thresh, kernel, iterations=1)
cv2_output = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
# len(cv2_output) depends on cv2 version :/
if cv2.__version__[0] == '4':
cont = cv2_output[0]
elif cv2.__version__[0] == '3':
cont = cv2_output[1]
else:
raise NotImplementedError("cv version {} unsupported".format(cv2.__version__))
# remove extra dim
contours = [np.vstack([c[:,0,1], c[:,0,0]]).T for c in cont]
return contours
def plot_contours(self, *args, **kwargs):
from matplotlib import pyplot as plt
if not args:
raise ValueError("args empty. contours must be supplied as first argument.")
if len(args) == 1:
args = args + ('-,',)
contours = args[0]
args = args[1:]
for c in contours:
# add the first vertice at the end to close the plotted contour
cplus = np.concatenate((c, c[:1]), axis=0)
plt.plot(cplus[:,0], cplus[:,1], *args, **kwargs)
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision(True)
cdef cas_sdf(self, np.int64_t[:,::1] occupied_points_ij, np.float32_t[:, ::1] min_distances):
""" everything in ij units """
cdef np.int64_t[:] point
cdef np.int64_t pi
cdef np.int64_t pj
cdef np.float32_t norm
cdef np.int64_t i
cdef np.int64_t j
cdef np.float32_t smallest_dist
cdef int n_occupied_points_ij = len(occupied_points_ij)
for i in range(min_distances.shape[0]):
for j in range(min_distances.shape[1]):
smallest_dist = min_distances[i, j]
for k in range(n_occupied_points_ij):
point = occupied_points_ij[k]
pi = point[0]
pj = point[1]
norm = csqrt((pi - i) ** 2 + (pj - j) ** 2)
if norm < smallest_dist:
smallest_dist = norm
min_distances[i, j] = smallest_dist
def distance_transform_2d(self):
f = np.zeros_like(self.occupancy(), dtype=np.float32)
f[self.occupancy() <= self.thresh_occupied()] = np.inf
D = np.ones_like(self.occupancy(), dtype=np.float32) * np.inf
cdistance_transform_2d(f, D)
return np.sqrt(D)*self.resolution()
def distance_transform_2d_ij(self):
f = np.zeros_like(self.occupancy(), dtype=np.float32)
f[self.occupancy() <= self.thresh_occupied()] = np.inf
D = np.ones_like(self.occupancy(), dtype=np.float32) * np.inf
cdistance_transform_2d(f, D)
return np.sqrt(D)
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision(True)
cdef cas_tsdf(self, np.float32_t max_dist_m, np.int64_t[:,::1] occupied_points_ij, np.float32_t[:, ::1] min_distances):
# DEPRECATED
""" everything in ij units """
cdef np.int64_t max_dist_ij = np.int64((max_dist_m / self.resolution_))
cdef np.int64_t[:] point
cdef np.int64_t pi
cdef np.int64_t pj
cdef np.float32_t norm
cdef np.int64_t i
cdef np.int64_t j
cdef np.int64_t iend
cdef np.int64_t jend
for k in range(len(occupied_points_ij)):
point = occupied_points_ij[k]
pi = point[0]
pj = point[1]
i = max(pi - max_dist_ij, 0)
iend = min(pi + max_dist_ij, min_distances.shape[0] - 1)
j = max(pj - max_dist_ij, 0)
jend = min(pj + max_dist_ij, min_distances.shape[1] - 1)
while True:
j = max(pj - max_dist_ij, 0)
while True:
norm = csqrt((pi - i) ** 2 + (pj - j) ** 2)
if norm < min_distances[i, j]:
min_distances[i, j] = norm
j = j+1
if j >= jend: break
i = i+1
if i >= iend: break
def as_tsdf(self, max_dist_m):
# this is faster than the still poorly optimized cas_tsdf
min_distances = self.as_sdf()
min_distances[min_distances > max_dist_m] = max_dist_m
min_distances[min_distances < -max_dist_m] = -max_dist_m
return min_distances
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision(True)
cdef cxy_to_ij(self, np.float32_t[:,::1] xy, np.float32_t[:,::1] ij, bool clip_if_outside=True):
if xy.shape[1] != 2:
raise IndexError("xy should be of shape (n, 2)")
for k in range(xy.shape[0]):
ij[k, 0] = (xy[k, 0] - self.origin[0]) / self.resolution_
ij[k, 1] = (xy[k, 1] - self.origin[1]) / self.resolution_
if clip_if_outside:
for k in range(xy.shape[0]):
if ij[k, 0] >= self.occupancy_shape0:
ij[k, 0] = self.occupancy_shape0 - 1
if ij[k, 1] >= self.occupancy_shape1:
ij[k, 1] = self.occupancy_shape1 - 1
if ij[k, 0] < 0:
ij[k, 0] = 0
if ij[k, 1] < 0:
ij[k, 1] = 0
return ij
def xy_to_ij(self, xy, clip_if_outside=True):
if type(xy) is not np.ndarray:
xy = np.array(xy)
ij = np.zeros_like(xy, dtype=np.float32)
self.cxy_to_ij(xy.astype(np.float32), ij, clip_if_outside)
return ij.astype(np.int64)
def xy_to_floatij(self, xy, clip_if_outside=True):
if type(xy) is not np.ndarray:
xy = np.array(xy)
ij = np.zeros_like(xy, dtype=np.float32)
self.cxy_to_ij(xy.astype(np.float32), ij, clip_if_outside)
return ij
def old_xy_to_ij(self, x, y=None, clip_if_outside=True):
# if no y argument is given, assume x is a [...,2] array with xy in last dim
"""
for each x y coordinate, return an i j cell index
Examples
--------
>>> a = Map2D()
>>> a.xy_to_ij(0.01, 0.02)
(1, 2)
>>> a.xy_to_ij([0.01, 0.02])
array([1, 2])
>>> a.xy_to_ij([[0.01, 0.02], [-0.01, 0.]])
array([[1, 2],
[0, 0]])
"""
if y is None:
return np.concatenate(
self.xy_to_ij(
*np.split(np.array(x), 2, axis=-1), clip_if_outside=clip_if_outside
),
axis=-1,
)
i = (x - self.origin[0]) / self.resolution_
j = (y - self.origin[1]) / self.resolution_
i = i.astype(int)
j = j.astype(int)
if clip_if_outside:
i_gt = i >= self._occupancy.shape[0]
i_lt = i < 0
j_gt = j >= self._occupancy.shape[1]
j_lt = j < 0
if isinstance(i, np.ndarray):
i[i_gt] = self._occupancy.shape[0] - 1
i[i_lt] = 0
j[j_gt] = self._occupancy.shape[1] - 1
j[j_lt] = 0
else:
if i_gt:
i = self._occupancy.shape[0] - 1
if i_lt:
i = 0
if j_gt:
j = self._occupancy.shape[1] - 1
if j_lt:
j = 0
return i, j
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision(True)
cdef cij_to_xy(self, np.float32_t[:,::1] ij):
xy = np.zeros([ij.shape[0], ij.shape[1]], dtype=np.float32)
for k in range(ij.shape[0]):
# adds 0.5 so that x y is in the middle of the cell. Otherwise ij->xy->ij is not identity
xy[k, 0] = (ij[k, 0]+0.5) * self.resolution_ + self.origin[0]
xy[k, 1] = (ij[k, 1]+0.5) * self.resolution_ + self.origin[1]
return xy
def ij_to_xy(self, i, j=None):
"""
Examples
--------
>>> a = Map2D()
>>> a.ij_to_xy(1, 2)
(0.01, 0.02)
>>> a.ij_to_xy([1,2])
array([0.01, 0.02])
>>> a.ij_to_xy([[1,2], [-1, 0]])
array([[ 0.01, 0.02],
[-0.01, 0. ]])
"""
# if no j argument is given, assume i is a [...,2] array with ij in last dim
if j is None:
return np.concatenate(
self.ij_to_xy(*np.split(np.array(i), 2, axis=-1)), axis=-1
)
# adds 0.5 so that x y is in the middle of the cell. Otherwise ij->xy->ij is not identity
x = (i + 0.5) * self.resolution_ + self.origin[0]
y = (j + 0.5) * self.resolution_ + self.origin[1]
return x, y
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision(True)
cdef cis_inside_ij(self, np.float32_t[:,::1] ij, np.uint8_t[:] is_inside):
cdef int k
for k in range(ij.shape[0]):
if ij[k, 0] >= self.occupancy_shape0:
is_inside[k] = 0
continue
if ij[k, 1] >= self.occupancy_shape1:
is_inside[k] = 0
continue
if ij[k, 0] < 0:
is_inside[k] = 0
continue
if ij[k, 1] < 0:
is_inside[k] = 0
continue
def is_inside_ij(self, ij):
from functools import reduce
"""
Examples
--------
>>> a = Map2D()
>>> a.is_inside_ij([[1,2]])
array([ True])
>>> a.is_inside_ij([[1,a._occupancy.shape[1]]])
array([False])
>>> a.is_inside_ij([[a._occupancy.shape[0],2]])
array([False])
>>> a.is_inside_ij([[1,2], [-1, 0]])
array([ True, False])
"""
is_inside = np.ones([ij.shape[0],], dtype=np.uint8)
self.cis_inside_ij(ij, is_inside)
return is_inside
def old_is_inside_ij(self, i, j=None):
from functools import reduce
"""
Examples
--------
>>> a = Map2D()
>>> a.is_inside_ij(1, 2)
True
>>> a.is_inside_ij([1,2])
array(True)
>>> a.is_inside_ij([[1,2]])
array([ True])
>>> a.is_inside_ij([[1,a._occupancy.shape[1]]])
array([False])
>>> a.is_inside_ij([[a._occupancy.shape[0],2]])
array([False])
>>> a.is_inside_ij([[1,2], [-1, 0]])
array([ True, False])
"""
if j is None:
return self.is_inside_ij(*np.split(np.array(i), 2, axis=-1))[..., 0]
return reduce(
np.logical_and,
[i >= 0, i < self._occupancy.shape[0], j >= 0, j < self._occupancy.shape[1]],
)
def origin_xy(self):
""" output:
ndarray of shape (2,) - xy coordinates [meters] of point at i = j = 0 """
origin = np.array(self.origin)
return origin
def occupancy(self):
occ = np.array(self._occupancy)
return occ
def occupancy_T(self):
occ_T = np.zeros((self.occupancy_shape1, self.occupancy_shape0), dtype=np.float32)
for i in range(self.occupancy_shape1):
for j in range(self.occupancy_shape0):
occ_T[i, j] = self._occupancy[j, i]
return occ_T
def as_sdf(self, raytracer=None):
min_distances = self.distance_transform_2d()
# Switch sign for occupied and unkown points (*signed* distance field)
min_distances[self.occupancy() > self.thresh_free] *= -1.
return min_distances
def as_sdf_ij(self, raytracer=None):
min_distances = self.distance_transform_2d_ij()
# Switch sign for occupied and unkown points (*signed* distance field)
min_distances[self.occupancy() > self.thresh_free] *= -1.
return min_distances
def as_idx_array(self, axis=None):
""" Returns an array of shape a containing indices for a
Parameters
----------
a : array_like
Array to be reshaped.
axis : int, None, list of ints, or 'all'
Axis along which to return indices. If None, the flat index.
Returns
-------
result : ndarray
Array of shape (a.shape, len(axis))
if axis is None or a single int, (a.shape,)
"""
a = self.occupancy()
if axis is None:
return np.arange(len(a.flatten())).reshape(a.shape)
idxs = np.array(np.where(np.ones(a.shape)), dtype=np.float32).T.reshape(a.shape + (-1,))
if axis == "all":
return idxs
return idxs[..., axis]
def as_xy_array(self):
""" returns an array containing xy coordinates at every cell """
idxarray = self.as_idx_array(axis='all')
flatidxarray = idxarray.reshape((-1, 2))
flatxyarray = self.ij_to_xy(flatidxarray)
xyarray = flatxyarray.reshape(idxarray.shape)
return xyarray
def as_meshgrid_ij(self):
""" returns a tuple of 2 arrays with same dimension as map, containing respectively
i and j indices of each cell
ii, jj = map2d.as_meshgrid_ij()
"""
idxarray = self.as_idx_array(axis='all')
ii, jj = np.moveaxis(idxarray, -1, 0)
return (ii, jj)
def as_meshgrid_xy(self):
""" returns a tuple of 2 arrays with same dimension as map, containing respectively
x and y indices of each cell
xx, yy = map2d.as_meshgrid_xy()
"""
xx, yy = np.moveaxis(self.as_xy_array(), -1, 0)
return (xx, yy)
cpdef as_coarse_map2d(self, n=1):
# recursion to provide a convenient way to coarsen x times
if n > 1:
return self.as_coarse_map2d(n=int(n-1)).as_coarse_map2d()
coarse = CMap2D()
# if the number of rows/column is not even, this will discard the last one
coarse.occupancy_shape0 = int(cfloor(self.occupancy_shape0 / 2))
coarse.occupancy_shape1 = int(cfloor(self.occupancy_shape1 / 2))
coarse._occupancy = np.zeros((coarse.occupancy_shape0, coarse.occupancy_shape1), dtype=np.float32)
for i in range(coarse.occupancy_shape0):
for j in range(coarse.occupancy_shape1):
coarse._occupancy[i, j] = max(
self._occupancy[i*2 , j*2 ],
self._occupancy[i*2+1, j*2 ],
self._occupancy[i*2 , j*2+1],
self._occupancy[i*2+1, j*2+1],
)
coarse.resolution_ = self.resolution_ * 2
coarse.origin = np.array([0., 0.], dtype=np.float32)
coarse.origin[0] = self.origin[0]
coarse.origin[1] = self.origin[1]
coarse._thresh_occupied = self._thresh_occupied
coarse.thresh_free = self.thresh_free
coarse.HUGE_ = self.HUGE_
return coarse
def direction_in_field(self, pos_ij, field):
norm_dir = np.zeros((2,), dtype=np.float32)
self.cdirection_in_field(pos_ij, field, norm_dir)
return norm_dir
def cdirection_in_field(self, np.int64_t[:] ij , np.float32_t[:,::1] field, np.float32_t[:] norm_dir):
cdef int k
cdef np.int64_t i = ij[0]
cdef np.int64_t j = ij[1]
cdef np.int64_t offset_i
cdef np.int64_t offset_j
cdef np.int64_t neighbor_i
cdef np.int64_t neighbor_j
cdef int n_neighbors = 8
cdef np.int64_t[:,::1] neighbor_offsets = np.array([
[0, 1], [1, 0], [ 0,-1], [-1, 0],
[1, 1], [1,-1], [-1, 1], [-1,-1]], dtype=np.int64)
cdef np.float32_t b_val_min = field[i, j]
cdef np.float32_t b_val
cdef np.float32_t norm
norm_dir[0] = 0.
norm_dir[1] = 0.
for k in range(n_neighbors):
offset_i = neighbor_offsets[k][0]
offset_j = neighbor_offsets[k][1]
neighbor_i = i + offset_i
neighbor_j = j + offset_j
if (neighbor_i >= self.occupancy_shape0 or
neighbor_i < 0 or
neighbor_j >= self.occupancy_shape1 or
neighbor_i < 0):
continue
b_val = field[neighbor_i, neighbor_j]
if b_val < b_val_min:
b_val_min = b_val
norm_dir[0] = offset_i
norm_dir[1] = offset_j
norm = csqrt(norm_dir[0]**2 + norm_dir[1]**2)
if norm > 0:
norm_dir[0] = norm_dir[0] / norm
norm_dir[1] = norm_dir[1] / norm
def fastmarch(self, goal_ij, mask=None, speeds=None):
"""
Nodes are cells in a 2d grid
calculates time to goal (sec) , assuming speed at nodes (ij/sec)
"""
# Mask (close) unattainable nodes
if mask is None:
mask = (self.occupancy() >= self.thresh_free).astype(np.uint8)
# initialize extra costs
if speeds is None:
speeds = np.ones((self.occupancy_shape0, self.occupancy_shape1), dtype=np.float32)
# initialize field to large value
inv_value = np.inf
result = np.ones_like(self.occupancy(), dtype=np.float32) * inv_value
if not self.is_inside_ij(np.array([goal_ij]).astype(np.float32))[0]:
raise ValueError("Goal ij ({}, {}) not inside map of size ({}, {})".format(
goal_ij[0], goal_ij[1], self.occupancy_shape0, self.occupancy_shape1))
self.cfastmarch(goal_ij, result, mask, speeds)
return result
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision(True)
cdef cfastmarch(self, np.int64_t[:] goal_ij,
np.float32_t[:, ::1] tentative,
np.uint8_t[:, ::1] mask,
np.float32_t[:, ::1] speeds,
):
# Initialize bool arrays
cdef np.uint8_t[:, ::1] open_ = np.ones((self.occupancy_shape0, self.occupancy_shape1), dtype=np.uint8)
# Mask (close) unattainable nodes
for i in range(self.occupancy_shape0):
for j in range(self.occupancy_shape1):
if mask[i, j]:
open_[i, j] = 0
# Start at the goal location
tentative[goal_ij[0], goal_ij[1]] = 0
cdef cpp_priority_queue[cpp_pair[np.float32_t, cpp_pair[np.int64_t, np.int64_t]]] priority_queue
priority_queue.push(
cpp_pair[np.float32_t, cpp_pair[np.int64_t, np.int64_t]](0, cpp_pair[np.int64_t, np.int64_t](goal_ij[0], goal_ij[1]))
)
cdef cpp_pair[np.float32_t, cpp_pair[np.int64_t, np.int64_t]] popped
cdef np.int64_t popped_idxi
cdef np.int64_t popped_idxj
cdef np.int64_t[:, ::1] neighbor_offsets
neighbor_offsets = np.array([
[0, 1], [1, 0], [0, -1], [-1, 0]], dtype=np.int64) # first row must be up right down left
cdef np.int64_t n_neighbor_offsets = len(neighbor_offsets)
cdef np.int64_t len_i = tentative.shape[0]
cdef np.int64_t len_j = tentative.shape[1]
cdef np.int64_t smallest_tentative_id
cdef np.float32_t value
cdef np.float32_t smallest_tentative_value
cdef np.int64_t node_idxi
cdef np.int64_t node_idxj
cdef np.int64_t neighbor_idxi
cdef np.int64_t neighbor_idxj
cdef np.int64_t oi
cdef np.int64_t oj
cdef np.int64_t currenti = goal_ij[0]
cdef np.int64_t currentj = goal_ij[1]
cdef np.float32_t new_cost
cdef np.float32_t old_cost
cdef np.float32_t a
cdef np.float32_t b
cdef np.float32_t s
cdef np.float32_t s2inv
cdef np.float32_t delta
while not priority_queue.empty():
# Pop the node with the smallest tentative value from the to_visit list
while not priority_queue.empty():
popped = priority_queue.top()
priority_queue.pop()
popped_idxi = popped.second.first
popped_idxj = popped.second.second
# skip nodes which are already closed (stagnant duplicates in the heap)
if open_[popped_idxi, popped_idxj] == 1:
currenti = popped_idxi
currentj = popped_idxj
break
# Iterate over neighbors
for n in range(n_neighbor_offsets):
# Indices for the neighbours
oi = neighbor_offsets[n, 0]
oj = neighbor_offsets[n, 1]
neighbor_idxi = currenti + oi
neighbor_idxj = currentj + oj
# exclude forbidden/explored areas of the grid
if neighbor_idxi < 0:
continue
if neighbor_idxi >= len_i:
continue
if neighbor_idxj < 0:
continue
if neighbor_idxj >= len_j:
continue
# Exclude invalid neighbors
if not open_[neighbor_idxi, neighbor_idxj]:
continue
# Fastmarch update
a = np.inf
if neighbor_idxi != 0:
a = tentative[neighbor_idxi-1, neighbor_idxj]
if neighbor_idxi != len_i-1:
a = min(a, tentative[neighbor_idxi+1, neighbor_idxj])
b = np.inf
if neighbor_idxj != 0:
b = tentative[neighbor_idxi, neighbor_idxj-1]
if neighbor_idxj != len_j-1:
b = min(b, tentative[neighbor_idxi, neighbor_idxj+1])
s = speeds[neighbor_idxi, neighbor_idxj]
s2inv = 1./s**2
delta = 2 * s2inv - (a-b)**2
if delta > 0:
new_cost = ( a + b + csqrt(delta) ) / 2
else:
new_cost = 1./s + min(a,b)
old_cost = tentative[neighbor_idxi, neighbor_idxj]
if new_cost < old_cost or old_cost == np.inf:
tentative[neighbor_idxi, neighbor_idxj] = new_cost
# Add neighbor to priority queue
priority_queue.push(
cpp_pair[np.float32_t, cpp_pair[np.int64_t, np.int64_t]](
-new_cost, cpp_pair[np.int64_t, np.int64_t](neighbor_idxi, neighbor_idxj))
)
# Close the current node
open_[currenti, currentj] = 0
return tentative
def dijkstra(self, goal_ij, mask=None, extra_costs=None, inv_value=None, connectedness=8):
""" 4, 8, 16, or 32 connected dijkstra
Nodes are cells in a 2d grid
Assumes edge costs are xy distance between two nodes
"""
# Mask (close) unattainable nodes
if mask is None:
mask = (self.occupancy() >= self.thresh_free).astype(np.uint8)
# initialize extra costs
if extra_costs is None:
extra_costs = np.zeros((self.occupancy_shape0, self.occupancy_shape1), dtype=np.float32)
# initialize field to large value
if inv_value is None:
inv_value = self.HUGE_
result = np.ones_like(self.occupancy(), dtype=np.float32) * inv_value
if not self.is_inside_ij(np.array([goal_ij]).astype(np.float32))[0]:
raise ValueError("Goal ij ({}, {}) not inside map of size ({}, {})".format(
goal_ij[0], goal_ij[1], self.occupancy_shape0, self.occupancy_shape1))
self.cdijkstra(goal_ij, result, mask, extra_costs, inv_value, connectedness)
return result
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision(True)
cdef cdijkstra(self, np.int64_t[:] goal_ij,
np.float32_t[:, ::1] tentative,
np.uint8_t[:, ::1] mask,
np.float32_t[:, ::1] extra_costs,
np.float32_t inv_value, connectedness=8):
cdef np.float32_t kEdgeLength = 1. * self.resolution_ # meters
# Initialize bool arrays
cdef np.uint8_t[:, ::1] open_ = np.ones((self.occupancy_shape0, self.occupancy_shape1), dtype=np.uint8)
# Mask (close) unattainable nodes
for i in range(self.occupancy_shape0):
for j in range(self.occupancy_shape1):
if mask[i, j]:
open_[i, j] = 0
# Start at the goal location
tentative[goal_ij[0], goal_ij[1]] = 0
cdef cpp_priority_queue[cpp_pair[np.float32_t, cpp_pair[np.int64_t, np.int64_t]]] priority_queue
priority_queue.push(
cpp_pair[np.float32_t, cpp_pair[np.int64_t, np.int64_t]](0, cpp_pair[np.int64_t, np.int64_t](goal_ij[0], goal_ij[1]))
)
cdef cpp_pair[np.float32_t, cpp_pair[np.int64_t, np.int64_t]] popped
cdef np.int64_t popped_idxi
cdef np.int64_t popped_idxj
cdef np.int64_t[:, ::1] neighbor_offsets
if connectedness == 32:
neighbor_offsets = np.array([
[0, 1], [ 1, 0], [ 0,-1], [-1, 0], # first row must be up right down left
[1, 1], [ 1,-1], [-1, 1], [-1,-1],
[2, 1], [ 2,-1], [-2, 1], [-2,-1],
[1, 2], [-1, 2], [ 1,-2], [-1,-2],
[3, 1], [ 3,-1], [-3, 1], [-3,-1],
[1, 3], [-1, 3], [ 1,-3], [-1,-3],
[3, 2], [ 3,-2], [-3, 2], [-3,-2],
[2, 3], [-2, 3], [ 2,-3], [-2,-3]], dtype=np.int64)
elif connectedness==16:
neighbor_offsets = np.array([
[0, 1], [ 1, 0], [ 0,-1], [-1, 0], # first row must be up right down left
[1, 1], [ 1,-1], [-1, 1], [-1,-1],
[2, 1], [ 2,-1], [-2, 1], [-2,-1],
[1, 2], [-1, 2], [ 1,-2], [-1,-2]], dtype=np.int64)
elif connectedness==8:
neighbor_offsets = np.array([
[0, 1], [1, 0], [ 0,-1], [-1, 0], # first row must be up right down left
[1, 1], [1,-1], [-1, 1], [-1,-1]], dtype=np.int64)
elif connectedness==4:
neighbor_offsets = np.array([
[0, 1], [1, 0], [0, -1], [-1, 0]], dtype=np.int64) # first row must be up right down left
else:
raise ValueError("invalid value {} for connectedness passed as argument".format(connectedness))
cdef np.int64_t n_neighbor_offsets = len(neighbor_offsets)
cdef np.int64_t len_i = tentative.shape[0]
cdef np.int64_t len_j = tentative.shape[1]
cdef np.int64_t smallest_tentative_id
cdef np.float32_t value
cdef np.float32_t smallest_tentative_value
cdef np.int64_t node_idxi
cdef np.int64_t node_idxj
cdef np.int64_t neighbor_idxi
cdef np.int64_t neighbor_idxj
cdef np.int64_t oi
cdef np.int64_t oj
cdef np.int64_t currenti = goal_ij[0]
cdef np.int64_t currentj = goal_ij[1]
cdef np.float32_t edge_extra_costs
cdef np.float32_t new_cost
cdef np.float32_t old_cost
cdef np.float32_t edge_ratio
cdef np.uint8_t[::1] blocked = np.zeros((8), dtype=np.uint8)
while not priority_queue.empty():
# Pop the node with the smallest tentative value from the to_visit list
while not priority_queue.empty():
popped = priority_queue.top()
priority_queue.pop()
popped_idxi = popped.second.first
popped_idxj = popped.second.second
# skip nodes which are already closed (stagnant duplicates in the heap)
if open_[popped_idxi, popped_idxj] == 1:
currenti = popped_idxi
currentj = popped_idxj
break
# Iterate over neighbors
for n in range(n_neighbor_offsets):
# Indices for the neighbours
oi = neighbor_offsets[n, 0]
oj = neighbor_offsets[n, 1]
neighbor_idxi = currenti + oi
neighbor_idxj = currentj + oj
edge_ratio = csqrt(oi**2 + oj**2)
# exclude forbidden/explored areas of the grid
if neighbor_idxi < 0:
continue
if neighbor_idxi >= len_i:
continue
if neighbor_idxj < 0:
continue
if neighbor_idxj >= len_j:
continue
# check whether path is obstructed (for 16/32 connectedness)
if n < 4:
blocked[n] = mask[neighbor_idxi, neighbor_idxj]
elif n < 8:
blocked[n] = mask[neighbor_idxi, neighbor_idxj]
# Exclude obstructed jumps (for 16/32 connectedness)
if n > 4: # for example, prevent ur if u is blocked
# assumes first row of offsets is up right down left (see offset init!)
if (oj > 0 and blocked[0]) or \
(oi > 0 and blocked[1]) or \
(oj < 0 and blocked[2]) or \
(oi < 0 and blocked[3]):
continue
if n > 8: # for example, prevent uuur if ur is blocked
# assumes second row ru rd lu ld
if (oi > 0 and oj > 0 and blocked[4]) or \