Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 65 additions & 46 deletions src/roboticstoolbox/mobile/DstarPlanner.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from spatialmath.base.types import ArrayLike2

from roboticstoolbox.mobile.OccGrid import BinaryOccupancyGrid, OccupancyGrid
from roboticstoolbox.mobile.PlannerBase import PlannerBase
from roboticstoolbox.mobile.PlannerBase import NoPathError, PlannerBase
from roboticstoolbox.tools.types import NDArray

show_animation = True
Expand Down Expand Up @@ -265,6 +265,7 @@ def insert(self, _State: _State, h_new: float) -> None:
for i, item in enumerate(self.open_list):
if item[1] is _State:
del self.open_list[i]
heapq.heapify(self.open_list)
break

# _State.k = min(_State.k, h_new)
Expand Down Expand Up @@ -429,6 +430,11 @@ def plan(

Compute the minimum-cost obstacle-free distance to the goal from all
points in the grid.

.. versionchanged:: 1.6.0
Each call starts a fresh plan using the current goal and costmap.
Previously, a second call retained the old goal's costs and parents.
The expansion count is reset for the new plan.
"""
for name, value in (("animate", animate), ("progress", progress is not True)):
if value:
Expand All @@ -444,6 +450,12 @@ def plan(
if self._goal is None:
raise ValueError("No goal specified here or in constructor")

# A new goal (or edited costmap) needs a new shortest-path tree. The
# incremental updates during query() continue to reuse this tree.
self._Map = _Map(self.costmap.shape[0], self.costmap.shape[1])
self._Map.costmap = self.costmap * self._costgrid.cellsize
self._Dstar = _Dstar(self._Map)

c, r = self._costgrid.w2g(self._goal)
goal_State = self._Map._Map[r][c]
self.goal_State = goal_State
Expand Down Expand Up @@ -492,8 +504,10 @@ def query(
(filename, frame interval), defaults to the planner's :attr:`movie`.
Implies ``animate``.
:param verbose: display detailed diagnostic information about D* operations, defaults to False
:return: path from start to goal, one point :math:`(x, y)` per row
:rtype: ndarray(N,2)
:return: path from start to goal, one point :math:`(x, y)` per row,
and its cost in the returned status
:rtype: tuple(ndarray(N,2), DstarStatus)
:raises NoPathError: the goal is unreachable, including after sensor updates

If ``sensor`` is None then the plan determined by the ``plan`` phase
is used unaltered.
Expand All @@ -510,6 +524,12 @@ def query(
replanning. In this case the value returned by :meth:`nexpand` will
increase, according to the severity of the replanning.

.. versionchanged:: 1.6.0
The status cost sums the steps actually followed, including detours
caused by sensor updates. Previously it reported the initial plan's
cost. An unreachable goal raises :class:`NoPathError` instead of
returning a path through infinite-cost cells.

.. seealso:: :meth:`plan`
"""
self.validate_start_goal(start)
Expand All @@ -520,54 +540,53 @@ def query(
if sensor is not None and not callable(sensor):
raise ValueError("sensor must be callable")

cost = tmp.h
cost = 0.0
self.goal_State.h = 0

animating = self.animation_start(animate, movie, draw=self.plot)

path = []
while True:
position = self._costgrid.g2w((tmp.x, tmp.y))
path.append(position)
if animating:
plt.plot(*position, "y.", markersize=12)
self.animation_frame()
if tmp == self.goal_State:
break

# x, y = tmp.parent.x, tmp.parent.y

if sensor is not None:
changes = sensor(tuple(position))
if changes is not None:
# make changes to the plan
val = -1.0
for x, y, newcost in changes:
c, r = self._costgrid.w2g((x, y))
if not (
0 <= r < self.costmap.shape[0]
and 0 <= c < self.costmap.shape[1]
):
raise ValueError("sensor cell is outside the costmap")
X = self._Dstar._Map._Map[r][c]
self.costmap[r, c] = newcost
# print(f"change cost at ({x}, {y}) to {newcost}")
val = self._Dstar.modify_cost(
X, newcost * self._costgrid.cellsize
)
# propagate the changes to plan
self.message("propagate the cost changes")
# self._Dstar.showparents()
while val != -1 and val < tmp.h:
val = self._Dstar.process__State(verbose=verbose)
# print('open set', len(self._Dstar.open_list))
# self._Dstar.showparents()

assert tmp.parent is not None # nosec B101: narrows the type for mypy
tmp = tmp.parent
# print('move to ', tmp)

self.animation_end()
try:
while True:
position = self._costgrid.g2w((tmp.x, tmp.y))
path.append(position)
if animating:
plt.plot(*position, "y.", markersize=12)
self.animation_frame()
if tmp == self.goal_State:
break

if sensor is not None:
changes = sensor(tuple(position))
if changes is not None:
# make changes to the plan
val = -1.0
for x, y, newcost in changes:
c, r = self._costgrid.w2g((x, y))
if not (
0 <= r < self.costmap.shape[0]
and 0 <= c < self.costmap.shape[1]
):
raise ValueError("sensor cell is outside the costmap")
X = self._Dstar._Map._Map[r][c]
self.costmap[r, c] = newcost
val = self._Dstar.modify_cost(
X, newcost * self._costgrid.cellsize
)
# propagate the changes to plan
self.message("propagate the cost changes")
while val != -1 and val < tmp.h:
val = self._Dstar.process__State(verbose=verbose)

if tmp.parent is None or not math.isfinite(tmp.h):
raise NoPathError("goal is unreachable")
step_cost = self._Map.cost(tmp, tmp.parent)
if not math.isfinite(step_cost):
raise NoPathError("goal is unreachable")
cost += step_cost
tmp = tmp.parent
finally:
self.animation_end()

return np.array(path), DstarStatus(cost)

Expand Down
151 changes: 151 additions & 0 deletions tests/test_dstar_replanning.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
"""D* replanning must use the current goal, costs and ordered frontier."""

import heapq
from itertools import pairwise

import matplotlib

matplotlib.use("Agg")
import numpy as np
import numpy.testing as nt
import pytest
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra

from roboticstoolbox import DstarPlanner, OccupancyGrid
from roboticstoolbox.mobile.DstarPlanner import _Dstar, _Map
from roboticstoolbox.mobile.PlannerBase import NoPathError


def path_cost(path: np.ndarray, grid: OccupancyGrid) -> float:
"""Sum the documented mean-cell-cost times world-distance edge costs."""
total = 0.0
for start, end in pairwise(path):
c0, r0 = grid.w2g(start)
c1, r1 = grid.w2g(end)
total += (
(grid.grid[r0, c0] + grid.grid[r1, c1]) / 2 * np.linalg.norm(end - start)
)
return float(total)


@pytest.mark.parametrize("cellsize,origin", [(1.0, (0, 0)), (0.25, (-2, 3))])
def test_plan_can_replace_the_goal(
cellsize: float, origin: tuple[float, float]
) -> None:
grid = OccupancyGrid(np.ones((4, 5)), cellsize=cellsize, origin=origin)
planner = DstarPlanner(grid)
old_goal = grid.g2w((4, 3))
new_goal = grid.g2w((0, 0))
planner.plan(old_goal)
planner.query(new_goal)
planner.plan(new_goal)

path, status = planner.query(old_goal)

nt.assert_allclose(path[0], old_goal)
nt.assert_allclose(path[-1], new_goal)
assert status.cost == pytest.approx((3 * np.sqrt(2) + 1) * cellsize)
assert status.cost == pytest.approx(path_cost(path, grid))


def test_plan_reads_revised_costs_even_for_the_same_goal() -> None:
grid = OccupancyGrid(np.ones((5, 6)))
planner = DstarPlanner(grid)
planner.plan((4, 2))
planner.costmap[2, 2] = 100
planner.plan()

path, status = planner.query((1, 2))

assert not np.any(np.all(path == [2, 2], axis=1))
assert status.cost == pytest.approx(1 + 2 * np.sqrt(2))
assert status.cost == pytest.approx(path_cost(path, grid))


@pytest.mark.parametrize("cellsize,origin", [(1.0, (0, 0)), (0.25, (-2, 3))])
def test_status_cost_includes_the_sensor_detour(
cellsize: float, origin: tuple[float, float]
) -> None:
grid = OccupancyGrid(np.ones((5, 6)), cellsize=cellsize, origin=origin)
planner = DstarPlanner(grid)
planner.plan(grid.g2w((4, 2)))
called = False

def sensor(position: tuple[float, float]) -> list[tuple[float, float, float]]:
nonlocal called
if called:
return []
called = True
return [(*grid.g2w((2, 2)), np.inf)]

path, status = planner.query(grid.g2w((1, 2)), sensor=sensor)

assert status.cost == pytest.approx((1 + 2 * np.sqrt(2)) * cellsize)
assert status.cost == pytest.approx(path_cost(path, grid))


def test_unreachable_goal_does_not_return_a_path_through_obstacles() -> None:
costs = np.ones((5, 6))
costs[2, :] = np.inf
planner = DstarPlanner(costs)
planner.plan((4, 4))

with pytest.raises(NoPathError):
planner.query((1, 0))


def test_sensor_can_make_the_goal_unreachable() -> None:
planner = DstarPlanner(np.ones((5, 6)))
planner.plan((4, 4))

def sensor(position: tuple[float, float]) -> list[tuple[float, float, float]]:
return [(x, 2, np.inf) for x in range(6)]

with pytest.raises(NoPathError):
planner.query((1, 0), sensor=sensor)


def test_query_at_goal_has_zero_cost() -> None:
planner = DstarPlanner(np.ones((3, 4)))
planner.plan((2, 1))
path, status = planner.query((2, 1))
nt.assert_array_equal(path, [[2, 1]])
assert status.cost == 0


@pytest.mark.parametrize("seed", [0, 10, 17])
def test_weighted_paths_match_independent_shortest_paths(seed: int) -> None:
costs = np.random.default_rng(seed).integers(1, 20, size=(5, 6)).astype(float)
grid = OccupancyGrid(costs, cellsize=0.25, origin=(-2, 3))
planner = DstarPlanner(grid)
planner.plan(grid.g2w((4, 3)))
rows, columns = costs.shape
edges = np.zeros((costs.size, costs.size))
for y, x in np.ndindex(costs.shape):
for dy, dx in np.ndindex(3, 3):
yy, xx = y + dy - 1, x + dx - 1
if (yy, xx) == (y, x) or not (0 <= yy < rows and 0 <= xx < columns):
continue
edges[y * columns + x, yy * columns + xx] = (
(costs[y, x] + costs[yy, xx]) / 2 * np.hypot(xx - x, yy - y) * 0.25
)
expected = dijkstra(csr_matrix(edges), indices=3 * columns + 4)

for start in [(0, 0), (5, 0), (0, 4), (5, 4)]:
path, status = planner.query(grid.g2w(start))
assert status.cost == pytest.approx(expected[start[1] * columns + start[0]])
assert status.cost == pytest.approx(path_cost(path, grid))


def test_decreased_frontier_key_preserves_priority_order() -> None:
grid = _Map(1, 20)
planner = _Dstar(grid)
priorities = [10, 6, 17, 15, 12, 8, 7, 2, 5, 16, 11, 20, 4, 19, 3, 13, 18, 9, 1, 14]
for state, priority in zip(grid._Map[0], priorities):
planner.insert(state, priority)

planner.insert(grid._Map[0][18], 0)

observed = [heapq.heappop(planner.open_list)[0] for _ in range(20)]
assert observed == [0, *range(2, 21)]
Loading