chessai.search.position

  1import typing
  2
  3import chessai.core.action
  4import chessai.core.gamestate
  5import chessai.core.search
  6import chessai.core.coordinate
  7import chessai.core.types
  8import chessai.search.common
  9import chessai.tour.gamestate
 10import chessai.util.alias
 11
 12class PositionSearchNode(chessai.core.search.SearchNode):
 13    """
 14    A search node for the position search problem.
 15    The state for this problem is simple,
 16    it is just the current position being searched.
 17    """
 18
 19    def __init__(self, position: chessai.core.coordinate.Coordinate, state: chessai.core.gamestate.GameState) -> None:
 20        self.position: chessai.core.coordinate.Coordinate = position
 21        """ The current position being searched. """
 22
 23        self.state: chessai.core.gamestate.GameState = state
 24        """ The gamestate of the search node. """
 25
 26    def __lt__(self, other: object) -> bool:
 27        if (not isinstance(other, PositionSearchNode)):
 28            return False
 29
 30        return (self.position < other.position)
 31
 32    def __eq__(self, other: object) -> bool:
 33        if (not isinstance(other, PositionSearchNode)):
 34            return False
 35
 36        return (self.position == other.position)
 37
 38    def __hash__(self) -> int:
 39        return hash(self.position)
 40
 41class PositionSearchProblem(chessai.core.search.SearchProblem[PositionSearchNode]):
 42    """
 43    A search problem for finding a specific position on the board.
 44    """
 45
 46    def __init__(self,
 47            game_state: chessai.core.gamestate.GameState,
 48            goal_positions: list[chessai.core.coordinate.Coordinate] | None = None,
 49            start_position: chessai.core.coordinate.Coordinate | None = None,
 50            cost_function: chessai.core.search.CostFunction | str = chessai.util.alias.COST_FUNC_UNIT.long,
 51            **kwargs: typing.Any) -> None:
 52        """
 53        Create a positional search problem.
 54
 55        If no goal position is provided, the board's search target will be used,
 56            if that does not exist, then DEFAULT_GOAL_POSITION will be used.
 57        If no start position is provided, the current agent's position will be used.
 58        If no cost function is provided, chessai.util.alias.COST_FUNC_UNIT will be used.
 59        """
 60
 61        super().__init__()
 62
 63        self.state: chessai.tour.gamestate.GameState = typing.cast(chessai.tour.gamestate.GameState, game_state)
 64        """ Keep track of the gamestate so we can navigate. """
 65
 66        if (goal_positions is None):
 67            if (len(self.state.search_targets) == 0):
 68                raise ValueError("Cannot create a position search problem without at least one goal position.")
 69
 70            goal_positions = self.state.search_targets
 71
 72        self.goal_positions: list[chessai.core.coordinate.Coordinate] = goal_positions
 73        """ The positions to search for. """
 74
 75        if (start_position is None):
 76            all_coordinates = self.state.get_coordinate_map(self.state.search_agent)
 77            for (coordinate, piece) in all_coordinates.items():
 78                if isinstance(piece, chessai.tour.piece.Rock):
 79                    continue
 80
 81                start_position = coordinate
 82                break
 83
 84        if (start_position is None):
 85            raise ValueError("Could not find starting position.")
 86
 87        self.start_position: chessai.core.coordinate.Coordinate = start_position
 88        """ The position to start from. """
 89
 90        self.start_state: chessai.core.gamestate.GameState = self.state.copy()
 91        """ The board the problem started from. """
 92
 93        if (isinstance(cost_function, str)):
 94            cost_function = typing.cast(chessai.core.search.CostFunction, chessai.util.reflection.fetch(cost_function))
 95
 96        self._cost_function: chessai.core.search.CostFunction = cost_function
 97        """ The function used to score search nodes. """
 98
 99    def get_starting_node(self) -> PositionSearchNode:
100        return PositionSearchNode(self.start_position, self.start_state)
101
102    def is_goal_node(self, node: PositionSearchNode) -> bool:
103        return (node.position in self.goal_positions)
104
105    def complete(self, goal_node: PositionSearchNode) -> None:
106        # Mark the final node in the history.
107        self.position_history.append(goal_node.position)
108
109    def get_successor_nodes(self, node: PositionSearchNode) -> list[chessai.core.search.SuccessorInfo]:
110        successors = []
111
112        # Check all the neighbors.
113        for (action, position) in node.state.get_neighbors(node.position):
114            next_state = node.state.copy()
115            next_state.push(action)
116
117            # Push a null move for black.
118            next_state._progress_state(chessai.core.action.NoneAction(), False)
119
120            next_node = PositionSearchNode(position, next_state)
121            cost = self._cost_function(next_node)
122
123            successors.append(chessai.core.search.SuccessorInfo(next_node, action, cost))
124
125        # Do bookkeeping on the states/positions we visited.
126        self.expanded_node_count += 1
127        if (node not in self.visited_nodes):
128            self.position_history.append(node.position)
129
130        return successors
class PositionSearchNode(chessai.core.search.SearchNode):
13class PositionSearchNode(chessai.core.search.SearchNode):
14    """
15    A search node for the position search problem.
16    The state for this problem is simple,
17    it is just the current position being searched.
18    """
19
20    def __init__(self, position: chessai.core.coordinate.Coordinate, state: chessai.core.gamestate.GameState) -> None:
21        self.position: chessai.core.coordinate.Coordinate = position
22        """ The current position being searched. """
23
24        self.state: chessai.core.gamestate.GameState = state
25        """ The gamestate of the search node. """
26
27    def __lt__(self, other: object) -> bool:
28        if (not isinstance(other, PositionSearchNode)):
29            return False
30
31        return (self.position < other.position)
32
33    def __eq__(self, other: object) -> bool:
34        if (not isinstance(other, PositionSearchNode)):
35            return False
36
37        return (self.position == other.position)
38
39    def __hash__(self) -> int:
40        return hash(self.position)

A search node for the position search problem. The state for this problem is simple, it is just the current position being searched.

PositionSearchNode( position: chessai.core.coordinate.Coordinate, state: chessai.core.gamestate.GameState)
20    def __init__(self, position: chessai.core.coordinate.Coordinate, state: chessai.core.gamestate.GameState) -> None:
21        self.position: chessai.core.coordinate.Coordinate = position
22        """ The current position being searched. """
23
24        self.state: chessai.core.gamestate.GameState = state
25        """ The gamestate of the search node. """

The current position being searched.

The gamestate of the search node.

 42class PositionSearchProblem(chessai.core.search.SearchProblem[PositionSearchNode]):
 43    """
 44    A search problem for finding a specific position on the board.
 45    """
 46
 47    def __init__(self,
 48            game_state: chessai.core.gamestate.GameState,
 49            goal_positions: list[chessai.core.coordinate.Coordinate] | None = None,
 50            start_position: chessai.core.coordinate.Coordinate | None = None,
 51            cost_function: chessai.core.search.CostFunction | str = chessai.util.alias.COST_FUNC_UNIT.long,
 52            **kwargs: typing.Any) -> None:
 53        """
 54        Create a positional search problem.
 55
 56        If no goal position is provided, the board's search target will be used,
 57            if that does not exist, then DEFAULT_GOAL_POSITION will be used.
 58        If no start position is provided, the current agent's position will be used.
 59        If no cost function is provided, chessai.util.alias.COST_FUNC_UNIT will be used.
 60        """
 61
 62        super().__init__()
 63
 64        self.state: chessai.tour.gamestate.GameState = typing.cast(chessai.tour.gamestate.GameState, game_state)
 65        """ Keep track of the gamestate so we can navigate. """
 66
 67        if (goal_positions is None):
 68            if (len(self.state.search_targets) == 0):
 69                raise ValueError("Cannot create a position search problem without at least one goal position.")
 70
 71            goal_positions = self.state.search_targets
 72
 73        self.goal_positions: list[chessai.core.coordinate.Coordinate] = goal_positions
 74        """ The positions to search for. """
 75
 76        if (start_position is None):
 77            all_coordinates = self.state.get_coordinate_map(self.state.search_agent)
 78            for (coordinate, piece) in all_coordinates.items():
 79                if isinstance(piece, chessai.tour.piece.Rock):
 80                    continue
 81
 82                start_position = coordinate
 83                break
 84
 85        if (start_position is None):
 86            raise ValueError("Could not find starting position.")
 87
 88        self.start_position: chessai.core.coordinate.Coordinate = start_position
 89        """ The position to start from. """
 90
 91        self.start_state: chessai.core.gamestate.GameState = self.state.copy()
 92        """ The board the problem started from. """
 93
 94        if (isinstance(cost_function, str)):
 95            cost_function = typing.cast(chessai.core.search.CostFunction, chessai.util.reflection.fetch(cost_function))
 96
 97        self._cost_function: chessai.core.search.CostFunction = cost_function
 98        """ The function used to score search nodes. """
 99
100    def get_starting_node(self) -> PositionSearchNode:
101        return PositionSearchNode(self.start_position, self.start_state)
102
103    def is_goal_node(self, node: PositionSearchNode) -> bool:
104        return (node.position in self.goal_positions)
105
106    def complete(self, goal_node: PositionSearchNode) -> None:
107        # Mark the final node in the history.
108        self.position_history.append(goal_node.position)
109
110    def get_successor_nodes(self, node: PositionSearchNode) -> list[chessai.core.search.SuccessorInfo]:
111        successors = []
112
113        # Check all the neighbors.
114        for (action, position) in node.state.get_neighbors(node.position):
115            next_state = node.state.copy()
116            next_state.push(action)
117
118            # Push a null move for black.
119            next_state._progress_state(chessai.core.action.NoneAction(), False)
120
121            next_node = PositionSearchNode(position, next_state)
122            cost = self._cost_function(next_node)
123
124            successors.append(chessai.core.search.SuccessorInfo(next_node, action, cost))
125
126        # Do bookkeeping on the states/positions we visited.
127        self.expanded_node_count += 1
128        if (node not in self.visited_nodes):
129            self.position_history.append(node.position)
130
131        return successors

A search problem for finding a specific position on the board.

PositionSearchProblem( game_state: chessai.core.gamestate.GameState, goal_positions: list[chessai.core.coordinate.Coordinate] | None = None, start_position: chessai.core.coordinate.Coordinate | None = None, cost_function: chessai.core.search.CostFunction | str = 'chessai.search.common.unit_cost_function', **kwargs: Any)
47    def __init__(self,
48            game_state: chessai.core.gamestate.GameState,
49            goal_positions: list[chessai.core.coordinate.Coordinate] | None = None,
50            start_position: chessai.core.coordinate.Coordinate | None = None,
51            cost_function: chessai.core.search.CostFunction | str = chessai.util.alias.COST_FUNC_UNIT.long,
52            **kwargs: typing.Any) -> None:
53        """
54        Create a positional search problem.
55
56        If no goal position is provided, the board's search target will be used,
57            if that does not exist, then DEFAULT_GOAL_POSITION will be used.
58        If no start position is provided, the current agent's position will be used.
59        If no cost function is provided, chessai.util.alias.COST_FUNC_UNIT will be used.
60        """
61
62        super().__init__()
63
64        self.state: chessai.tour.gamestate.GameState = typing.cast(chessai.tour.gamestate.GameState, game_state)
65        """ Keep track of the gamestate so we can navigate. """
66
67        if (goal_positions is None):
68            if (len(self.state.search_targets) == 0):
69                raise ValueError("Cannot create a position search problem without at least one goal position.")
70
71            goal_positions = self.state.search_targets
72
73        self.goal_positions: list[chessai.core.coordinate.Coordinate] = goal_positions
74        """ The positions to search for. """
75
76        if (start_position is None):
77            all_coordinates = self.state.get_coordinate_map(self.state.search_agent)
78            for (coordinate, piece) in all_coordinates.items():
79                if isinstance(piece, chessai.tour.piece.Rock):
80                    continue
81
82                start_position = coordinate
83                break
84
85        if (start_position is None):
86            raise ValueError("Could not find starting position.")
87
88        self.start_position: chessai.core.coordinate.Coordinate = start_position
89        """ The position to start from. """
90
91        self.start_state: chessai.core.gamestate.GameState = self.state.copy()
92        """ The board the problem started from. """
93
94        if (isinstance(cost_function, str)):
95            cost_function = typing.cast(chessai.core.search.CostFunction, chessai.util.reflection.fetch(cost_function))
96
97        self._cost_function: chessai.core.search.CostFunction = cost_function
98        """ The function used to score search nodes. """

Create a positional search problem.

If no goal position is provided, the board's search target will be used, if that does not exist, then DEFAULT_GOAL_POSITION will be used. If no start position is provided, the current agent's position will be used. If no cost function is provided, chessai.util.alias.COST_FUNC_UNIT will be used.

Keep track of the gamestate so we can navigate.

goal_positions: list[chessai.core.coordinate.Coordinate]

The positions to search for.

The position to start from.

The board the problem started from.

def get_starting_node(self) -> PositionSearchNode:
100    def get_starting_node(self) -> PositionSearchNode:
101        return PositionSearchNode(self.start_position, self.start_state)

Get the starting node for the search problem.

def is_goal_node(self, node: PositionSearchNode) -> bool:
103    def is_goal_node(self, node: PositionSearchNode) -> bool:
104        return (node.position in self.goal_positions)

Check if this node is a valid goal node.

def complete(self, goal_node: PositionSearchNode) -> None:
106    def complete(self, goal_node: PositionSearchNode) -> None:
107        # Mark the final node in the history.
108        self.position_history.append(goal_node.position)

Notify this search problem that the solver choose this goal node.

def get_successor_nodes( self, node: PositionSearchNode) -> list[chessai.core.search.SuccessorInfo]:
110    def get_successor_nodes(self, node: PositionSearchNode) -> list[chessai.core.search.SuccessorInfo]:
111        successors = []
112
113        # Check all the neighbors.
114        for (action, position) in node.state.get_neighbors(node.position):
115            next_state = node.state.copy()
116            next_state.push(action)
117
118            # Push a null move for black.
119            next_state._progress_state(chessai.core.action.NoneAction(), False)
120
121            next_node = PositionSearchNode(position, next_state)
122            cost = self._cost_function(next_node)
123
124            successors.append(chessai.core.search.SuccessorInfo(next_node, action, cost))
125
126        # Do bookkeeping on the states/positions we visited.
127        self.expanded_node_count += 1
128        if (node not in self.visited_nodes):
129            self.position_history.append(node.position)
130
131        return successors

Get all the possible successors (successor nodes) to the current node. This action can be though of expanding a search node, or getting the children of a node in the search tree.