def get_player(player_args): assert 1 <= len(player_args) <= 2 if len(player_args) == 1: return fixed_players[player_args[0]]() Player = get_ga_player(player_args[0]) chromosome = np.load(player_args[1]) return Player(chromosome)
def eval_population_worker(queue: mp.Queue, games_per_chromosome, task_counter_queue: mp.Queue, Opponent): while True: population_path = queue.get() folder_path = os.path.dirname(population_path) folder_name = os.path.basename(folder_path) player_name = folder_name.split("+")[0] Player = get_ga_player(player_name) population = np.load(population_path) N = min(len(population), 20) population_idx = np.random.choice(np.arange(len(population)), N, replace=False) population = population[population_idx] save_matrix = np.empty((2, N), np.float) save_matrix[0] = population_idx scores = save_matrix[1] for i, chromosome in enumerate(population): players = [Player(chromosome)] + [Opponent() for _ in range(3)] win_count = 0 for _ in range(games_per_chromosome): random.shuffle(players) game = LudoGame(players) winner = players[game.play_full_game()] if isinstance(winner, Player): win_count += 1 scores[i] = win_count / games_per_chromosome generation_str = os.path.basename(population_path).split(".")[0] scores_path = get_score_file_path(folder_path, generation_str, Opponent.name) assert not os.path.exists(scores_path), "Scores already exists: {}".format(scores_path) np.save(scores_path, save_matrix) task_counter_queue.put(('finished', population_path))
def get_player_class(folder_path): player_name, *player_args = os.path.basename(folder_path).split( "+")[0].split("-") Player = get_ga_player(player_name) player_args = [ arg_def[1](arg) for arg, arg_def in zip(player_args, Player.args) ] return Player, player_args
def main(): parser = argparse.ArgumentParser() parser.add_argument("--population_path", required=True) parser.add_argument("--games_per_tournament", type=int, required=True) args = parser.parse_args() folder_path = os.path.dirname(args.population_path) folder_name = os.path.basename(folder_path) gen_id = int(os.path.basename(args.population_path).split(".")[0]) player_name = folder_name.split("+")[0] Player = get_ga_player(player_name) population = list(np.load(args.population_path)) N = len(population) required_tournament_count = get_required_tournament_count(N) required_game_count = required_tournament_count * args.games_per_tournament print("required game count:", required_game_count) tournaments_played = 0 while N > 1: tournament_count = N // 4 if tournament_count == 0: tournament_count = 1 print( "Currently {} players in the population. Playing {} tournaments.". format(N, tournament_count)) next_population = population[tournament_count * 4:] for i in range(tournament_count): chromosomes = population[i * 4:(i + 1) * 4] winner_id = tournament(chromosomes, Player, args.games_per_tournament) next_population.append(chromosomes[winner_id]) tournaments_played += 1 print("{:.2f}: {} of {} games".format( tournaments_played / required_tournament_count, tournaments_played * args.games_per_tournament, required_tournament_count * args.games_per_tournament)) population = next_population N = len(population) winner = population[0] np.save("{}/{}.pop.winner.npy".format(folder_path, gen_id), winner)
def main(): parser = argparse.ArgumentParser() parser.add_argument("--player", nargs='+', required=True) parser.add_argument("--selection", nargs='+', required=True) parser.add_argument("--recombination", nargs='+', required=True) parser.add_argument("--mutation", nargs='+', required=True) parser.add_argument("--gen_count", type=int, required=True) parser.add_argument("--save_nth_gen", type=int, required=True) parser.add_argument("--cont", action="store_const", const=True, default=False) args = parser.parse_args() Player = get_ga_player(args.player[0]) player_args, player_args_str = parse_args(args.player[1:], Player.args) gene_count = Player.gene_count Selection = get_selection(args.selection[0]) selection_args, selection_args_str = parse_args(args.selection[1:], Selection.args) Recombinator = get_recombinator(args.recombination[0]) recombinator_args, recombinator_args_str = parse_args(args.recombination[1:], Recombinator.args) Mutator = get_mutator(args.mutation[0]) mutator_args, mutator_args_str = parse_args(args.mutation[1:], Mutator.args) mutator = Mutator(gene_count, *mutator_args) recombinator = Recombinator(gene_count, *recombinator_args) generation_count = args.gen_count save_every_nth_generation = args.save_nth_gen pop_init = functools.partial(Player.pop_init, Player, mutator.chromosome_length - Player.gene_count) selection = Selection(Player, pop_init, recombinator, mutator, *selection_args) folder_name = "{}{}+{}{}+{}{}+{}{}".format( Player.name, args_str_to_string(player_args_str), Selection.name, args_str_to_string(selection_args_str), Recombinator.name, args_str_to_string(recombinator_args_str), Mutator.name, args_str_to_string(mutator_args_str), ) folder_path = "populations/" + folder_name assert os.path.isdir(folder_path) == args.cont, '{} should{} exist'.format(folder_path, '' if args.cont else ' not') if not args.cont: os.mkdir(folder_path) else: gen_ids = [int(os.path.basename(path).split(".")[0]) for path in glob.glob(folder_path + "/*.pop.npy")] selection.current_generation = max(gen_ids) selection.population = np.load(folder_path + "/{}.pop.npy".format(selection.current_generation)) if generation_count == 0: generation_count = int(1e9) if not args.cont: save(folder_path, 0, selection.get_flat_pop()) for i in range(selection.current_generation, generation_count): selection.step() if selection.current_generation % save_every_nth_generation == 0: save(folder_path, selection.current_generation, selection.get_flat_pop()) flat_pop = selection.get_flat_pop() chromo_mean = flat_pop.mean(axis=0) chromo_std = flat_pop.std(axis=0) print("gene mean", chromo_mean[:gene_count]) print("gene std ", chromo_std[:gene_count]) print("sigma mean", chromo_mean[gene_count:]) print("sigma std ", chromo_std[gene_count:]) print(*sys.argv[1:])