Files
PathPlanning/Search-based Planning/Search_2D/bfs.py
T

83 lines
2.2 KiB
Python
Raw Normal View History

2020-06-27 00:38:38 -07:00
"""
2020-06-28 20:41:44 -07:00
BFS 2D (Breadth-first Searching)
2020-06-27 00:38:38 -07:00
@author: huiming zhou
"""
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)) +
"/../../Search-based Planning/")
from Search_2D import queue
from Search_2D import plotting
from Search_2D import env
2020-06-16 14:04:55 -07:00
2020-06-21 21:50:11 -07:00
2020-06-19 14:18:34 -07:00
class BFS:
2020-06-18 17:08:10 -07:00
def __init__(self, x_start, x_goal):
2020-06-18 14:57:03 -07:00
self.xI, self.xG = x_start, x_goal
2020-06-18 15:52:17 -07:00
2020-06-20 12:46:49 -07:00
self.Env = env.Env()
2020-06-20 19:12:34 -07:00
self.plotting = plotting.Plotting(self.xI, self.xG)
2020-06-28 20:41:44 -07:00
self.u_set = self.Env.motions # feasible input set
self.obs = self.Env.obs # position of obstacles
2020-06-20 19:12:34 -07:00
2020-07-01 01:06:21 -07:00
self.OPEN = queue.QueueFIFO() # U set: visited nodes
2020-06-28 20:41:44 -07:00
self.OPEN.put(self.xI)
self.CLOSED = [] # CLOSED set: explored nodes
self.PARENT = {self.xI: self.xI} # relations
2020-06-19 14:18:34 -07:00
2020-06-28 20:41:44 -07:00
def searching(self):
2020-06-18 10:56:12 -07:00
"""
2020-06-28 20:41:44 -07:00
:return: path, order of visited nodes in the planning
2020-06-18 10:56:12 -07:00
"""
2020-06-28 20:41:44 -07:00
while not self.OPEN.empty():
s = self.OPEN.get()
if s == self.xG:
2020-06-18 10:56:12 -07:00
break
2020-06-28 20:41:44 -07:00
self.CLOSED.append(s)
2020-06-20 12:46:49 -07:00
2020-06-28 20:41:44 -07:00
for u_next in self.u_set: # explore neighborhoods
s_next = tuple([s[i] + u_next[i] for i in range(2)])
if s_next not in self.PARENT and s_next not in self.obs: # node not visited and not in obstacles
self.OPEN.put(s_next)
self.PARENT[s_next] = s
2020-06-20 12:46:49 -07:00
2020-06-28 20:41:44 -07:00
return self.extract_path(), self.CLOSED
2020-06-20 12:46:49 -07:00
2020-06-28 20:41:44 -07:00
def extract_path(self):
2020-06-20 12:46:49 -07:00
"""
Extract the path based on the relationship of nodes.
:return: The planning path
"""
2020-06-28 20:41:44 -07:00
path = [self.xG]
s = self.xG
2020-06-25 14:21:36 -07:00
2020-06-28 20:41:44 -07:00
while True:
s = self.PARENT[s]
path.append(s)
if s == self.xI:
2020-06-25 14:21:36 -07:00
break
2020-06-19 14:18:34 -07:00
2020-06-28 20:41:44 -07:00
return list(path)
def main():
x_start = (5, 5) # Starting node
2020-06-29 20:15:34 -07:00
x_goal = (45, 25) # Goal node
2020-06-28 20:41:44 -07:00
bfs = BFS(x_start, x_goal)
plot = plotting.Plotting(x_start, x_goal)
fig_name = "Breadth-first Searching (BFS)"
path, visited = bfs.searching()
plot.animation(path, visited, fig_name) # animation
2020-06-18 10:56:12 -07:00
if __name__ == '__main__':
2020-06-28 20:41:44 -07:00
main()