base_env.py 5.3 KB
Newer Older
N
v0.1.0  
niuyazhe 已提交
1 2 3
from abc import ABC, abstractmethod
from typing import Any, List, Tuple
import gym
N
niuyazhe 已提交
4
import copy
N
v0.1.0  
niuyazhe 已提交
5 6 7 8 9 10 11 12 13
from easydict import EasyDict
from namedlist import namedlist
from collections import namedtuple
from ding.utils import import_module, ENV_REGISTRY

BaseEnvTimestep = namedtuple('BaseEnvTimestep', ['obs', 'reward', 'done', 'info'])
BaseEnvInfo = namedlist('BaseEnvInfo', ['agent_num', 'obs_space', 'act_space', 'rew_space', 'use_wrappers'])


14
class BaseEnv(ABC, gym.Env):
N
v0.1.0  
niuyazhe 已提交
15 16 17 18 19
    """
    Overview:
        basic environment class, extended from ``gym.Env``
    Interface:
        ``__init__``, ``reset``, ``close``, ``step``, ``info``, ``create_collector_env_cfg``, \
N
niuyazhe 已提交
20
            ``create_evaluator_env_cfg``, ``enable_save_replay``, ``default_config``
N
v0.1.0  
niuyazhe 已提交
21 22
    """

N
niuyazhe 已提交
23 24 25 26 27 28
    @classmethod
    def default_config(cls: type) -> EasyDict:
        cfg = EasyDict(copy.deepcopy(cls.config))
        cfg.cfg_type = cls.__name__ + 'Dict'
        return cfg

N
v0.1.0  
niuyazhe 已提交
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 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 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
    @abstractmethod
    def __init__(self, cfg: dict) -> None:
        """
        Overview:
            Lazy init, only parameters will be initialized in ``self.__init__()``
        """
        raise NotImplementedError

    @abstractmethod
    def reset(self) -> Any:
        """
        Overview:
            Resets the env to an initial state and returns an initial observation. Abstract Method from ``gym.Env``.
        """
        raise NotImplementedError

    @abstractmethod
    def close(self) -> None:
        """
        Overview:
            Environments will automatically ``close()`` themselves when garbage collected or exits. \
                Abstract Method from ``gym.Env``.
        """
        raise NotImplementedError

    @abstractmethod
    def step(self, action: Any) -> 'BaseEnv.timestep':
        """
        Overview:
            Run one timestep of the environment's dynamics. Abstract Method from ``gym.Env``.
        Arguments:
            - action (:obj:`Any`): the ``action`` input to step with
        Returns:
            - timestep (:obj:`BaseEnv.timestep`)
        """
        raise NotImplementedError

    @abstractmethod
    def seed(self, seed: int) -> None:
        """
        Overview:
            Sets the seed for this env's random number generator(s). Abstract Method from ``gym.Env``.
        """
        raise NotImplementedError

    @abstractmethod
    def info(self) -> 'BaseEnvInfo':
        """
        Overview:
            Show space in code and return namedlist.
        Returns:
             - info (:obj:`BaseEnvInfo`)
        """
        raise NotImplementedError

    @abstractmethod
    def __repr__(self) -> str:
        raise NotImplementedError

    @staticmethod
    def create_collector_env_cfg(cfg: dict) -> List[dict]:
        """
        Overview:
            Return a list of all of the environment from input config.
        Arguments:
            - cfg (:obj:`Dict`) Env config, same config where ``self.__init__()`` takes arguments from
        Returns:
            - List of ``cfg`` including all of the collector env's config
        """
        collector_env_num = cfg.pop('collector_env_num')
        return [cfg for _ in range(collector_env_num)]

    @staticmethod
    def create_evaluator_env_cfg(cfg: dict) -> List[dict]:
        """
        Overview:
            Return a list of all of the environment from input config.
        Arguments:
            - cfg (:obj:`Dict`) Env config, same config where ``self.__init__()`` takes arguments from
        Returns:
            - List of ``cfg`` including all of the evaluator env's config
        """
        evaluator_env_num = cfg.pop('evaluator_env_num')
        return [cfg for _ in range(evaluator_env_num)]

    # optional method
    def enable_save_replay(self, replay_path: str) -> None:
        """
        Overview:
            Save replay file in the given path, need to be self-implemented.
        Arguments:
            - replay_path(:obj:`str`): Storage path.
        """
        raise NotImplementedError


def get_vec_env_setting(cfg: dict) -> Tuple[type, List[dict], List[dict]]:
    """
    Overview:
       Get vectorized env setting(env_fn, collector_env_cfg, evaluator_env_cfg)
    Arguments:
        - cfg (:obj:`Dict`) Env config, same config where ``self.__init__()`` takes arguments from
    Returns:
        - env_fn (:obj:`type`): Callable object, call it with proper arguments and then get a new env instance.
        - collector_env_cfg (:obj:`List[dict]`): A list contains the config of collecting data envs.
        - evaluator_env_cfg (:obj:`List[dict]`): A list contains the config of evaluation envs.

    .. note::
        elements(env config) in collector_env_cfg/evaluator_env_cfg can be different, such as server ip and port.

    """
    import_module(cfg.get('import_names', []))
    env_fn = ENV_REGISTRY.get(cfg.type)
    collector_env_cfg = env_fn.create_collector_env_cfg(cfg)
    evaluator_env_cfg = env_fn.create_evaluator_env_cfg(cfg)
    return env_fn, collector_env_cfg, evaluator_env_cfg


def get_env_cls(cfg: EasyDict) -> type:
    """
    Overview:
       Get the env class by correspondng module of ``cfg`` and return the callable class
    Arguments:
        - cfg (:obj:`Dict`) Env config, same config where ``self.__init__()`` takes arguments from
    Returns:
        - Env module as the corresponding callable class

    """
    import_module(cfg.get('import_names', []))
    return ENV_REGISTRY.get(cfg.type)