<repo_name>JoekingCooper/project_attenuation<file_sep>/README.md
# project_attenuation

This is an mysterious project with no information ...
<file_sep>/notebooks/.ipynb_checkpoints/breed_generation-checkpoint.py
import numpy as np
import random
import os
import pickle


class BreedGeneration:
    
    
    """
    
    
    A class just used too create the first generation of fighters fr the tournament
    
    
    """
    
    def __init__(self,dead_generation,mutation_rate = 0.1,number_of_fighters = 16, last_name_list_file = 'last-names.txt',first_name_list_file = 'first-names.txt'):
        
        """
        
        Initialize some values mostly with nothings
        
        """
        
        self.dead_generation = dead_generation
        self.generation_number = dead_generation['generation_number']+1
        self.cwd = os.getcwd()
        self.matrix_dimensions = dead_generation['fighters'][list(dead_generation['fighters'].keys())[1]]['attributes'].shape

        
        self.ids = None
        self.generation_dict = dict()
        self.number_of_fighters = number_of_fighters
        self.file_last_name_list = last_name_list_file
        self.file_first_name_list = first_name_list_file
        self.mutation_rate = mutation_rate
        self.gen_storage_location = os.path.abspath(os.path.join(self.cwd,
                                                                 '..', 'storage',
                                                                 'generation_'+str(self.generation_number)+'_pool',
                                                                 'gen'+str(self.generation_number)+'begin.pickle'))
    def createIDList(self):
        self.ids = ["g"+str(self.generation_number)+"_c" + str(num) for num in range(self.number_of_fighters)]
    def pullNameList(self):
        last_name_list_path = os.path.abspath(os.path.join(self.cwd, '..', 'storage','resources',self.file_last_name_list))
        text_file = open(last_name_list_path, "r")
        self.last_name_list = text_file.read().split('\n')
        text_file.close()
        
        first_name_list_path = os.path.abspath(os.path.join(self.cwd, '..', 'storage','resources',self.file_first_name_list))
        text_file = open(first_name_list_path, "r")
        self.first_name_list = text_file.read().split('\n')
        text_file.close()
    def populateProbabilities(self):
        self.indexlist = list(self.dead_generation['fighters'].keys())
        wins = []
        for key in self.indexlist:
            wins.append(self.dead_generation['fighters'][key]['wins'])
        self.fighter_probabilities = np.array(wins)/sum(wins)
    def get_matrix_mask_2(self):
        mask_test = np.full(self.matrix_dimensions[0]**2,True)

        mask_test[0:int(self.matrix_dimensions[0]**2/2)] = False
        np.random.shuffle(mask_test)
        return mask_test.reshape(self.matrix_dimensions)
    def breedFighters(self):
        fighter_1 = self.dead_generation['fighters'][np.random.choice(self.indexlist, p=self.fighter_probabilities)]
        fighter_2 = self.dead_generation['fighters'][np.random.choice(self.indexlist, p=self.fighter_probabilities)]
        #get name
        new_first_name = random.choice(self.first_name_list)
        new_last_name = random.choice([fighter_1['last_name'],fighter_2['last_name']])
        name = new_first_name+' '+new_last_name
        #get masks for equation
        tf1_mask = self.get_matrix_mask_2()
        tf2_mask = np.invert(tf1_mask)
        #create base stats
        base_fighter_attributes = (fighter_1['attributes']*tf1_mask+fighter_2['attributes']*tf2_mask)
        base_fighter_attributes = np.nan_to_num(base_fighter_attributes)
        #mutate base stats
        mutation = np.random.rand(self.matrix_dimensions[0],self.matrix_dimensions[0])-0.5
        new_fighter_attributes = base_fighter_attributes + mutation*self.mutation_rate
        return name, new_last_name, new_fighter_attributes
    def populateDictionary(self):
        self.generation_dict['generation_number']=self.generation_number
        self.generation_dict['mutation_rate']=self.mutation_rate
        self.generation_dict['fighters']=dict()
        for num,i in enumerate(self.ids):
            self.generation_dict['fighters'][i] = dict()
            #create name
            name,last_name, attributes = self.breedFighters()
            #other attributes
            self.generation_dict['fighters'][i]['name'] = name
            self.generation_dict['fighters'][i]['last_name'] = last_name
            self.generation_dict['fighters'][i]['alive'] = 1
            self.generation_dict['fighters'][i]['attributes'] = attributes
            self.generation_dict['fighters'][i]['wins'] = 0
            self.generation_dict['fighters'][i]['tournament_count'] = 0
    def saveDictionary(self):
        with open(self.gen_storage_location, 'wb') as handle:
            pickle.dump(self.generation_dict, handle, protocol=pickle.HIGHEST_PROTOCOL)

    def pipeline(self):
        self.createIDList()
        self.pullNameList()
        self.populateProbabilities()
        self.populateDictionary()
        self.saveDictionary()
<file_sep>/notebooks/alpha_motive_tournament.py
import numpy as np
import random
import pickle
def number_of_rounds(n):
    return np.floor(np.log(n)/np.log(2))
"""
DONE:
- reset wins and reset life function so that tournament can be rerun
- test with different matrix sizes

TODO:

- combination of attributes as decider (instead of one) + a weight matrix for that combination




"""

class AlphaMotiveTournament():
    
    
    """
    
    
    The tournament class, hosted by AlphaMotive.
    
    
    """
    
    
    def __init__(self,fighter_dict:"Dictionary with fighter data."):
        
        """
        Initialize for the tournament
        """
        
        
        self.pool_dead = []
        self.pool_2 = []
        self.fighter_dict = fighter_dict.copy()
        self.number_of_rounds = number_of_rounds(len(fighter_dict['fighters']))
        self.pool_1 = list(self.fighter_dict['fighters'].keys())
        self.pool_init = list(self.fighter_dict['fighters'].keys())
        self.fight_number = 0
        dummy_attribute_matrix = self.fighter_dict['fighters'][self.pool_1[0]]['attributes']
        self.att_matrix_dimension_0 = len(dummy_attribute_matrix)-1
        self.att_matrix_dimension_1 = len(dummy_attribute_matrix[0])-1
        
    def single_fight(self,pool,printswitch=True):
        contestant1 = random.choice(pool)
        pool.remove(contestant1)
        contestant2 = random.choice(pool)
        pool.remove(contestant2)
        #get indx mapping for fight, random values are compared to decide the winner.
        inx_0 = random.randint(0, self.att_matrix_dimension_0)
        inx_1 = random.randint(0, self.att_matrix_dimension_1)
        #print names of contestants
        if printswitch:
            print('... Fight',self.fight_number)
            print('... - ',self.fighter_dict['fighters'][contestant1]['name'],'Vs.',self.fighter_dict['fighters'][contestant2]['name'])
        #access the comparison fight values
        contestant1_score = self.fighter_dict['fighters'][contestant1]['attributes'][inx_0][inx_1]
        contestant2_score = self.fighter_dict['fighters'][contestant2]['attributes'][inx_0][inx_1]
        # give winner and looser
        winner = np.where(contestant1_score>=contestant2_score,contestant1,contestant2).item()
        if printswitch:
            print('... - ',self.fighter_dict['fighters'][winner]['name'],'is the winner!')
        loser = np.where(contestant1_score<contestant2_score,contestant1,contestant2).item()
        return winner, loser
    def tournament(self,printswitch=True):
        winner = None
        pool_1 = self.pool_1 
        pool_dead = self.pool_dead
        pool_2 = self.pool_2
        self.fight_number = 0
        for tournament_round in range(int(self.number_of_rounds)):
            #print stage number
            if printswitch:
                print('Stage:',tournament_round)
            for fight_num in range(int(len(pool_1)/2)):
                #run fight
                self.fight_number += 1
                winner, loser = self.single_fight(pool_1,printswitch=printswitch)
                # add winner to next pool
                pool_2.append(winner)
                self.fighter_dict['fighters'][winner]['wins']+=1
                # add loser to pool dead pool
                pool_dead.append(loser)
                self.fighter_dict['fighters'][loser]['alive']=0
                self.fighter_dict['fighters'][loser]['tournament_count']+=1
            pool_1 = pool_2.copy()
            pool_2 = []
        self.pool_1 = pool_1
        self.pool_2 = pool_2
        self.pool_dead = pool_dead
        self.tournament_winner = winner
        self.tournament_winner_stats = self.fighter_dict['fighters'][winner]['attributes']
        self.fighter_dict['fighters'][winner]['tournament_count']+=1
        if printswitch:
            print('The Alpha Motive Champion is',self.fighter_dict['fighters'][self.tournament_winner]['name'])
            print('Kills =',self.fighter_dict['fighters'][self.tournament_winner]['wins'])
    def produceAverageWinner(self):
        fights = self.fighter_dict['fighters'][self.tournament_winner]['wins']
        attribute_addition = self.fighter_dict['fighters'][self.tournament_winner]['wins']*self.fighter_dict['fighters'][self.tournament_winner]['attributes']
        for fighter in self.pool_dead:
            attribute_addition += self.fighter_dict['fighters'][fighter]['wins']*self.fighter_dict['fighters'][fighter]['attributes']
            fights += self.fighter_dict['fighters'][fighter]['wins']
        self.averagewinner_stats = attribute_addition/fights
    def resetPools(self):
        self.pool_dead = []
        self.pool_2 = []
        self.pool_1 = list(self.fighter_dict['fighters'].keys())
    def resetAlive(self):
        for fighter in list(self.fighter_dict['fighters'].keys()):
            self.fighter_dict['fighters'][fighter]['alive']=1
    def resetWins(self):
        for fighter in list(self.fighter_dict['fighters'].keys()):
            self.fighter_dict['fighters'][fighter]['wins']=0
    def resetAll(self):
        self.resetPools()
        self.resetAlive()
        self.resetWins()
        <file_sep>/notebooks/create_gen_0.py
import numpy as np
import random
import os
import pickle


class CreateGeneration0:
    
    
    """
    
    
    A class just used too create the first generation of fighters fr the tournament
    
    
    """
    
    def __init__(self,number_of_fighters = 16, last_name_list_file = 'last-names.txt',first_name_list_file = 'first-names.txt',attribute_dimensions = 2):
        
        """
        
        Initialize some values mostly with nothings
        
        """
        self.cwd = os.getcwd()
        self.ids = None
        self.name_list = None
        self.generation0 = dict()
        self.number_of_fighters = number_of_fighters
        self.file_last_name_list = last_name_list_file
        self.file_first_name_list = first_name_list_file
        self.attribute_dimensions = attribute_dimensions
        self.gen0_storage_location = os.path.abspath(os.path.join(self.cwd, '..', 'storage','base','data_dict_gen0.pickle'))
    def createIDList(self):
        self.ids = ["g1_c" + str(num) for num in range(self.number_of_fighters)]
    def pullNameList(self):
        last_name_list_path = os.path.abspath(os.path.join(self.cwd, '..', 'storage','resources',self.file_last_name_list))
        text_file = open(last_name_list_path, "r")
        self.last_name_list = text_file.read().split('\n')
        text_file.close()
        
        first_name_list_path = os.path.abspath(os.path.join(self.cwd, '..', 'storage','resources',self.file_first_name_list))
        text_file = open(first_name_list_path, "r")
        self.first_name_list = text_file.read().split('\n')
        text_file.close()
    def populateDictionary(self):
        self.generation0['generation_number']=0
        self.generation0['mutation_rate']=0
        self.generation0['fighters']=dict()
        for num,i in enumerate(self.ids):
            self.generation0['fighters'][i] = dict()
            #create name
            last_name = random.choice(self.last_name_list) 
            first_name = random.choice(self.first_name_list) 
            self.generation0['fighters'][i]['name'] = first_name+' '+last_name
            self.generation0['fighters'][i]['last_name'] = last_name
            #remove used names
            self.first_name_list.remove(first_name)
            self.last_name_list.remove(last_name)
            #other attributes
            self.generation0['fighters'][i]['alive'] = 1
            self.generation0['fighters'][i]['attributes'] = np.random.rand(self.attribute_dimensions,self.attribute_dimensions)
            self.generation0['fighters'][i]['wins'] = 0
            self.generation0['fighters'][i]['tournament_count'] = 0
    def saveDictionary(self):
        with open(self.gen0_storage_location, 'wb') as handle:
            pickle.dump(self.generation0, handle, protocol=pickle.HIGHEST_PROTOCOL)

    def pipeline(self):
        self.createIDList()
        self.pullNameList()
        self.populateDictionary()
        self.saveDictionary()