|
| 1 | +import time |
| 2 | +import warnings |
| 3 | +from typing import Optional |
| 4 | + |
| 5 | +import gym |
| 6 | +import gymnasium |
| 7 | +import numpy as np |
| 8 | +from envpool.python.protocol import EnvPool |
| 9 | +from packaging import version |
| 10 | +from stable_baselines3.common.vec_env import VecEnvWrapper as BaseWrapper |
| 11 | +from stable_baselines3.common.vec_env import VecMonitor |
| 12 | +from stable_baselines3.common.vec_env.base_vec_env import (VecEnvObs, |
| 13 | + VecEnvStepReturn) |
| 14 | + |
| 15 | +is_legacy_gym = version.parse(gym.__version__) < version.parse("0.26.0") |
| 16 | + |
| 17 | + |
| 18 | +class VecEnvWrapper(BaseWrapper): |
| 19 | + @property |
| 20 | + def agent_num(self): |
| 21 | + if self.is_original_envpool_env(): |
| 22 | + return 1 |
| 23 | + else: |
| 24 | + return self.env.agent_num |
| 25 | + |
| 26 | + def is_original_envpool_env(self): |
| 27 | + return not hasattr(self.venv, "agent_num`") |
| 28 | + |
| 29 | + |
| 30 | +class VecAdapter(VecEnvWrapper): |
| 31 | + """ |
| 32 | + Convert EnvPool object to a Stable-Baselines3 (SB3) VecEnv. |
| 33 | +
|
| 34 | + :param venv: The envpool object. |
| 35 | + """ |
| 36 | + |
| 37 | + def __init__(self, venv: EnvPool): |
| 38 | + venv.num_envs = venv.spec.config.num_envs |
| 39 | + observation_space = venv.observation_space |
| 40 | + new_observation_space = gymnasium.spaces.Box( |
| 41 | + low=observation_space.low, |
| 42 | + high=observation_space.high, |
| 43 | + dtype=observation_space.dtype, |
| 44 | + ) |
| 45 | + action_space = venv.action_space |
| 46 | + if isinstance(action_space, gym.spaces.Discrete): |
| 47 | + new_action_space = gymnasium.spaces.Discrete(action_space.n) |
| 48 | + elif isinstance(action_space, gym.spaces.MultiDiscrete): |
| 49 | + new_action_space = gymnasium.spaces.MultiDiscrete(action_space.nvec) |
| 50 | + elif isinstance(action_space, gym.spaces.MultiBinary): |
| 51 | + new_action_space = gymnasium.spaces.MultiBinary(action_space.n) |
| 52 | + elif isinstance(action_space, gym.spaces.Box): |
| 53 | + new_action_space = gymnasium.spaces.Box( |
| 54 | + low=action_space.low, |
| 55 | + high=action_space.high, |
| 56 | + dtype=action_space.dtype, |
| 57 | + ) |
| 58 | + else: |
| 59 | + raise NotImplementedError(f"Action space {action_space} is not supported") |
| 60 | + super().__init__( |
| 61 | + venv=venv, |
| 62 | + observation_space=new_observation_space, |
| 63 | + action_space=new_action_space, |
| 64 | + ) |
| 65 | + |
| 66 | + def step_async(self, actions: np.ndarray) -> None: |
| 67 | + self.actions = actions |
| 68 | + |
| 69 | + def reset(self) -> VecEnvObs: |
| 70 | + if is_legacy_gym: |
| 71 | + return self.venv.reset(), {} |
| 72 | + else: |
| 73 | + return self.venv.reset() |
| 74 | + |
| 75 | + def step_wait(self) -> VecEnvStepReturn: |
| 76 | + if is_legacy_gym: |
| 77 | + obs, rewards, dones, info_dict = self.venv.step(self.actions) |
| 78 | + else: |
| 79 | + obs, rewards, terms, truncs, info_dict = self.venv.step(self.actions) |
| 80 | + dones = terms + truncs |
| 81 | + rewards = rewards |
| 82 | + infos = [] |
| 83 | + for i in range(self.num_envs): |
| 84 | + infos.append( |
| 85 | + { |
| 86 | + key: info_dict[key][i] |
| 87 | + for key in info_dict.keys() |
| 88 | + if isinstance(info_dict[key], np.ndarray) |
| 89 | + } |
| 90 | + ) |
| 91 | + if dones[i]: |
| 92 | + infos[i]["terminal_observation"] = obs[i] |
| 93 | + if is_legacy_gym: |
| 94 | + obs[i] = self.venv.reset(np.array([i])) |
| 95 | + else: |
| 96 | + obs[i] = self.venv.reset(np.array([i]))[0] |
| 97 | + return obs, rewards, dones, infos |
| 98 | + |
| 99 | + |
| 100 | +class VecMonitor(VecEnvWrapper): |
| 101 | + def __init__( |
| 102 | + self, |
| 103 | + venv, |
| 104 | + filename: Optional[str] = None, |
| 105 | + info_keywords=(), |
| 106 | + ): |
| 107 | + # Avoid circular import |
| 108 | + from stable_baselines3.common.monitor import Monitor, ResultsWriter |
| 109 | + |
| 110 | + try: |
| 111 | + is_wrapped_with_monitor = venv.env_is_wrapped(Monitor)[0] |
| 112 | + except AttributeError: |
| 113 | + is_wrapped_with_monitor = False |
| 114 | + |
| 115 | + if is_wrapped_with_monitor: |
| 116 | + warnings.warn( |
| 117 | + "The environment is already wrapped with a `Monitor` wrapper" |
| 118 | + "but you are wrapping it with a `VecMonitor` wrapper, the `Monitor` statistics will be" |
| 119 | + "overwritten by the `VecMonitor` ones.", |
| 120 | + UserWarning, |
| 121 | + ) |
| 122 | + |
| 123 | + VecEnvWrapper.__init__(self, venv) |
| 124 | + self.episode_count = 0 |
| 125 | + self.t_start = time.time() |
| 126 | + |
| 127 | + env_id = None |
| 128 | + if hasattr(venv, "spec") and venv.spec is not None: |
| 129 | + env_id = venv.spec.id |
| 130 | + |
| 131 | + self.results_writer: Optional[ResultsWriter] = None |
| 132 | + if filename: |
| 133 | + self.results_writer = ResultsWriter( |
| 134 | + filename, |
| 135 | + header={"t_start": self.t_start, "env_id": str(env_id)}, |
| 136 | + extra_keys=info_keywords, |
| 137 | + ) |
| 138 | + |
| 139 | + self.info_keywords = info_keywords |
| 140 | + self.episode_returns = np.zeros(self.num_envs, dtype=np.float32) |
| 141 | + self.episode_lengths = np.zeros(self.num_envs, dtype=np.int32) |
| 142 | + |
| 143 | + def reset(self, **kwargs) -> VecEnvObs: |
| 144 | + obs, info = self.venv.reset() |
| 145 | + self.episode_returns = np.zeros(self.num_envs, dtype=np.float32) |
| 146 | + self.episode_lengths = np.zeros(self.num_envs, dtype=np.int32) |
| 147 | + return obs, info |
| 148 | + |
| 149 | + def step_wait(self) -> VecEnvStepReturn: |
| 150 | + obs, rewards, dones, infos = self.venv.step_wait() |
| 151 | + self.episode_returns += rewards |
| 152 | + self.episode_lengths += 1 |
| 153 | + new_infos = list(infos[:]) |
| 154 | + for i in range(len(dones)): |
| 155 | + if dones[i]: |
| 156 | + info = infos[i].copy() |
| 157 | + episode_return = self.episode_returns[i] |
| 158 | + episode_length = self.episode_lengths[i] |
| 159 | + episode_info = { |
| 160 | + "r": episode_return, |
| 161 | + "l": episode_length, |
| 162 | + "t": round(time.time() - self.t_start, 6), |
| 163 | + } |
| 164 | + for key in self.info_keywords: |
| 165 | + episode_info[key] = info[key] |
| 166 | + info["episode"] = episode_info |
| 167 | + self.episode_count += 1 |
| 168 | + self.episode_returns[i] = 0 |
| 169 | + self.episode_lengths[i] = 0 |
| 170 | + if self.results_writer: |
| 171 | + self.results_writer.write_row(episode_info) |
| 172 | + new_infos[i] = info |
| 173 | + rewards = np.expand_dims(rewards, 1) |
| 174 | + return obs, rewards, dones, new_infos |
| 175 | + |
| 176 | + def close(self) -> None: |
| 177 | + if self.results_writer: |
| 178 | + self.results_writer.close() |
| 179 | + return self.venv.close() |
| 180 | + |
| 181 | + |
| 182 | +__all__ = ["VecAdapter", "VecMonitor"] |
0 commit comments