chessai.agents.searchproblem

  1import logging
  2import typing
  3
  4import edq.util.time
  5
  6import chessai.core.action
  7import chessai.core.agent
  8import chessai.core.agentaction
  9import chessai.core.agentinfo
 10import chessai.core.board
 11import chessai.core.gamestate
 12import chessai.core.search
 13import chessai.core.coordinate
 14import chessai.search.common
 15import chessai.search.random
 16import chessai.search.position
 17import chessai.util.alias
 18import chessai.util.reflection
 19
 20DEFAULT_PROBLEM: str = chessai.util.alias.SEARCH_PROBLEM_POSITION.long
 21DEFAULT_PROBLEM_COST: str = chessai.util.alias.COST_FUNC_UNIT.long
 22DEFAULT_SOLVER: str = chessai.util.alias.SEARCH_SOLVER_RANDOM.long
 23DEFAULT_HEURISTIC: str = chessai.util.alias.HEURISTIC_NULL.long
 24
 25class SearchProblemAgent(chessai.core.agent.Agent):
 26    """
 27    An agent that works by first solving a search problem (chessai.core.search.Problem),
 28    and then executing the path found during the search.
 29    """
 30
 31    def __init__(self,
 32            problem: type[chessai.core.search.SearchProblem] | chessai.util.reflection.Reference | str = DEFAULT_PROBLEM,
 33            problem_cost: chessai.core.search.CostFunction | chessai.util.reflection.Reference | str = DEFAULT_PROBLEM_COST,
 34            solver: chessai.core.search.SearchProblemSolver | chessai.util.reflection.Reference | str = DEFAULT_SOLVER,
 35            heuristic: chessai.core.search.SearchHeuristic | chessai.util.reflection.Reference | str = DEFAULT_HEURISTIC,
 36            **kwargs: typing.Any) -> None:
 37        super().__init__(**kwargs)
 38
 39        claen_problem_class = chessai.util.reflection.resolve_and_fetch(type, problem)
 40        self._problem_class: type[chessai.core.search.SearchProblem] = claen_problem_class
 41        """ The search problem class this agent will use. """
 42
 43        claen_problem_cost_function = chessai.util.reflection.resolve_and_fetch(chessai.core.search.CostFunction, problem_cost)
 44        self._problem_cost_function: chessai.core.search.CostFunction = claen_problem_cost_function
 45        """ The cost function for this agent's search problem. """
 46
 47        claen_solver_function = chessai.util.reflection.resolve_and_fetch(chessai.core.search.SearchProblemSolver, solver)
 48        self._solver_function: chessai.core.search.SearchProblemSolver = claen_solver_function
 49        """ The search solver function this agent will use. """
 50
 51        claen_heuristic_function = chessai.util.reflection.resolve_and_fetch(chessai.core.search.SearchHeuristic, heuristic)
 52        self._heuristic_function: chessai.core.search.SearchHeuristic = claen_heuristic_function
 53        """ The search heuristic function this agent will use. """
 54
 55        self._actions: list[chessai.core.action.Action] = []
 56        """ The actions that the search solver came up with. """
 57
 58        logging.debug("Created a SearchProblemAgent using problem '%s', cost function '%s', solver '%s', and heuristic '%s'.",
 59                chessai.util.reflection.get_qualified_name(problem),
 60                chessai.util.reflection.get_qualified_name(problem_cost),
 61                chessai.util.reflection.get_qualified_name(solver),
 62                chessai.util.reflection.get_qualified_name(heuristic))
 63
 64    def get_action(self, state: chessai.core.gamestate.GameState) -> chessai.core.action.Action:
 65        if (len(self._actions) == 0):
 66            return chessai.core.action.NoneAction()
 67
 68        return self._actions.pop(0)
 69
 70    def game_start_full(self,
 71            player: chessai.core.types.Color,
 72            suggested_seed: int,
 73            initial_state: chessai.core.gamestate.GameState,
 74            ) -> chessai.core.agentaction.AgentAction:
 75        # Do the standard game initialization steps.
 76        super().game_start_full(player, suggested_seed, initial_state)
 77
 78        # This is the agent's first time seeing the game's state (which includes the board).
 79        # Create a search problem using the game's state, and solve the problem.
 80
 81        start_time = edq.util.time.Timestamp.now()
 82        (solution, position_history, expanded_node_count) = self._do_search(initial_state)
 83        end_time = edq.util.time.Timestamp.now()
 84
 85        self._actions = solution.actions
 86
 87        logging.info("Path found with %d steps and a total cost of %0.2f in %0.2f seconds. %d search nodes expanded.",
 88                len(solution.actions), solution.cost, (end_time.sub(start_time).to_secs()), expanded_node_count)
 89        logging.trace(f"Position history: '{position_history}'.") # type: ignore[attr-defined]  # pylint: disable=no-member
 90
 91        return chessai.core.agentaction.AgentAction()
 92
 93    def _do_search(self,
 94            state: chessai.core.gamestate.GameState,
 95            ) -> tuple[chessai.core.search.SearchSolution, list[chessai.core.coordinate.Coordinate], int]:
 96        """
 97        Perform the actual search operation.
 98        Children may override this to change searching behavior.
 99        Return: (solution, position history, expanded node count).
100        """
101
102        search_problem = self._problem_class(game_state = state, cost_function = self._problem_cost_function)
103        solution = self._solver_function(search_problem, self._heuristic_function, self.rng)
104
105        if (solution.goal_node is not None):
106            search_problem.complete(solution.goal_node)
107
108        return (solution, search_problem.position_history, search_problem.expanded_node_count)
109
110class GreedySubproblemSearchAgent(SearchProblemAgent):
111    """
112    An agent that greedily solves several search problems (instead of just one main one).
113    This agent will repeatedly create and solve search problems until the game state signals the game is over
114    (chessai.core.gamestate.GameState.game_over == True).
115    Once the goal is reached, the actions from all subproblem solutions will be concatenated to form the final list of actions.
116    """
117
118    def _do_search(self,
119            state: chessai.core.gamestate.GameState,
120            ) -> tuple[chessai.core.search.SearchSolution, list[chessai.core.coordinate.Coordinate], int]:
121        actions = []
122        total_cost = 0.0
123        goal_node = None
124        total_position_history = []
125        total_expanded_node_count = 0
126
127        while (not state.game_over):
128            # Solve the subproblem.
129            (solution, position_history, expanded_node_count) = super()._do_search(state)
130
131            if (solution.goal_node is None):
132                raise ValueError("Failed to solve subproblem.")
133
134            # Add all the components of the sub-solution to the total solution.
135            actions += solution.actions
136            total_cost += solution.cost
137            goal_node = solution.goal_node
138            total_position_history += position_history
139            total_expanded_node_count += expanded_node_count
140
141            # Move to the next state by applying all the actions.
142            for action in solution.actions:
143                state = state.generate_successor(action, self.rng)
144
145        solution = chessai.core.search.SearchSolution(actions, total_cost, goal_node)
146        return (solution, total_position_history, total_expanded_node_count)
DEFAULT_PROBLEM_COST: str = 'chessai.search.common.unit_cost_function'
DEFAULT_SOLVER: str = 'chessai.search.random.random_search'
DEFAULT_HEURISTIC: str = 'chessai.search.common.null_heuristic'
class SearchProblemAgent(chessai.core.agent.Agent):
 26class SearchProblemAgent(chessai.core.agent.Agent):
 27    """
 28    An agent that works by first solving a search problem (chessai.core.search.Problem),
 29    and then executing the path found during the search.
 30    """
 31
 32    def __init__(self,
 33            problem: type[chessai.core.search.SearchProblem] | chessai.util.reflection.Reference | str = DEFAULT_PROBLEM,
 34            problem_cost: chessai.core.search.CostFunction | chessai.util.reflection.Reference | str = DEFAULT_PROBLEM_COST,
 35            solver: chessai.core.search.SearchProblemSolver | chessai.util.reflection.Reference | str = DEFAULT_SOLVER,
 36            heuristic: chessai.core.search.SearchHeuristic | chessai.util.reflection.Reference | str = DEFAULT_HEURISTIC,
 37            **kwargs: typing.Any) -> None:
 38        super().__init__(**kwargs)
 39
 40        claen_problem_class = chessai.util.reflection.resolve_and_fetch(type, problem)
 41        self._problem_class: type[chessai.core.search.SearchProblem] = claen_problem_class
 42        """ The search problem class this agent will use. """
 43
 44        claen_problem_cost_function = chessai.util.reflection.resolve_and_fetch(chessai.core.search.CostFunction, problem_cost)
 45        self._problem_cost_function: chessai.core.search.CostFunction = claen_problem_cost_function
 46        """ The cost function for this agent's search problem. """
 47
 48        claen_solver_function = chessai.util.reflection.resolve_and_fetch(chessai.core.search.SearchProblemSolver, solver)
 49        self._solver_function: chessai.core.search.SearchProblemSolver = claen_solver_function
 50        """ The search solver function this agent will use. """
 51
 52        claen_heuristic_function = chessai.util.reflection.resolve_and_fetch(chessai.core.search.SearchHeuristic, heuristic)
 53        self._heuristic_function: chessai.core.search.SearchHeuristic = claen_heuristic_function
 54        """ The search heuristic function this agent will use. """
 55
 56        self._actions: list[chessai.core.action.Action] = []
 57        """ The actions that the search solver came up with. """
 58
 59        logging.debug("Created a SearchProblemAgent using problem '%s', cost function '%s', solver '%s', and heuristic '%s'.",
 60                chessai.util.reflection.get_qualified_name(problem),
 61                chessai.util.reflection.get_qualified_name(problem_cost),
 62                chessai.util.reflection.get_qualified_name(solver),
 63                chessai.util.reflection.get_qualified_name(heuristic))
 64
 65    def get_action(self, state: chessai.core.gamestate.GameState) -> chessai.core.action.Action:
 66        if (len(self._actions) == 0):
 67            return chessai.core.action.NoneAction()
 68
 69        return self._actions.pop(0)
 70
 71    def game_start_full(self,
 72            player: chessai.core.types.Color,
 73            suggested_seed: int,
 74            initial_state: chessai.core.gamestate.GameState,
 75            ) -> chessai.core.agentaction.AgentAction:
 76        # Do the standard game initialization steps.
 77        super().game_start_full(player, suggested_seed, initial_state)
 78
 79        # This is the agent's first time seeing the game's state (which includes the board).
 80        # Create a search problem using the game's state, and solve the problem.
 81
 82        start_time = edq.util.time.Timestamp.now()
 83        (solution, position_history, expanded_node_count) = self._do_search(initial_state)
 84        end_time = edq.util.time.Timestamp.now()
 85
 86        self._actions = solution.actions
 87
 88        logging.info("Path found with %d steps and a total cost of %0.2f in %0.2f seconds. %d search nodes expanded.",
 89                len(solution.actions), solution.cost, (end_time.sub(start_time).to_secs()), expanded_node_count)
 90        logging.trace(f"Position history: '{position_history}'.") # type: ignore[attr-defined]  # pylint: disable=no-member
 91
 92        return chessai.core.agentaction.AgentAction()
 93
 94    def _do_search(self,
 95            state: chessai.core.gamestate.GameState,
 96            ) -> tuple[chessai.core.search.SearchSolution, list[chessai.core.coordinate.Coordinate], int]:
 97        """
 98        Perform the actual search operation.
 99        Children may override this to change searching behavior.
100        Return: (solution, position history, expanded node count).
101        """
102
103        search_problem = self._problem_class(game_state = state, cost_function = self._problem_cost_function)
104        solution = self._solver_function(search_problem, self._heuristic_function, self.rng)
105
106        if (solution.goal_node is not None):
107            search_problem.complete(solution.goal_node)
108
109        return (solution, search_problem.position_history, search_problem.expanded_node_count)

An agent that works by first solving a search problem (chessai.core.search.Problem), and then executing the path found during the search.

32    def __init__(self,
33            problem: type[chessai.core.search.SearchProblem] | chessai.util.reflection.Reference | str = DEFAULT_PROBLEM,
34            problem_cost: chessai.core.search.CostFunction | chessai.util.reflection.Reference | str = DEFAULT_PROBLEM_COST,
35            solver: chessai.core.search.SearchProblemSolver | chessai.util.reflection.Reference | str = DEFAULT_SOLVER,
36            heuristic: chessai.core.search.SearchHeuristic | chessai.util.reflection.Reference | str = DEFAULT_HEURISTIC,
37            **kwargs: typing.Any) -> None:
38        super().__init__(**kwargs)
39
40        claen_problem_class = chessai.util.reflection.resolve_and_fetch(type, problem)
41        self._problem_class: type[chessai.core.search.SearchProblem] = claen_problem_class
42        """ The search problem class this agent will use. """
43
44        claen_problem_cost_function = chessai.util.reflection.resolve_and_fetch(chessai.core.search.CostFunction, problem_cost)
45        self._problem_cost_function: chessai.core.search.CostFunction = claen_problem_cost_function
46        """ The cost function for this agent's search problem. """
47
48        claen_solver_function = chessai.util.reflection.resolve_and_fetch(chessai.core.search.SearchProblemSolver, solver)
49        self._solver_function: chessai.core.search.SearchProblemSolver = claen_solver_function
50        """ The search solver function this agent will use. """
51
52        claen_heuristic_function = chessai.util.reflection.resolve_and_fetch(chessai.core.search.SearchHeuristic, heuristic)
53        self._heuristic_function: chessai.core.search.SearchHeuristic = claen_heuristic_function
54        """ The search heuristic function this agent will use. """
55
56        self._actions: list[chessai.core.action.Action] = []
57        """ The actions that the search solver came up with. """
58
59        logging.debug("Created a SearchProblemAgent using problem '%s', cost function '%s', solver '%s', and heuristic '%s'.",
60                chessai.util.reflection.get_qualified_name(problem),
61                chessai.util.reflection.get_qualified_name(problem_cost),
62                chessai.util.reflection.get_qualified_name(solver),
63                chessai.util.reflection.get_qualified_name(heuristic))
def get_action( self, state: chessai.core.gamestate.GameState) -> chessai.core.action.Action:
65    def get_action(self, state: chessai.core.gamestate.GameState) -> chessai.core.action.Action:
66        if (len(self._actions) == 0):
67            return chessai.core.action.NoneAction()
68
69        return self._actions.pop(0)

Get an action for this agent given the current state of the game. This is simplified version of get_action_full(), see that method for full details.

def game_start_full( self, player: chessai.core.types.Color, suggested_seed: int, initial_state: chessai.core.gamestate.GameState) -> chessai.core.agentaction.AgentAction:
71    def game_start_full(self,
72            player: chessai.core.types.Color,
73            suggested_seed: int,
74            initial_state: chessai.core.gamestate.GameState,
75            ) -> chessai.core.agentaction.AgentAction:
76        # Do the standard game initialization steps.
77        super().game_start_full(player, suggested_seed, initial_state)
78
79        # This is the agent's first time seeing the game's state (which includes the board).
80        # Create a search problem using the game's state, and solve the problem.
81
82        start_time = edq.util.time.Timestamp.now()
83        (solution, position_history, expanded_node_count) = self._do_search(initial_state)
84        end_time = edq.util.time.Timestamp.now()
85
86        self._actions = solution.actions
87
88        logging.info("Path found with %d steps and a total cost of %0.2f in %0.2f seconds. %d search nodes expanded.",
89                len(solution.actions), solution.cost, (end_time.sub(start_time).to_secs()), expanded_node_count)
90        logging.trace(f"Position history: '{position_history}'.") # type: ignore[attr-defined]  # pylint: disable=no-member
91
92        return chessai.core.agentaction.AgentAction()

Notify this agent that the game is about to start. The state represents the initial state of the game. Any precomputation for this game should be done in this method. Calls to this method may be subject to a timeout.

class GreedySubproblemSearchAgent(SearchProblemAgent):
111class GreedySubproblemSearchAgent(SearchProblemAgent):
112    """
113    An agent that greedily solves several search problems (instead of just one main one).
114    This agent will repeatedly create and solve search problems until the game state signals the game is over
115    (chessai.core.gamestate.GameState.game_over == True).
116    Once the goal is reached, the actions from all subproblem solutions will be concatenated to form the final list of actions.
117    """
118
119    def _do_search(self,
120            state: chessai.core.gamestate.GameState,
121            ) -> tuple[chessai.core.search.SearchSolution, list[chessai.core.coordinate.Coordinate], int]:
122        actions = []
123        total_cost = 0.0
124        goal_node = None
125        total_position_history = []
126        total_expanded_node_count = 0
127
128        while (not state.game_over):
129            # Solve the subproblem.
130            (solution, position_history, expanded_node_count) = super()._do_search(state)
131
132            if (solution.goal_node is None):
133                raise ValueError("Failed to solve subproblem.")
134
135            # Add all the components of the sub-solution to the total solution.
136            actions += solution.actions
137            total_cost += solution.cost
138            goal_node = solution.goal_node
139            total_position_history += position_history
140            total_expanded_node_count += expanded_node_count
141
142            # Move to the next state by applying all the actions.
143            for action in solution.actions:
144                state = state.generate_successor(action, self.rng)
145
146        solution = chessai.core.search.SearchSolution(actions, total_cost, goal_node)
147        return (solution, total_position_history, total_expanded_node_count)

An agent that greedily solves several search problems (instead of just one main one). This agent will repeatedly create and solve search problems until the game state signals the game is over (chessai.core.gamestate.GameState.game_over == True). Once the goal is reached, the actions from all subproblem solutions will be concatenated to form the final list of actions.