def test_buildgrid(self):
        cA = CellularAutomata()
        grid = cA.buildGrid('1' * 8, 9)  # Width of the grid is greater than the length of the start state
        self.assertEqual(len(grid[0]), 9)

        grid = cA.buildGrid('1' * 10, 9)  # Width of the grid is less than the length of the start state
        self.assertEqual(len(grid[0]), 10)

        grid = cA.buildGrid('11', 10)
        self.assertTrue('11' in '%s' % ''.join(map(str, grid[0])))
Пример #2
0
def run2(options):

    rows = options.size
    columns = options.size

    enviroments = [CellularAutomata(rows, columns) for i in range(5)]

    for i in enviroments: i.drawCycle(options.radius, options.X_center, options.Y_center)

    enviroments[1].applyNoiseBoundary()
    enviroments[2].applyNoiseBoundary(noiseLevel = options.noise_level)
    enviroments[3].applyNoiseRandom()
    enviroments[4].applyNoiseRandom(noiseLevel = options.noise_level)

    for i in range(options.time_steps):
        print("Time Step: ",i)
        # env.printCA()
        for env in enviroments: env.step(timeStep=i)

    data = [env.getData() for env in enviroments]
    titles = [env.getTitle() for env in enviroments]

    for index, d in enumerate(data):
        plt.plot(d, label=titles[index])
    plt.legend()
    plt.xlabel('Time Step')
    plt.ylabel('Non Zero Elements [Activated Cells]')
    plt.show()
Пример #3
0
def run(options):

    rows = options.size
    columns = options.size

    env =  CellularAutomata(rows, columns)

    currentV, currentT = getCurrentW2E(options.size, 35, 7)
    # currentV, currentT = getCurrentVοrtice(options.size)

    env.addIsland(options.R_island, options.X_island, options.Y_island)
    env.addSource(options.X_oil, options.Y_oil)
    env.addCurrent(currentV, currentT)

    for i in range(options.time_steps):
        if (i%15==0):
            # env.printCA(step = i)
            print("-- Time Step: ",i)
        env.step(step = i )
Пример #4
0
def run(options):

    #initiate enviroment
    atari = gym.make('BankHeist-v0')

    observation = atari.reset()

    # initiate class
    envCA = CellularAutomata(observation)

    for i in range(options.time_steps):
        atari.render()

        action = envCA.step(observation)

        observation, reward, done, info = atari.step(
            action)  # take a random action
        time.sleep(0.1)
        # pdb.set_trace()

        # envCA.print()

    atari.close()
Пример #5
0
def start_match(name_game, n_players, raw_mode):
    #PARAMETRI
    flags = "W1B"
    list_mode = ["007", "kamikaze"]

    players_mode = []
    if raw_mode == "R":
        players_mode = [
            list_mode[random.randint(0, 1)] for elem in range(n_players)
        ]
    else:
        players_mode = (["007"] * raw_mode[0]) + (["kamikaze"] * raw_mode[1])

    #INIZIALIZZAZIONE THREAD COMMUNICATION
    manager = multiprocessing.Manager()

    #OTHER_PLAYER_GAME_INTERFACE___________________________________________________________________
    threads = []
    for i in range(n_players):
        pl = GameInterface(name_game,
                           name_game,
                           "Garada" + str(i + 1),
                           player_descr="AI9-v1.1",
                           flags=flags)

        print(pl.interact("join"))
        pl.command_chat("name")
        pl.command_chat("join")

        manager_dict = manager.dict()

        ca = CellularAutomata(pl,
                              manager_dict,
                              debug=False,
                              mode=players_mode[i])  # to Debug

        ca_chat = CellularAutomata_chat(pl, manager_dict, debug=False)

        t = multiprocessing.Process(target=start_game, args=(ca, ))
        c = multiprocessing.Process(target=start_chat, args=(ca_chat, ))

        threads.append(c)
        threads.append(t)
    #_______________________________________________________________________________

    for n in range(0, len(threads)):
        threads[n].start()

    for n in range(len(threads)):
        threads[n].join()
Пример #6
0
def evaluate(individual):
    p_trans = individual[0]
    p_mutat = individual[1]
    print('P(I)={:4.3f} \t P(M)={:4.3f}'.format(p_trans, p_mutat))

    ca = CA(rule=lambda n_states, c_state: rule(n_states, c_state, p_trans,
                                                p_mutat),
            graph=grid(40, 40),
            node_states=['S', 'I', 'R'])

    Tot_S, Tot_I, Tot_R = 0, 0, 0
    num_samples = 10
    max_steps = 40

    for n in range(num_samples):

        inital_state = {node: 'S' for node in ca.graph}
        for node in random.sample(list(ca.graph), 5):
            inital_state[node] = 'I'
        ca.setNodeStates(inital_state)

        ca.step(max_steps)
        num_steps = len(ca.state_count) - 1
        print('\t{}:{}/{}'.format(n + 1, num_steps, max_steps), end='')
        N_S, N_I, N_R = ca.state_count[-1]
        Tot_S += N_S / (N_S + N_I + N_R)
        Tot_I += N_I / (N_S + N_I + N_R)
        Tot_R += N_R / (N_S + N_I + N_R)
    print()
    print('\tS:{:4.3}\tI:{:4.3}\tR:{:4.3}\t'.format(
        Tot_S / num_samples,
        Tot_I / num_samples,
        Tot_R / num_samples,
    ))
    print('Score:', Tot_I / num_samples - p_mutat)
    return Tot_I / num_samples,
Пример #7
0
        #Creazione Gioco
        if (i == 0):
            pl.manage_game("new")

        print(pl.interact("join"))
        pl.command_chat("name")
        pl.command_chat("join")

        # Aggiunta log
        if (i == 0 and "l" in flags):
            pl.command_chat("join_log")

        manager_dict = manager.dict()

        if (i == 0):
            ca = CellularAutomata(pl, manager_dict, debug=False,
                                  mode="007")  # to Debug
        else:
            if (i % 2 == 1):
                ca = CellularAutomata(pl,
                                      manager_dict,
                                      debug=False,
                                      mode="007")  # to Debug
            else:
                ca = CellularAutomata(pl,
                                      manager_dict,
                                      debug=False,
                                      mode="007")  # to Debug

        ca_chat = CellularAutomata_chat(pl, manager_dict, debug=False)

        if (i == 0):
Пример #8
0
def single_match():

    #PARAMETRI
    NAME_GAME = "ai9_" + datetime.datetime.now().strftime(
        "%Y%m%d_%H%M%S")  #"Species"
    n_players = randint(4, 8)
    flags = "T"

    if (randint(0, 1) == 1):
        flags += "Q"
    else:
        flags += "W"
    flags += str(randint(1, 3))

    if (randint(0, 1) == 1):
        flags += "B"

    print(NAME_GAME)
    print(flags)
    print(n_players)

    #INIZIALIZZAZIONE THREAD COMMUNICATION
    manager = multiprocessing.Manager()

    #OTHER_PLAYER_GAME_INTERFACE___________________________________________________________________
    threads = []
    for i in range(n_players):

        #Game Interface
        pl = GameInterface(NAME_GAME,
                           NAME_GAME,
                           "Garada" + str(i + 1),
                           player_descr="AI9-v1.1",
                           flags=flags)
        if (i == 0):
            pl.manage_game("new")

        #Join game and chat
        print(pl.interact("join"))
        pl.command_chat("name")
        pl.command_chat("join")

        manager_dict = manager.dict()

        #Cellular automata
        if (i == 0):
            ca = CellularAutomata(pl,
                                  manager_dict,
                                  debug=False,
                                  mode="007",
                                  save_maps=True)  # to Debug
        else:
            if (i % 2 == 1):
                ca = CellularAutomata(pl,
                                      manager_dict,
                                      debug=False,
                                      mode="007",
                                      save_maps=True)  # to Debug
            else:
                ca = CellularAutomata(pl,
                                      manager_dict,
                                      debug=False,
                                      mode="007",
                                      save_maps=True)  # to Debug

        # Cellula automata chat
        if (i == 0):
            ca_chat = CellularAutomata_chat(pl, manager_dict, debug=False)
        else:
            ca_chat = CellularAutomata_chat(pl, manager_dict, debug=False)

        # Multiprocessing
        if (i == 0):
            t = multiprocessing.Process(target=start_game, args=(ca, True))
        else:
            t = multiprocessing.Process(target=start_game, args=(ca, ))

        c = multiprocessing.Process(target=start_chat, args=(ca_chat, ))

        threads.append(c)
        threads.append(t)
    #_______________________________________________________________________________

    for n in range(0, len(threads)):
        threads[n].start()

    for n in range(len(threads)):
        threads[n].join()
Пример #9
0
#grid = Grid()

if simulation:
    # generate random grid with size m
    grid1.rndGenerator(grid_size=250, savePlots=False, name='rnd_simulation')
else:
    # load Image to grid
    grid1.image2Grid(fname, path='Images\\', mode='yuv', output=False, ext_colors=False)
    grid2.image2Grid(fname, path='Images\\', mode='yuv', output=False, ext_colors=True)
    prob_grid1.image2Grid(fname, path='Images\\', mode='yuv', output=False, ext_colors=False)
    prob_grid2.image2Grid(fname, path='Images\\', mode='yuv', output=False, ext_colors=True)

# save initial state
#init = grid.grid.copy()
# Create CA with reference image
ca = CellularAutomata(prob_grid2, neighbourhood='Moore', rules='Conway', ref_name=ref_name)
#ca2 = CellularAutomata(grid2, neighbourhood='Moore', rules='Probabilistic', ref_name=ref_name)
#ca3 = CellularAutomata(prob_grid1, neighbourhood='Moore', rules='Conway', ref_name=ref_name)
#ca4 = CellularAutomata(prob_grid2, neighbourhood='Moore', rules='Probabilistic', ref_name=ref_name)

print 'intial state: '
ca.grid.visualize()
#ca1.grid.saveImage(path='EMDimages\\')
#ca2.grid.saveImage(path='EMDimages\\')
#ca3.grid.saveImage(path='EMDimages\\')
#ca4.grid.saveImage(path='EMDimages\\')

for gen in range(1,generations+1):
    
    # update grid and save number of changes
    curr = ca.grid.grid.copy();
Пример #10
0
simulation = False;

# generate grid
grid = Grid()

if simulation:
    # generate random grid with size m
    grid.rndGenerator(grid_size=250, savePlots=False, name='rnd_simulation')
else:
    # load Image to grid
    grid.image2Grid(fname, path='Images\\', mode='yuv', output=False, ext_colors=True)

# save initial state
init = grid.grid.copy()
# Create CA with reference image
ca = CellularAutomata(grid, neighbourhood='Moore', rules='Conway', ref_name=ref_name)

print 'intial state: '
ca.grid.visualize()

for gen in range(1,generations+1):
    
    # update grid and save number of changes
    curr = ca.grid.grid.copy();   
    ca.update()    
    ca.gridDifference(curr)   
    ca.rmsd_dist()

    
    if gen%5==0:
        # compute distance between current image and target
Пример #11
0
        value = tournament + "-" + str(i) + "-1"
        print("Start game on: " + value)
        input('wait')
        SAME_NAME = value
        NAME_GAME = SAME_NAME  #+datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        NAME_CHAT = SAME_NAME
        debug = False
        debug_chat = False

        pl1 = GameInterface(game_name=NAME_GAME,
                            chat_name=NAME_CHAT,
                            player_name="ai9_pl1",
                            player_descr="ai9_1.0")
        print(pl1.interact("join"))
        ai_dict = manager.dict()
        ca = CellularAutomata(pl1, ai_dict, debug=debug, mode='007')
        ca_chat = CellularAutomata_chat(pl1, ai_dict, debug=debug_chat)
        pl1.command_chat("join")
        t_pl1 = multiprocessing.Process(target=start_game, args=(ca, ))
        c_pl1 = multiprocessing.Process(target=start_chat, args=(ca_chat, ))

        pl2 = GameInterface(game_name=NAME_GAME,
                            chat_name=NAME_CHAT,
                            player_name="ai9_pl2",
                            player_descr="ai9_1.0")
        print(pl2.interact("join"))
        ai_dict = manager.dict()
        ca2 = CellularAutomata(pl2, ai_dict, debug=debug, mode='kamikaze')
        ca2_chat = CellularAutomata_chat(pl2, ai_dict, debug=debug_chat)
        t_pl2 = multiprocessing.Process(target=start_game, args=(ca2, ))
        c_pl2 = multiprocessing.Process(target=start_chat, args=(ca2_chat, ))
 def test_rowsarecorrect(self):
     cA = CellularAutomata()
     grid = cA.buildGrid('1', 100)
     cA.buildRules(30)
     grid = cA.mutate(grid, int(3))
     self.assertTrue('0110010' in '%s' % ''.join(map(str, grid[2])))
Пример #13
0
                    result = temp.manage_game("new").lower()
                    print(result)
                    if (result.find("error") != -1):
                        print("ERRORE CREAZIONE")
                        exit()
                    else:
                        creation_game = False
                        created = True
                        manager_game = temp
                print(temp.interact("join"))
                temp.command_chat("name")
                temp.command_chat("join")

                manager_dict = manager.dict()
                ca = CellularAutomata(temp,
                                      manager_dict,
                                      debug=debug,
                                      mode=mode)  # to Debug
                if (i == 0):
                    ca_chat = CellularAutomata_chat(temp,
                                                    manager_dict,
                                                    debug=True)
                else:
                    ca_chat = CellularAutomata_chat(temp,
                                                    manager_dict,
                                                    debug=False)
                t_player = multiprocessing.Process(target=start_game,
                                                   args=(ca, ))
                chat_player = multiprocessing.Process(target=start_chat,
                                                      args=(ca_chat, ))
                threads_player.append(t_player)
                threads_chat.append(chat_player)