from __future__ import annotations
from pathlib import Path
from typing import Tuple
import gymnasium as gym
import numpy as np
import joltsim
from joltsim.assets import get_asset_path
from joltsim.gym import JoltVectorEnv
[docs]
class ClutteredGraspEnv(JoltVectorEnv):
"""Franka Panda + 30 dynamic tabletop clutter objects + target cube."""
def __init__(
self,
num_envs: int = 16,
num_threads: int = 0,
num_clutter: int = 30,
urdf_path: str | Path | None = None,
max_episode_steps: int = 150,
) -> None:
if urdf_path is None:
urdf_path = get_asset_path("franka_panda/panda.urdf")
cfg = joltsim.SolverConfig()
cfg.num_velocity_steps = 16
cfg.num_position_steps = 4
cfg.max_bodies = 256
cfg.max_body_pairs = 4096
cfg.max_contact_constraints = 2048
vw = joltsim.VecWorld(num_envs=num_envs, num_threads=num_threads, config=cfg)
vw.add_ground_plane(z=0.0, friction=0.8)
model = joltsim.load_urdf(urdf_path, fixed_base=True, default_kp=250.0, default_kd=25.0)
vw.add_articulation(model.desc)
self._ee_body_idx = 1 + len(model.link_names) - 3
# Target cube
target_bd = joltsim.BodyDesc()
target_bd.name = "target_cube"
target_bd.pos = [0.5, 0.0, 0.04]
target_bd.mass = 0.2
ts = joltsim.ShapeDesc()
ts.type = joltsim.ShapeType.Box
ts.half_extents = [0.025, 0.025, 0.025]
target_bd.collision_shapes = [ts]
self._target_body_idx = vw.add_body(target_bd)
# Clutter objects around the workspace
for i in range(num_clutter):
bd = joltsim.BodyDesc()
bd.name = f"clutter_{i}"
gx = 0.42 + (i % 5) * 0.07
gy = -0.22 + ((i // 5) % 6) * 0.08
gz = 0.04 + (i // 30) * 0.08
bd.pos = [float(gx), float(gy), float(gz)]
bd.mass = 0.15
sd = joltsim.ShapeDesc()
if i % 2 == 0:
sd.type = joltsim.ShapeType.Box
sd.half_extents = [0.02, 0.02, 0.02]
else:
sd.type = joltsim.ShapeType.Sphere
sd.radius = 0.02
bd.collision_shapes = [sd]
vw.add_body(bd)
vw.optimize_broadphase()
self._nominal = np.array([0.0, -0.4, 0.0, -1.8, 0.0, 1.4, 0.7, 0.03, 0.03], dtype=np.float32)
obs_dim = 9 + 9 + 3 + 3 # qpos, qvel, ee_pos, target_pos
single_obs = gym.spaces.Box(-np.inf, np.inf, shape=(obs_dim,), dtype=np.float32)
single_act = gym.spaces.Box(-1.0, 1.0, shape=(8,), dtype=np.float32) # 7 arm + 1 gripper open/close
super().__init__(vw, single_obs, single_act, dt=1.0 / 60.0, substeps=4, max_episode_steps=max_episode_steps)
def _reset_task_envs(self, env_ids: np.ndarray) -> None:
n = len(env_ids)
pos = np.zeros((n, 3), dtype=np.float32)
pos[:, 0] = self.np_random.uniform(0.40, 0.62, size=n).astype(np.float32)
pos[:, 1] = self.np_random.uniform(-0.18, 0.18, size=n).astype(np.float32)
pos[:, 2] = 0.03
quat = np.tile(np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float32), (n, 1))
self.vec_world.set_body_poses(env_ids, self._target_body_idx, pos, quat)
self.vec_world.ctrl[env_ids] = self._nominal
def _apply_actions(self, actions: np.ndarray) -> None:
self.vec_world.ctrl[:, :7] = self._nominal[:7] + 0.8 * actions[:, :7]
grip = 0.02 * (actions[:, 7] + 1.0) # [0.0, 0.04]
self.vec_world.ctrl[:, 7] = grip
self.vec_world.ctrl[:, 8] = grip
def _compute_observations(self) -> np.ndarray:
q = self.vec_world.qpos[:, :9]
dq = np.clip(self.vec_world.qvel[:, :9], -10.0, 10.0)
ee = self.vec_world.body_pos[:, self._ee_body_idx, :]
tgt = self.vec_world.body_pos[:, self._target_body_idx, :]
return np.concatenate([q, dq, ee, tgt], axis=1).astype(np.float32)
def _compute_rewards_and_dones(self) -> Tuple[np.ndarray, np.ndarray]:
ee = self.vec_world.body_pos[:, self._ee_body_idx, :]
tgt = self.vec_world.body_pos[:, self._target_body_idx, :]
dist = np.linalg.norm(ee - tgt, axis=1)
lift = np.maximum(0.0, tgt[:, 2] - 0.03)
rewards = (-dist + 5.0 * lift).astype(np.float32)
terminated = np.zeros(self.num_envs, dtype=bool)
return rewards, terminated