lunarlander_env.py 4.6 KB
Newer Older
1

N
v0.1.0  
niuyazhe 已提交
2 3 4 5 6 7
from typing import Any, List, Union, Optional
import time
import gym
import numpy as np
from ding.envs import BaseEnv, BaseEnvTimestep, BaseEnvInfo
from ding.envs.common.env_element import EnvElement, EnvElementInfo
8
from ding.torch_utils import to_ndarray, to_list
N
v0.1.0  
niuyazhe 已提交
9
from ding.utils import ENV_REGISTRY
10
from ding.envs.common import affine_transform
N
v0.1.0  
niuyazhe 已提交
11 12 13 14 15 16 17 18


@ENV_REGISTRY.register('lunarlander')
class LunarLanderEnv(BaseEnv):

    def __init__(self, cfg: dict) -> None:
        self._cfg = cfg
        self._init_flag = False
19
        self._act_scale = cfg.act_scale
N
v0.1.0  
niuyazhe 已提交
20 21 22

    def reset(self) -> np.ndarray:
        if not self._init_flag:
23 24 25 26
            if self._cfg.env_id == 'LunarLanderContinuous-v2':
                self._env = gym.make('LunarLanderContinuous-v2')
            else:
                self._env = gym.make('LunarLander-v2')
N
v0.1.0  
niuyazhe 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
            self._init_flag = True
        if hasattr(self, '_seed') and hasattr(self, '_dynamic_seed') and self._dynamic_seed:
            np_seed = 100 * np.random.randint(1, 1000)
            self._env.seed(self._seed + np_seed)
        elif hasattr(self, '_seed'):
            self._env.seed(self._seed)
        self._final_eval_reward = 0
        obs = self._env.reset()
        obs = to_ndarray(obs).astype(np.float32)
        return obs

    def close(self) -> None:
        if self._init_flag:
            self._env.close()
        self._init_flag = False

    def render(self) -> None:
        self._env.render()

    def seed(self, seed: int, dynamic_seed: bool = True) -> None:
        self._seed = seed
        self._dynamic_seed = dynamic_seed
        np.random.seed(self._seed)

    def step(self, action: np.ndarray) -> BaseEnvTimestep:
        assert isinstance(action, np.ndarray), type(action)
        if action.shape == (1, ):
54
            action = action.squeeze()  # 0-dim array
55 56
        if self._act_scale:
            action = affine_transform(action, min_val=-1, max_val=1)
N
v0.1.0  
niuyazhe 已提交
57
        obs, rew, done, info = self._env.step(action)
蒲源 已提交
58
        # self._env.render()
N
v0.1.0  
niuyazhe 已提交
59 60 61 62 63
        rew = float(rew)
        self._final_eval_reward += rew
        if done:
            info['final_eval_reward'] = self._final_eval_reward
        obs = to_ndarray(obs).astype(np.float32)
64
        rew = to_ndarray([rew])  # wrapped to be transfered to a array with shape (1,)
N
v0.1.0  
niuyazhe 已提交
65 66 67 68
        return BaseEnvTimestep(obs, rew, done, info)

    def info(self) -> BaseEnvInfo:
        T = EnvElementInfo
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
        if self._cfg.env_id == 'LunarLanderContinuous-v2':
            return BaseEnvInfo(
                agent_num=1,
                obs_space=T(
                    (8,),
                    {
                        'min': [float("-inf")] * 8,
                        'max': [float("inf")] * 8,
                        'dtype': np.float32,
                    },
                ),
                # [min, max) TODO(pu)
                act_space=T(
                    (2,),
                    {
                        'min': float("-inf"),
                        'max': float("inf"),
                        'dtype': np.float32,
                    },
                ),
                rew_space=T(
                    (1,),
                    {
                        'min': -1000.0,
                        'max': 1000.0,
                        'dtype': np.float32,
                    },
                ),
                use_wrappers=None,
            )
        else:
            return BaseEnvInfo(
                agent_num=1,
                obs_space=T(
                    (8, ),
                    {
                        'min': [float("-inf")] * 8,
                        'max': [float("inf")] * 8,
                        'dtype': np.float32,
                    },
                ),
                # [min, max)
                act_space=T(
                    (1, ),
                    {
                        'min': 0,
                        'max': 4,
                        'dtype': int,
                    },
                ),
                rew_space=T(
                    (1, ),
                    {
                        'min': -1000.0,
                        'max': 1000.0,
                        'dtype': np.float32,
                    },
                ),
                use_wrappers=None,
            )
N
v0.1.0  
niuyazhe 已提交
129 130 131 132 133 134 135 136 137 138 139 140

    def __repr__(self) -> str:
        return "DI-engine LunarLander Env"

    def enable_save_replay(self, replay_path: Optional[str] = None) -> None:
        if replay_path is None:
            replay_path = './video'
        self._replay_path = replay_path
        # this function can lead to the meaningless result
        self._env = gym.wrappers.Monitor(
            self._env, self._replay_path, video_callable=lambda episode_id: True, force=True
        )