-
Notifications
You must be signed in to change notification settings - Fork 0
/
Hybrid_A_Star.py
412 lines (312 loc) · 12.9 KB
/
Hybrid_A_Star.py
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
'''
Modify vehicle parameters in Kinetic_Model berfore use!
Usage: call: path = hybrid_a_star_planning(start, goal, ox, oy, xy_resolution, yaw_resolution)
Parameters:
start: start node (start = [10.0, 40.0, np.deg2rad(-45.0)])
goal: goal node (goal = [50.0, 30.0, np.deg2rad(40.0)])
ox: x position list of Obstacles [m]
oy: y position list of Obstacles [m]
xy_resolution: grid resolution [m]
yaw_resolution: yaw angle resolution [rad]
Output: a collision free path form start position to end position
'''
import heapq
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial import cKDTree
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent))
from A_star_search import calc_distance_heuristic
import reeds_shepp as rs
from Kinetic_Model import *
XY_GRID_RESOLUTION = 0.2 # [m]
YAW_GRID_RESOLUTION = np.deg2rad(2.0) # [rad]
MOTION_RESOLUTION = 0.08 # [m] path interpolate resolution
N_STEER = 40 # number of steer command
SB_COST = 3.0 # switch back penalty cost
BACK_COST = 0.0 # backward penalty cost
STEER_CHANGE_COST = 1.0 # steer angle change penalty cost
STEER_COST = 5.0 # steer angle not zero cost
H_COST = 0 # Heuristic cost
class Node:
def __init__(self, x_ind, y_ind, yaw_ind, direction,
x_list, y_list, yaw_list, directions,
steer=0.0, parent_index=None, cost=None):
self.x_index = x_ind
self.y_index = y_ind
self.yaw_index = yaw_ind
self.direction = direction
self.x_list = x_list
self.y_list = y_list
self.yaw_list = yaw_list
self.directions = directions
self.steer = steer
self.parent_index = parent_index
self.cost = cost
class Path:
def __init__(self, x_list, y_list, yaw_list, direction_list, cost):
self.x_list = x_list
self.y_list = y_list
self.yaw_list = yaw_list
self.direction_list = direction_list
self.cost = cost
class Config:
'''
Calculate all the space constraints based on the given obstacles.
'''
def __init__(self, ox, oy, xy_resolution, yaw_resolution):
min_x_m = min(ox)
min_y_m = min(oy)
max_x_m = max(ox)
max_y_m = max(oy)
ox.append(min_x_m)
oy.append(min_y_m)
ox.append(max_x_m)
oy.append(max_y_m)
self.min_x = round(min_x_m / xy_resolution)
self.min_y = round(min_y_m / xy_resolution)
self.max_x = round(max_x_m / xy_resolution)
self.max_y = round(max_y_m / xy_resolution)
self.x_w = round(self.max_x - self.min_x)
self.y_w = round(self.max_y - self.min_y)
self.min_yaw = round(- math.pi / yaw_resolution) - 1
self.max_yaw = round(math.pi / yaw_resolution)
self.yaw_w = round(self.max_yaw - self.min_yaw)
def calc_motion_inputs():
for steer in np.concatenate((np.linspace(-MAX_STEER, MAX_STEER,
N_STEER), [0.0])):
for d in [1, -1]:
yield [steer, d]
def get_neighbors(current, config, ox, oy, kd_tree):
for steer, d in calc_motion_inputs():
node = calc_next_node(current, steer, d, config, ox, oy, kd_tree)
if node and verify_index(node, config):
yield node
def calc_next_node(current, steer, direction, config, ox, oy, kd_tree):
x, y, yaw = current.x_list[-1], current.y_list[-1], current.yaw_list[-1]
arc_l = XY_GRID_RESOLUTION * 1.5
x_list, y_list, yaw_list = [], [], []
# Simulate about one grid in length.
# put all the intermediate points into the list.
for _ in np.arange(0, arc_l, MOTION_RESOLUTION):
x, y, yaw = move(x, y, yaw, MOTION_RESOLUTION * direction, steer)
x_list.append(x)
y_list.append(y)
yaw_list.append(yaw)
# Make sure there is no collision along the way.
if not check_car_collision(x_list, y_list, yaw_list, ox, oy, kd_tree):
return None
d = direction == 1
# Use the last point as the next node.
x_ind = round(x / XY_GRID_RESOLUTION)
y_ind = round(y / XY_GRID_RESOLUTION)
yaw_ind = round(yaw / YAW_GRID_RESOLUTION)
# Calculate the cost base on the actions.
added_cost = 0.0
if d != current.direction:
added_cost += SB_COST
# steer penalty
added_cost += STEER_COST * abs(steer)
# steer change penalty
added_cost += STEER_CHANGE_COST * abs(current.steer - steer)
# cost = huristic cost + motion cost + traveled cost
cost = current.cost + added_cost + arc_l
node = Node(x_ind, y_ind, yaw_ind, d, x_list,
y_list, yaw_list, [d],
parent_index=calc_index(current, config),
cost=cost, steer=steer)
return node
def is_same_grid(n1, n2):
if n1.x_index == n2.x_index \
and n1.y_index == n2.y_index \
and n1.yaw_index == n2.yaw_index:
return True
return False
def analytic_expansion(current, goal, ox, oy, kd_tree):
start_x = current.x_list[-1]
start_y = current.y_list[-1]
start_yaw = current.yaw_list[-1]
goal_x = goal.x_list[-1]
goal_y = goal.y_list[-1]
goal_yaw = goal.yaw_list[-1]
max_curvature = math.tan(MAX_STEER) / WB / 1.5
paths = rs.calc_paths(start_x, start_y, start_yaw,
goal_x, goal_y, goal_yaw,
max_curvature, step_size=MOTION_RESOLUTION)
if not paths:
return None
best_path, best = None, None
for path in paths:
if check_car_collision(path.x, path.y, path.yaw, ox, oy, kd_tree):
cost = calc_rs_path_cost(path)
if not best or best > cost:
best = cost
best_path = path
return best_path
def update_node_with_analytic_expansion(current, goal,
c, ox, oy, kd_tree):
'''
One shot test from current node to goal node.
The path type is chosed from "Dubins path" and "Reeds-Shepp path"
'''
path = analytic_expansion(current, goal, ox, oy, kd_tree)
if path:
f_x = path.x[1:]
f_y = path.y[1:]
f_yaw = path.yaw[1:]
f_cost = current.cost + calc_rs_path_cost(path)
f_parent_index = calc_index(current, c)
fd = []
for d in path.directions[1:]:
fd.append(d >= 0)
f_steer = 0.0
f_path = Node(current.x_index, current.y_index, current.yaw_index,
current.direction, f_x, f_y, f_yaw, fd,
cost=f_cost, parent_index=f_parent_index, steer=f_steer)
return True, f_path
return False, None
def calc_rs_path_cost(reed_shepp_path):
cost = 0.0
for length in reed_shepp_path.lengths:
if length >= 0: # forward
cost += length
else: # back
cost += abs(length) * BACK_COST
# switch back penalty
for i in range(len(reed_shepp_path.lengths) - 1):
# switch back
if reed_shepp_path.lengths[i] * reed_shepp_path.lengths[i + 1] < 0.0:
cost += SB_COST
# steer penalty
for course_type in reed_shepp_path.ctypes:
if course_type != "S": # curve
cost += STEER_COST * abs(MAX_STEER)
# ==steer change penalty
# calc steer profile
n_ctypes = len(reed_shepp_path.ctypes)
u_list = [0.0] * n_ctypes
for i in range(n_ctypes):
if reed_shepp_path.ctypes[i] == "R":
u_list[i] = - MAX_STEER
elif reed_shepp_path.ctypes[i] == "L":
u_list[i] = MAX_STEER
for i in range(len(reed_shepp_path.ctypes) - 1):
cost += STEER_CHANGE_COST * abs(u_list[i + 1] - u_list[i])
return cost
def hybrid_a_star_planning(start, goal, ox, oy, xy_resolution, yaw_resolution):
"""
start: start node
goal: goal node
ox: x position list of Obstacles [m]
oy: y position list of Obstacles [m]
xy_resolution: grid resolution [m]
yaw_resolution: yaw angle resolution [rad]
"""
start[2], goal[2] = rs.pi_2_pi(start[2]), rs.pi_2_pi(goal[2])
tox, toy = ox[:], oy[:]
# Speed up the search point process
obstacle_kd_tree = cKDTree(np.vstack((tox, toy)).T)
config = Config(tox, toy, xy_resolution, yaw_resolution)
start_node = Node(round(start[0] / xy_resolution),
round(start[1] / xy_resolution),
round(start[2] / yaw_resolution), True,
[start[0]], [start[1]], [start[2]], [True], cost=0)
goal_node = Node(round(goal[0] / xy_resolution),
round(goal[1] / xy_resolution),
round(goal[2] / yaw_resolution), True,
[goal[0]], [goal[1]], [goal[2]], [True])
# openList and closedList only have the index of the node.
# openList stores the frontier nodes of current search.
# closedList stores the visited nodes.
openList, closedList = {}, {}
# Calculate all free space L2 distance to goal. (BFS)
# Make it a heuristic lookup table.
h_dp = calc_distance_heuristic(
goal_node.x_list[-1], goal_node.y_list[-1],
ox, oy, xy_resolution, BUBBLE_R)
# pq is a heap queue that stores the cost and index of the node.
pq = []
openList[calc_index(start_node, config)] = start_node
heapq.heappush(pq, (calc_cost(start_node, h_dp, config),
calc_index(start_node, config)))
final_path = None
# Just like the triditional A* search:
# - Expand the node with the lowest cost in the openList.
# - Add the expanded node to the closedList.
# - Add the children of current node to the openList.
while True:
if not openList:
print("Error: Cannot find path, No open set")
return [], [], []
cost, c_id = heapq.heappop(pq)
if c_id in openList:
current = openList.pop(c_id)
closedList[c_id] = current
else:
continue
is_updated, final_path = update_node_with_analytic_expansion(
current, goal_node, config, ox, oy, obstacle_kd_tree)
# If we get one shot path, we can stop searching and return the path.
if is_updated:
print("path found")
break
# expand the node with vehicle kinamatics model.
for neighbor in get_neighbors(current, config, ox, oy,
obstacle_kd_tree):
neighbor_index = calc_index(neighbor, config)
if neighbor_index in closedList:
continue
if neighbor not in openList \
or openList[neighbor_index].cost > neighbor.cost:
heapq.heappush(
pq, (calc_cost(neighbor, h_dp, config),
neighbor_index))
openList[neighbor_index] = neighbor
path = get_final_path(closedList, final_path)
return path
def calc_cost(n, h_dp, c):
'''
calculate the distance heuristic cost of a each based on the lookup table h_dp.
'''
ind = (n.y_index - c.min_y) * c.x_w + (n.x_index - c.min_x)
if ind not in h_dp:
return n.cost + 999999999 # collision cost
return n.cost + H_COST * h_dp[ind].cost
def get_final_path(closed, goal_node):
reversed_x, reversed_y, reversed_yaw = \
list(reversed(goal_node.x_list)), list(reversed(goal_node.y_list)), \
list(reversed(goal_node.yaw_list))
direction = list(reversed(goal_node.directions))
nid = goal_node.parent_index
final_cost = goal_node.cost
while nid:
n = closed[nid]
reversed_x.extend(list(reversed(n.x_list)))
reversed_y.extend(list(reversed(n.y_list)))
reversed_yaw.extend(list(reversed(n.yaw_list)))
direction.extend(list(reversed(n.directions)))
nid = n.parent_index
reversed_x = list(reversed(reversed_x))
reversed_y = list(reversed(reversed_y))
reversed_yaw = list(reversed(reversed_yaw))
direction = list(reversed(direction))
# adjust first direction
#direction[0] = direction[1]
path = Path(reversed_x, reversed_y, reversed_yaw, direction, final_cost)
return path
def verify_index(node, c):
x_ind, y_ind = node.x_index, node.y_index
if c.min_x <= x_ind <= c.max_x and c.min_y <= y_ind <= c.max_y:
return True
return False
def calc_index(node, c):
'''
Map the node to a 1D array.
'''
ind = (node.yaw_index - c.min_yaw) * c.x_w * c.y_w + \
(node.y_index - c.min_y) * c.x_w + (node.x_index - c.min_x)
# if ind <= 0:
# print("Error(calc_index):", ind)
return ind