Skip to content

Commit 39d1255

Browse files
committed
add Breadth-First Search
1 parent 93e2116 commit 39d1255

File tree

1 file changed

+270
-0
lines changed
  • PathPlanning/BreadthFirstSearch

1 file changed

+270
-0
lines changed
Lines changed: 270 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,270 @@
1+
"""
2+
3+
Breadth-First grid planning
4+
5+
author: Erwin Lejeune (@spida_rwin)
6+
7+
See Wikipedia article (https://en.wikipedia.org/wiki/Breadth-First_search)
8+
9+
"""
10+
11+
import math
12+
13+
import matplotlib.pyplot as plt
14+
15+
import random
16+
17+
show_animation = True
18+
19+
20+
class BFSPlanner:
21+
22+
def __init__(self, ox, oy, reso, rr):
23+
"""
24+
Initialize grid map for bfs planning
25+
26+
ox: x position list of Obstacles [m]
27+
oy: y position list of Obstacles [m]
28+
reso: grid resolution [m]
29+
rr: robot radius[m]
30+
"""
31+
32+
self.reso = reso
33+
self.rr = rr
34+
self.calc_obstacle_map(ox, oy)
35+
self.motion = self.get_motion_model()
36+
37+
class Node:
38+
def __init__(self, x, y, cost, pind, parent):
39+
self.x = x # index of grid
40+
self.y = y # index of grid
41+
self.cost = cost
42+
self.pind = pind
43+
self.parent = parent
44+
45+
def __str__(self):
46+
return str(self.x) + "," + str(self.y) + "," + str(
47+
self.cost) + "," + str(self.pind)
48+
49+
def planning(self, sx, sy, gx, gy):
50+
"""
51+
Breadth First search
52+
53+
input:
54+
sx: start x position [m]
55+
sy: start y position [m]
56+
gx: goal x position [m]
57+
gy: goal y position [m]
58+
59+
output:
60+
rx: x position list of the final path
61+
ry: y position list of the final path
62+
"""
63+
64+
nstart = self.Node(self.calc_xyindex(sx, self.minx),
65+
self.calc_xyindex(sy, self.miny), 0.0, -1, None)
66+
ngoal = self.Node(self.calc_xyindex(gx, self.minx),
67+
self.calc_xyindex(gy, self.miny), 0.0, -1, None)
68+
69+
open_set, closed_set = dict(), dict()
70+
open_set[self.calc_grid_index(nstart)] = nstart
71+
72+
while 1:
73+
if len(open_set) == 0:
74+
print("Open set is empty..")
75+
break
76+
77+
c_id = min(
78+
open_set,
79+
key=lambda o: open_set[o].pind)
80+
81+
current = open_set[c_id]
82+
83+
# show graph
84+
if show_animation: # pragma: no cover
85+
plt.plot(self.calc_grid_position(current.x, self.minx),
86+
self.calc_grid_position(current.y, self.miny), "xc")
87+
# for stopping simulation with the esc key.
88+
plt.gcf().canvas.mpl_connect('key_release_event',
89+
lambda event: [exit(
90+
0) if event.key == 'escape' else None])
91+
if len(closed_set.keys()) % 10 == 0:
92+
plt.pause(0.001)
93+
94+
if current.x == ngoal.x and current.y == ngoal.y:
95+
print("Find goal")
96+
ngoal.pind = current.pind
97+
ngoal.cost = current.cost
98+
break
99+
100+
# Remove the item from the open set
101+
del open_set[c_id]
102+
103+
# expand_grid search grid based on motion model
104+
successors = [self.Node(current.x + self.motion[i][0],
105+
current.y + self.motion[i][1],
106+
current.cost + self.motion[i][2], c_id+1, current) for i, _ in enumerate(self.motion)]
107+
108+
random.shuffle(successors)
109+
for node in successors:
110+
n_id = self.calc_grid_index(node)
111+
112+
# If the node is not safe, do nothing
113+
if not self.verify_node(node):
114+
continue
115+
116+
if n_id not in closed_set:
117+
closed_set[n_id] = node
118+
open_set[n_id] = node
119+
120+
rx, ry = self.calc_final_path(ngoal, closed_set)
121+
return rx, ry
122+
123+
def calc_final_path(self, ngoal, closedset):
124+
# generate final course
125+
rx, ry = [self.calc_grid_position(ngoal.x, self.minx)], [
126+
self.calc_grid_position(ngoal.y, self.miny)]
127+
n = closedset[ngoal.pind]
128+
while n.parent is not None:
129+
rx.append(self.calc_grid_position(n.x, self.minx))
130+
ry.append(self.calc_grid_position(n.y, self.miny))
131+
n = n.parent
132+
133+
return rx, ry
134+
135+
@staticmethod
136+
def calc_heuristic(n1, n2):
137+
w = 1.0 # weight of heuristic
138+
d = w * math.hypot(n1.x - n2.x, n1.y - n2.y)
139+
return d
140+
141+
def calc_grid_position(self, index, minp):
142+
"""
143+
calc grid position
144+
145+
:param index:
146+
:param minp:
147+
:return:
148+
"""
149+
pos = index * self.reso + minp
150+
return pos
151+
152+
def calc_xyindex(self, position, min_pos):
153+
return round((position - min_pos) / self.reso)
154+
155+
def calc_grid_index(self, node):
156+
return (node.y - self.miny) * self.xwidth + (node.x - self.minx)
157+
158+
def verify_node(self, node):
159+
px = self.calc_grid_position(node.x, self.minx)
160+
py = self.calc_grid_position(node.y, self.miny)
161+
162+
if px < self.minx:
163+
return False
164+
elif py < self.miny:
165+
return False
166+
elif px >= self.maxx:
167+
return False
168+
elif py >= self.maxy:
169+
return False
170+
171+
# collision check
172+
if self.obmap[node.x][node.y]:
173+
return False
174+
175+
return True
176+
177+
def calc_obstacle_map(self, ox, oy):
178+
179+
self.minx = round(min(ox))
180+
self.miny = round(min(oy))
181+
self.maxx = round(max(ox))
182+
self.maxy = round(max(oy))
183+
print("minx:", self.minx)
184+
print("miny:", self.miny)
185+
print("maxx:", self.maxx)
186+
print("maxy:", self.maxy)
187+
188+
self.xwidth = round((self.maxx - self.minx) / self.reso)
189+
self.ywidth = round((self.maxy - self.miny) / self.reso)
190+
print("xwidth:", self.xwidth)
191+
print("ywidth:", self.ywidth)
192+
193+
# obstacle map generation
194+
self.obmap = [[False for i in range(self.ywidth)]
195+
for i in range(self.xwidth)]
196+
for ix in range(self.xwidth):
197+
x = self.calc_grid_position(ix, self.minx)
198+
for iy in range(self.ywidth):
199+
y = self.calc_grid_position(iy, self.miny)
200+
for iox, ioy in zip(ox, oy):
201+
d = math.hypot(iox - x, ioy - y)
202+
if d <= self.rr:
203+
self.obmap[ix][iy] = True
204+
break
205+
206+
@staticmethod
207+
def get_motion_model():
208+
# dx, dy, cost
209+
motion = [[1, 0, 1],
210+
[0, 1, 1],
211+
[-1, 0, 1],
212+
[0, -1, 1],
213+
[-1, -1, math.sqrt(2)],
214+
[-1, 1, math.sqrt(2)],
215+
[1, -1, math.sqrt(2)],
216+
[1, 1, math.sqrt(2)]]
217+
218+
return motion
219+
220+
221+
def main():
222+
print(__file__ + " start!!")
223+
224+
# start and goal position
225+
sx = 10.0 # [m]
226+
sy = 10.0 # [m]
227+
gx = 50.0 # [m]
228+
gy = 50.0 # [m]
229+
grid_size = 2.0 # [m]
230+
robot_radius = 1.0 # [m]
231+
232+
# set obstable positions
233+
ox, oy = [], []
234+
for i in range(-10, 60):
235+
ox.append(i)
236+
oy.append(-10.0)
237+
for i in range(-10, 60):
238+
ox.append(60.0)
239+
oy.append(i)
240+
for i in range(-10, 61):
241+
ox.append(i)
242+
oy.append(60.0)
243+
for i in range(-10, 61):
244+
ox.append(-10.0)
245+
oy.append(i)
246+
for i in range(-10, 40):
247+
ox.append(20.0)
248+
oy.append(i)
249+
for i in range(0, 40):
250+
ox.append(40.0)
251+
oy.append(60.0 - i)
252+
253+
if show_animation: # pragma: no cover
254+
plt.plot(ox, oy, ".k")
255+
plt.plot(sx, sy, "og")
256+
plt.plot(gx, gy, "xb")
257+
plt.grid(True)
258+
plt.axis("equal")
259+
260+
bfs = BFSPlanner(ox, oy, grid_size, robot_radius)
261+
rx, ry = bfs.planning(sx, sy, gx, gy)
262+
263+
if show_animation: # pragma: no cover
264+
plt.plot(rx, ry, "-r")
265+
plt.pause(0.01)
266+
plt.show()
267+
268+
269+
if __name__ == '__main__':
270+
main()

0 commit comments

Comments
 (0)