Okay, let's create a recipe for training a humanoid robot in PyBullet using Reinforcement Learning. This will involve:
Setting up the PyBullet Environment: Loading the humanoid model and a ground plane.
Defining the RL Environment Interface: Using the gymnasium (the maintained fork of OpenAI Gym) standard. This includes defining observation space, action space, reward function, and termination conditions.
Integrating with an RL Library: Using Stable Baselines3 (SB3) as a popular and easy-to-use choice for training.
Assumptions:
You want the humanoid to learn a basic behavior like standing or walking forward.
You have Python installed.
You're comfortable with basic Python programming and the concept of Reinforcement Learning.
Recipe: PyBullet Humanoid RL Training
Phase 1: Installation
bash
pip install pybullet numpy gymnasium stable-baselines3 torch # Or tensorflow if you prefer
Phase 2: The Gymnasium Environment (humanoid_env.py)
This file defines how the RL agent interacts with the PyBullet simulation.
python
import pybullet as p
import pybullet_data
import gymnasium as gym
from gymnasium import spaces
import numpy as np
import math
import time # Optional: for rendering delay
class HumanoidEnv(gym.Env):
"""
Custom PyBullet Environment for a Humanoid Robot based on Gymnasium API.
Goal: Learn to stand up and potentially walk forward.
"""
metadata = {'render_modes': ['human', 'rgb_array'], 'render_fps': 50}
def __init__(self, render_mode=None):
super().__init__()
self.render_mode = render_mode
self._physics_client_id = -1 # Store client ID for cleanup
# --- PyBullet Setup ---
if self.render_mode == 'human':
self._physics_client_id = p.connect(p.GUI)
p.configureDebugVisualizer(p.COV_ENABLE_GUI, 0) # Disable default GUI elements
else:
self._physics_client_id = p.connect(p.DIRECT)
p.setAdditionalSearchPath(pybullet_data.getDataPath())
p.setGravity(0, 0, -9.81)
p.setPhysicsEngineParameter(fixedTimeStep=1.0/240.0, numSubSteps=4) # Standard simulation params
# Load plane and humanoid
p.loadURDF("plane.urdf")
start_pos = [0, 0, 1.3] # Initial height
start_orientation = p.getQuaternionFromEuler([0, 0, 0])
# Use the built-in humanoid URDF
# You might need to adjust the path if pybullet_data isn't set up correctly
# or use your own custom humanoid URDF
try:
self.humanoid_id = p.loadURDF("humanoid/humanoid.urdf",
start_pos, start_orientation,
physicsClientId=self._physics_client_id)
except p.error as e:
print("\n" + "="*20)
print("Error loading humanoid URDF. Common causes:")
print("1. pybullet_data is not found. Ensure pybullet installed correctly.")
print(f" (Looking in: {pybullet_data.getDataPath()})")
print("2. The specific 'humanoid/humanoid.urdf' file is missing/corrupted.")
print("Original error:", e)
print("="*20 + "\n")
raise
# --- Get Joint Information ---
self.num_joints = p.getNumJoints(self.humanoid_id, physicsClientId=self._physics_client_id)
self.joint_indices = []
self.active_joint_indices = [] # Joints that are controllable (not fixed)
self.joint_ll = [] # Lower limits
self.joint_ul = [] # Upper limits
self.joint_ranges = []
for i in range(self.num_joints):
info = p.getJointInfo(self.humanoid_id, i, physicsClientId=self._physics_client_id)
joint_type = info[2]
if joint_type in [p.JOINT_REVOLUTE, p.JOINT_PRISMATIC]: # Only control non-fixed joints
self.joint_indices.append(i)
ll, ul = info[8], info[9] # Lower and upper limits
self.joint_ll.append(ll)
self.joint_ul.append(ul)
self.joint_ranges.append(ul - ll)
self.active_joint_indices.append(i) # Keep track for actions
self.num_active_joints = len(self.active_joint_indices)
print(f"Humanoid loaded with {self.num_joints} total joints, {self.num_active_joints} controllable joints.")
# --- Define Observation Space ---
# Example: Base position (z), orientation (quat), base velocities (lin/ang), joint angles, joint velocities
obs_dim = 3 + 4 + 3 + 3 + self.num_active_joints + self.num_active_joints
obs_low = np.full(obs_dim, -np.inf, dtype=np.float32)
obs_high = np.full(obs_dim, np.inf, dtype=np.float32)
self.observation_space = spaces.Box(obs_low, obs_high, dtype=np.float32)
# --- Define Action Space ---
# Typically torque control or position control for joints
# Using position control here for simplicity (requires tuning PD gains potentially)
# Action = target position for each controllable joint
action_dim = self.num_active_joints
action_low = np.array(self.joint_ll, dtype=np.float32)
action_high = np.array(self.joint_ul, dtype=np.float32)
# It's often better to normalize actions to [-1, 1] and scale them later
self.action_scale = (action_high - action_low) / 2.0
self.action_bias = (action_high + action_low) / 2.0
self.action_space = spaces.Box(low=-1.0, high=1.0, shape=(action_dim,), dtype=np.float32)
# --- State Variables (Optional but useful) ---
self.step_counter = 0
self.max_steps = 1000 # Max steps per episode
def _get_observation(self):
"""Collects the current state of the humanoid."""
base_pos, base_orn_quat = p.getBasePositionAndOrientation(self.humanoid_id, physicsClientId=self._physics_client_id)
base_lin_vel, base_ang_vel = p.getBaseVelocity(self.humanoid_id, physicsClientId=self._physics_client_id)
joint_states = p.getJointStates(self.humanoid_id, self.active_joint_indices, physicsClientId=self._physics_client_id)
joint_pos = [state[0] for state in joint_states]
joint_vel = [state[1] for state in joint_states]
# Simple observation: z-pos, orientation, linear/angular vel, joint pos, joint vel
observation = np.concatenate([
[base_pos[2]], # Only z-position might be enough
base_orn_quat,
base_lin_vel,
base_ang_vel,
joint_pos,
joint_vel
]).astype(np.float32)
return observation
def _compute_reward(self, base_pos, base_orn_quat, base_lin_vel):
"""Calculates the reward for the current state."""
# --- Reward Components ---
# 1. Stay Alive Bonus: Encourage not falling
alive_bonus = 0.5
# 2. Upright Bonus: Reward keeping the torso upright
# Convert quaternion to Euler angles to check pitch/roll
base_orn_euler = p.getEulerFromQuaternion(base_orn_quat)
roll, pitch = base_orn_euler[0], base_orn_euler[1]
# Penalize deviation from upright (0 roll, 0 pitch)
upright_penalty = -1.0 * (abs(roll) + abs(pitch)) # Adjust coefficient as needed
# 3. Height Reward: Encourage staying at a certain height
target_height = 1.2 # Target CoM height
height_reward = 1.0 * (1.0 / (1.0 + (base_pos[2] - target_height)**2)) # Closer = better
# 4. Forward Progress Reward (Optional: for walking)
forward_velocity = base_lin_vel[0] # Velocity along X-axis
progress_reward = 1.5 * forward_velocity # Adjust coefficient
# 5. Action Cost (Optional: penalize large actions/torques)
# If using torque control, p.getJointStates gives applied torque (index 3)
# If using position control, penalize large *changes* in action or just action magnitude
# action_cost = -0.001 * np.mean(np.square(self.last_action)) # Example if last_action is stored
# --- Combine Rewards ---
# Focus on standing first: alive + upright + height
reward = alive_bonus + upright_penalty + height_reward #+ progress_reward #+ action_cost
# Example for walking:
# reward = alive_bonus + 0.5 * upright_penalty + 0.1 * height_reward + progress_reward # + action_cost
return reward
def _is_terminated(self, base_pos, base_orn_quat):
"""Checks if the episode should end (e.g., humanoid fell)."""
# Termination condition: Fell over
if base_pos[2] < 0.6: # Torso height below threshold
#print("Terminated: Fell (height too low)")
return True
# Optional: Terminate if roll/pitch is too large
base_orn_euler = p.getEulerFromQuaternion(base_orn_quat)
if abs(base_orn_euler[0]) > 1.0 or abs(base_orn_euler[1]) > 1.0: # Radians (~57 degrees)
#print("Terminated: Fell (orientation too extreme)")
return True
return False
def reset(self, seed=None, options=None):
"""Resets the environment to an initial state."""
super().reset(seed=seed) # Important for reproducibility
# Reset simulation state
start_pos = [0, 0, 1.3]
start_orientation = p.getQuaternionFromEuler([0, 0, 0])
p.resetBasePositionAndOrientation(self.humanoid_id, start_pos, start_orientation, physicsClientId=self._physics_client_id)
p.resetBaseVelocity(self.humanoid_id, [0,0,0], [0,0,0], physicsClientId=self._physics_client_id)
# Reset joint states (optional: add noise for better exploration)
initial_joint_positions = np.zeros(self.num_active_joints, dtype=np.float32)
for i, joint_index in enumerate(self.active_joint_indices):
p.resetJointState(self.humanoid_id, joint_index,
targetValue=initial_joint_positions[i], targetVelocity=0,
physicsClientId=self._physics_client_id)
# Reset internal state
self.step_counter = 0
self.last_action = np.zeros(self.action_space.shape) # For action cost calculation if needed
observation = self._get_observation()
info = {} # Can provide auxiliary info here if needed
# Ensure PD controllers are active if using POSITION_CONTROL or VELOCITY_CONTROL
# Set reasonable default gains (these often need tuning!)
# Use high position gain (kp) for position control, moderate velocity gain (kd) for damping
kp = 0.8 # Proportional gain
kd = 1.0 # Derivative gain (damping)
max_force = 100 # Max force/torque per joint motor
for joint_index in self.active_joint_indices:
p.setJointMotorControl2(self.humanoid_id, joint_index, p.POSITION_CONTROL,
# targetPosition=0, # Initial target can be 0
# targetVelocity=0,
positionGain=kp,
velocityGain=kd,
force=max_force,
physicsClientId=self._physics_client_id)
if self.render_mode == "human":
self.render()
return observation, info
def step(self, action):
"""Applies an action, steps the simulation, and returns results."""
# --- Apply Action ---
# Scale action from [-1, 1] back to joint limits/target range
# For POSITION_CONTROL, action is the target joint position
scaled_action = self.action_bias + self.action_scale * action
self.last_action = action # Store normalized action if needed for reward
# Apply position targets to joints
p.setJointMotorControlArray(
bodyUniqueId=self.humanoid_id,
jointIndices=self.active_joint_indices,
controlMode=p.POSITION_CONTROL,
targetPositions=scaled_action,
# Optionally set target velocities if using VELOCITY_CONTROL
# targetVelocities=...,
# Forces/torques are determined by PD controller based on gains set in reset()
# Can also specify max forces/torques here per joint if needed
forces=[100] * self.num_active_joints, # Example max force per joint
positionGains=[0.8] * self.num_active_joints, # kp
velocityGains=[1.0] * self.num_active_joints, # kd
physicsClientId=self._physics_client_id
)
# --- Step Simulation ---
p.stepSimulation(physicsClientId=self._physics_client_id)
self.step_counter += 1
# --- Get Results ---
observation = self._get_observation()
base_pos, base_orn_quat = p.getBasePositionAndOrientation(self.humanoid_id, physicsClientId=self._physics_client_id)
base_lin_vel, _ = p.getBaseVelocity(self.humanoid_id, physicsClientId=self._physics_client_id)
reward = self._compute_reward(base_pos, base_orn_quat, base_lin_vel)
terminated = self._is_terminated(base_pos, base_orn_quat)
truncated = self.step_counter >= self.max_steps # Episode truncated due to time limit
info = {} # Optional info dictionary
if self.render_mode == "human":
self.render()
return observation, reward, terminated, truncated, info
def render(self):
"""Renders the environment."""
if self.render_mode == 'human':
# Optional: Add a small delay for smoother viewing
time.sleep(1./self.metadata['render_fps'])
# Optional: Camera tracking
base_pos, _ = p.getBasePositionAndOrientation(self.humanoid_id, physicsClientId=self._physics_client_id)
p.resetDebugVisualizerCamera(cameraDistance=3, cameraYaw=45, cameraPitch=-30, cameraTargetPosition=base_pos, physicsClientId=self._physics_client_id)
# PyBullet handles the actual rendering loop in GUI mode
pass
elif self.render_mode == 'rgb_array':
# Return an RGB array (requires setting up camera parameters)
view_matrix = p.computeViewMatrixFromYawPitchRoll(cameraTargetPosition=[0,0,1], distance=3, yaw=90, pitch=-20, roll=0, upAxisIndex=2, physicsClientId=self._physics_client_id)
proj_matrix = p.computeProjectionMatrixFOV(fov=60, aspect=1.0, nearVal=0.1, farVal=100.0, physicsClientId=self._physics_client_id)
_, _, rgb_img, _, _ = p.getCameraImage(width=224, height=224, viewMatrix=view_matrix, projectionMatrix=proj_matrix, renderer=p.ER_BULLET_HARDWARE_OPENGL, physicsClientId=self._physics_client_id) # Use ER_TINY_RENDERER if OpenGL not available
return np.array(rgb_img) # Shape (H, W, 4), discard alpha if needed
# else: 'None' or other modes -> do nothing
def close(self):
"""Cleans up the PyBullet connection."""
if self._physics_client_id >= 0:
p.disconnect(physicsClientId=self._physics_client_id)
self._physics_client_id = -1 # Mark as disconnected
# Optional: Seed method for reproducibility if not handled by super().reset()
# def seed(self, seed=None):
# self.np_random, seed = gym.utils.seeding.np_random(seed)
# return [seed]
# --- Basic Test (Optional) ---
if __name__ == '__main__':
# Test the environment
env = HumanoidEnv(render_mode='human') # Or 'None'
obs, info = env.reset()
print("Observation space:", env.observation_space)
print("Action space:", env.action_space)
print("Initial observation shape:", obs.shape)
terminated = False
truncated = False
total_reward = 0
steps = 0
while not terminated and not truncated:
action = env.action_space.sample() # Take random actions
obs, reward, terminated, truncated, info = env.step(action)
total_reward += reward
steps += 1
if steps % 100 == 0:
print(f"Step: {steps}, Reward: {reward:.3f}, Total Reward: {total_reward:.3f}")
# env.render() # Already called in step if render_mode='human'
print(f"Episode finished after {steps} steps. Total Reward: {total_reward:.3f}")
env.close()
Phase 3: Training Script (train_humanoid.py)
This script uses Stable Baselines3 to train an agent on the environment defined above.
import time
from stable_baselines3 import PPO
from humanoid_env import HumanoidEnv # Make sure this import works
import os
# --- Configuration ---
# Make sure this matches the path where the model was saved
log_dir = "./ppo_humanoid_logs/"
model_load_path = os.path.join(log_dir, "ppo_humanoid_model.zip")
# Alternatively, load a specific checkpoint:
# checkpoint_num = 100000 # Example step number
# model_load_path = os.path.join(log_dir, f"checkpoints/ppo_humanoid_{checkpoint_num}_steps.zip")
if not os.path.exists(model_load_path):
print(f"Error: Model not found at {model_load_path}")
exit()
# --- Load Environment and Model ---
# Create a single environment instance with rendering enabled
env = HumanoidEnv(render_mode='human')
print(f"Loading model from {model_load_path}...")
model = PPO.load(model_load_path, env=env) # Pass env if needed for action/obs space checks
print("Model loaded.")
# --- Run Evaluation Loop ---
episodes = 5
for ep in range(episodes):
obs, info = env.reset()
terminated = False
truncated = False
total_reward = 0
steps = 0
print(f"\n--- Starting Episode {ep+1} ---")
while not terminated and not truncated:
# Use the model to predict the action (deterministic=True for evaluation)
action, _states = model.predict(obs, deterministic=True)
# Step the environment
obs, reward, terminated, truncated, info = env.step(action)
total_reward += reward
steps += 1
# env.render() is called inside env.step() if render_mode='human'
# Optional small delay if rendering too fast
# time.sleep(1./100)
if terminated:
print(f"Episode finished: Terminated naturally.")
if truncated:
print(f"Episode finished: Truncated (max steps reached).")
print(f"Episode {ep+1} finished after {steps} steps. Total Reward: {total_reward:.3f}")
time.sleep(1) # Pause between episodes
env.close()
print("\n--- Evaluation Complete ---")
How to Run:
Save the environment code as humanoid_env.py.
Save the training code as train_humanoid.py.
Save the evaluation code as evaluate_humanoid.py.
Run the training: python train_humanoid.py
Monitor training progress using TensorBoard: tensorboard --logdir ./ppo_humanoid_logs/ (open the provided URL in your browser).
After training (or using a checkpoint), run the evaluation: python evaluate_humanoid.py
Key Considerations & Next Steps:
Reward Shaping: This is CRUCIAL. The example reward function is basic. You'll likely need to experiment heavily with different components and coefficients to get the desired behavior (e.g., penalizing excessive joint torques, rewarding foot contact patterns for walking, rewarding specific torso orientation, adding penalties for joint limit violations).
Hyperparameter Tuning: RL algorithms (PPO, SAC, etc.) are sensitive to hyperparameters (learning_rate, batch_size, n_steps, network architecture, gamma, gae_lambda, etc.). You'll need to tune these. Tools like Optuna can help automate this.
Observation Space: The provided observation space is standard but might be insufficient or too complex. Consider adding/removing elements (e.g., foot contact sensors, relative target position for goal-conditioned tasks). Normalizing observations (e.g., using VecNormalize wrapper in SB3) is often beneficial.
Action Space/Control Mode:
Position Control (used here): Simpler to start, relies on PyBullet's internal PD controllers. Requires tuning positionGain (kp) and velocityGain (kd) in the environment (reset or step function). High kp can lead to jerky movements, low kp might not overcome dynamics. kd provides damping.
Torque Control: More direct physics control, often preferred for dynamic tasks but harder to learn initially. The action space would represent joint torques. Requires careful reward shaping to avoid excessive forces.
Humanoid Model: The default humanoid.urdf is quite complex. You might start with simpler bipeds or modify the URDF if needed.
Stability: Humanoid control is inherently unstable. Training can take a long time (millions or tens of millions of steps). Parallel environments (num_envs > 1) significantly speed this up.
Termination Conditions: Fine-tune when an episode ends (e.g., height thresholds, orientation limits). Early termination for bad states speeds up learning.
Curriculum Learning: Start with an easier task (e.g., just balancing) and gradually increase complexity (e.g., walking slowly, then faster).
RL Algorithm Choice: PPO is robust, but other algorithms like SAC (Soft Actor-Critic) or TD3 (Twin Delayed Deep Deterministic Policy Gradient) are also popular for continuous control and might perform better on certain tasks.
This recipe provides a solid starting point. Be prepared for significant experimentation and tuning to achieve robust humanoid locomotion! Good luck!
import os
from stable_baselines3 import PPO # Or SAC, TD3 etc.
from stable_baselines3.common.env_util import make_vec_env
from stable_baselines3.common.vec_env import SubprocVecEnv # For parallel environments
from stable_baselines3.common.callbacks import CheckpointCallback
# Import the custom environment
from humanoid_env import HumanoidEnv
# --- Configuration ---
env_id = "HumanoidEnv-v0" # Can register env with gymnasium later if desired
log_dir = "./ppo_humanoid_logs/" # Directory to save logs and models
model_save_path = os.path.join(log_dir, "ppo_humanoid_model")
checkpoint_save_path = os.path.join(log_dir, "checkpoints/")
os.makedirs(log_dir, exist_ok=True)
os.makedirs(checkpoint_save_path, exist_ok=True)
# Training parameters
total_timesteps = 2_000_000 # Adjust as needed (humanoids often require millions)
num_envs = 8 # Number of parallel environments (adjust based on CPU cores)
learning_rate = 3e-4 # Typical starting point for PPO
batch_size = 64 # PPO's minibatch size
n_steps = 2048 # Steps per environment per policy update (PPO buffer size = n_envs * n_steps)
checkpoint_freq = 50000 # Save a checkpoint every N steps (total steps = N * num_envs)
# --- Create Environment ---
# Use make_vec_env for vectorized environments (faster training)
# Use SubprocVecEnv for true parallelism (requires if __name__ == '__main__': guard)
if __name__ == "__main__": # Necessary for SubprocVecEnv
vec_env = make_vec_env(lambda: HumanoidEnv(), n_envs=num_envs, vec_env_cls=SubprocVecEnv)
# --- Setup Callbacks ---
# Save checkpoints during training
checkpoint_callback = CheckpointCallback(
save_freq=max(checkpoint_freq // num_envs, 1), # Adjust frequency based on n_envs
save_path=checkpoint_save_path,
name_prefix="ppo_humanoid",
save_replay_buffer=False, # Usually False for on-policy algorithms like PPO
save_vecnormalize=True, # Save normalization stats if VecNormalize wrapper is used
)
# --- Initialize Agent ---
# PPO is a good default for continuous control in PyBullet
# MlpPolicy uses standard Multi-Layer Perceptrons for actor and critic networks
# You might need to tune hyperparameters (learning_rate, n_steps, batch_size, gamma, gae_lambda, etc.)
model = PPO(
"MlpPolicy",
vec_env,
verbose=1, # Print training progress (0=silent, 1=info, 2=debug)
learning_rate=learning_rate,
n_steps=n_steps,
batch_size=batch_size,
n_epochs=10, # Number of optimization epochs per PPO update
gamma=0.99, # Discount factor
gae_lambda=0.95, # Factor for Generalized Advantage Estimation
clip_range=0.2, # PPO clipping parameter
ent_coef=0.0, # Entropy coefficient (can encourage exploration)
vf_coef=0.5, # Value function coefficient
max_grad_norm=0.5, # Max gradient norm for clipping
tensorboard_log=log_dir
)
# --- Train Agent ---
print("Starting training...")
model.learn(
total_timesteps=total_timesteps,
callback=checkpoint_callback,
log_interval=10, # Log stats every 10 updates
tb_log_name="PPO_Humanoid"
)
# --- Save Final Model ---
print("Training finished. Saving final model...")
model.save(model_save_path)
print(f"Model saved to {model_save_path}")
# --- Clean up Environment ---
vec_env.close() # Important to close the vectorized environment
print("--- Training Script Complete ---")
print(f"To view training logs: tensorboard --logdir {log_dir}")
print(f"To load and test the trained model, see the 'evaluate_humanoid.py' example.")