Skip to content
Merged
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
21 changes: 10 additions & 11 deletions pytools/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,13 @@ def reverse_graph(graph: GraphT[NodeT]) -> GraphT[NodeT]:

# {{{ a_star

@dataclass(frozen=True)
class _AStarNode(Generic[NodeT]):
state: NodeT
parent: _AStarNode[NodeT] | None
path_cost: float | int


def a_star(
initial_state: NodeT, goal_state: NodeT, neighbor_map: GraphT[NodeT],
estimate_remaining_cost: Callable[[NodeT], float] | None = None,
Expand All @@ -135,19 +142,11 @@ def estimate_remaining_cost(x: NodeT) -> float:
return 1
return 0

class AStarNode:
__slots__ = ["parent", "path_cost", "state"]

def __init__(self, state: NodeT, parent: Any, path_cost: float) -> None:
self.state = state
self.parent = parent
self.path_cost = path_cost

inf = float("inf")
init_remcost = estimate_remaining_cost(initial_state)
assert init_remcost != inf

queue = [(init_remcost, AStarNode(initial_state, parent=None, path_cost=0))]
queue = [(init_remcost, _AStarNode(initial_state, parent=None, path_cost=0))]
visited_states = set()

while queue:
Expand All @@ -156,7 +155,7 @@ def __init__(self, state: NodeT, parent: Any, path_cost: float) -> None:

if top.state == goal_state:
result = []
it: AStarNode | None = top
it: _AStarNode[NodeT] | None = top
while it is not None:
result.append(it.state)
it = it.parent
Expand All @@ -174,7 +173,7 @@ def __init__(self, state: NodeT, parent: Any, path_cost: float) -> None:
estimated_path_cost = top.path_cost+step_cost+remaining_cost
heappush(queue,
(estimated_path_cost,
AStarNode(state, top, path_cost=top.path_cost + step_cost)))
_AStarNode(state, top, path_cost=top.path_cost + step_cost)))

raise RuntimeError("no solution")

Expand Down
Loading