forked from danieldugas/pymap2d
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CMap2D.pyx
2649 lines (2460 loc) · 115 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 atan2 as catan
from libc.math cimport sqrt as csqrt
from libc.math cimport floor as cfloor
from cython.parallel import prange
import os
from yaml import load, SafeLoader
from matplotlib.pyplot import imread
import numpy as np
cdef class DWAController:
cdef double min_speed
cdef double max_speed
cdef double max_yaw_rate
cdef double max_accel
cdef double max_delta_yaw_rate
cdef double dt
cdef double predict_time
cdef double v_resolution
cdef double yaw_rate_resolution
cdef double to_goal_cost_gain
cdef double speed_cost_gain
cdef double obstacle_cost_gain
cdef double robot_stuck_flag_cons
def __init__(self, double min_speed, double max_speed, double max_yaw_rate, double max_accel,
double max_delta_yaw_rate, double dt, double predict_time, double v_resolution,
double yaw_rate_resolution, double to_goal_cost_gain, double speed_cost_gain,
double obstacle_cost_gain, double robot_stuck_flag_cons):
self.min_speed = min_speed
self.max_speed = max_speed
self.max_yaw_rate = max_yaw_rate
self.max_accel = max_accel
self.max_delta_yaw_rate = max_delta_yaw_rate
self.dt = dt
self.predict_time = predict_time
self.v_resolution = v_resolution
self.yaw_rate_resolution = yaw_rate_resolution
self.to_goal_cost_gain = to_goal_cost_gain
self.speed_cost_gain = speed_cost_gain
self.obstacle_cost_gain = obstacle_cost_gain
self.robot_stuck_flag_cons = robot_stuck_flag_cons
cpdef tuple dwa_control(self, np.ndarray robot_info, np.ndarray goal, np.ndarray ob, np.ndarray radius):
dw = self.calc_dynamic_window(robot_info)
u, trajectory = self.calc_control_and_trajectory(robot_info, dw, goal, ob, radius)
return np.asarray(u), np.asarray(trajectory)
cdef np.ndarray motion(self, np.ndarray x, np.ndarray u, double dt):
x[2] += u[1] * dt
x[0] += u[0] * ccos(x[2]) * dt
x[1] += u[0] * csin(x[2]) * dt
x[3] = u[0]
x[4] = u[1]
return x
cdef list calc_dynamic_window(self, np.ndarray x):
Vs = [self.min_speed, self.max_speed, -self.max_yaw_rate, self.max_yaw_rate]
Vd = [x[3] - self.max_accel * self.dt,
x[3] + self.max_accel * self.dt,
x[4] - self.max_delta_yaw_rate * self.dt,
x[4] + self.max_delta_yaw_rate * self.dt]
dw = [max(Vs[0], Vd[0]), min(Vs[1], Vd[1]), max(Vs[2], Vd[2]), min(Vs[3], Vd[3])]
return dw
cdef np.ndarray predict_trajectory(self, np.ndarray x_init, double v, double y):
cdef np.ndarray trajectory = np.array(x_init, dtype=np.float64)
time = 0
cdef np.ndarray x = np.array(x_init, dtype=np.float64)
cdef np.ndarray u = np.array([v, y], dtype=np.float64)
while time <= self.predict_time:
x = self.motion(x, u, self.dt)
trajectory = np.vstack((trajectory, x))
time += self.dt
return trajectory
cdef tuple calc_control_and_trajectory(self, np.ndarray x, list dw, np.ndarray goal, np.ndarray ob, np.ndarray radius):
cdef double min_cost = float("inf")
cdef np.ndarray best_trajectory = np.array([x], dtype=np.float64)
cdef double[2] best_u = [0.0, 0.0]
cdef np.ndarray trajectory
for v in np.arange(dw[0], dw[1], self.v_resolution):
for y in np.arange(dw[2], dw[3], self.yaw_rate_resolution):
trajectory = self.predict_trajectory(x, v, y)
to_goal_cost = self.to_goal_cost_gain * self.calc_to_goal_cost(trajectory, goal)
speed_cost = self.speed_cost_gain * (self.max_speed - trajectory[-1, 3])
ob_cost = self.obstacle_cost_gain * self.calc_obstacle_cost(trajectory, ob, radius)
final_cost = to_goal_cost + speed_cost + ob_cost
if min_cost >= final_cost:
min_cost = final_cost
best_u = [v, y]
best_trajectory = trajectory
if abs(best_u[0]) < self.robot_stuck_flag_cons and abs(x[3]) < self.robot_stuck_flag_cons:
best_u[1] = -self.max_delta_yaw_rate
return np.asarray(best_u), best_trajectory
cdef double calc_obstacle_cost(self, np.ndarray trajectory, np.ndarray ob, np.ndarray radius):
ox = ob[:, 0]
oy = ob[:, 1]
dx = trajectory[:, 0] - ox[:, None]
dy = trajectory[:, 1] - oy[:, None]
r = np.hypot(dx, dy)
min_r = np.min(r)
return 1.0 / min_r if min_r > 0 else float("inf")
cdef double calc_to_goal_cost(self, np.ndarray trajectory, np.ndarray goal):
dx = goal[0] - trajectory[-1, 0]
dy = goal[1] - trajectory[-1, 1]
error_angle = catan(dy, dx)
cost_angle = error_angle - trajectory[-1, 2]
return abs(catan(csin(cost_angle), ccos(cost_angle)))
cdef class OccupancyGridMap:
cdef double xy_resolution
cdef double map_size
def __init__(self, double xy_resolution = 0.05, map_size = 11.2 ):
self.xy_resolution = xy_resolution
self.map_size = map_size
@cython.boundscheck(False)
@cython.wraparound(False)
cdef np.ndarray[int, ndim=2] bresenham(self, tuple start, tuple end):
cdef:
int x1, y1, x2, y2, dx, dy, y_step, error, x, y
bint is_steep, swapped
list points = []
np.ndarray[int, ndim=2] points_arr
x1, y1 = start
x2, y2 = end
dx = x2 - x1
dy = y2 - y1
is_steep = abs(dy) > abs(dx)
if is_steep:
x1, y1 = y1, x1
x2, y2 = y2, x2
swapped = False
if x1 > x2:
x1, x2 = x2, x1
y1, y2 = y2, y1
swapped = True
dx = x2 - x1
dy = y2 - y1
error = dx // 2
y_step = 1 if y1 < y2 else -1
y = y1
for x in range(x1, x2 + 1):
coord = (y, x) if is_steep else (x, y)
points.append(coord)
error -= abs(dy)
if error < 0:
y += y_step
error += dx
if swapped:
points.reverse()
points_arr = np.array(points, dtype=np.int32)
return points_arr
@cython.boundscheck(False)
@cython.wraparound(False)
cdef calc_grid_map_config(self):
cdef:
double min_x, min_y, max_x, max_y
int xw, yw
min_x = -self.map_size/ 2.0
min_y = -self.map_size/ 2.0
max_x = self.map_size/ 2.0
max_y = self.map_size/ 2.0
xw = int(round((max_x - min_x) / self.xy_resolution))
yw = int(round((max_y - min_y) / self.xy_resolution))
return min_x, min_y, xw, yw
@cython.boundscheck(False)
@cython.wraparound(False)
cdef np.ndarray[double, ndim=2] init_flood_fill(self,
np.ndarray[int, ndim=1] center_point,
np.ndarray[double, ndim=2] obstacle_points,
np.ndarray[int, ndim=1] xy_points,
np.ndarray[double, ndim=1] min_coord,
):
cdef:
int center_x, center_y, prev_ix, prev_iy, ix, iy
int xw, yw, i
double x, y
np.ndarray[double, ndim=2] occupancy_map
np.ndarray[int, ndim=2] free_area
center_x, center_y = center_point[0], center_point[1]
prev_ix, prev_iy = center_x - 1, center_y
ox, oy = obstacle_points[:,0], obstacle_points[:, 1]
xw, yw = xy_points[0], xy_points[1]
min_x, min_y = min_coord[0], min_coord[1]
occupancy_map = np.ones((xw, yw), dtype=np.float64) * 0.5
for i in range(len(ox)):
x = ox[i]
y = oy[i]
ix = int(round((x - min_x) / self.xy_resolution))
iy = int(round((y - min_y) / self.xy_resolution))
free_area = self.bresenham((prev_ix, prev_iy), (ix, iy))
for fa in free_area:
occupancy_map[fa[0], fa[1]] = 0.0
prev_ix, prev_iy = ix, iy
return occupancy_map
@cython.boundscheck(False)
@cython.wraparound(False)
cdef void flood_fill(self, tuple center_point, np.ndarray[double, ndim=2] occupancy_map):
cdef:
int sx, sy, nx, ny
tuple n
list fringe
sx, sy = occupancy_map.shape[0] , occupancy_map.shape[1]
fringe = []
fringe.append(center_point)
while fringe:
n = fringe.pop()
nx, ny = n
if nx > 0 and occupancy_map[nx - 1, ny] == 0.5:
occupancy_map[nx - 1, ny] = 0.0
fringe.append((nx - 1, ny))
if nx < sx - 1 and occupancy_map[nx + 1, ny] == 0.5:
occupancy_map[nx + 1, ny] = 0.0
fringe.append((nx + 1, ny))
if ny > 0 and occupancy_map[nx, ny - 1] == 0.5:
occupancy_map[nx, ny - 1] = 0.0
fringe.append((nx, ny - 1))
if ny < sy - 1 and occupancy_map[nx, ny + 1] == 0.5:
occupancy_map[nx, ny + 1] = 0.0
fringe.append((nx, ny + 1))
@cython.boundscheck(False)
@cython.wraparound(False)
cpdef generate_ray_casting_grid_map(self, np.ndarray[double, ndim=1] ranges, np.ndarray[double, ndim=1] angles):
cdef:
double min_x, min_y, max_x, max_y
int x_w, y_w, ix, iy
np.ndarray[double, ndim=2] occupancy_map
int center_x, center_y
np.ndarray[double, ndim=1] ox = ranges * np.cos(angles)
np.ndarray[double, ndim=1] oy = ranges * np.sin(angles)
min_x, min_y, x_w, y_w = self.calc_grid_map_config()
occupancy_map = np.ones((x_w, y_w), dtype=np.float64) / 2
center_x = int(round(-min_x / self.xy_resolution))
center_y = int(round(-min_y / self.xy_resolution))
cdef np.ndarray[int, ndim=1] center_point = np.array([center_x, center_y], dtype=np.int32)
cdef np.ndarray[int, ndim=1] xy_points = np.array([x_w, y_w], dtype=np.int32)
cdef np.ndarray[double, ndim=1] min_coord = np.array([min_x, min_y], dtype=np.float64)
cdef np.ndarray[double, ndim=2] obstacle_points = np.concatenate([ox[:,None], oy[:,None]], axis = -1, dtype=np.double)
occupancy_map = self.init_flood_fill(center_point, obstacle_points, xy_points, min_coord)
self.flood_fill((center_x, center_y), occupancy_map)
occupancy_map = np.array(occupancy_map, dtype=np.float64)
for i in range(len(ox)):
x, y = ox[i], oy[i]
ix = int(round((x - min_x) / self.xy_resolution))
iy = int(round((y - min_y) / self.xy_resolution))
occupancy_map[ix, iy] = 1.0
occupancy_map[ix + 1, iy] = 1.0
occupancy_map[ix, iy + 1] = 1.0
occupancy_map[ix + 1, iy + 1] = 1.0
return occupancy_map
cdef class PurePursuit:
cdef float look_ahead_dist
def __init__(self, float look_ahead_dist = 3.0):
self.look_ahead_dist = look_ahead_dist
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision(True)
cdef cfind_closest_point(
self,
np.ndarray[np.float32_t, ndim=2] path,
np.ndarray[np.float32_t, ndim=1] x,
int seg
):
cdef np.ndarray[np.float32_t, ndim=1] pt_min = np.array([np.nan, np.nan], dtype=np.float32)
cdef np.ndarray[np.float32_t, ndim=1] p_start = np.zeros(2, dtype=np.float32)
cdef np.ndarray[np.float32_t, ndim=1] p_end = np.zeros(2, dtype=np.float32)
cdef np.ndarray[np.float32_t, ndim=1] v = np.zeros(2, dtype=np.float32)
cdef np.float32_t dist_min = np.float32(np.inf)
cdef int seg_min = -1
cdef int path_len = path.shape[0]
if seg == -1:
for i in range(path_len - 1):
pt, dist, s = self.cfind_closest_point(path, x, i)
if dist < dist_min:
pt_min = pt
dist_min = dist
seg_min = s
else:
p_start[0], p_start[1] = path[seg, 0], path[seg, 1]
p_end[0], p_end[1] = path[seg + 1, 0], path[seg + 1, 1]
v = p_end - p_start
length_seg = np.linalg.norm(v)
#if length_seg > 0:
v /= length_seg
dist_projected = np.dot(x - p_start, v)
if dist_projected < 0.:
pt_min = p_start
elif dist_projected > length_seg:
pt_min = p_end
else:
pt_min = p_start + dist_projected * v
dist_min = np.linalg.norm(pt_min - x)
seg_min = seg
return pt_min, dist_min, seg_min
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision(True)
cdef cfind_subgoal(
self,
np.ndarray[np.float32_t, ndim=2] path,
np.ndarray[np.float32_t, ndim=1] x,
np.ndarray[np.float32_t, ndim=1] pt,
np.float32_t dist,
int seg
):
cdef int seg_max = path.shape[0] - 2
cdef np.ndarray[np.float32_t, ndim=1] goal = np.zeros(2, dtype=np.float32)
cdef np.ndarray[np.float32_t, ndim=1] p_end = np.zeros(2, dtype=np.float32)
cdef np.ndarray[np.float32_t, ndim=1] p_start = np.zeros(2, dtype=np.float32)
cdef np.ndarray[np.float32_t, ndim=1] v = np.zeros(2, dtype=np.float32)
cdef np.float32_t length_seg
cdef np.float32_t dist_end
cdef np.float32_t dist_projected_x
cdef np.float32_t dist_projected_y
if dist > self.look_ahead_dist:
goal = pt
else:
p_end[0], p_end[1] = path[seg+1, 0], path[seg+1, 1]
dist_end = np.linalg.norm(x - p_end)
while dist_end < self.look_ahead_dist and seg < seg_max:
seg += 1
p_end[0], p_end[1] = path[seg+1, 0], path[seg+1, 1]
dist_end = np.linalg.norm(x - p_end)
if dist_end < self.look_ahead_dist:
goal[0], goal[1] = path[seg_max+1, 0], path[seg_max+1, 1]
else:
pt, dist, seg = self.cfind_closest_point(path, x, seg)
p_start[0], p_start[1] = path[seg, 0], path[seg, 1]
p_end[0], p_end[1] = path[seg+1, 0], path[seg+1, 1]
v = p_end - p_start
length_seg = np.linalg.norm(v)
v = v / length_seg
dist_projected_x = np.dot(x - pt, v)
dist_projected_y = np.linalg.norm(np.cross(x - pt, v))
goal = pt + (np.sqrt(self.look_ahead_dist**2 - dist_projected_y**2) + dist_projected_x) * v
return goal
def find_subgoal(self, path, x):
pt, dist, seg = self.cfind_closest_point(path, x, -1)
goal = self.cfind_subgoal(path, x, pt, dist, seg)
return goal
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
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
@cython.cdivision(True)
cdef void cas_sdf(self, np.int64_t[:, ::1] occupied_points_ij, np.float32_t[:, ::1] min_distances):
""" everything in ij units """
cdef np.int64_t pi, pj
cdef np.float64_t norm_sq, smallest_dist_sq
cdef int i, j, k
cdef int n_occupied_points_ij = occupied_points_ij.shape[0]
cdef int rows = min_distances.shape[0]
cdef int cols = min_distances.shape[1]
# Parallelize the outer loop over 'i' and 'j'
for i in prange(rows, nogil=True, schedule='dynamic'):
for j in range(cols):
# Initialize with the square of the smallest distance
smallest_dist_sq = min_distances[i, j] ** 2
# Compare each occupied point
for k in range(n_occupied_points_ij):
# Use direct indexing with memoryview to avoid Python object coercion
pi = occupied_points_ij[k, 0]
pj = occupied_points_ij[k, 1]
norm_sq = (pi - i) ** 2 + (pj - j) ** 2
# If the squared distance is smaller, update the smallest distance
if norm_sq < smallest_dist_sq:
smallest_dist_sq = norm_sq
# Store the actual distance (taking sqrt only at the end)
min_distances[i, j] = csqrt(smallest_dist_sq)
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]],
)