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)	
	mongoread = mongo.read_state(name, last_step['data'])
	cellState = np.array(mongoread['data'])

	state = game.getState()
	
	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)
	
	decisions = json.loads(decisions)

	for x in decisions:
		#print(x)
		game.setDecisions(x['species'], x['decisions']) 

	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)
Example #2
0
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)
Example #3
0
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 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
Example #5
0
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_())
Example #6
0
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]
Example #7
0
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")
# this is just some simple function that makes decisions for species 'Move' and 'Clone'
def makeDecision(state, spec):
    mask = state['cells'][:, 1] == spec
    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()
Example #9
0
    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()
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")