chessai.util.bin
1import argparse 2import logging 3import math 4import typing 5 6import edq.util.json 7 8import chessai.core.agentaction 9import chessai.core.agentinfo 10import chessai.core.game 11import chessai.core.log 12import chessai.core.ui 13import chessai.util.alias 14 15SCORE_LIST_MAX_INFO_LENGTH: int = 50 16""" If a score list is less than this, log it to info. """ 17 18@typing.runtime_checkable 19class SetCLIArgs(typing.Protocol): 20 """ 21 A function that can be used to modify a CLI parser before use. 22 """ 23 24 def __call__(self, 25 parser: argparse.ArgumentParser, 26 ) -> argparse.ArgumentParser: 27 """ 28 Modify the CLI parser before use. 29 Any changes may be made, including adding arguments. 30 The modified (or new) parser should be returned. 31 """ 32 33@typing.runtime_checkable 34class GetAdditionalOptions(typing.Protocol): 35 """ 36 A function that can be used to get additional initialization options. 37 """ 38 39 def __call__(self, 40 args: argparse.Namespace, 41 ) -> dict[str, typing.Any]: 42 """ 43 Get additional/custom initialization options. 44 """ 45 46@typing.runtime_checkable 47class InitFromArgs(typing.Protocol): 48 """ 49 A function that can be used to initialize components from CLI args. 50 """ 51 52 def __call__(self, 53 args: argparse.Namespace, 54 ) -> tuple[dict[chessai.core.types.Color, chessai.core.agentinfo.AgentInfo], list[chessai.core.types.Color], dict[str, typing.Any]]: 55 """ 56 Initialize components from arguments and return 57 the base agent infos, a list of agents to remove from the board, as well as any board options. 58 See base_init_from_args() for the default implementation. 59 """ 60 61@typing.runtime_checkable 62class LogResults(typing.Protocol): 63 """ 64 A function that can be used to log game results. 65 """ 66 67 def __call__(self, 68 results: list[chessai.core.game.GameResult], 69 winning_agent_teams: set[chessai.core.types.Color], 70 prefix: str = '', 71 ) -> None: 72 """ 73 Log the result of running several games. 74 """ 75 76def base_init_from_args(args: argparse.Namespace) -> tuple[dict[chessai.core.types.Color, chessai.core.agentinfo.AgentInfo], 77 list[chessai.core.types.Color], dict[str, typing.Any]]: 78 """ 79 Take in args from a parser that was passed to set_cli_args(), 80 and initialize the proper components. 81 """ 82 83 # Create base arguments for all possible agents. 84 base_agent_infos: dict[chessai.core.types.Color, chessai.core.agentinfo.AgentInfo] = { 85 chessai.core.types.Color.WHITE: chessai.core.agentinfo.AgentInfo(name = chessai.util.alias.AGENT_RANDOM.long), 86 chessai.core.types.Color.BLACK: chessai.core.agentinfo.AgentInfo(name = chessai.util.alias.AGENT_RANDOM.long), 87 } 88 89 return base_agent_infos, [], {} 90 91def base_log_results(results: list[chessai.core.game.GameResult], winning_agent_teams: set[chessai.core.types.Color], prefix: str = '') -> None: 92 """ 93 Log the result of running several games. 94 """ 95 96 move_counts: list[int] = [len(result.history) for result in results] 97 scores: list[float] = [result.score for result in results] 98 99 record: list[str] = [] 100 for result in results: 101 if (math.isclose(result.score, 0.5)): 102 record.append('Tie') 103 elif (math.isclose(result.score, 1.0)): 104 record.append('Win') 105 else: 106 record.append('Loss') 107 108 average_score: float = (sum(scores)) / len(scores) 109 logging.info('Average Score: %0.2f', average_score) 110 111 # Avoid logging long lists (which can be a bit slow in Python's logging module). 112 log_lists_to_info: bool = (len(results) < chessai.util.bin.SCORE_LIST_MAX_INFO_LENGTH) 113 log_lists_to_debug: bool = (logging.getLogger().getEffectiveLevel() <= logging.DEBUG) 114 115 joined_scores: str = '' 116 joined_record: str = '' 117 joined_move_counts: str = '' 118 119 if (log_lists_to_info or log_lists_to_debug): 120 joined_scores = ', '.join([str(score) for score in scores]) 121 joined_record = ', '.join(record) 122 joined_move_counts = ', '.join([str(move_count) for move_count in move_counts]) 123 124 if (log_lists_to_info): 125 logging.info('%sScores: %s', prefix, joined_scores) 126 elif (log_lists_to_debug): 127 logging.debug('%sScores: %s', prefix, joined_scores) 128 129 if (log_lists_to_info): 130 logging.info('%sRecord: %s', prefix, joined_record) 131 elif (log_lists_to_debug): 132 logging.debug('%sRecord: %s', prefix, joined_record) 133 134 logging.info('%sAverage Moves: %s', prefix, sum(move_counts) / float(len(results))) 135 136 if (log_lists_to_info): 137 logging.info('%sMove Counts: %s', prefix, joined_move_counts) 138 elif (log_lists_to_debug): 139 logging.debug('%sMove Counts: %s', prefix, joined_move_counts) 140 141def run_main( 142 description: str, 143 game_class: typing.Type[chessai.core.game.Game], 144 state_class: typing.Type[chessai.core.gamestate.GameState], 145 default_board: str | None = None, 146 custom_set_cli_args: SetCLIArgs | None = None, 147 custom_init_from_args: InitFromArgs = base_init_from_args, 148 winning_agent_teams: set[chessai.core.types.Color] | None = None, 149 log_results: LogResults | None = base_log_results, 150 argv: list[str] | None = None, 151 ) -> list[chessai.core.game.GameResult]: 152 """ 153 A full main function to prep and run games. 154 155 Returns the results of the games. 156 """ 157 158 # Create a CLI parser. 159 parser = get_parser(description, default_board, custom_set_cli_args = custom_set_cli_args) 160 161 # Parse the CLI args. 162 args = parse_args(parser, game_class, state_class, 163 custom_init_from_args = custom_init_from_args, 164 argv = argv) 165 166 return run_games(args, winning_agent_teams = winning_agent_teams, log_results = log_results) 167 168def get_parser( 169 description: str, 170 default_board: str | None = None, 171 custom_set_cli_args: SetCLIArgs | None = None, 172 ) -> argparse.ArgumentParser: 173 """ Get a parser with all the options. """ 174 175 parser = argparse.ArgumentParser(description = description) 176 177 # Add logging arguments. 178 parser = chessai.core.log.set_cli_args(parser) 179 180 # Add UI arguments. 181 parser = chessai.core.ui.set_cli_args(parser) 182 183 # Add game arguments. 184 parser = chessai.core.game.set_cli_args(parser, default_board = default_board) 185 186 # Add custom options. 187 if (custom_set_cli_args is not None): 188 parser = custom_set_cli_args(parser) 189 190 return parser 191 192def parse_args( 193 parser: argparse.ArgumentParser, 194 game_class: typing.Type[chessai.core.game.Game], 195 state_class: typing.Type[chessai.core.gamestate.GameState], 196 custom_init_from_args: InitFromArgs = base_init_from_args, 197 argv: list[str] | None = None, 198 ) -> argparse.Namespace: 199 """ Parse the args from the parser returned by get_parser(). """ 200 201 args = parser.parse_args(args = argv) 202 203 # Parse logging arguments. 204 args = chessai.core.log.init_from_args(parser, args) 205 206 # Parse custom options. 207 base_agent_infos, _, kwargs = custom_init_from_args(args) 208 209 # Parse UI options. 210 211 additional_ui_args: dict[str, str] = {} 212 null_out_uis = 0 213 214 args = chessai.core.ui.init_from_args(args, null_out_uis = null_out_uis, additional_args = additional_ui_args) 215 216 # Parse game arguments. 217 args = chessai.core.game.init_from_args(args, game_class, state_class, 218 base_agent_infos = base_agent_infos, **kwargs) 219 220 return args 221 222def run_games( 223 args: argparse.Namespace, 224 winning_agent_teams: set[chessai.core.types.Color] | None = None, 225 log_results: LogResults | None = base_log_results, 226 ) -> list[chessai.core.game.GameResult]: 227 """ 228 Run one or more standard games using pre-parsed arguments. 229 The arguments are expected to have `_games`, 230 as if `chessai.core.game.init_from_args()` `chessai.core.ui.init_from_args` have been called. 231 232 Returns the results of the games. 233 """ 234 235 if (winning_agent_teams is None): 236 winning_agent_teams = set() 237 238 results = [] 239 240 for i in range(args.num_games): 241 game = args._games[i] 242 ui = args._uis[i] 243 244 result = game.run(ui) 245 results.append(result) 246 247 if (len(results) > 0): 248 if (log_results is not None): 249 log_results(results, winning_agent_teams) 250 251 if (args.results_path is not None): 252 dict_results = [result.to_dict() for result in results] 253 edq.util.json.dump_path(dict_results, args.results_path) 254 255 return results
If a score list is less than this, log it to info.
19@typing.runtime_checkable 20class SetCLIArgs(typing.Protocol): 21 """ 22 A function that can be used to modify a CLI parser before use. 23 """ 24 25 def __call__(self, 26 parser: argparse.ArgumentParser, 27 ) -> argparse.ArgumentParser: 28 """ 29 Modify the CLI parser before use. 30 Any changes may be made, including adding arguments. 31 The modified (or new) parser should be returned. 32 """
A function that can be used to modify a CLI parser before use.
1953def _no_init_or_replace_init(self, *args, **kwargs): 1954 cls = type(self) 1955 1956 if cls._is_protocol: 1957 raise TypeError('Protocols cannot be instantiated') 1958 1959 # Already using a custom `__init__`. No need to calculate correct 1960 # `__init__` to call. This can lead to RecursionError. See bpo-45121. 1961 if cls.__init__ is not _no_init_or_replace_init: 1962 return 1963 1964 # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`. 1965 # The first instantiation of the subclass will call `_no_init_or_replace_init` which 1966 # searches for a proper new `__init__` in the MRO. The new `__init__` 1967 # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent 1968 # instantiation of the protocol subclass will thus use the new 1969 # `__init__` and no longer call `_no_init_or_replace_init`. 1970 for base in cls.__mro__: 1971 init = base.__dict__.get('__init__', _no_init_or_replace_init) 1972 if init is not _no_init_or_replace_init: 1973 cls.__init__ = init 1974 break 1975 else: 1976 # should not happen 1977 cls.__init__ = object.__init__ 1978 1979 cls.__init__(self, *args, **kwargs)
34@typing.runtime_checkable 35class GetAdditionalOptions(typing.Protocol): 36 """ 37 A function that can be used to get additional initialization options. 38 """ 39 40 def __call__(self, 41 args: argparse.Namespace, 42 ) -> dict[str, typing.Any]: 43 """ 44 Get additional/custom initialization options. 45 """
A function that can be used to get additional initialization options.
1953def _no_init_or_replace_init(self, *args, **kwargs): 1954 cls = type(self) 1955 1956 if cls._is_protocol: 1957 raise TypeError('Protocols cannot be instantiated') 1958 1959 # Already using a custom `__init__`. No need to calculate correct 1960 # `__init__` to call. This can lead to RecursionError. See bpo-45121. 1961 if cls.__init__ is not _no_init_or_replace_init: 1962 return 1963 1964 # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`. 1965 # The first instantiation of the subclass will call `_no_init_or_replace_init` which 1966 # searches for a proper new `__init__` in the MRO. The new `__init__` 1967 # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent 1968 # instantiation of the protocol subclass will thus use the new 1969 # `__init__` and no longer call `_no_init_or_replace_init`. 1970 for base in cls.__mro__: 1971 init = base.__dict__.get('__init__', _no_init_or_replace_init) 1972 if init is not _no_init_or_replace_init: 1973 cls.__init__ = init 1974 break 1975 else: 1976 # should not happen 1977 cls.__init__ = object.__init__ 1978 1979 cls.__init__(self, *args, **kwargs)
47@typing.runtime_checkable 48class InitFromArgs(typing.Protocol): 49 """ 50 A function that can be used to initialize components from CLI args. 51 """ 52 53 def __call__(self, 54 args: argparse.Namespace, 55 ) -> tuple[dict[chessai.core.types.Color, chessai.core.agentinfo.AgentInfo], list[chessai.core.types.Color], dict[str, typing.Any]]: 56 """ 57 Initialize components from arguments and return 58 the base agent infos, a list of agents to remove from the board, as well as any board options. 59 See base_init_from_args() for the default implementation. 60 """
A function that can be used to initialize components from CLI args.
1953def _no_init_or_replace_init(self, *args, **kwargs): 1954 cls = type(self) 1955 1956 if cls._is_protocol: 1957 raise TypeError('Protocols cannot be instantiated') 1958 1959 # Already using a custom `__init__`. No need to calculate correct 1960 # `__init__` to call. This can lead to RecursionError. See bpo-45121. 1961 if cls.__init__ is not _no_init_or_replace_init: 1962 return 1963 1964 # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`. 1965 # The first instantiation of the subclass will call `_no_init_or_replace_init` which 1966 # searches for a proper new `__init__` in the MRO. The new `__init__` 1967 # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent 1968 # instantiation of the protocol subclass will thus use the new 1969 # `__init__` and no longer call `_no_init_or_replace_init`. 1970 for base in cls.__mro__: 1971 init = base.__dict__.get('__init__', _no_init_or_replace_init) 1972 if init is not _no_init_or_replace_init: 1973 cls.__init__ = init 1974 break 1975 else: 1976 # should not happen 1977 cls.__init__ = object.__init__ 1978 1979 cls.__init__(self, *args, **kwargs)
62@typing.runtime_checkable 63class LogResults(typing.Protocol): 64 """ 65 A function that can be used to log game results. 66 """ 67 68 def __call__(self, 69 results: list[chessai.core.game.GameResult], 70 winning_agent_teams: set[chessai.core.types.Color], 71 prefix: str = '', 72 ) -> None: 73 """ 74 Log the result of running several games. 75 """
A function that can be used to log game results.
1953def _no_init_or_replace_init(self, *args, **kwargs): 1954 cls = type(self) 1955 1956 if cls._is_protocol: 1957 raise TypeError('Protocols cannot be instantiated') 1958 1959 # Already using a custom `__init__`. No need to calculate correct 1960 # `__init__` to call. This can lead to RecursionError. See bpo-45121. 1961 if cls.__init__ is not _no_init_or_replace_init: 1962 return 1963 1964 # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`. 1965 # The first instantiation of the subclass will call `_no_init_or_replace_init` which 1966 # searches for a proper new `__init__` in the MRO. The new `__init__` 1967 # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent 1968 # instantiation of the protocol subclass will thus use the new 1969 # `__init__` and no longer call `_no_init_or_replace_init`. 1970 for base in cls.__mro__: 1971 init = base.__dict__.get('__init__', _no_init_or_replace_init) 1972 if init is not _no_init_or_replace_init: 1973 cls.__init__ = init 1974 break 1975 else: 1976 # should not happen 1977 cls.__init__ = object.__init__ 1978 1979 cls.__init__(self, *args, **kwargs)
77def base_init_from_args(args: argparse.Namespace) -> tuple[dict[chessai.core.types.Color, chessai.core.agentinfo.AgentInfo], 78 list[chessai.core.types.Color], dict[str, typing.Any]]: 79 """ 80 Take in args from a parser that was passed to set_cli_args(), 81 and initialize the proper components. 82 """ 83 84 # Create base arguments for all possible agents. 85 base_agent_infos: dict[chessai.core.types.Color, chessai.core.agentinfo.AgentInfo] = { 86 chessai.core.types.Color.WHITE: chessai.core.agentinfo.AgentInfo(name = chessai.util.alias.AGENT_RANDOM.long), 87 chessai.core.types.Color.BLACK: chessai.core.agentinfo.AgentInfo(name = chessai.util.alias.AGENT_RANDOM.long), 88 } 89 90 return base_agent_infos, [], {}
Take in args from a parser that was passed to set_cli_args(), and initialize the proper components.
92def base_log_results(results: list[chessai.core.game.GameResult], winning_agent_teams: set[chessai.core.types.Color], prefix: str = '') -> None: 93 """ 94 Log the result of running several games. 95 """ 96 97 move_counts: list[int] = [len(result.history) for result in results] 98 scores: list[float] = [result.score for result in results] 99 100 record: list[str] = [] 101 for result in results: 102 if (math.isclose(result.score, 0.5)): 103 record.append('Tie') 104 elif (math.isclose(result.score, 1.0)): 105 record.append('Win') 106 else: 107 record.append('Loss') 108 109 average_score: float = (sum(scores)) / len(scores) 110 logging.info('Average Score: %0.2f', average_score) 111 112 # Avoid logging long lists (which can be a bit slow in Python's logging module). 113 log_lists_to_info: bool = (len(results) < chessai.util.bin.SCORE_LIST_MAX_INFO_LENGTH) 114 log_lists_to_debug: bool = (logging.getLogger().getEffectiveLevel() <= logging.DEBUG) 115 116 joined_scores: str = '' 117 joined_record: str = '' 118 joined_move_counts: str = '' 119 120 if (log_lists_to_info or log_lists_to_debug): 121 joined_scores = ', '.join([str(score) for score in scores]) 122 joined_record = ', '.join(record) 123 joined_move_counts = ', '.join([str(move_count) for move_count in move_counts]) 124 125 if (log_lists_to_info): 126 logging.info('%sScores: %s', prefix, joined_scores) 127 elif (log_lists_to_debug): 128 logging.debug('%sScores: %s', prefix, joined_scores) 129 130 if (log_lists_to_info): 131 logging.info('%sRecord: %s', prefix, joined_record) 132 elif (log_lists_to_debug): 133 logging.debug('%sRecord: %s', prefix, joined_record) 134 135 logging.info('%sAverage Moves: %s', prefix, sum(move_counts) / float(len(results))) 136 137 if (log_lists_to_info): 138 logging.info('%sMove Counts: %s', prefix, joined_move_counts) 139 elif (log_lists_to_debug): 140 logging.debug('%sMove Counts: %s', prefix, joined_move_counts)
Log the result of running several games.
142def run_main( 143 description: str, 144 game_class: typing.Type[chessai.core.game.Game], 145 state_class: typing.Type[chessai.core.gamestate.GameState], 146 default_board: str | None = None, 147 custom_set_cli_args: SetCLIArgs | None = None, 148 custom_init_from_args: InitFromArgs = base_init_from_args, 149 winning_agent_teams: set[chessai.core.types.Color] | None = None, 150 log_results: LogResults | None = base_log_results, 151 argv: list[str] | None = None, 152 ) -> list[chessai.core.game.GameResult]: 153 """ 154 A full main function to prep and run games. 155 156 Returns the results of the games. 157 """ 158 159 # Create a CLI parser. 160 parser = get_parser(description, default_board, custom_set_cli_args = custom_set_cli_args) 161 162 # Parse the CLI args. 163 args = parse_args(parser, game_class, state_class, 164 custom_init_from_args = custom_init_from_args, 165 argv = argv) 166 167 return run_games(args, winning_agent_teams = winning_agent_teams, log_results = log_results)
A full main function to prep and run games.
Returns the results of the games.
169def get_parser( 170 description: str, 171 default_board: str | None = None, 172 custom_set_cli_args: SetCLIArgs | None = None, 173 ) -> argparse.ArgumentParser: 174 """ Get a parser with all the options. """ 175 176 parser = argparse.ArgumentParser(description = description) 177 178 # Add logging arguments. 179 parser = chessai.core.log.set_cli_args(parser) 180 181 # Add UI arguments. 182 parser = chessai.core.ui.set_cli_args(parser) 183 184 # Add game arguments. 185 parser = chessai.core.game.set_cli_args(parser, default_board = default_board) 186 187 # Add custom options. 188 if (custom_set_cli_args is not None): 189 parser = custom_set_cli_args(parser) 190 191 return parser
Get a parser with all the options.
193def parse_args( 194 parser: argparse.ArgumentParser, 195 game_class: typing.Type[chessai.core.game.Game], 196 state_class: typing.Type[chessai.core.gamestate.GameState], 197 custom_init_from_args: InitFromArgs = base_init_from_args, 198 argv: list[str] | None = None, 199 ) -> argparse.Namespace: 200 """ Parse the args from the parser returned by get_parser(). """ 201 202 args = parser.parse_args(args = argv) 203 204 # Parse logging arguments. 205 args = chessai.core.log.init_from_args(parser, args) 206 207 # Parse custom options. 208 base_agent_infos, _, kwargs = custom_init_from_args(args) 209 210 # Parse UI options. 211 212 additional_ui_args: dict[str, str] = {} 213 null_out_uis = 0 214 215 args = chessai.core.ui.init_from_args(args, null_out_uis = null_out_uis, additional_args = additional_ui_args) 216 217 # Parse game arguments. 218 args = chessai.core.game.init_from_args(args, game_class, state_class, 219 base_agent_infos = base_agent_infos, **kwargs) 220 221 return args
Parse the args from the parser returned by get_parser().
223def run_games( 224 args: argparse.Namespace, 225 winning_agent_teams: set[chessai.core.types.Color] | None = None, 226 log_results: LogResults | None = base_log_results, 227 ) -> list[chessai.core.game.GameResult]: 228 """ 229 Run one or more standard games using pre-parsed arguments. 230 The arguments are expected to have `_games`, 231 as if `chessai.core.game.init_from_args()` `chessai.core.ui.init_from_args` have been called. 232 233 Returns the results of the games. 234 """ 235 236 if (winning_agent_teams is None): 237 winning_agent_teams = set() 238 239 results = [] 240 241 for i in range(args.num_games): 242 game = args._games[i] 243 ui = args._uis[i] 244 245 result = game.run(ui) 246 results.append(result) 247 248 if (len(results) > 0): 249 if (log_results is not None): 250 log_results(results, winning_agent_teams) 251 252 if (args.results_path is not None): 253 dict_results = [result.to_dict() for result in results] 254 edq.util.json.dump_path(dict_results, args.results_path) 255 256 return results
Run one or more standard games using pre-parsed arguments.
The arguments are expected to have _games,
as if chessai.core.game.init_from_args() chessai.core.ui.init_from_args have been called.
Returns the results of the games.