Skip to content

Commit d0d4f11

Browse files
committed
add Depth-First Search
1 parent 93e2116 commit d0d4f11

File tree

1 file changed

+273
-0
lines changed
  • PathPlanning/DepthFirstSearch

1 file changed

+273
-0
lines changed

PathPlanning/DepthFirstSearch/dfs.py

+273
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,273 @@
1+
"""
2+
3+
Depth-First grid planning
4+
5+
author: Erwin Lejeune (@spida_rwin)
6+
7+
See Wikipedia article (https://en.wikipedia.org/wiki/depth-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 DFSPlanner:
21+
22+
def __init__(self, ox, oy, reso, rr):
23+
"""
24+
Initialize grid map for DFS 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+
Depth 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 = max(
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+
closed_set[current.pind] = current
99+
break
100+
101+
# Remove the item from the open set
102+
del open_set[c_id]
103+
104+
# Add it to the closed set
105+
closed_set[c_id] = current
106+
107+
# expand_grid search grid based on motion model
108+
successors = [self.Node(current.x + self.motion[i][0],
109+
current.y + self.motion[i][1],
110+
current.cost + self.motion[i][2], c_id+1, current) for i, _ in enumerate(self.motion)]
111+
112+
random.shuffle(successors)
113+
for node in successors:
114+
n_id = self.calc_grid_index(node)
115+
116+
# If the node is not safe, do nothing
117+
if not self.verify_node(node):
118+
continue
119+
120+
if n_id not in closed_set:
121+
open_set[n_id] = node
122+
123+
rx, ry = self.calc_final_path(ngoal, closed_set)
124+
return rx, ry
125+
126+
def calc_final_path(self, ngoal, closedset):
127+
# generate final course
128+
rx, ry = [self.calc_grid_position(ngoal.x, self.minx)], [
129+
self.calc_grid_position(ngoal.y, self.miny)]
130+
n = closedset[ngoal.pind]
131+
while n.parent is not None:
132+
rx.append(self.calc_grid_position(n.x, self.minx))
133+
ry.append(self.calc_grid_position(n.y, self.miny))
134+
n = n.parent
135+
136+
return rx, ry
137+
138+
@staticmethod
139+
def calc_heuristic(n1, n2):
140+
w = 1.0 # weight of heuristic
141+
d = w * math.hypot(n1.x - n2.x, n1.y - n2.y)
142+
return d
143+
144+
def calc_grid_position(self, index, minp):
145+
"""
146+
calc grid position
147+
148+
:param index:
149+
:param minp:
150+
:return:
151+
"""
152+
pos = index * self.reso + minp
153+
return pos
154+
155+
def calc_xyindex(self, position, min_pos):
156+
return round((position - min_pos) / self.reso)
157+
158+
def calc_grid_index(self, node):
159+
return (node.y - self.miny) * self.xwidth + (node.x - self.minx)
160+
161+
def verify_node(self, node):
162+
px = self.calc_grid_position(node.x, self.minx)
163+
py = self.calc_grid_position(node.y, self.miny)
164+
165+
if px < self.minx:
166+
return False
167+
elif py < self.miny:
168+
return False
169+
elif px >= self.maxx:
170+
return False
171+
elif py >= self.maxy:
172+
return False
173+
174+
# collision check
175+
if self.obmap[node.x][node.y]:
176+
return False
177+
178+
return True
179+
180+
def calc_obstacle_map(self, ox, oy):
181+
182+
self.minx = round(min(ox))
183+
self.miny = round(min(oy))
184+
self.maxx = round(max(ox))
185+
self.maxy = round(max(oy))
186+
print("minx:", self.minx)
187+
print("miny:", self.miny)
188+
print("maxx:", self.maxx)
189+
print("maxy:", self.maxy)
190+
191+
self.xwidth = round((self.maxx - self.minx) / self.reso)
192+
self.ywidth = round((self.maxy - self.miny) / self.reso)
193+
print("xwidth:", self.xwidth)
194+
print("ywidth:", self.ywidth)
195+
196+
# obstacle map generation
197+
self.obmap = [[False for i in range(self.ywidth)]
198+
for i in range(self.xwidth)]
199+
for ix in range(self.xwidth):
200+
x = self.calc_grid_position(ix, self.minx)
201+
for iy in range(self.ywidth):
202+
y = self.calc_grid_position(iy, self.miny)
203+
for iox, ioy in zip(ox, oy):
204+
d = math.hypot(iox - x, ioy - y)
205+
if d <= self.rr:
206+
self.obmap[ix][iy] = True
207+
break
208+
209+
@staticmethod
210+
def get_motion_model():
211+
# dx, dy, cost
212+
motion = [[1, 0, 1],
213+
[0, 1, 1],
214+
[-1, 0, 1],
215+
[0, -1, 1],
216+
[-1, -1, math.sqrt(2)],
217+
[-1, 1, math.sqrt(2)],
218+
[1, -1, math.sqrt(2)],
219+
[1, 1, math.sqrt(2)]]
220+
221+
return motion
222+
223+
224+
def main():
225+
print(__file__ + " start!!")
226+
227+
# start and goal position
228+
sx = 10.0 # [m]
229+
sy = 10.0 # [m]
230+
gx = 50.0 # [m]
231+
gy = 50.0 # [m]
232+
grid_size = 2.0 # [m]
233+
robot_radius = 1.0 # [m]
234+
235+
# set obstable positions
236+
ox, oy = [], []
237+
for i in range(-10, 60):
238+
ox.append(i)
239+
oy.append(-10.0)
240+
for i in range(-10, 60):
241+
ox.append(60.0)
242+
oy.append(i)
243+
for i in range(-10, 61):
244+
ox.append(i)
245+
oy.append(60.0)
246+
for i in range(-10, 61):
247+
ox.append(-10.0)
248+
oy.append(i)
249+
for i in range(-10, 40):
250+
ox.append(20.0)
251+
oy.append(i)
252+
for i in range(0, 40):
253+
ox.append(40.0)
254+
oy.append(60.0 - i)
255+
256+
if show_animation: # pragma: no cover
257+
plt.plot(ox, oy, ".k")
258+
plt.plot(sx, sy, "og")
259+
plt.plot(gx, gy, "xb")
260+
plt.grid(True)
261+
plt.axis("equal")
262+
263+
DFS = DFSPlanner(ox, oy, grid_size, robot_radius)
264+
rx, ry = DFS.planning(sx, sy, gx, gy)
265+
266+
if show_animation: # pragma: no cover
267+
plt.plot(rx, ry, "-r")
268+
plt.pause(0.01)
269+
plt.show()
270+
271+
272+
if __name__ == '__main__':
273+
main()

0 commit comments

Comments
 (0)