Source code for joltsim.gym
from __future__ import annotations
from typing import Any, Dict, Optional, Tuple
import numpy as np
try:
import gymnasium as gym
from gymnasium.vector.utils import batch_space
except ImportError as exc:
raise ImportError(
"gymnasium is required for joltsim.gym. Install with `pip install joltsim[rl]`."
) from exc
from joltsim._core import VecWorld
[docs]
class JoltVectorEnv(gym.vector.VectorEnv):
"""Base Gymnasium VectorEnv wrapping a JoltSim VecWorld with zero-copy stepping and auto-reset."""
metadata = {"render_modes": []}
def __init__(
self,
vec_world: VecWorld,
single_observation_space: gym.Space,
single_action_space: gym.Space,
dt: float = 1.0 / 60.0,
substeps: int = 4,
max_episode_steps: int = 200,
) -> None:
self.vec_world = vec_world
self.dt = float(dt)
self.substeps = int(substeps)
self.max_episode_steps = int(max_episode_steps)
self.num_envs = int(vec_world.num_envs)
self.single_observation_space = single_observation_space
self.single_action_space = single_action_space
self.observation_space = batch_space(single_observation_space, self.num_envs)
self.action_space = batch_space(single_action_space, self.num_envs)
self._step_counts = np.zeros(self.num_envs, dtype=np.int32)
self._ep_returns = np.zeros(self.num_envs, dtype=np.float32)
super().__init__()
# Subclass hooks
def _reset_task_envs(self, env_ids: np.ndarray) -> None:
pass
def _apply_actions(self, actions: np.ndarray) -> None:
self.vec_world.ctrl[:] = actions
def _compute_observations(self) -> np.ndarray:
raise NotImplementedError
def _compute_rewards_and_dones(self) -> Tuple[np.ndarray, np.ndarray]:
raise NotImplementedError
[docs]
def reset(
self,
*,
seed: Optional[int] = None,
options: Optional[Dict[str, Any]] = None,
) -> Tuple[np.ndarray, Dict[str, Any]]:
super().reset(seed=seed, options=options)
self.vec_world.reset_all()
all_ids = np.arange(self.num_envs, dtype=np.uint32)
self._reset_task_envs(all_ids)
self._step_counts.fill(0)
self._ep_returns.fill(0.0)
obs = self._compute_observations()
return obs, {}
[docs]
def step(
self, actions: np.ndarray
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, Dict[str, Any]]:
act = np.asarray(actions, dtype=np.float32)
if act.ndim == 1:
act = act.reshape(self.num_envs, -1)
act = np.clip(act, self.action_space.low, self.action_space.high)
self._apply_actions(act)
self.vec_world.step(self.dt, self.substeps)
self._step_counts += 1
obs = self._compute_observations()
rewards, terminated = self._compute_rewards_and_dones()
self._ep_returns += rewards
truncated = self._step_counts >= self.max_episode_steps
dones = np.logical_or(terminated, truncated)
infos: Dict[str, Any] = {}
if np.any(dones):
done_ids = np.nonzero(dones)[0].astype(np.uint32)
infos["final_observation"] = obs.copy()
infos["_final_observation"] = dones.copy()
infos["episode_returns"] = self._ep_returns[done_ids].copy()
self.vec_world.reset_envs(done_ids)
self._reset_task_envs(done_ids)
self._step_counts[done_ids] = 0
self._ep_returns[done_ids] = 0.0
obs = self._compute_observations()
return obs, rewards, terminated, truncated, infos