Source code for joltsim.envs.a1_walk

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 A1WalkEnv(JoltVectorEnv): """Floating-base 12-DoF Unitree A1 quadruped locomotion environment.""" def __init__( self, num_envs: int = 16, num_threads: int = 0, urdf_path: str | Path | None = None, max_episode_steps: int = 300, ) -> None: if urdf_path is None: urdf_path = get_asset_path("a1/a1.urdf") cfg = joltsim.SolverConfig() cfg.num_velocity_steps = 16 cfg.num_position_steps = 4 cfg.max_bodies = 64 cfg.max_body_pairs = 512 cfg.max_contact_constraints = 256 vw = joltsim.VecWorld(num_envs=num_envs, num_threads=num_threads, config=cfg) vw.add_ground_plane(z=0.0, friction=1.0) model = joltsim.load_urdf( urdf_path, base_pos=(0.0, 0.0, 0.35), fixed_base=False, default_kp=80.0, default_kd=3.0 ) vw.add_articulation(model.desc) vw.optimize_broadphase() self._nominal = np.tile(np.array([0.0, 0.9, -1.8], dtype=np.float32), 4) self._last_actions = np.zeros((num_envs, 12), dtype=np.float32) obs_dim = 1 + 4 + 3 + 3 + 12 + 12 # trunk_z, quat, linvel, angvel, q_j, dq_j 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=(12,), dtype=np.float32) 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: self._last_actions[env_ids] = 0.0 self.vec_world.ctrl[env_ids] = self._nominal def _apply_actions(self, actions: np.ndarray) -> None: self._last_actions[:] = actions self.vec_world.ctrl[:] = self._nominal + 0.4 * actions def _compute_observations(self) -> np.ndarray: qpos = self.vec_world.qpos qvel = self.vec_world.qvel trunk_z = qpos[:, 2:3] trunk_quat = qpos[:, 3:7] linvel = np.clip(qvel[:, 0:3], -10.0, 10.0) angvel = np.clip(qvel[:, 3:6], -10.0, 10.0) jpos = qpos[:, 7:19] jvel = np.clip(qvel[:, 6:18], -20.0, 20.0) return np.concatenate([trunk_z, trunk_quat, linvel, angvel, jpos, jvel], axis=1).astype(np.float32) def _compute_rewards_and_dones(self) -> Tuple[np.ndarray, np.ndarray]: qpos = self.vec_world.qpos qvel = self.vec_world.qvel vx = qvel[:, 0] trunk_z = qpos[:, 2] # Uprightness from quaternion z-axis dot world z: 1 - 2*(qx^2 + qy^2) up_z = 1.0 - 2.0 * (qpos[:, 3] ** 2 + qpos[:, 4] ** 2) act_pen = 0.01 * np.sum(self._last_actions ** 2, axis=1) fallen = (trunk_z < 0.16) | (up_z < 0.35) rewards = (vx + 0.25 * up_z - act_pen - 2.0 * fallen.astype(np.float32)).astype(np.float32) return rewards, fallen