ding.envs.env_manager.base_env_manager¶
ding.envs.env_manager.base_env_manager
¶
BaseEnvManager
¶
Bases: object
Overview
The basic class of env manager to manage multiple vectorized environments. BaseEnvManager define all the necessary interfaces and derived class must extend this basic class.
The class is implemented by the pseudo-parallelism (i.e. serial) mechanism, therefore, this class is only used in some tiny environments and for debug purpose.
Interfaces: reset, step, seed, close, enable_save_replay, launch, default_config, reward_shaping, enable_save_figure Properties: env_num, env_ref, ready_obs, ready_obs_id, ready_imgs, done, closed, method_name_list, observation_space, action_space, reward_space
env_num
property
¶
Overview
env_num is the number of sub-environments in env manager.
Returns:
- env_num (:obj:int): The number of sub-environments.
env_ref
property
¶
Overview
env_ref is used to acquire some common attributes of env, like obs_shape and act_shape.
Returns:
- env_ref (:obj:BaseEnv): The reference of sub-environment.
observation_space
property
¶
Overview
observation_space is the observation space of sub-environment, following the format of gym.spaces.
Returns:
- observation_space (:obj:gym.spaces.Space): The observation space of sub-environment.
action_space
property
¶
Overview
action_space is the action space of sub-environment, following the format of gym.spaces.
Returns:
- action_space (:obj:gym.spaces.Space): The action space of sub-environment.
reward_space
property
¶
Overview
reward_space is the reward space of sub-environment, following the format of gym.spaces.
Returns:
- reward_space (:obj:gym.spaces.Space): The reward space of sub-environment.
ready_obs
property
¶
Overview
Get the ready (next) observation, which is a special design to unify both aysnc/sync env manager.
For each interaction between policy and env, the policy will input the ready_obs and output the action.
Then the env_manager will step with the action and prepare the next ready_obs.
Returns:
- ready_obs (:obj:Dict[int, Any]): A dict with env_id keys and observation values.
Example:
>>> obs = env_manager.ready_obs
>>> stacked_obs = np.concatenate(list(obs.values()))
>>> action = policy(obs) # here policy inputs np obs and outputs np action
>>> action = {env_id: a for env_id, a in zip(obs.keys(), action)}
>>> timesteps = env_manager.step(action)
ready_obs_id
property
¶
Overview
Get the ready (next) observation id, which is a special design to unify both aysnc/sync env manager.
Returns:
- ready_obs_id (:obj:List[int]): A list of env_ids for ready observations.
ready_imgs
property
¶
Overview
Sometimes, we need to render the envs, this function is used to get the next ready renderd frame and corresponding env id.
Arguments:
- render_mode (:obj:Optional[str]): The render mode, can be 'rgb_array' or 'depth_array', which follows the definition in the render function of ding.utils .
Returns:
- ready_imgs (:obj:Dict[int, np.ndarray]): A dict with env_id keys and rendered frames.
done
property
¶
Overview
done is a flag to indicate whether env manager is done, i.e., whether all sub-environments have executed enough episodes.
Returns:
- done (:obj:bool): Whether env manager is done.
method_name_list
property
¶
Overview
The public methods list of sub-environments that can be directly called from the env manager level. Other methods and attributes will be accessed with the __getattr__ method.
Methods defined in this list can be regarded as the vectorized extension of methods in sub-environments.
Sub-class of BaseEnvManager can override this method to add more methods.
Returns:
- method_name_list (:obj:list): The public methods list of sub-environments.
closed
property
¶
Overview
closed is a property that returns whether the env manager is closed.
Returns:
- closed (:obj:bool): Whether the env manager is closed.
default_config()
classmethod
¶
Overview
Return the deepcopyed default config of env manager.
Returns:
- cfg (:obj:EasyDict): The default config of env manager.
__init__(env_fn, cfg=EasyDict({}))
¶
Overview
Initialize the base env manager with callable the env function and the EasyDict-type config. Here we use
env_fn to ensure the lazy initialization of sub-environments, which is benetificial to resource
allocation and parallelism. cfg is the merged result between the default config of this class
and user's config.
This construction function is in lazy-initialization mode, the actual initialization is in launch.
Arguments:
- env_fn (:obj:List[Callable]): A list of functions to create env_num sub-environments.
- cfg (:obj:EasyDict): Final merged config.
.. note::
For more details about how to merge config, please refer to the system document of DI-engine (en link1 <../03_system/config.html>_).
__getattr__(key)
¶
Note
If a python object doesn't have the attribute whose name is key, it will call this method.
We suppose that all envs have the same attributes.
If you need different envs, please implement other env managers.
launch(reset_param=None)
¶
Overview
Launch the env manager, instantiate the sub-environments and set up the environments and their parameters.
Arguments:
- reset_param (:obj:Optional[Dict]): A dict of reset parameters for each environment, key is the env_id, value is the corresponding reset parameter, defaults to None.
reset(reset_param=None)
¶
Overview
Forcely reset the sub-environments their corresponding parameters. Because in env manager all the sub-environments usually are reset automatically as soon as they are done, this method is only called when the caller must forcely reset all the sub-environments, such as in evaluation.
Arguments:
- reset_param (:obj:List): Dict of reset parameters for each environment, key is the env_id, value is the corresponding reset parameters.
step(actions)
¶
Overview
Execute env step according to input actions. If some sub-environments are done after this execution, they will be reset automatically when self._auto_reset is True, otherwise they need to be reset when the caller use the reset method of env manager.
Arguments:
- actions (:obj:Dict[int, Any]): A dict of actions, key is the env_id, value is corresponding action. action can be any type, it depends on the env, and the env will handle it. Ususlly, the action is a dict of numpy array, and the value is generated by the outer caller like policy.
Returns:
- timesteps (:obj:Dict[int, BaseEnvTimestep]): Each timestep is a BaseEnvTimestep object, usually including observation, reward, done, info. Some special customized environments will have the special timestep definition. The length of timesteps is the same as the length of actions in synchronous env manager.
Example:
>>> timesteps = env_manager.step(action)
>>> for env_id, timestep in enumerate(timesteps):
>>> if timestep.done:
>>> print('Env {} is done'.format(env_id))
seed(seed, dynamic_seed=None)
¶
Overview
Set the random seed for each environment.
Arguments:
- seed (:obj:Union[Dict[int, int], List[int], int]): Dict or List of seeds for each environment; If only one seed is provided, it will be used in the same way for all environments.
- dynamic_seed (:obj:bool): Whether to use dynamic seed.
.. note::
For more details about dynamic_seed, please refer to the best practice document of DI-engine (en link2 <../04_best_practice/random_seed.html>_).
enable_save_replay(replay_path)
¶
Overview
Enable all environments to save replay video after each episode terminates.
Arguments:
- replay_path (:obj:Union[List[str], str]): List of paths for each environment; Or one path for all environments.
enable_save_figure(env_id, figure_path)
¶
Overview
Enable a specific env to save figure (e.g. environment statistics or episode return curve).
Arguments:
- figure_path (:obj:str): The file directory path for all environments to save figures.
close()
¶
Overview
Close the env manager and release all the environment resources.
reward_shaping(env_id, transitions)
¶
Overview
Execute reward shaping for a specific environment, which is often called when a episode terminates.
Arguments:
- env_id (:obj:int): The id of the environment to be shaped.
- transitions (:obj:List[dict]): The transition data list of the environment to be shaped.
Returns:
- transitions (:obj:List[dict]): The shaped transition data list.
BaseEnvManagerV2
¶
Bases: BaseEnvManager
Overview
The basic class of env manager to manage multiple vectorized environments. BaseEnvManager define all the necessary interfaces and derived class must extend this basic class.
The class is implemented by the pseudo-parallelism (i.e. serial) mechanism, therefore, this class is only used in some tiny environments and for debug purpose.
V2 means this env manager is designed for new task pipeline and interfaces coupled with treetensor.`
.. note::
For more details about new task pipeline, please refer to the system document of DI-engine (system en link3 <../03_system/index.html>_).
Interfaces
reset, step, seed, close, enable_save_replay, launch, default_config, reward_shaping, enable_save_figure
Properties: env_num, env_ref, ready_obs, ready_obs_id, ready_imgs, done, closed, method_name_list, observation_space, action_space, reward_space
ready_obs
property
¶
Overview
Get the ready (next) observation, which is a special design to unify both aysnc/sync env manager.
For each interaction between policy and env, the policy will input the ready_obs and output the action.
Then the env_manager will step with the action and prepare the next ready_obs.
For V2 version, the observation is transformed and packed up into tnp.array type, which allows
more convenient operations.
Return:
- ready_obs (:obj:tnp.array): A stacked treenumpy-type observation data.
Example:
>>> obs = env_manager.ready_obs
>>> action = policy(obs) # here policy inputs treenp obs and output np action
>>> timesteps = env_manager.step(action)
step(actions)
¶
Overview
Execute env step according to input actions. If some sub-environments are done after this execution, they will be reset automatically by default.
Arguments:
- actions (:obj:List[tnp.ndarray]): A list of treenumpy-type actions, the value is generated by the outer caller like policy.
Returns:
- timesteps (:obj:List[tnp.ndarray]): A list of timestep, Each timestep is a tnp.ndarray object, usually including observation, reward, done, info, env_id. Some special environments will have the special timestep definition. The length of timesteps is the same as the length of actions in synchronous env manager. For the compatibility of treenumpy, here we use make_key_as_identifier and remove_illegal_item functions to modify the original timestep.
Example:
>>> timesteps = env_manager.step(action)
>>> for timestep in timesteps:
>>> if timestep.done:
>>> print('Env {} is done'.format(timestep.env_id))
timeout_wrapper(func=None, timeout=None)
¶
Overview
Watch the function that must be finihsed within a period of time. If timeout, raise the captured error.
create_env_manager(manager_cfg, env_fn)
¶
Overview
Create an env manager according to manager_cfg and env functions.
Arguments:
- manager_cfg (:obj:EasyDict): Final merged env manager config.
- env_fn (:obj:List[Callable]): A list of functions to create env_num sub-environments.
ArgumentsKeys:
- type (:obj:str): Env manager type set in ENV_MANAGER_REGISTRY.register , such as base .
- import_names (:obj:List[str]): A list of module names (paths) to import before creating env manager, such as ding.envs.env_manager.base_env_manager .
Returns:
- env_manager (:obj:BaseEnvManager): The created env manager.
.. tip::
This method will not modify the manager_cfg , it will deepcopy the manager_cfg and then modify it.
get_env_manager_cls(cfg)
¶
Overview
Get the env manager class according to config, which is used to access related class variables/methods.
Arguments:
- manager_cfg (:obj:EasyDict): Final merged env manager config.
ArgumentsKeys:
- type (:obj:str): Env manager type set in ENV_MANAGER_REGISTRY.register , such as base .
- import_names (:obj:List[str]): A list of module names (paths) to import before creating env manager, such as ding.envs.env_manager.base_env_manager .
Returns:
- env_manager_cls (:obj:type): The corresponding env manager class.
Full Source Code
../ding/envs/env_manager/base_env_manager.py