2021-04-13 16:09:31 +00:00
|
|
|
import numpy as np
|
2023-05-04 18:27:15 +00:00
|
|
|
from gymnasium import spaces
|
2021-04-13 16:09:31 +00:00
|
|
|
|
|
|
|
|
from stable_baselines3.common.vec_env.base_vec_env import VecEnv, VecEnvStepReturn, VecEnvWrapper
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class VecExtractDictObs(VecEnvWrapper):
|
|
|
|
|
"""
|
|
|
|
|
A vectorized wrapper for extracting dictionary observations.
|
|
|
|
|
|
|
|
|
|
:param venv: The vectorized environment
|
|
|
|
|
:param key: The key of the dictionary observation
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
def __init__(self, venv: VecEnv, key: str):
|
|
|
|
|
self.key = key
|
2023-05-04 18:27:15 +00:00
|
|
|
assert isinstance(
|
|
|
|
|
venv.observation_space, spaces.Dict
|
|
|
|
|
), f"VecExtractDictObs can only be used with Dict obs space, not {venv.observation_space}"
|
2021-04-13 16:09:31 +00:00
|
|
|
super().__init__(venv=venv, observation_space=venv.observation_space.spaces[self.key])
|
|
|
|
|
|
|
|
|
|
def reset(self) -> np.ndarray:
|
|
|
|
|
obs = self.venv.reset()
|
2023-05-04 18:27:15 +00:00
|
|
|
assert isinstance(obs, dict)
|
2021-04-13 16:09:31 +00:00
|
|
|
return obs[self.key]
|
|
|
|
|
|
|
|
|
|
def step_wait(self) -> VecEnvStepReturn:
|
2023-04-12 13:20:04 +00:00
|
|
|
obs, reward, done, infos = self.venv.step_wait()
|
2023-05-04 18:27:15 +00:00
|
|
|
assert isinstance(obs, dict)
|
2023-04-12 13:20:04 +00:00
|
|
|
for info in infos:
|
|
|
|
|
if "terminal_observation" in info:
|
|
|
|
|
info["terminal_observation"] = info["terminal_observation"][self.key]
|
|
|
|
|
return obs[self.key], reward, done, infos
|