|
| 1 | +import gymnasium as gym |
| 2 | +from gymnasium import spaces |
| 3 | +import pybullet as p |
| 4 | +import pybullet_data |
| 5 | +import numpy as np |
| 6 | + |
| 7 | +class simpleBipedEnv(gym.Env): |
| 8 | + def __init__(self, render=False, max_steps=1000): |
| 9 | + super(simpleBipedEnv, self).__init__() |
| 10 | + self.render_mode = render |
| 11 | + self.physicsClient = p.connect(p.GUI if render else p.DIRECT) |
| 12 | + p.setAdditionalSearchPath(pybullet_data.getDataPath()) |
| 13 | + |
| 14 | + num_joints = 2 # left_hip, right_hip |
| 15 | + self.action_space = spaces.Box(low=-1, high=1, shape=(num_joints,), dtype=np.float32) |
| 16 | + self.observation_space = spaces.Box(low=-np.inf, high=np.inf, shape=(2*num_joints + 6,), dtype=np.float32) |
| 17 | + self.max_steps = max_steps |
| 18 | + self.current_step = 0 |
| 19 | + self.last_action = None |
| 20 | + |
| 21 | + |
| 22 | + |
| 23 | + def reset(self, seed=None, options=None): |
| 24 | + p.resetSimulation() |
| 25 | + p.setGravity(0, 0, -9.8) |
| 26 | + plane_id = p.loadURDF("plane.urdf") |
| 27 | + self.robot_id = p.loadURDF("walkers/simple_biped.urdf", [0, 0, 1.0]) |
| 28 | + base_pos = p.getBasePositionAndOrientation(self.robot_id)[0] |
| 29 | + print(f"Robot spawned at position: {base_pos}") |
| 30 | + self.current_step = 0 |
| 31 | + return self._get_obs(), {} |
| 32 | + |
| 33 | + def step(self, action): |
| 34 | + num_joints = p.getNumJoints(self.robot_id) |
| 35 | + if np.isscalar(action) or (isinstance(action, np.ndarray) and action.shape == (1,)): |
| 36 | + action = np.full((num_joints,), action if np.isscalar(action) else action[0], dtype=np.float32) |
| 37 | + else: |
| 38 | + action = np.asarray(action, dtype=np.float32) |
| 39 | + if action.shape[0] != num_joints: |
| 40 | + raise ValueError(f"Action shape {action.shape} does not match number of joints {num_joints}") |
| 41 | + |
| 42 | + self.last_action = action |
| 43 | + |
| 44 | + p.setJointMotorControlArray( |
| 45 | + bodyUniqueId=self.robot_id, |
| 46 | + jointIndices=list(range(num_joints)), |
| 47 | + controlMode=p.TORQUE_CONTROL, |
| 48 | + forces=action.tolist() |
| 49 | + ) |
| 50 | + p.stepSimulation() |
| 51 | + obs = self._get_obs() |
| 52 | + reward = self._compute_reward() |
| 53 | + done = self._check_termination() |
| 54 | + |
| 55 | + self.current_step += 1 |
| 56 | + truncated = self.current_step >= self.max_steps |
| 57 | + |
| 58 | + return obs, reward, done, truncated, {} |
| 59 | + |
| 60 | + def _get_obs(self): |
| 61 | + joint_states = p.getJointStates(self.robot_id, range(p.getNumJoints(self.robot_id))) |
| 62 | + joint_positions = [state[0] for state in joint_states] |
| 63 | + joint_velocities = [state[1] for state in joint_states] |
| 64 | + base_pos, base_ori = p.getBasePositionAndOrientation(self.robot_id) |
| 65 | + base_vel, base_ang_vel = p.getBaseVelocity(self.robot_id) |
| 66 | + return np.array(joint_positions + joint_velocities + list(base_pos) + list(base_vel), dtype=np.float32) |
| 67 | + |
| 68 | + |
| 69 | + def _check_termination(self): |
| 70 | + base_pos = p.getBasePositionAndOrientation(self.robot_id)[0] |
| 71 | + return base_pos[2] < 0.5 # fallen |
| 72 | + |
| 73 | + def _compute_reward(self): |
| 74 | + base_pos, _ = p.getBasePositionAndOrientation(self.robot_id) |
| 75 | + base_vel, _ = p.getBaseVelocity(self.robot_id) |
| 76 | + |
| 77 | + forward_reward = base_vel[0] # reward x velocity |
| 78 | + alive_bonus = 0.5 # encourage staying up |
| 79 | + torque_penalty = 0.001 * np.sum(np.square(self.last_action)) |
| 80 | + |
| 81 | + return forward_reward + alive_bonus - torque_penalty |
| 82 | + |
| 83 | + |
| 84 | + def render(self): |
| 85 | + if self.render_mode: |
| 86 | + if hasattr(self, 'robot_id'): |
| 87 | + base_pos = p.getBasePositionAndOrientation(self.robot_id)[0] |
| 88 | + p.resetDebugVisualizerCamera( |
| 89 | + cameraDistance=2.0, |
| 90 | + cameraYaw=45, |
| 91 | + cameraPitch=-30, |
| 92 | + cameraTargetPosition=base_pos |
| 93 | + ) |
| 94 | + else: |
| 95 | + pass |
| 96 | + |
| 97 | + def close(self): |
| 98 | + p.disconnect() |
0 commit comments