Пример #1
0
def atari_preprocessing(
    env: Union[ParallelEnvWrapper, SequentialEnvWrapper]
) -> Union[ParallelEnvWrapper, SequentialEnvWrapper]:

    # Preprocessing
    env = supersuit.max_observation_v0(env, 2)

    # repeat_action_probability is set to 0.25
    # to introduce non-determinism to the system
    env = supersuit.sticky_actions_v0(env, repeat_action_probability=0.25)

    # skip frames for faster processing and less control
    # to be compatable with gym, use frame_skip(env, (2,5))
    env = supersuit.frame_skip_v0(env, 4)

    # downscale observation for faster processing
    env = supersuit.resize_v0(env, 84, 84)

    # allow agent to see everything on the screen
    # despite Atari's flickering screen problem
    env = supersuit.frame_stack_v1(env, 4)

    # set dtype to float32
    env = supersuit.dtype_v0(env, np.float32)

    return env
Пример #2
0
    def env_creator():
        if args.game.__package__.endswith('atari'):
            if (args.game_name.startswith('foozpong') or
                args.game_name.startswith('basketball_pong') or
                args.game_name.startswith('volleyball_pong')
                ):
                env = args.game.env(obs_type=args.atari_obs_type,
                                    max_cycles=args.max_steps['atari'],
                                    full_action_space=False,
                                    num_players=2)
            else:
                env = args.game.env(obs_type=args.atari_obs_type,
                                    full_action_space=False,
                                    max_cycles=args.max_steps['atari'])
            env = frame_skip_v0(env, args.atari_frame_skip_num)
            env = frame_stack_v1(env, args.atari_frame_stack_num)

        else:
            env = args.game.env()
        if args.game_name.startswith('rps'):
            env = one_hot_obs_wrapper(env)
        env = dtype_v0(env, dtype=float32)
        env = pad_observations_v0(env)
        env = pad_action_space_v0(env)
        if args.game_name.startswith('connect_four') or args.game_name.startswith('tictactoe'):
            env = FlattenEnvWrapper(env)
        GAUSSIAN_STD = 1.0
        assert abs(GAUSSIAN_STD - 1.0) < 1e-5, "must be 1.0, otherwise simple ensemble implementation is wrong"
        env = LatentGaussianAugmentedEnvWrapper(env,
                                                latent_parameter_dim=args.latent_para_dim,
                                                gaussian_std=1.0,
                                                use_dict_obs_space=args.use_dict_obs_space)
        return env
Пример #3
0
def env_creator():
    env = pistonball_v4.env(n_pistons=20, local_ratio=0, time_penalty=-0.1, continuous=True, random_drop=True, random_rotate=True, ball_mass=0.75, ball_friction=0.3, ball_elasticity=1.5, max_cycles=125)
    env = ss.color_reduction_v0(env, mode='B')
    env = ss.dtype_v0(env, 'float32')
    env = ss.resize_v0(env, x_size=84, y_size=84)
    env = ss.normalize_obs_v0(env, env_min=0, env_max=1)
    env = ss.frame_stack_v1(env, 3)
    return env
Пример #4
0
def test_basic():
    env = DummyParEnv(base_obs, base_obs_space, base_act_spaces)
    env = supersuit.delay_observations_v0(env, 4)
    env = supersuit.dtype_v0(env, np.uint8)
    orig_obs = env.reset()
    for i in range(10):
        action = {agent: env.action_spaces[agent].sample() for agent in env.agents}
        obs, rew, done, info = env.step(action)
Пример #5
0
def make_env(env_name):
    if env_name == "pistonball":
        env = pistonball_v0.parallel_env(max_frames=100)
        env = supersuit.resize_v0(env, 16, 16)
        env = supersuit.dtype_v0(env, np.float32)
        env = supersuit.normalize_obs_v0(env)
        return supersuit.flatten_v0(env)
    if env_name == "KAZ":
        env = knights_archers_zombies_v2.parallel_env(max_frames=100)
        env = supersuit.resize_v0(env, 32, 32)
        env = supersuit.dtype_v0(env, np.float32)
        env = supersuit.normalize_obs_v0(env)
        return supersuit.flatten_v0(env)
    if env_name == "pursuit":
        env = pursuit_v1.parallel_env(max_frames=100)
        env = supersuit.resize_v0(env, 32, 32)
        return supersuit.flatten_v0(env)
    elif env_name == "waterworld":
        return waterworld_v1.parallel_env(max_frames=100)
    elif env_name == "multiwalker":
        return multiwalker_v3.parallel_env(max_frames=100)
    else:
        raise RuntimeError("bad environment name")
Пример #6
0
def make_env(env_name='boxing_v1', seed=1, obs_type='rgb_image'):
    '''https://www.pettingzoo.ml/atari'''
    if env_name == 'slimevolley_v0':
        env = SlimeVolleyWrapper(gym.make("SlimeVolley-v0"))

    else:  # PettingZoo envs
        env = eval(env_name).parallel_env(obs_type=obs_type)

        if obs_type == 'rgb_image':
            # as per openai baseline's MaxAndSKip wrapper, maxes over the last 2 frames
            # to deal with frame flickering
            env = supersuit.max_observation_v0(env, 2)

            # repeat_action_probability is set to 0.25 to introduce non-determinism to the system
            env = supersuit.sticky_actions_v0(env,
                                              repeat_action_probability=0.25)

            # skip frames for faster processing and less control
            # to be compatable with gym, use frame_skip(env, (2,5))
            env = supersuit.frame_skip_v0(env, 4)

            # downscale observation for faster processing
            env = supersuit.resize_v0(env, 84, 84)

            # allow agent to see everything on the screen despite Atari's flickering screen problem
            env = supersuit.frame_stack_v1(env, 4)

        else:
            env = supersuit.frame_skip_v0(env, 4)

        #   env = PettingZooWrapper(env)  # need to be put at the end
        if env_name in AtariEnvs:  # normalize the observation of Atari for both image or RAM
            env = supersuit.dtype_v0(
                env, 'float32'
            )  # need to transform uint8 to float first for normalizing observation: https://github.com/PettingZoo-Team/SuperSuit
            env = supersuit.normalize_obs_v0(
                env, env_min=0,
                env_max=1)  # normalize the observation to (0,1)

        # assign observation and action spaces
        env.observation_space = list(env.observation_spaces.values())[0]
        env.action_space = list(env.action_spaces.values())[0]

    env.seed(seed)
    return env
 def env_creator(args):
     env = env_constr.env(
     )  #killable_knights=False, killable_archers=False)
     resize_size = 84 if model == None else 32
     env = supersuit.resize_v0(env,
                               resize_size,
                               resize_size,
                               linear_interp=True)
     env = supersuit.color_reduction_v0(env)
     env = supersuit.pad_action_space_v0(env)
     env = supersuit.pad_observations_v0(env)
     # env = supersuit.frame_stack_v0(env,2)
     env = supersuit.dtype_v0(env, np.float32)
     env = supersuit.normalize_obs_v0(env)
     if model == "MLPModelV2":
         env = supersuit.flatten_v0(env)
     env = PettingZooEnv(env)
     return env
Пример #8
0
def unwrapped_check(env):
    # image observations
    if isinstance(env.observation_space, spaces.Box):
        if ((env.observation_space.low.shape == 3)
                and (env.observation_space.low == 0).all()
                and (len(env.observation_space.shape[2]) == 3)
                and (env.observation_space.high == 255).all()):
            env = max_observation_v0(env, 2)
            env = color_reduction_v0(env, mode="full")
            env = normalize_obs_v0(env)

    # box action spaces
    if isinstance(env.action_space, spaces.Box):
        env = clip_actions_v0(env)
        env = scale_actions_v0(env, 0.5)

    # stackable observations
    if isinstance(env.observation_space, spaces.Box) or isinstance(
            env.observation_space, spaces.Discrete):
        env = frame_stack_v1(env, 2)

    # not discrete and not multibinary observations
    if not isinstance(env.observation_space,
                      spaces.Discrete) and not isinstance(
                          env.observation_space, spaces.MultiBinary):
        env = dtype_v0(env, np.float16)
        env = flatten_v0(env)
        env = frame_skip_v0(env, 2)

    # everything else
    env = clip_reward_v0(env, lower_bound=-1, upper_bound=1)
    env = delay_observations_v0(env, 2)
    env = sticky_actions_v0(env, 0.5)
    env = nan_random_v0(env)
    env = nan_zeros_v0(env)

    assert env.unwrapped.__class__ == DummyEnv, f"Failed to unwrap {env}"
Пример #9
0
def wrap_env(env, obs_type='ram'):
    env = env.parallel_env(obs_type=obs_type)
    env_agents = env.unwrapped.agents
    if obs_type == 'rgb_image':
        env = supersuit.max_observation_v0(
            env, 2
        )  # as per openai baseline's MaxAndSKip wrapper, maxes over the last 2 frames to deal with frame flickering
        env = supersuit.sticky_actions_v0(
            env, repeat_action_probability=0.25
        )  # repeat_action_probability is set to 0.25 to introduce non-determinism to the system
        env = supersuit.frame_skip_v0(
            env, 4
        )  # skip frames for faster processing and less control to be compatable with gym, use frame_skip(env, (2,5))
        env = supersuit.resize_v0(
            env, 84, 84)  # downscale observation for faster processing
        env = supersuit.frame_stack_v1(
            env, 4
        )  # allow agent to see everything on the screen despite Atari's flickering screen problem
    else:
        env = supersuit.frame_skip_v0(
            env, 4
        )  # RAM version also need frame skip, essential for boxing-v1, etc

    # normalize the observation of Atari for both image or RAM
    env = supersuit.dtype_v0(
        env, 'float32'
    )  # need to transform uint8 to float first for normalizing observation: https://github.com/PettingZoo-Team/SuperSuit
    env = supersuit.normalize_obs_v0(
        env, env_min=0, env_max=1)  # normalize the observation to (0,1)

    env.observation_space = list(env.observation_spaces.values())[0]
    env.action_space = list(env.action_spaces.values())[0]
    env.agents = env_agents
    env = Dict2TupleWrapper(env)

    return env
Пример #10
0
def unwrapped_check(env):
    env.reset()
    agents = env.agents

    if image_observation(env, agents):
        env = max_observation_v0(env, 2)
        env = color_reduction_v0(env, mode="full")
        env = normalize_obs_v0(env)

    if box_action(env, agents):
        env = clip_actions_v0(env)
        env = scale_actions_v0(env, 0.5)

    if observation_homogenizable(env, agents):
        env = pad_observations_v0(env)
        env = frame_stack_v1(env, 2)
        env = agent_indicator_v0(env)
        env = black_death_v3(env)

    if (not_dict_observation(env, agents)
            and not_discrete_observation(env, agents)
            and not_multibinary_observation(env, agents)):
        env = dtype_v0(env, np.float16)
        env = flatten_v0(env)
        env = frame_skip_v0(env, 2)

    if action_homogenizable(env, agents):
        env = pad_action_space_v0(env)

    env = clip_reward_v0(env, lower_bound=-1, upper_bound=1)
    env = delay_observations_v0(env, 2)
    env = sticky_actions_v0(env, 0.5)
    env = nan_random_v0(env)
    env = nan_zeros_v0(env)

    assert env.unwrapped.__class__ == DummyEnv, f"Failed to unwrap {env}"
Пример #11
0
    first_obs, _, _, _ = env.step(5)
    assert np.all(np.equal(first_obs, base_obs.reshape([64, 3])))


def new_continuous_dummy():
    base_act_spaces = Box(low=np.float32(0.), high=np.float32(10.), shape=[3])
    return DummyEnv(base_obs, base_obs_space, base_act_spaces)


def new_dummy():
    return DummyEnv(base_obs, base_obs_space, base_act_spaces)


wrappers = [
    supersuit.color_reduction_v0(new_dummy(), "R"),
    supersuit.resize_v0(dtype_v0(new_dummy(), np.uint8), x_size=5, y_size=10),
    supersuit.resize_v0(dtype_v0(new_dummy(), np.uint8),
                        x_size=5,
                        y_size=10,
                        linear_interp=True),
    supersuit.dtype_v0(new_dummy(), np.int32),
    supersuit.flatten_v0(new_dummy()),
    supersuit.reshape_v0(new_dummy(), (64, 3)),
    supersuit.normalize_obs_v0(new_dummy(), env_min=-1, env_max=5.),
    supersuit.frame_stack_v1(new_dummy(), 8),
    #supersuit.normalize_reward(new_dummy()),
    supersuit.reward_lambda_v0(new_dummy(), lambda x: x / 10),
    supersuit.clip_reward_v0(new_dummy()),
    supersuit.clip_actions_v0(new_continuous_dummy()),
    supersuit.frame_skip_v0(new_dummy(), 4),
    supersuit.frame_skip_v0(new_dummy(), (4, 6)),
Пример #12
0
    first_obs, _, _, _ = env.step(5)
    assert np.all(np.equal(first_obs, base_obs.reshape([64, 3])))


def new_continuous_dummy():
    base_act_spaces = Box(low=np.float32(0.0), high=np.float32(10.0), shape=[3])
    return DummyEnv(base_obs, base_obs_space, base_act_spaces)


def new_dummy():
    return DummyEnv(base_obs, base_obs_space, base_act_spaces)


wrappers = [
    supersuit.color_reduction_v0(new_dummy(), "R"),
    supersuit.resize_v0(dtype_v0(new_dummy(), np.uint8), x_size=5, y_size=10),
    supersuit.resize_v0(dtype_v0(new_dummy(), np.uint8), x_size=5, y_size=10, linear_interp=True),
    supersuit.dtype_v0(new_dummy(), np.int32),
    supersuit.flatten_v0(new_dummy()),
    supersuit.reshape_v0(new_dummy(), (64, 3)),
    supersuit.normalize_obs_v0(new_dummy(), env_min=-1, env_max=5.0),
    supersuit.frame_stack_v1(new_dummy(), 8),
    supersuit.reward_lambda_v0(new_dummy(), lambda x: x / 10),
    supersuit.clip_reward_v0(new_dummy()),
    supersuit.clip_actions_v0(new_continuous_dummy()),
    supersuit.frame_skip_v0(new_dummy(), 4),
    supersuit.frame_skip_v0(new_dummy(), (4, 6)),
    supersuit.sticky_actions_v0(new_dummy(), 0.75),
    supersuit.delay_observations_v0(new_dummy(), 1),
]
    wrapped_env = pad_action_space_v0(_env)
    api_test(wrapped_env)
    seed_test(lambda: sticky_actions_v0(simple_world_comm_v2.env(), 0.5), 100)


def test_pettingzoo_parallel_env():
    _env = simple_world_comm_v2.parallel_env()
    wrapped_env = pad_action_space_v0(_env)
    parallel_test.parallel_api_test(wrapped_env)


wrappers = [
    supersuit.color_reduction_v0(
        knights_archers_zombies_v10.env(vector_state=False), "R"),
    supersuit.resize_v1(
        dtype_v0(knights_archers_zombies_v10.env(vector_state=False),
                 np.uint8),
        x_size=5,
        y_size=10,
    ),
    supersuit.resize_v1(
        dtype_v0(knights_archers_zombies_v10.env(vector_state=False),
                 np.uint8),
        x_size=5,
        y_size=10,
        linear_interp=True,
    ),
    supersuit.dtype_v0(knights_archers_zombies_v10.env(), np.int32),
    supersuit.flatten_v0(knights_archers_zombies_v10.env()),
    supersuit.reshape_v0(knights_archers_zombies_v10.env(vector_state=False),
                         (512 * 512, 3)),
    supersuit.normalize_obs_v0(dtype_v0(knights_archers_zombies_v10.env(),
Пример #14
0
def env_creator(config):
    env = pistonball_v6.env()
    env = dtype_v0(env, dtype=np.float32)
    env = color_reduction_v0(env, mode="R")
    env = normalize_obs_v0(env)
    return env
Пример #15
0
 def env_creator(config):
     env = pistonball_v4.env(local_ratio=config.get("local_ratio", 0.2))
     env = dtype_v0(env, dtype=float32)
     env = color_reduction_v0(env, mode="R")
     env = normalize_obs_v0(env)
     return env
Пример #16
0
    _env = simple_world_comm_v2.env()
    wrapped_env = pad_action_space_v0(_env)
    api_test.api_test(wrapped_env)
    seed_test.seed_test(
        lambda: sticky_actions_v0(simple_world_comm_v2.env(), 0.5), 100)


def test_pettingzoo_parallel_env():
    _env = simple_world_comm_v2.parallel_env()
    wrapped_env = pad_action_space_v0(_env)
    parallel_test.parallel_play_test(wrapped_env)


wrappers = [
    supersuit.color_reduction_v0(knights_archers_zombies_v4.env(), "R"),
    supersuit.resize_v0(dtype_v0(knights_archers_zombies_v4.env(), np.uint8),
                        x_size=5,
                        y_size=10),
    supersuit.resize_v0(dtype_v0(knights_archers_zombies_v4.env(), np.uint8),
                        x_size=5,
                        y_size=10,
                        linear_interp=True),
    supersuit.dtype_v0(knights_archers_zombies_v4.env(), np.int32),
    supersuit.flatten_v0(knights_archers_zombies_v4.env()),
    supersuit.reshape_v0(knights_archers_zombies_v4.env(), (512 * 512, 3)),
    supersuit.normalize_obs_v0(dtype_v0(knights_archers_zombies_v4.env(),
                                        np.float32),
                               env_min=-1,
                               env_max=5.0),
    supersuit.frame_stack_v1(knights_archers_zombies_v4.env(), 8),
    supersuit.pad_observations_v0(knights_archers_zombies_v4.env()),
import numpy as np
from pettingzoo.test import api_test, seed_test, parallel_test
from pettingzoo.test.example_envs import (
    generated_agents_parallel_v0,
    generated_agents_env_v0,
)

import supersuit
from supersuit import dtype_v0
import pytest

wrappers = [
    supersuit.dtype_v0(generated_agents_parallel_v0.env(), np.int32),
    supersuit.flatten_v0(generated_agents_parallel_v0.env()),
    supersuit.normalize_obs_v0(
        dtype_v0(generated_agents_parallel_v0.env(), np.float32),
        env_min=-1,
        env_max=5.0,
    ),
    supersuit.frame_stack_v1(generated_agents_parallel_v0.env(), 8),
    supersuit.reward_lambda_v0(generated_agents_parallel_v0.env(),
                               lambda x: x / 10),
    supersuit.clip_reward_v0(generated_agents_parallel_v0.env()),
    supersuit.nan_noop_v0(generated_agents_parallel_v0.env(), 0),
    supersuit.nan_zeros_v0(generated_agents_parallel_v0.env()),
    supersuit.nan_random_v0(generated_agents_parallel_v0.env()),
    supersuit.frame_skip_v0(generated_agents_parallel_v0.env(), 4),
    supersuit.sticky_actions_v0(generated_agents_parallel_v0.env(), 0.75),
    supersuit.delay_observations_v0(generated_agents_parallel_v0.env(), 3),
    supersuit.max_observation_v0(generated_agents_parallel_v0.env(), 3),
]
Пример #18
0
def create_single_env(args):
    env_name = args.env
    if args.num_envs > 1:
        keep_info = True  # keep_info True to maintain dict type for parallel envs (otherwise cannot pass VectorEnv wrapper)
    else:
        keep_info = False
    '''https://www.pettingzoo.ml/atari'''
    if "slimevolley" in env_name or "SlimeVolley" in env_name:
        print(f'Load SlimeVolley env: {env_name}')
        env = gym.make(env_name)
        if env_name in [
                'SlimeVolleySurvivalNoFrameskip-v0',
                'SlimeVolleyNoFrameskip-v0', 'SlimeVolleyPixel-v0'
        ]:
            # For image-based envs, apply following wrappers (from gym atari) to achieve pettingzoo style env,
            # or use supersuit (requires input env to be either pettingzoo or gym env).
            # same as: https://github.com/hardmaru/slimevolleygym/blob/master/training_scripts/train_ppo_pixel.py
            # TODO Note: this cannot handle the two obervations in above SlimeVolley envs,
            # since the wrappers are for single agent.
            if env_name != 'SlimeVolleyPixel-v0':
                env = NoopResetEnv(env, noop_max=30)
            env = MaxAndSkipEnv(env, skip=4)
            env = WarpFrame(env)
            # #env = ClipRewardEnv(env)
            env = FrameStack(env, 4)

        env = SlimeVolleyWrapper(
            env, args.against_baseline)  # slimevolley to pettingzoo style
        env = NFSPPettingZooWrapper(
            env, keep_info=keep_info
        )  # pettingzoo to nfsp style, keep_info True to maintain dict type for parallel envs

    elif env_name in AtariEnvs:  # PettingZoo Atari envs
        print(f'Load PettingZoo Atari env: {env_name}')
        if args.ram:
            obs_type = 'ram'
        else:
            obs_type = 'rgb_image'

        env = eval(env_name).parallel_env(obs_type=obs_type)
        env_agents = env.unwrapped.agents  # this cannot go through supersuit wrapper, so get it first and reassign it

        if obs_type == 'rgb_image':
            # as per openai baseline's MaxAndSKip wrapper, maxes over the last 2 frames
            # to deal with frame flickering
            env = supersuit.max_observation_v0(env, 2)

            # repeat_action_probability is set to 0.25 to introduce non-determinism to the system
            env = supersuit.sticky_actions_v0(env,
                                              repeat_action_probability=0.25)

            # skip frames for faster processing and less control
            # to be compatable with gym, use frame_skip(env, (2,5))
            env = supersuit.frame_skip_v0(env, 4)

            # downscale observation for faster processing
            env = supersuit.resize_v0(env, 84, 84)

            # allow agent to see everything on the screen despite Atari's flickering screen problem
            env = supersuit.frame_stack_v1(env, 4)

        else:
            env = supersuit.frame_skip_v0(
                env, 4
            )  # RAM version also need frame skip, essential for boxing-v1, etc

        #   env = PettingZooWrapper(env)  # need to be put at the end

        # normalize the observation of Atari for both image or RAM
        env = supersuit.dtype_v0(
            env, 'float32'
        )  # need to transform uint8 to float first for normalizing observation: https://github.com/PettingZoo-Team/SuperSuit
        env = supersuit.normalize_obs_v0(
            env, env_min=0, env_max=1)  # normalize the observation to (0,1)

        # assign observation and action spaces
        env.observation_space = list(env.observation_spaces.values())[0]
        env.action_space = list(env.action_spaces.values())[0]
        env.agents = env_agents
        env = NFSPPettingZooWrapper(
            env, keep_info=keep_info
        )  # pettingzoo to nfsp style, keep_info True to maintain dict type for parallel envs)

    elif env_name in ClassicEnvs:  # PettingZoo Classic envs
        print(f'Load PettingZoo Classic env: {env_name}')
        if env_name in ['rps_v1', 'rpsls_v1']:
            env = eval(env_name).parallel_env()
            env = PettingzooClassicWrapper(env, observation_mask=1.)
        else:  # only rps_v1 can use parallel_env at present
            env = eval(env_name).env()
            env = PettingzooClassic_Iterate2Parallel(
                env, observation_mask=None
            )  # since Classic games do not support Parallel API yet

        env = NFSPPettingZooWrapper(env, keep_info=keep_info)

    elif "LaserTag" in env_name:  # LaserTag: https://github.com/younggyoseo/pytorch-nfsp
        print(f'Load LaserTag env: {env_name}')
        env = gym.make(env_name)
        env = wrap_pytorch(env)

    else:  # gym env
        print(f'Load Gym env: {env_name}')
        try:
            env = gym.make(env_name)
        except:
            print(f"Error: No such env: {env_name}!")
        # may need more wrappers here, e.g. Pong-ram-v0 need scaled observation!
        # Ref: https://towardsdatascience.com/deep-q-network-dqn-i-bce08bdf2af
        env = NFSPAtariWrapper(env, keep_info=keep_info)

    env.seed(args.seed)
    return env
Пример #19
0
 def env_creator(config):
     env = zoo_yaniv.env(config=config)
     env = dtype_v0(env, dtype=float32)
     env = color_reduction_v0(env, mode="R")
     env = normalize_obs_v0(env)
     return env