Beispiel #1
0
def play_to_significance(bots,width=10,alpha_thresh=0.1):
    """
    ______
    Input:
        significance interval
        significance value
        method of training
        loaded player instances of all bots
    ______
    Output:
        none
    ______
        makes the bots play until each of their score values has
        a significance value of alpha or lower
        
    """
    
    above_alpha = use_multi_core(bots,width,alpha_thresh)
                        
    scrape_pool(multiprocessing.cpu_count(),bots)#scrape leftover scores
    
    score_tuples = [(diagnostics.score_estim(width,bot.name),bot.name) for bot in bots]
    if [tuple[1] for tuple in score_tuples if tuple[0][1] > alpha_thresh]:
        play_to_significance(bots,width=width,alpha_thresh=alpha_thresh)
        score_tuples = [(diagnostics.score_estim(width,bot.name),bot.name) for bot in bots]
        
    assert not (insignificant_scores := ([tuple[1] for tuple in score_tuples if tuple[0][1] > alpha_thresh])),f"{insignificant_scores} are left over!"
    
    
    print("Significance achieved")
    return True
def mutate_species(species_names, link_thresh, node_thresh, weights_mut_thresh,
                   rand_weight_thresh, pert_rate):
    """
    ______
    Input:
        list of bot names that belong to one species
        mutation parameters
    ______
    Output:
        None
    ______
        All bot genomes in the given species are mutated randomly
        except if the species is larger than five, in which case a single champion is spared from mutation

    """
    if len(species_names) >= 5:
        species_members = species_names.copy()
        species_member_scores = {
            bot_name: diagnostics.score_estim(999, bot_name)[0]
            for bot_name in species_members
        }
        species_members.sort(key=lambda x: species_member_scores[x],
                             reverse=True)
        for bot in species_members[1:]:
            print(f"Mutating {bot}")
            mutation_step(bot, link_thresh, node_thresh, weights_mut_thresh,
                          rand_weight_thresh, pert_rate)
    else:
        for bot in species_names:
            print(f"Mutating {bot}")
            mutation_step(bot, link_thresh, node_thresh, weights_mut_thresh,
                          rand_weight_thresh, pert_rate)
    return
Beispiel #3
0
def assign_scores_to_species(gen_idx):
    """
    assigns a species average score to the species dictionary
    """
    species_dict=utils.load_gen_species(gen_idx)
    for species_idx,species in species_dict.items():
        species_mean_score = np.mean([diagnostics.score_estim(1,botname)[0] for botname in species_dict[species_idx]["MEMBERS"]])
        species_dict[species_idx]["SCORE"] = species_mean_score
    utils.save_generation_species(gen_idx, species_dict)
    return   
Beispiel #4
0
def use_multi_core(bots,width=10,alpha_thresh=0.1):
    """
    ______
    Input:
        significance interval
        significance value
        loaded player instances of all bots

    ______
    Output:
        none
    ______
        uses four core to make the bots play until each of their score values has
        a significance value of alpha or lower
    """
    n_cores = multiprocessing.cpu_count()
    above_alpha = bots.copy()    

    while len(above_alpha):
        
        above_alpha = bots.copy()
        score_estim_list = [(diagnostics.score_estim(width,bot.name),bot) for bot in bots]
        for significant_tuple in (significant_tuples := [tuple for tuple in score_estim_list if tuple[0][1] < alpha_thresh]):
            above_alpha.remove(significant_tuple[1])
        print(f"{len(significant_tuples)} out of {len(bots)} scores are significant")

        if not above_alpha: 
            return above_alpha #hacky catch number one
        
        average_alpha = np.mean([tuple[0][1] for tuple in score_estim_list])
        n_games = min([int(np.ceil(average_alpha/alpha_thresh**3)+50)])#a rough estimate, can be made more precise

        if n_games<10:
            n_games=10 #hacky catch number two
            
        print( f"The pools score estimates have a {np.round(average_alpha*100,2)}% chance of being off by more than {width}")

        
        pool_list = []
        
        for game_idx in range(n_games):
            random.shuffle(above_alpha) #st every bot has a diverse set of enemies
            random.shuffle(significant_tuples) #st excess score is distributed more evenly
            pools = [above_alpha[i:i + 4] for i in range(0, len(above_alpha), 4)]
            if (missing_bots := 4 - len(pools[-1])) > 0:#if the last pool is not 4 players
                pools[-1].extend([significant_tuple[1] for significant_tuple in significant_tuples[:missing_bots]])               
            pool_list.extend(pools)
Beispiel #5
0
    while True:
        current_gen +=1
        print(f"Training generation {current_gen-1} to produce generation {current_gen}")
        generation(current_gen,
                   significance_width,significance_val,population_size,
                   link_thresh,node_thresh,weights_mut_thresh,rand_weight_thresh,pert_rate,preservation_rate,improvement_timer)



        
if __name__ == "__main__": #so it doesnt run when imported
    print(txt)

    botnames=utils.load_bot_names()
    botnames.sort(key=lambda bot_name : diagnostics.score_estim(10,bot_name)[0],reverse=True)
    bots = [Player(bot_name) for bot_name in botnames]
    
    print(f"{multiprocessing.cpu_count()} cores available.")
    diagnostics.population_progress()

    diagnostics.species_over_time(pop_size=500)
    for _ in range(2):
        diagnostics.graph(bots[_].name,'play')
        diagnostics.graph(bots[_].name,'bid')
        diagnostics.graph(bots[_].name,'stm')
        diagnostics.score_hist(bots[_].name)
  
    
    scrape_pool(4,utils.load_bot_names())
    start_training(significance_val=0.25,
                    if hmp_int > 4 or hmp_int < 1:
                            print("Must be between 0 and 4!")
                    else:
                            if not hmp_int == 1:
                                    print("Game is played with {} Player(s) and {} Bots.".format(hmp_int,(4-hmp_int)))
                            else:
                                    print("Game is played with {} Player and {} Bots.".format(hmp_int,(4-hmp_int)))

                            hmp = hmp_int
                            hmp_given = True
            except ValueError:
                    print("Must be an Integer!")
                            
                            
    bot_names = utils.load_bot_names()
    bot_names.sort(key=lambda bot_name : diagnostics.score_estim(10,bot_name)[0],reverse=True)
    real_players = [Human_Player(_) for _ in range(hmp)]
    bot_players  = [Player(bot_name) for bot_name in bot_names[:(4-hmp)]]
    current_pool = []            
    current_pool.extend(real_players)
    current_pool.extend(bot_players)
            
    print(f"\nYour enemies have the following average scores:")
    for bot in bot_players:
        print(bot,':',int(np.round(diagnostics.score_estim(10,bot)[0],0)))
    print("Good Luck!\n")
    print("Game starts!")

    pausevar = input("\nPress any button to continue")
    clear()
    play_game(current_pool)