Exemple #1
0
    def _test_obj_fun_1call(self):
        m = 2
        n = 1

        e1 = Ship(player_id=1,
                  ship_id=1,
                  x=100,
                  y=100,
                  hp=100,
                  vel_x=0,
                  vel_y=0,
                  docking_status=0,
                  planet=None,
                  progress=0,
                  cooldown=0)
        e2 = Planet(planet_id=1,
                    x=100,
                    y=150,
                    hp=100,
                    radius=15,
                    docking_spots=2,
                    current=0,
                    remaining=5,
                    owned=0,
                    owner=0,
                    docked_ships=0)
        params = map_parameters(map_parameters([]).values())

        e1.augment(1, params)
        e2.augment(1, params)
        all_entities = [e1, e2]
        fun_grad, hess = nav.objective_function(n, m, all_entities)

        print(fun_grad([0, 10])[0])
Exemple #2
0
    def _test_obj_fun(self):
        m = 3
        n = 1

        e1 = Ship(player_id=1,
                  ship_id=1,
                  x=100,
                  y=100,
                  hp=100,
                  vel_x=0,
                  vel_y=0,
                  docking_status=0,
                  planet=None,
                  progress=0,
                  cooldown=0)
        e2 = Planet(planet_id=1,
                    x=100,
                    y=150,
                    hp=100,
                    radius=15,
                    docking_spots=2,
                    current=0,
                    remaining=5,
                    owned=0,
                    owner=0,
                    docked_ships=0)
        e3 = Planet(planet_id=2,
                    x=30,
                    y=75,
                    hp=100,
                    radius=10,
                    docking_spots=7,
                    current=0,
                    remaining=5,
                    owned=0,
                    owner=0,
                    docked_ships=0)
        all_entities = [e1, e2, e3]
        params = map_parameters(map_parameters([]).values())

        for e in all_entities:
            e.augment(1, params)

        fun_grad, hess = nav.objective_function(n, m, all_entities)

        unit_vec, apex, rad, all_pos, dist = constraints_pre(
            n, m, all_entities)

        x = self.entities[0].x
        y = self.entities[0].y

        img = [[fun_grad([i - x, j - y])[0] for i in range(200)]
               for j in range(200)]

        img = fit_255(np.array(img))

        img = np.dstack((img, img, img))

        draw_entities(img, all_entities, unit_vec=unit_vec)
Exemple #3
0
def async_score(args, num_games=CORES):
    """
    Evaluating bot
    :param args: the values of the learnable parameters passed to the bot
    :type args: ndarray
    :return:
    :rtype:
    """
    if max(args) > 1 or min(args) < 0:
        print("error!!!")
        return 0
    print('no error')
    start = time()
    session_id = update_id("session")

    command = get_play_command(args)
    print("Session {}, playing {} games".format(session_id, num_games))
    pool = Pool()
    pool.map(play_game, [command] * num_games)
    pool.close()
    pool.join()

    print("All games of the session have been played")

    score, log_perfs = get_score()
    print("Score: {:.4}".format(score))
    print("Session run in {:.4}s".format(time() - start))

    log_performances(score, log_perfs, map_parameters(list(args)))

    # clean_repository()

    # function often try to minimize score ^^
    return score
Exemple #4
0
def command_player(args, idx_player):
    kwargs = map_parameters(args)
    bot_command = "python3 " + BOT[0] + " "
    bot_command += " ".join(
        ["--{} {}".format(k, v) for k, v in kwargs.items()])
    bot_command += " --name {}".format(idx_player)

    return bot_command
Exemple #5
0
def initPopulation(pcls, ind_init):
    my_path = "./.data/params"
    param_files = [f for f in os.listdir(my_path) if f.startswith("params")]
    param_files = sorted(param_files, reverse=True)[:MU]
    population = []
    for file in param_files:
        with open(path.join(my_path, file)) as f:
            population.append(list(map_parameters(json.load(f)).values()))
    return pcls(ind_init(c) for c in population)
Exemple #6
0
def launch_game(args):
    kwargs = map_parameters(list(args))
    map_height = random.sample(MAP_HEIGHTS, 1)[0]
    map_width = int(3 * map_height / 2)

    bot_command = "python3 MyBot.py "
    bot_command += " ".join(
        ["--{} {}".format(k, v) for k, v in kwargs.items()])

    if OPPONENT_COMMAND == "self":
        opp_kwargs = map_parameters(map_parameters(()).values())
        opp_command = "python3 MyBot.py "
        opp_command += " ".join(
            ["--{} {}".format(k, v) for k, v in opp_kwargs.items()])
    else:
        opp_command = OPPONENT_COMMAND

    _play_game("./halite", map_width, map_height, [bot_command, opp_command])

    print(".")
Exemple #7
0
def write_tournament_perfs(pool_path_prefix, scores, log_perfs, params):
    for pool, pool_scores in enumerate(scores):
        pool_path = pool_path_prefix + str(pool)

        for p, s in pool_scores.items():
            file_name = "params-{:.4}-{}.json".format(float(s), p)
            log_path = path.join(pool_path, file_name)
            with open(log_path, "w") as f:
                if int(p) < len(params):
                    json.dump(map_parameters(params[int(p)]), f)

        log_path = path.join(pool_path, "stats.json")
        with open(log_path, "w") as f:
            json.dump(log_perfs[pool], f)
Exemple #8
0
def get_play_command(args):
    kwargs = map_parameters(list(args))
    map_height = random.sample(MAP_HEIGHTS, 1)[0]
    map_width = int(3 * map_height / 2)

    bot_command = "python3 MyBot.py "
    bot_command += " ".join(
        ["--{} {}".format(k, v) for k, v in kwargs.items()])

    if OPPONENT_COMMAND == "self":
        opp_kwargs = map_parameters(map_parameters(()).values())
        opp_command = "python3 MyBot.py "
        opp_command += " ".join(
            ["--{} {}".format(k, v) for k, v in opp_kwargs.items()])
    else:
        opp_command = OPPONENT_COMMAND

    binary = "./halite"
    game_run_command = '\"{}\" -d "{} {}" -t'.format(binary, map_width,
                                                     map_height)
    game_run_command += " \"{}\"".format(bot_command)
    game_run_command += " \"{}\"".format(opp_command)

    return game_run_command
Exemple #9
0
        opp_command = "python3 MyBot.py "
        opp_command += " ".join(
            ["--{} {}".format(k, v) for k, v in opp_kwargs.items()])
    else:
        opp_command = OPPONENT_COMMAND

    _play_game("./halite", map_width, map_height, [bot_command, opp_command])

    print(".")


if __name__ == "__main__":
    while True:
        update_id("experiment")

        args = np.array([v for v in map_parameters([]).values()])
        bounds = [(0, 1) for _ in args]
        try:
            a = opt.minimize(async_score,
                             args,
                             method='L-BFGS-B',
                             jac='2-point',
                             bounds=bounds,
                             options={
                                 "eps": 0.05,
                                 "maxls": 5,
                                 "maxfun": 50
                             })
            update_parameter_mapping()
        except InterruptedError:
            update_parameter_mapping()