def test_step_sync_vector_env(use_single_action_space):
    env_fns = [make_env('CubeCrash-v0', i) for i in range(8)]
    try:
        env = SyncVectorEnv(env_fns)
        observations = env.reset()
        if use_single_action_space:
            actions = [env.single_action_space.sample() for _ in range(8)]
        else:
            actions = env.action_space.sample()
        observations, rewards, dones, _ = env.step(actions)
    finally:
        env.close()

    assert isinstance(env.observation_space, Box)
    assert isinstance(observations, np.ndarray)
    assert observations.dtype == env.observation_space.dtype
    assert observations.shape == (8, ) + env.single_observation_space.shape
    assert observations.shape == env.observation_space.shape

    assert isinstance(rewards, np.ndarray)
    assert isinstance(rewards[0], (float, np.floating))
    assert rewards.ndim == 1
    assert rewards.size == 8

    assert isinstance(dones, np.ndarray)
    assert dones.dtype == np.bool_
    assert dones.ndim == 1
    assert dones.size == 8
Ejemplo n.º 2
0
def test_custom_space_sync_vector_env():
    env_fns = [make_custom_space_env(i) for i in range(4)]
    try:
        env = SyncVectorEnv(env_fns)
        reset_observations = env.reset()

        assert isinstance(env.single_action_space, CustomSpace)
        assert isinstance(env.action_space, Tuple)

        actions = ("action-2", "action-3", "action-5", "action-7")
        step_observations, rewards, dones, _ = env.step(actions)
    finally:
        env.close()

    assert isinstance(env.single_observation_space, CustomSpace)
    assert isinstance(env.observation_space, Tuple)

    assert isinstance(reset_observations, tuple)
    assert reset_observations == ("reset", "reset", "reset", "reset")

    assert isinstance(step_observations, tuple)
    assert step_observations == (
        "step(action-2)",
        "step(action-3)",
        "step(action-5)",
        "step(action-7)",
    )
def test_create_sync_vector_env():
    env_fns = [make_env('CubeCrash-v0', i) for i in range(8)]
    try:
        env = SyncVectorEnv(env_fns)
    finally:
        env.close()

    assert env.num_envs == 8
def test_check_observations_sync_vector_env():
    # CubeCrash-v0 - observation_space: Box(40, 32, 3)
    env_fns = [make_env('CubeCrash-v0', i) for i in range(8)]
    # MemorizeDigits-v0 - observation_space: Box(24, 32, 3)
    env_fns[1] = make_env('MemorizeDigits-v0', 1)
    with pytest.raises(RuntimeError):
        env = SyncVectorEnv(env_fns)
        env.close()
Ejemplo n.º 5
0
def test_create_sync_vector_env():
    env_fns = [make_env("FrozenLake-v1", i) for i in range(8)]
    try:
        env = SyncVectorEnv(env_fns)
    finally:
        env.close()

    assert env.num_envs == 8
Ejemplo n.º 6
0
def test_check_spaces_sync_vector_env():
    # CartPole-v1 - observation_space: Box(4,), action_space: Discrete(2)
    env_fns = [make_env("CartPole-v1", i) for i in range(8)]
    # FrozenLake-v1 - Discrete(16), action_space: Discrete(4)
    env_fns[1] = make_env("FrozenLake-v1", 1)
    with pytest.raises(RuntimeError):
        env = SyncVectorEnv(env_fns)
        env.close()
Ejemplo n.º 7
0
def test_set_attr_sync_vector_env():
    env_fns = [make_env("CartPole-v1", i) for i in range(4)]
    try:
        env = SyncVectorEnv(env_fns)
        env.set_attr("gravity", [9.81, 3.72, 8.87, 1.62])
        gravity = env.get_attr("gravity")
        assert gravity == (9.81, 3.72, 8.87, 1.62)
    finally:
        env.close()
def test_reset_sync_vector_env():
    env_fns = [make_env('CubeCrash-v0', i) for i in range(8)]
    try:
        env = SyncVectorEnv(env_fns)
        observations = env.reset()
    finally:
        env.close()

    assert isinstance(env.observation_space, Box)
    assert isinstance(observations, np.ndarray)
    assert observations.dtype == env.observation_space.dtype
    assert observations.shape == (8, ) + env.single_observation_space.shape
    assert observations.shape == env.observation_space.shape
def main():
    np.set_printoptions(suppress=True,
                        formatter={'float_kind': '{:0.2f}'.format})
    env_fns = [make_env('MountainCar-v0', i) for i in range(4)]
    try:
        env = SyncVectorEnv(env_fns)
    finally:
        env.close()

    state_size = env.observation_space.shape[1]
    action_size = env.action_space[0].n

    NUM_EPISODES = 1000
    STEPS_PER_EPISODE = 200
    batch_size = 32
    eps_mean_reward = [0.0] * NUM_EPISODES

    agent = DQNAgent(state_size, action_size)
    start_time = datetime.now()
    for ep_count in range(NUM_EPISODES):
        episode_rew = 0
        state = env.reset()
        if (ep_count == 0):
            print("ep={} state.shape={}".format(ep_count, state.shape))
        #state = np.reshape(state, [-1, state_size])
        ep_start_time = datetime.now()
        for time in range(STEPS_PER_EPISODE):
            # env.render()
            action = agent.act(state)
            next_state, reward, done, _ = env.step(action)
            episode_rew += np.sum(reward)
            #next_state = np.reshape(next_state, [-1, state_size])
            if (time == 0):
                print("ep={} time={} action.len={} next_state.shape={} elaps_time={}".format( \
                    ep_count, time, len(action), next_state.shape, (datetime.now() - ep_start_time)) )
            #add to DQN buffer
            for idx in range(0, env.num_envs):
                agent.memorize(state[idx], action[idx], reward[idx],
                               next_state[idx], done[idx])
            state = next_state
            if time >= STEPS_PER_EPISODE - 1:
                eps_mean_reward[ep_count] = np.mean(episode_rew) / time
                print("ep: {}/{}, mean_avg_reward: {}, exec_time= {}".format( \
                    ep_count , NUM_EPISODES, eps_mean_reward[ep_count], (datetime.now() - ep_start_time)))
            #update DQN model if there are enough samples
            if len(agent.memory) > batch_size and time % 8 == 0:
                agent.replay(batch_size)
        #if ep_count % 2 == 0:
        #    agent.save(str(os.path.join(save_path,'ma-foraging-dqn.h5')))
    print("Finish train DQN Agent with {} episodes in {}".format(
        NUM_EPISODES, (datetime.now() - start_time)))
Ejemplo n.º 10
0
def test_vector_env_equal(shared_memory):
    env_fns = [make_env("CubeCrash-v0", i) for i in range(4)]
    num_steps = 100
    try:
        async_env = AsyncVectorEnv(env_fns, shared_memory=shared_memory)
        sync_env = SyncVectorEnv(env_fns)

        async_env.seed(0)
        sync_env.seed(0)

        assert async_env.num_envs == sync_env.num_envs
        assert async_env.observation_space == sync_env.observation_space
        assert async_env.single_observation_space == sync_env.single_observation_space
        assert async_env.action_space == sync_env.action_space
        assert async_env.single_action_space == sync_env.single_action_space

        async_observations = async_env.reset()
        sync_observations = sync_env.reset()
        assert np.all(async_observations == sync_observations)

        for _ in range(num_steps):
            actions = async_env.action_space.sample()
            assert actions in sync_env.action_space

            # fmt: off
            async_observations, async_rewards, async_dones, async_infos = async_env.step(
                actions)
            sync_observations, sync_rewards, sync_dones, sync_infos = sync_env.step(
                actions)
            # fmt: on

            for idx in range(len(sync_dones)):
                if sync_dones[idx]:
                    assert "terminal_observation" in async_infos[idx]
                    assert "terminal_observation" in sync_infos[idx]
                    assert sync_dones[idx]

            assert np.all(async_observations == sync_observations)
            assert np.all(async_rewards == sync_rewards)
            assert np.all(async_dones == sync_dones)

    finally:
        async_env.close()
        sync_env.close()
def test_custom_space_sync_vector_env():
    env_fns = [make_custom_space_env(i) for i in range(4)]
    try:
        env = SyncVectorEnv(env_fns)
        reset_observations = env.reset()
        actions = ('action-2', 'action-3', 'action-5', 'action-7')
        step_observations, rewards, dones, _ = env.step(actions)
    finally:
        env.close()

    assert isinstance(env.single_observation_space, CustomSpace)
    assert isinstance(env.observation_space, Tuple)

    assert isinstance(reset_observations, tuple)
    assert reset_observations == ('reset', 'reset', 'reset', 'reset')

    assert isinstance(step_observations, tuple)
    assert step_observations == ('step(action-2)', 'step(action-3)',
                                 'step(action-5)', 'step(action-7)')
Ejemplo n.º 12
0
def test_call_sync_vector_env():
    env_fns = [make_env("CartPole-v1", i) for i in range(4)]
    try:
        env = SyncVectorEnv(env_fns)
        _ = env.reset()
        images = env.call("render", mode="rgb_array")
        gravity = env.call("gravity")
    finally:
        env.close()

    assert isinstance(images, tuple)
    assert len(images) == 4
    for i in range(4):
        assert isinstance(images[i], np.ndarray)

    assert isinstance(gravity, tuple)
    assert len(gravity) == 4
    for i in range(4):
        assert isinstance(gravity[i], float)
        assert gravity[i] == 9.8
Ejemplo n.º 13
0
def test_vector_env_equal(shared_memory):
    env_fns = [make_env("CartPole-v1", i) for i in range(4)]
    num_steps = 100
    try:
        async_env = AsyncVectorEnv(env_fns, shared_memory=shared_memory)
        sync_env = SyncVectorEnv(env_fns)

        assert async_env.num_envs == sync_env.num_envs
        assert async_env.observation_space == sync_env.observation_space
        assert async_env.single_observation_space == sync_env.single_observation_space
        assert async_env.action_space == sync_env.action_space
        assert async_env.single_action_space == sync_env.single_action_space

        async_observations = async_env.reset(seed=0)
        sync_observations = sync_env.reset(seed=0)
        assert np.all(async_observations == sync_observations)

        for _ in range(num_steps):
            actions = async_env.action_space.sample()
            assert actions in sync_env.action_space

            # fmt: off
            async_observations, async_rewards, async_dones, async_infos = async_env.step(
                actions)
            sync_observations, sync_rewards, sync_dones, sync_infos = sync_env.step(
                actions)
            # fmt: on

            if any(sync_dones):
                assert "terminal_observation" in async_infos
                assert "_terminal_observation" in async_infos
                assert "terminal_observation" in sync_infos
                assert "_terminal_observation" in sync_infos

            assert np.all(async_observations == sync_observations)
            assert np.all(async_rewards == sync_rewards)
            assert np.all(async_dones == sync_dones)

    finally:
        async_env.close()
        sync_env.close()
def test_vector_env_equal(shared_memory):
    env_fns = [make_env('CubeCrash-v0', i) for i in range(4)]
    num_steps = 100
    try:
        async_env = AsyncVectorEnv(env_fns, shared_memory=shared_memory)
        sync_env = SyncVectorEnv(env_fns)

        async_env.seed(0)
        sync_env.seed(0)

        assert async_env.num_envs == sync_env.num_envs
        assert async_env.observation_space == sync_env.observation_space
        assert async_env.single_observation_space == sync_env.single_observation_space
        assert async_env.action_space == sync_env.action_space
        assert async_env.single_action_space == sync_env.single_action_space

        async_observations = async_env.reset()
        sync_observations = sync_env.reset()
        assert np.all(async_observations == sync_observations)

        for _ in range(num_steps):
            actions = async_env.action_space.sample()
            assert actions in sync_env.action_space

            async_observations, async_rewards, async_dones, _ = async_env.step(
                actions)
            sync_observations, sync_rewards, sync_dones, _ = sync_env.step(
                actions)

            assert np.all(async_observations == sync_observations)
            assert np.all(async_rewards == sync_rewards)
            assert np.all(async_dones == sync_dones)

    finally:
        async_env.close()
        sync_env.close()
Ejemplo n.º 15
0
def test_reset_sync_vector_env():
    env_fns = [make_env("CartPole-v1", i) for i in range(8)]
    try:
        env = SyncVectorEnv(env_fns)
        observations = env.reset()
    finally:
        env.close()

    assert isinstance(env.observation_space, Box)
    assert isinstance(observations, np.ndarray)
    assert observations.dtype == env.observation_space.dtype
    assert observations.shape == (8,) + env.single_observation_space.shape
    assert observations.shape == env.observation_space.shape

    del observations

    try:
        env = SyncVectorEnv(env_fns)
        observations = env.reset(return_info=False)
    finally:
        env.close()

    assert isinstance(env.observation_space, Box)
    assert isinstance(observations, np.ndarray)
    assert observations.dtype == env.observation_space.dtype
    assert observations.shape == (8,) + env.single_observation_space.shape
    assert observations.shape == env.observation_space.shape

    del observations

    env_fns = [make_env("CartPole-v1", i) for i in range(8)]
    try:
        env = SyncVectorEnv(env_fns)
        observations, infos = env.reset(return_info=True)
    finally:
        env.close()

    assert isinstance(env.observation_space, Box)
    assert isinstance(observations, np.ndarray)
    assert observations.dtype == env.observation_space.dtype
    assert observations.shape == (8,) + env.single_observation_space.shape
    assert observations.shape == env.observation_space.shape
    assert isinstance(infos, list)
    assert all([isinstance(info, dict) for info in infos])