2020-08-19 15:00:24 +08:00
|
|
|
import gym
|
|
|
|
import numpy as np
|
2020-09-12 15:39:01 +08:00
|
|
|
from typing import Any, List, Callable, Tuple, Optional
|
2020-08-19 15:00:24 +08:00
|
|
|
|
|
|
|
from tianshou.env.worker import EnvWorker
|
|
|
|
|
|
|
|
try:
|
|
|
|
import ray
|
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class RayEnvWorker(EnvWorker):
|
|
|
|
"""Ray worker used in RayVectorEnv."""
|
|
|
|
|
|
|
|
def __init__(self, env_fn: Callable[[], gym.Env]) -> None:
|
|
|
|
self.env = ray.remote(gym.Wrapper).options(num_cpus=0).remote(env_fn())
|
2021-03-02 12:28:28 +08:00
|
|
|
super().__init__(env_fn)
|
2020-08-19 15:00:24 +08:00
|
|
|
|
2020-08-27 12:15:18 +08:00
|
|
|
def __getattr__(self, key: str) -> Any:
|
2020-08-19 15:00:24 +08:00
|
|
|
return ray.get(self.env.__getattr__.remote(key))
|
|
|
|
|
|
|
|
def reset(self) -> Any:
|
|
|
|
return ray.get(self.env.reset.remote())
|
|
|
|
|
|
|
|
@staticmethod
|
2020-09-13 19:31:50 +08:00
|
|
|
def wait( # type: ignore
|
2021-03-30 16:06:03 +08:00
|
|
|
workers: List["RayEnvWorker"], wait_num: int, timeout: Optional[float] = None
|
2020-09-12 15:39:01 +08:00
|
|
|
) -> List["RayEnvWorker"]:
|
2020-08-19 15:00:24 +08:00
|
|
|
results = [x.result for x in workers]
|
2021-03-02 12:28:28 +08:00
|
|
|
ready_results, _ = ray.wait(results, num_returns=wait_num, timeout=timeout)
|
2020-08-19 15:00:24 +08:00
|
|
|
return [workers[results.index(result)] for result in ready_results]
|
|
|
|
|
|
|
|
def send_action(self, action: np.ndarray) -> None:
|
|
|
|
# self.action is actually a handle
|
|
|
|
self.result = self.env.step.remote(action)
|
|
|
|
|
2021-03-02 12:28:28 +08:00
|
|
|
def get_result(self) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
2020-08-19 15:00:24 +08:00
|
|
|
return ray.get(self.result)
|
|
|
|
|
2021-03-02 12:28:28 +08:00
|
|
|
def seed(self, seed: Optional[int] = None) -> List[int]:
|
|
|
|
super().seed(seed)
|
|
|
|
return ray.get(self.env.seed.remote(seed))
|
2020-08-19 15:00:24 +08:00
|
|
|
|
2020-09-12 15:39:01 +08:00
|
|
|
def render(self, **kwargs: Any) -> Any:
|
2021-03-02 12:28:28 +08:00
|
|
|
return ray.get(self.env.render.remote(**kwargs))
|
2020-08-19 15:00:24 +08:00
|
|
|
|
|
|
|
def close_env(self) -> None:
|
|
|
|
ray.get(self.env.close.remote())
|