双向A*

原理

双向A*算法(bidirectional a star)是对A*的一种扩展,只是从起点和终点同时进行搜索而已;不过起点以终点为目标,终点以起点为目标,最后找到它们的交点。

例子

c_id_A = min( open_set_A, key=lambda o: self.find_total_cost(open_set_A, o, current_B))

current_A = open_set_A[c_id_A]

c_id_B = min(open_set_B,  key=lambda o: self.find_total_cost(open_set_B, o, current_A))

current_B = open_set_B[c_id_B]

分别弹出到起点和到终点代价最小的结点!

"""
Bidirectional A* grid planning
author: Erwin Lejeune (@spida_rwin)
See Wikipedia article (https://en.wikipedia.org/wiki/Bidirectional_search)
"""

import math

import matplotlib.pyplot as plt

show_animation = True


class BidirectionalAStarPlanner:

    def __init__(self, ox, oy, resolution, rr):
        """
        Initialize grid map for a star planning
        ox: x position list of Obstacles [m]
        oy: y position list of Obstacles [m]
        resolution: grid resolution [m]
        rr: robot radius[m]
        """

        self.min_x, self.min_y = None, None
        self.max_x, self.max_y = None, None
        self.x_width, self.y_width, self.obstacle_map = None, None, None
        self.resolution = resolution
        self.rr = rr
        self.calc_obstacle_map(ox, oy)
        self.motion = self.get_motion_model()

    class Node:
        def __init__(self, x, y, cost, parent_index):
            self.x = x  # index of grid
            self.y = y  # index of grid
            self.cost = cost
            self.parent_index = parent_index

        def __str__(self):
            return str(self.x) + "," + str(self.y) + "," + str(
                self.cost) + "," + str(self.parent_index)

    def planning(self, sx, sy, gx, gy):
        """
        Bidirectional A star path search
        input:
            s_x: start x position [m]
            s_y: start y position [m]
            gx: goal x position [m]
            gy: goal y position [m]
        output:
            rx: x position list of the final path
            ry: y position list of the final path
        """

        start_node = self.Node(self.calc_xy_index(sx, self.min_x),
                               self.calc_xy_index(sy, self.min_y), 0.0, -1)
        goal_node = self.Node(self.calc_xy_index(gx, self.min_x),
                              self.calc_xy_index(gy, self.min_y), 0.0, -1)

        open_set_A, closed_set_A = dict(), dict()
        open_set_B, closed_set_B = dict(), dict()
        open_set_A[self.calc_grid_index(start_node)] = start_node
        open_set_B[self.calc_grid_index(goal_node)] = goal_node

        current_A = start_node
        current_B = goal_node
        meet_point_A, meet_point_B = None, None

        while 1:
            if len(open_set_A) == 0:
                print("Open set A is empty..")
                break

            if len(open_set_B) == 0:
                print("Open set B is empty..")
                break

            c_id_A = min( open_set_A, key=lambda o: self.find_total_cost(open_set_A, o, current_B))

            current_A = open_set_A[c_id_A]

            c_id_B = min(open_set_B,  key=lambda o: self.find_total_cost(open_set_B, o, current_A))

            current_B = open_set_B[c_id_B]

            # show graph
            if show_animation:  # pragma: no cover
                plt.plot(self.calc_grid_position(current_A.x, self.min_x),
                         self.calc_grid_position(current_A.y, self.min_y),
                         "xc")
                plt.plot(self.calc_grid_position(current_B.x, self.min_x),
                         self.calc_grid_position(current_B.y, self.min_y),
                         "xc")
                # for stopping simulation with the esc key.
                plt.gcf().canvas.mpl_connect(
                    'key_release_event',
                    lambda event: [exit(0) if event.key == 'escape' else None])
                if len(closed_set_A.keys()) % 10 == 0:
                    plt.pause(0.001)

            if current_A.x == current_B.x and current_A.y == current_B.y:
                print("Found goal")
                meet_point_A = current_A
                meet_point_B = current_B
                break

            # Remove the item from the open set
            del open_set_A[c_id_A]
            del open_set_B[c_id_B]

            # Add it to the closed set
            closed_set_A[c_id_A] = current_A
            closed_set_B[c_id_B] = current_B

            # expand_grid search grid based on motion model
            for i, _ in enumerate(self.motion):

                c_nodes = [self.Node(current_A.x + self.motion[i][0],
                                     current_A.y + self.motion[i][1],
                                     current_A.cost + self.motion[i][2],
                                     c_id_A),
                           self.Node(current_B.x + self.motion[i][0],
                                     current_B.y + self.motion[i][1],
                                     current_B.cost + self.motion[i][2],
                                     c_id_B)]

                n_ids = [self.calc_grid_index(c_nodes[0]),
                         self.calc_grid_index(c_nodes[1])]

                # If the node is not safe, do nothing
                continue_ = self.check_nodes_and_sets(c_nodes, closed_set_A,
                                                      closed_set_B, n_ids)

                if not continue_[0]:
                    if n_ids[0] not in open_set_A:
                        # discovered a new node
                        open_set_A[n_ids[0]] = c_nodes[0]
                    else:
                        if open_set_A[n_ids[0]].cost > c_nodes[0].cost:
                            # This path is the best until now. record it
                            open_set_A[n_ids[0]] = c_nodes[0]

                if not continue_[1]:
                    if n_ids[1] not in open_set_B:
                        # discovered a new node
                        open_set_B[n_ids[1]] = c_nodes[1]
                    else:
                        if open_set_B[n_ids[1]].cost > c_nodes[1].cost:
                            # This path is the best until now. record it
                            open_set_B[n_ids[1]] = c_nodes[1]

        rx, ry = self.calc_final_bidirectional_path(
            meet_point_A, meet_point_B, closed_set_A, closed_set_B)

        return rx, ry

    # takes two sets and two meeting nodes and return the optimal path
    def calc_final_bidirectional_path(self, n1, n2, setA, setB):
        rx_A, ry_A = self.calc_final_path(n1, setA)
        rx_B, ry_B = self.calc_final_path(n2, setB)

        rx_A.reverse()
        ry_A.reverse()

        rx = rx_A + rx_B
        ry = ry_A + ry_B

        return rx, ry

    def calc_final_path(self, goal_node, closed_set):
        # generate final course
        rx, ry = [self.calc_grid_position(goal_node.x, self.min_x)], \
                 [self.calc_grid_position(goal_node.y, self.min_y)]
        parent_index = goal_node.parent_index
        while parent_index != -1:
            n = closed_set[parent_index]
            rx.append(self.calc_grid_position(n.x, self.min_x))
            ry.append(self.calc_grid_position(n.y, self.min_y))
            parent_index = n.parent_index

        return rx, ry

    def check_nodes_and_sets(self, c_nodes, closedSet_A, closedSet_B, n_ids):
        continue_ = [False, False]
        if not self.verify_node(c_nodes[0]) or n_ids[0] in closedSet_A:
            continue_[0] = True

        if not self.verify_node(c_nodes[1]) or n_ids[1] in closedSet_B:
            continue_[1] = True

        return continue_

    @staticmethod
    def calc_heuristic(n1, n2):
        w = 1.0  # weight of heuristic
        d = w * math.hypot(n1.x - n2.x, n1.y - n2.y)
        return d

    def find_total_cost(self, open_set, lambda_, n1):
        g_cost = open_set[lambda_].cost
        h_cost = self.calc_heuristic(n1, open_set[lambda_])
        f_cost = g_cost + h_cost
        return f_cost

    def calc_grid_position(self, index, min_position):
        """
        calc grid position
        :param index:
        :param min_position:
        :return:
        """
        pos = index * self.resolution + min_position
        return pos

    def calc_xy_index(self, position, min_pos):
        return round((position - min_pos) / self.resolution)

    def calc_grid_index(self, node):
        return (node.y - self.min_y) * self.x_width + (node.x - self.min_x)

    def verify_node(self, node):
        px = self.calc_grid_position(node.x, self.min_x)
        py = self.calc_grid_position(node.y, self.min_y)

        if px < self.min_x:
            return False
        elif py < self.min_y:
            return False
        elif px >= self.max_x:
            return False
        elif py >= self.max_y:
            return False

        # collision check
        if self.obstacle_map[node.x][node.y]:
            return False

        return True

    def calc_obstacle_map(self, ox, oy):

        self.min_x = round(min(ox))
        self.min_y = round(min(oy))
        self.max_x = round(max(ox))
        self.max_y = round(max(oy))
        print("min_x:", self.min_x)
        print("min_y:", self.min_y)
        print("max_x:", self.max_x)
        print("max_y:", self.max_y)

        self.x_width = round((self.max_x - self.min_x) / self.resolution)
        self.y_width = round((self.max_y - self.min_y) / self.resolution)
        print("x_width:", self.x_width)
        print("y_width:", self.y_width)

        # obstacle map generation
        self.obstacle_map = [[False for _ in range(self.y_width)]
                             for _ in range(self.x_width)]
        for ix in range(self.x_width):
            x = self.calc_grid_position(ix, self.min_x)
            for iy in range(self.y_width):
                y = self.calc_grid_position(iy, self.min_y)
                for iox, ioy in zip(ox, oy):
                    d = math.hypot(iox - x, ioy - y)
                    if d <= self.rr:
                        self.obstacle_map[ix][iy] = True
                        break

    @staticmethod
    def get_motion_model():
        # dx, dy, cost
        motion = [[1, 0, 1],
                  [0, 1, 1],
                  [-1, 0, 1],
                  [0, -1, 1],
                  [-1, -1, math.sqrt(2)],
                  [-1, 1, math.sqrt(2)],
                  [1, -1, math.sqrt(2)],
                  [1, 1, math.sqrt(2)]]

        return motion


def main():
    print(__file__ + " start!!")

    # start and goal position
    sx = 10.0  # [m]
    sy = 10.0  # [m]
    gx = 50.0  # [m]
    gy = 50.0  # [m]
    grid_size = 2.0  # [m]
    robot_radius = 1.0  # [m]

    # set obstacle positions
    ox, oy = [], []
    for i in range(-10, 60):
        ox.append(i)
        oy.append(-10.0)
    for i in range(-10, 60):
        ox.append(60.0)
        oy.append(i)
    for i in range(-10, 61):
        ox.append(i)
        oy.append(60.0)
    for i in range(-10, 61):
        ox.append(-10.0)
        oy.append(i)
    for i in range(-10, 40):
        ox.append(20.0)
        oy.append(i)
    for i in range(0, 40):
        ox.append(40.0)
        oy.append(60.0 - i)

    if show_animation:  # pragma: no cover
        plt.plot(ox, oy, ".k")
        plt.plot(sx, sy, "og")
        plt.plot(gx, gy, "ob")
        plt.grid(True)
        plt.axis("equal")

    bidir_a_star = BidirectionalAStarPlanner(ox, oy, grid_size, robot_radius)
    rx, ry = bidir_a_star.planning(sx, sy, gx, gy)

    if show_animation:  # pragma: no cover
        plt.plot(rx, ry, "-r")
        plt.pause(.0001)
        plt.show()


if __name__ == '__main__':
    main()

其栅格地图如下图所示:

其最终搜索的路径如下图所示:

最后需要注意的是本文使用的加权A*!

双向A*算法是一种启发式搜索算法,它在搜索过程中从起点和终点同时进行搜索,直到两个搜索路径相遇。以下是一个简单的双向A*算法实现: 假设我们有一个有向图G,节点的表示方式为node,边的表示方式为edge。每个节点都有一个估价函数h(n),代表从该节点到终点的估计距离。我们需要维护两个数据结构:openSet1和openSet2,分别代表从起点和终点开始的搜索队列。 1. 初始化openSet1和openSet2,将起点和终点分别加入两个队列中。 2. 从openSet1和openSet2中各取出一个节点n1和n2,分别进行扩展。 对于节点n1,遍历它的子节点n1_child,计算从起点到n1_child的实际距离g(n1_child)和估计距离f(n1_child) = g(n1_child) + h(n1_child)。如果n1_child已经在openSet2中,则说明两个搜索路径相遇,搜索结束。如果n1_child不在openSet1中,将n1_child加入openSet1,并记录它的父节点为n1。 对于节点n2,遍历它的父节点n2_parent,计算从终点到n2_parent的实际距离g(n2_parent)和估计距离f(n2_parent) = g(n2_parent) + h(n2_parent)。如果n2_parent已经在openSet1中,则说明两个搜索路径相遇,搜索结束。如果n2_parent不在openSet2中,将n2_parent加入openSet2,并记录它的子节点为n2。 3. 重复步骤2,直到两个搜索路径相遇或者任意一个openSet为空。 下面是一个Python实现代码: ``` import heapq def bidirectional_astar(start, goal, neighbors, heuristic): # Initialize open sets open_set1 = [(heuristic(start, goal), start)] open_set2 = [(heuristic(goal, start), goal)] closed_set1 = {} closed_set2 = {} came_from1 = {} came_from2 = {} while open_set1 and open_set2: # Take the node with the lowest f-score from both open sets f1, current1 = heapq.heappop(open_set1) f2, current2 = heapq.heappop(open_set2) if current1 in closed_set2 or current2 in closed_set1: # Paths have met, return the final path path = reconstruct_path(current1, came_from1, came_from2) return path # Add the current nodes to their respective closed sets closed_set1[current1] = f1 closed_set2[current2] = f2 for neighbor in neighbors(current1): # Calculate the g-score and f-score for the neighbor g = came_from1[current1][0] + distance(current1, neighbor) f = g + heuristic(neighbor, goal) if neighbor in closed_set1: # Ignore the neighbor if it has already been evaluated continue if (f, neighbor) in open_set1: # Update the neighbor's g-score and parent if a better path is found index = open_set1.index((f, neighbor)) if g < came_from1[neighbor][0]: came_from1[neighbor] = (g, current1) open_set1[index] = (f, neighbor) heapq.heapify(open_set1) else: # Add the neighbor to the open set and record its parent came_from1[neighbor] = (g, current1) heapq.heappush(open_set1, (f, neighbor)) for neighbor in neighbors(current2): # Calculate the g-score and f-score for the neighbor g = came_from2[current2][0] + distance(current2, neighbor) f = g + heuristic(goal, neighbor) if neighbor in closed_set2: # Ignore the neighbor if it has already been evaluated continue if (f, neighbor) in open_set2: # Update the neighbor's g-score and parent if a better path is found index = open_set2.index((f, neighbor)) if g < came_from2[neighbor][0]: came_from2[neighbor] = (g, current2) open_set2[index] = (f, neighbor) heapq.heapify(open_set2) else: # Add the neighbor to the open set and record its parent came_from2[neighbor] = (g, current2) heapq.heappush(open_set2, (f, neighbor)) # No path was found return None def reconstruct_path(current, came_from1, came_from2): # Reconstruct the final path by following the parent pointers path = [current] while current in came_from1: current = came_from1[current][1] path.append(current) path.reverse() current = path[-1] while current in came_from2: current = came_from2[current][1] path.append(current) return path ``` 该算法的时间复杂度为O(b^(d/2)),其中b是分支因子,d是起点和终点之间的距离。双向A*算法比传统A*算法更快,因为它可以同时从起点和终点开始搜索,在搜索空间中找到相遇点,从而减少了搜索的时间和空间。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JunJun~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值