def take_decisions_and_evolve(name, decisions): game = ca.CellularAutomaton(initialState=ca.initializeHexagonal( ca.defaultParameters['size']['x'], ca.defaultParameters['size']['y']), param=ca.defaultParameters) last_step = mongo.read_last_step(name) cellState = np.array(mongo.read_state(name, last_step)['data']) state = game.getState() state['step'] = last_step def num(s): try: return int(s) except ValueError: return s # here should actually be something used like map or np.vectorize unfortunately does not work for x in range(len(cellState)): for y in range(len(cellState[x])): state['cells'][x][y] = num(cellState[x][y]) game.setState(state) #for x in decisions # game.setDecisions("fucksor", [["stay", 0], ["stay", 0]]) game.evolve() step_string = "step" + str(game.getState()['step']) mongo.store_state(name, step_string, game.getState()['cells']) mongo.set_last_step(name, step_string)
def main(): filelist = glob.glob("pics/*") for f in filelist: os.remove(f) x = 16 y = 16 game = ca.CellularAutomaton(initialState=ca.initializeHexagonal(x,y),param=ca.defaultParameters) game.setNewSpecies(nicePositions4(0,x,y), 'Clone', 'green', 30) game.setNewSpecies(nicePositions4(1,x,y), 'Move', 'blue', 3) game.setNewSpecies(nicePositions4(2,x,y), 'Move', 'blue', 3) game.setNewSpecies(nicePositions4(3,x,y), 'Move', 'blue', 3) saveStatePicture(game.getState(), "pics") for _ in range(30): state = game.getState() for s in game.findSpecies(): game.setDecisions(s,makeDecision(state,s)) #print(game.cells[game.cells[:,1] != 'empty',:4]) game.evolve() saveStatePicture(state, "pics") #print(game.cells[game.cells[:,1] != 'empty',:4]) app = QApplication(sys.argv) pics = sort_nicely(glob.glob("pics/*")) gui = SimpleGUI(pics) gui.show() sys.exit(app.exec_())
def eval_fitness_single(genomes): #multiple fights make for better statistics num_runs = 1 for g in genomes: net = nn.create_recurrent_phenotype(g) achi = 0 for _ in range(num_runs): mooreNeighborhood = ca.Neighborhood(gocl.initNeighborhood) gameOfLife = ca.CellularAutomaton(mooreNeighborhood) gameOfLife.parameters = gameOfLife.world['parameters'] newSpecies(gameOfLife, { 'species': 'test', 'color': 'Blue', 'position': { 'x': 0, 'y': 0 } }) currentDecision = partial(netDecision, net=net) evolve = gameOfLife.evolve c = 0 while c < 20: dec = {} recursionDecision(gameOfLife.world['space'], dec, currentDecision) gameOfLife.decisions = dec evolve() c += 1 achi += countSpecies(gameOfLife.world['space'], 'test') g.fitness = achi / num_runs
def setUp(self): self.game = ca.CellularAutomaton(initialState=ca.initializeHexagonal( 3, 3), param=ca.defaultParameters) self.state = self.game.getState() self.game.setNewSpecies(0, 'Move', 'blue', 20) self.state['cells'][0, 1] = 'Move' self.state['cells'][0, 2] = 'blue' self.state['cells'][0, 3] = 20
def eval_fitness_internalfight(allgenomes): num_runs = 2 for g in allgenomes: g.fitness = 0 #sadly, the number of genomes from neat-python is not fixed, so we only train some to fit %4 genomes = allgenomes[:int(len(allgenomes) / 4) * 4] print(len(allgenomes), len(genomes)) for _ in range(num_runs): #geht nur, wenn genomes durch 4 teilbar ist grouping = np.reshape(np.random.permutation(len(genomes)), (len(genomes) / 4, 4)) for group in grouping: nets = [] mooreNeighborhood = ca.Neighborhood(gocl.initNeighborhood) gameOfLife = ca.CellularAutomaton(mooreNeighborhood) gameOfLife.parameters = gameOfLife.world['parameters'] for i, g in enumerate(group): nets.append(nn.create_recurrent_phenotype(genomes[g])) newSpecies( gameOfLife, { 'species': i, 'color': i, 'position': { 'x': int(i % 2) * 5, 'y': int((i / 2) % 2) * 5 } }) evolve = gameOfLife.evolve c = 0 #length of the game while c < 30: gameOfLife.decisions = {} for i, g in enumerate(group): dec = {} currentDecision = partial(netDecision, net=nets[i]) recursionDecision(gameOfLife.world['space'], dec, currentDecision) #if a species died there might be an error try: gameOfLife.decisions[i] = dec[i] except: pass evolve() c += 1 for i, g in enumerate(group): genomes[g].fitness += countSpecies(gameOfLife.world['space'], i) #results of fights define the fitness for g in genomes: g.fitness = g.fitness / num_runs
def visualizeWinners(checkpoint, config, picdir, rounds): colors = ['red', 'yellow', 'green', 'blue'] while len(checkpoint) < 4: checkpoint.extend(checkpoint) checkpoint = checkpoint[:4] print("Going to let fight: ", checkpoint) print("With colors: ", colors) nets = {} for i, c in enumerate(checkpoint): pop = population.Population(config) pop.load_checkpoint(c) trainfunc = partial(eval_fitness_internalfight, num_runs=10, steplength=200, x=16, y=16) pop.run(trainfunc, 1) winner = pop.statistics.best_genome() nets[c+str(i)] = nn.create_feed_forward_phenotype(winner) filelist = glob.glob(os.path.join(picdir, 'step*.png')) for f in filelist: os.remove(f) x = 40; y = 40 game = ca.CellularAutomaton(initialState=ca.initializeHexagonal(x, y), param=ca.defaultParameters) for i,k in enumerate(nets.keys()): game.setNewSpecies(util.nicePositions4(i,x, y), k, colors[i]) util.saveStatePicture(game.getState(), picdir) while game.step < rounds: state = game.getState() for s in game.findSpecies(): try: game.setDecisions(s, netDecision(state, s, nets[s])) except: pass game.evolve() util.saveStatePicture(state, picdir) app = QApplication(sys.argv) pics = util.sort_nicely(glob.glob(os.path.join(picdir, 'step*.png'))) gui = SimpleGUI(pics) gui.show() sys.exit(app.exec_())
def main(): print("Starting...") pop = population.Population( os.path.join(os.path.dirname(__file__), 'nn_config')) #HINT change checkpoints for new try or reloading pop.load_checkpoint( os.path.join(os.path.dirname(__file__), 'checkpoints/popv1.cpt')) pop.run(eval_fitness_internalfight, 5) pop.save_checkpoint( os.path.join(os.path.dirname(__file__), 'checkpoints/popv1.cpt')) statistics.save_stats(pop.statistics) statistics.save_species_count(pop.statistics) statistics.save_species_fitness(pop.statistics) winner = pop.statistics.best_genome() print('\nBest genome:\n{!s}'.format(winner)) print('\nOutput:') winner_net = nn.create_recurrent_phenotype(winner) mooreNeighborhood = ca.Neighborhood(gocl.initNeighborhood) gameOfLife = ca.CellularAutomaton(mooreNeighborhood) gameOfLife.parameters = gameOfLife.world['parameters'] newSpecies(gameOfLife, { 'species': 'test', 'color': 'Blue', 'position': { 'x': 0, 'y': 0 } }) currentDecision = partial(netDecision, net=winner_net) evolve = gameOfLife.evolve c = 0 while c < 20: dec = {} recursionDecision(gameOfLife.world['space'], dec, currentDecision) gameOfLife.decisions = dec evolve() c += 1 print("Ended with: ", countSpecies(gameOfLife.world['space'], 'test'))
def eval_fitness_internalfight(allgenomes, num_runs=3, steplength=100, x=16, y=16): for g in allgenomes: g.fitness = 0 # sadly, the number of genomes from neat-python is not fixed, so we only train some to fit %4 topad = int(np.ceil(len(allgenomes)/4)*4-len(allgenomes)) traincount = np.zeros(len(allgenomes)) trainfitness = np.zeros(len(allgenomes)) print(len(allgenomes),topad) for _ in range(num_runs): # geht nur, wenn genomes durch 4 teilbar ist TODO change this grouping = np.random.permutation(len(allgenomes)) if topad > 0: grouping = np.concatenate((grouping, np.random.choice(grouping,topad))) grouping = np.reshape(grouping, (len(grouping)/4, 4)) for group in grouping: nets = [] game = ca.CellularAutomaton(initialState=ca.initializeHexagonal(x, y), param=ca.defaultParameters) for i, g in enumerate(group): nets.append(nn.create_feed_forward_phenotype(allgenomes[g])) game.setNewSpecies(util.nicePositions4(i,x,y), 'spec' + str(i)) while game.step < steplength: state = game.getState() for j, g in enumerate(group): game.setDecisions('spec' + str(j), netDecision(state, 'spec' + str(j), nets[j])) game.evolve() for k, g in enumerate(group): trainfitness[g] += countSpecies(game.getState(), 'spec' + str(k)) traincount[g] += 1 # divide training results by traincount, bc of padding etc this has to be done # fitness of all below median is set to zero trainfitness = trainfitness/traincount trainfitness[trainfitness < np.median(trainfitness)] = 0 # results of fights define the fitness for k, g in enumerate(allgenomes): g.fitness = trainfitness[k]
def create(name, size): game = ca.CellularAutomaton(initialState=ca.initializeHexagonal( ca.defaultParameters['size']['x'], ca.defaultParameters['size']['y']), param=ca.defaultParameters) mongo.store_state(name, "step0", game.getState()['cells']) mongo.set_last_step(name, "step0")
import gameOfComplexLife as gocl import cellularAutomaton as ca import numpy as np # Initialisieren mooreNeighborhood = ca.Neighborhood(gocl.initNeighborhood) gameOfLife = ca.CellularAutomaton(mooreNeighborhood) evolve = gameOfLife.evolve def makeDecision(cell): if cell.state['species'] == 'empty': return {'action': "stay", 'value': 0} if cell.state['species'] == 'OnlyClone': return {'action': "clone", 'value': int(np.random.ranf() * 6)} if cell.state['species'] == 'CloneAndAttack': freeNeighbors = [] for i in range(len(cell.neighbors)): if cell.neighbors[i].state['species'] != 'empty': if cell.neighbors[i].state['species'] != cell.state['species']: if cell.neighbors[i].state['color'] != cell.state['color']: #print("attack ",cell.state['species'],cell.neighbors[i].state['species']) return {'action': 'fight', 'value': i} else: freeNeighbors.append(i) if (len(freeNeighbors) > 0): return {
N = np.sum(mask) if N < 1: return np.array([]) dec = np.empty((N, 2), dtype=object) dec[:, 0] = 'stay' dec[:, 1] = 0 cells = state['cells'][mask] neighbors = state['cells'][np.int_(state['neighbors'][mask])] secondneighbors = state['cells'][np.int_(state['secondneighbors'][mask])] if spec == 'Move': dec[:, 0] = 'move' dec[:, 1] = np.random.randint(0, len(neighbors[0]), N) if spec == 'Clone': dec[:, 0] = 'clone' dec[:, 1] = np.random.randint(0, len(neighbors[0]), N) if spec == 'CNC_CELL': dec = cnc.onNewIteration(state, N, cells, neighbors, secondneighbors, dec) return dec if __name__ == "__main__": cnc = CorticalNetworkCell() game = ca.CellularAutomaton(initialState=ca.initializeHexagonal(16, 16), param=ca.defaultParameters) main()