From d7d38a32f58ee59350426827f59d4242c9cf59b1 Mon Sep 17 00:00:00 2001 From: Andreas Kloeckner Date: Thu, 9 Jan 2025 08:30:50 -0600 Subject: [PATCH] A* node: use dataclass (ruff) --- pytools/graph.py | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/pytools/graph.py b/pytools/graph.py index 35ddfeef..f8f1a1a0 100644 --- a/pytools/graph.py +++ b/pytools/graph.py @@ -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, @@ -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: @@ -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 @@ -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")