Skip to main content

Sim-to-Real Transfer Techniques

Overview​

Sim-to-real transfer is a critical component of humanoid robotics development, enabling the transition of behaviors, models, and controllers trained in simulation to real-world humanoid robots. This chapter explores various techniques and methodologies that bridge the "reality gap" between simulation and real-world execution, focusing on humanoid-specific challenges such as complex dynamics, contact modeling, and sensor inaccuracies.

The chapter covers domain randomization, system identification, adaptive control, and practical techniques to ensure that simulation-trained models perform effectively on physical robots.

Learning Objectives​

After completing this chapter, you will be able to:

  1. Understand the challenges of sim-to-real transfer in humanoid robotics
  2. Apply domain randomization techniques to improve transfer performance
  3. Perform system identification to match simulation to reality
  4. Implement adaptive control methods for real-world deployment
  5. Evaluate and validate sim-to-real transfer performance
  6. Apply practical techniques to bridge the reality gap

Understanding the Reality Gap​

Definition and Causes​

The "reality gap" refers to the differences between simulation and real-world execution that can cause models trained in simulation to perform poorly on physical robots. In humanoid robotics, the reality gap is particularly challenging due to:

  1. Complex Dynamics: Humanoid robots have complex multi-body dynamics with many degrees of freedom
  2. Contact Modeling: Simulation often simplifies contact dynamics, which are crucial for bipedal locomotion
  3. Sensor Inaccuracies: Real sensors have noise, delays, and calibration errors not captured in simulation
  4. Actuator Limitations: Real actuators have limitations like backlash, friction, and saturation
  5. Environmental Variations: Real environments have unpredictable elements not present in simulation

Quantifying the Reality Gap​

To effectively address the reality gap, we need to quantify it:

import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist

class RealityGapAnalyzer:
"""Analyze and quantify the reality gap between simulation and reality"""

def __init__(self):
self.sim_data = []
self.real_data = []
self.metrics = {
'state_divergence': [],
'control_effort': [],
'tracking_error': []
}

def collect_data_pair(self, state_sim, state_real, action=None):
"""Collect a data pair from simulation and real robot"""
data_pair = {
'sim_state': state_sim.copy(),
'real_state': state_real.copy(),
'action': action.copy() if action is not None else None,
'timestamp': np.datetime64('now')
}
return data_pair

def calculate_state_divergence(self, sim_state, real_state):
"""Calculate divergence between simulation and real state"""
# Calculate various metrics to quantify state divergence

# Position difference
pos_diff = np.linalg.norm(sim_state[:3] - real_state[:3]) # Assuming first 3 are position

# Orientation difference (using quaternion distance)
quat_sim = sim_state[3:7] # Assuming quaternion is elements 3-6
quat_real = real_state[3:7]
quat_diff = self.quaternion_distance(quat_sim, quat_real)

# Velocity difference
vel_diff = np.linalg.norm(sim_state[7:10] - real_state[7:10]) # Assuming vel is elements 7-9

# Joint state differences (assuming joint positions start at index 10)
joint_pos_diff = np.mean(np.abs(sim_state[10:22] - real_state[10:22])) # Example for 12 joints
joint_vel_diff = np.mean(np.abs(sim_state[22:34] - real_state[22:34])) # Example for 12 joint velocities

# Combine metrics
total_divergence = pos_diff + quat_diff + vel_diff + joint_pos_diff + joint_vel_diff
return {
'position': pos_diff,
'orientation': quat_diff,
'velocity': vel_diff,
'joint_positions': joint_pos_diff,
'joint_velocities': joint_vel_diff,
'total': total_divergence
}

def quaternion_distance(self, q1, q2):
"""Calculate distance between two quaternions"""
# Using geodesic distance on quaternion manifold
dot_product = np.dot(q1, q2)
dot_product = np.clip(dot_product, -1.0, 1.0) # Numerical stability
return 2 * np.arccos(np.abs(dot_product))

def calculate_tracking_error(self, desired_state, actual_state):
"""Calculate error in tracking a desired state trajectory"""
# Position tracking error
pos_error = np.linalg.norm(desired_state[:3] - actual_state[:3])

# Orientation tracking error
quat_desired = desired_state[3:7]
quat_actual = actual_state[3:7]
orientation_error = self.quaternion_distance(quat_desired, quat_actual)

# Velocity tracking error
vel_error = np.linalg.norm(desired_state[7:10] - actual_state[7:10])

total_error = pos_error + orientation_error + vel_error
return {
'position': pos_error,
'orientation': orientation_error,
'velocity': vel_error,
'total': total_error
}

def evaluate_transfer_performance(self, policy, num_episodes=10):
"""Evaluate how well a policy transfers from sim to real"""
transfer_scores = []

for episode in range(num_episodes):
# Reset both sim and real
sim_state = self.reset_simulation()
real_state = self.reset_real_robot()

episode_score = 0
episode_length = 0

# Run policy for fixed number of steps
for step in range(500): # Fixed horizon
# Get action from policy based on sim state
action = policy.select_action(sim_state)

# Apply action in both sim and real
sim_next_state = self.apply_action_sim(sim_state, action)
real_next_state = self.apply_action_real(real_state, action)

# Calculate divergence and tracking error
divergence = self.calculate_state_divergence(sim_next_state, real_next_state)
tracking_error = self.calculate_tracking_error(sim_next_state, real_next_state)

# Aggregate metrics
episode_score += (1.0 - divergence['total']) * (1.0 - tracking_error['total'])
episode_length += 1

# Update states
sim_state = sim_next_state
real_state = real_next_state

# Check termination conditions
if (self.is_termination_state(sim_state) or
self.is_termination_state(real_state)):
break

# Normalize by episode length
normalized_score = episode_score / max(episode_length, 1)
transfer_scores.append(normalized_score)

# Calculate overall transfer performance
mean_score = np.mean(transfer_scores)
std_score = np.std(transfer_scores)

return {
'mean_transfer_score': mean_score,
'std_transfer_score': std_score,
'transfer_scores': transfer_scores,
'reliability': np.sum(np.array(transfer_scores) > 0.5) / len(transfer_scores) # Fraction above threshold
}

def plot_reality_gap_analysis(self):
"""Plot analysis of the reality gap"""
fig, axes = plt.subplots(2, 2, figsize=(15, 10))

# Plot state divergence over time
if len(self.metrics['state_divergence']) > 0:
axes[0, 0].plot(self.metrics['state_divergence'])
axes[0, 0].set_title('State Divergence Over Time')
axes[0, 0].set_xlabel('Time Step')
axes[0, 0].set_ylabel('Divergence')

# Plot control effort
if len(self.metrics['control_effort']) > 0:
axes[0, 1].plot(self.metrics['control_effort'])
axes[0, 1].set_title('Control Effort Over Time')
axes[0, 1].set_xlabel('Time Step')
axes[0, 1].set_ylabel('Effort')

# Plot tracking error
if len(self.metrics['tracking_error']) > 0:
axes[1, 0].plot(self.metrics['tracking_error'])
axes[1, 0].set_title('Tracking Error Over Time')
axes[1, 0].set_xlabel('Time Step')
axes[1, 0].set_ylabel('Error')

# Plot histogram of divergence
if len(self.metrics['state_divergence']) > 0:
axes[1, 1].hist(self.metrics['state_divergence'], bins=50)
axes[1, 1].set_title('Histogram of State Divergence')
axes[1, 1].set_xlabel('Divergence')
axes[1, 1].set_ylabel('Frequency')

plt.tight_layout()
plt.show()

def system_identification_example():
"""Example of quantifying the reality gap"""
analyzer = RealityGapAnalyzer()

# Simulate some example data collection
np.random.seed(42) # For reproducible results

# Generate example states (simulated vs real differences)
n_samples = 100
sim_states = np.random.randn(n_samples, 34) # Example state dimension
real_states = sim_states + np.random.randn(n_samples, 34) * 0.1 # Add noise to simulate reality gap

# Calculate divergences
divergences = []
for i in range(n_samples):
div = analyzer.calculate_state_divergence(sim_states[i], real_states[i])
divergences.append(div['total'])

print(f"Mean state divergence: {np.mean(divergences):.4f}")
print(f"Std of state divergence: {np.std(divergences):.4f}")

return divergences

if __name__ == "__main__":
divergences = system_identification_example()

Domain Randomization​

Principles of Domain Randomization​

Domain randomization is a technique that randomizes simulation parameters during training to make models robust to variations in the real world. For humanoid robots, this could include:

  • Physics parameters (mass, friction, damping)
  • Control parameters (latency, noise)
  • Sensor parameters (noise, delay, bias)
  • Environmental parameters (terrain, lighting)
import pybullet as p
import numpy as np
import random

class DomainRandomizer:
"""Implementation of domain randomization for humanoid simulation"""

def __init__(self, robot_id):
self.robot_id = robot_id
self.params = {
# Physical parameters
'gravity_range': (-10.1, -9.7),
'friction_range': (0.4, 1.6),
'restitution_range': (0.0, 0.2),
'mass_multiplier_range': (0.8, 1.2),
'damping_range': (0.0, 0.1),

# Control parameters
'control_latency_range': (0.0, 0.05), # seconds
'actuator_noise_range': (0.001, 0.01),
'sensor_noise_std_range': (0.001, 0.01),

# Environment parameters
'ground_roughness_range': (0.0, 0.05),
'wind_force_range': (0.0, 5.0) # Newtons
}

self.original_params = self.get_current_params()

def randomize_all(self, physics_client_id=None):
"""Randomize all parameters for domain randomization"""
client_id = physics_client_id or p.SHARED_MEMORY_KEY

# Randomize gravity
gravity_z = random.uniform(*self.params['gravity_range'])
p.setGravity(0, 0, gravity_z, physicsClientId=client_id)

# Randomize robot dynamics
self.randomize_robot_dynamics()

# Randomize ground properties
self.randomize_ground_properties()

# Randomize environmental conditions
self.randomize_environment()

def randomize_robot_dynamics(self):
"""Randomize robot dynamics parameters"""
for joint_id in range(p.getNumJoints(self.robot_id)):
# Randomize link mass
dynamics_info = p.getDynamicsInfo(self.robot_id, joint_id)
original_mass = dynamics_info[0]
mass_multiplier = random.uniform(*self.params['mass_multiplier_range'])
new_mass = original_mass * mass_multiplier

# Randomize friction
friction = random.uniform(*self.params['friction_range'])

# Randomize damping
linear_damping = random.uniform(*self.params['damping_range'])
angular_damping = random.uniform(*self.params['damping_range'])

# Apply new parameters
p.changeDynamics(
self.robot_id,
joint_id,
mass=new_mass,
lateralFriction=friction,
linearDamping=linear_damping,
angularDamping=angular_damping
)

def randomize_ground_properties(self):
"""Randomize ground properties"""
# For the ground plane, randomize friction
ground_friction = random.uniform(*self.params['friction_range'])
# Assuming ground is at link index -1 (base) or we can identify it
# This is a simplified approach - in practice, you'd identify the ground object
pass

def randomize_environment(self):
"""Randomize environmental conditions"""
# Add random wind force
wind_force = random.uniform(*self.params['wind_force_range'])
wind_direction = np.random.uniform(-1, 1, 3)
wind_direction = wind_direction / np.linalg.norm(wind_direction) # Normalize

# Apply wind force to base of robot
# This is a simplified approach - in practice, you'd apply forces more realistically
pass

def get_current_params(self):
"""Get current parameter values"""
current_params = {}

# For each joint, store dynamics info
for joint_id in range(p.getNumJoints(self.robot_id)):
dynamics_info = p.getDynamicsInfo(self.robot_id, joint_id)
current_params[joint_id] = {
'mass': dynamics_info[0],
'lateral_friction': dynamics_info[1],
'rolling_friction': dynamics_info[7],
'spinning_friction': dynamics_info[8]
}

return current_params

def restore_original_params(self):
"""Restore original parameters"""
for joint_id, params in self.original_params.items():
p.changeDynamics(
self.robot_id,
joint_id,
mass=params['mass'],
lateralFriction=params['lateral_friction'],
rollingFriction=params['rolling_friction'],
spinningFriction=params['spinning_friction']
)

class AdvancedDomainRandomizer(DomainRandomizer):
"""Advanced domain randomization with curriculum"""

def __init__(self, robot_id, curriculum_steps=100000):
super().__init__(robot_id)
self.curriculum_steps = curriculum_steps
self.current_step = 0

# Define curriculum stages
self.curriculum_stages = [
{'range_multiplier': 0.2}, # Start with small variations
{'range_multiplier': 0.5}, # Increase to medium variations
{'range_multiplier': 0.8}, # Increase to large variations
{'range_multiplier': 1.0} # Full variations
]

self.current_stage = 0
self.steps_per_stage = curriculum_steps // len(self.curriculum_stages)

def get_curriculum_multiplier(self):
"""Get the current curriculum multiplier"""
stage_idx = min(self.current_step // self.steps_per_stage, len(self.curriculum_stages) - 1)
return self.curriculum_stages[stage_idx]['range_multiplier']

def randomize_all(self, physics_client_id=None):
"""Randomize parameters with curriculum adjustment"""
client_id = physics_client_id or p.SHARED_MEMORY_KEY
mult = self.get_curriculum_multiplier()

# Adjust ranges based on curriculum
adjusted_params = self.adjust_ranges_for_curriculum(mult)

# Apply adjusted randomization
gravity_z = random.uniform(*adjusted_params['gravity_range'])
p.setGravity(0, 0, gravity_z, physicsClientId=client_id)

self.randomize_robot_dynamics_curriculum(adjusted_params)

# Update step counter
self.current_step += 1

def adjust_ranges_for_curriculum(self, multiplier):
"""Adjust parameter ranges based on curriculum"""
adjusted = {}
for key, range_val in self.params.items():
center = (range_val[0] + range_val[1]) / 2
radius = (range_val[1] - range_val[0]) / 2
new_radius = radius * multiplier
adjusted[key] = (center - new_radius, center + new_radius)
return adjusted

def randomize_robot_dynamics_curriculum(self, params):
"""Randomize robot dynamics with curriculum parameters"""
for joint_id in range(p.getNumJoints(self.robot_id)):
# Apply curriculum-adjusted parameters
mass_multiplier = random.uniform(*params['mass_multiplier_range'])
friction = random.uniform(*params['friction_range'])
damping = random.uniform(*params['damping_range'])

# Get original mass and apply multiplier
dynamics_info = p.getDynamicsInfo(self.robot_id, joint_id)
new_mass = dynamics_info[0] * mass_multiplier

p.changeDynamics(
self.robot_id,
joint_id,
mass=new_mass,
lateralFriction=friction,
linearDamping=damping,
angularDamping=damping
)

Domain Randomization in Practice​

Here's a more complete implementation combining domain randomization with RL training:

import gym
from stable_baselines3 import PPO
from stable_baselines3.common.env_util import make_vec_env
from stable_baselines3.common.callbacks import BaseCallback

class DomainRandomizationCallback(BaseCallback):
"""Callback to apply domain randomization during training"""

def __init__(self, verbose=0, randomizer=None, randomize_freq=1000):
super().__init__(verbose)
self.randomizer = randomizer
self.randomize_freq = randomize_freq
self.steps_since_randomization = 0

def _on_step(self) -> bool:
self.steps_since_randomization += 1

# Randomize environment parameters periodically
if self.steps_since_randomization >= self.randomize_freq:
if self.randomizer:
self.randomizer.randomize_all()
self.steps_since_randomization = 0

return True

class HumanoidEnvWithDR(gym.Wrapper):
"""Humanoid environment wrapper with domain randomization support"""

def __init__(self, env, randomizer=None, randomize_freq=100):
super().__init__(env)
self.randomizer = randomizer
self.randomize_freq = randomize_freq
self.step_count = 0
self.episode_count = 0

def reset(self, **kwargs):
# Randomize environment at start of episode
if self.randomizer and self.episode_count % self.randomize_freq == 0:
self.randomizer.randomize_all()
self.episode_count += 1
return self.env.reset(**kwargs)

def step(self, action):
self.step_count += 1
obs, reward, done, info = self.env.step(action)
return obs, reward, done, info

def train_with_domain_randomization():
"""Example training loop with domain randomization"""
# Create environment
env = gym.make('Humanoid-v3') # Use your environment
robot_id = env.unwrapped.robot.robot_id # Assuming access to robot ID

# Create randomizer
randomizer = AdvancedDomainRandomizer(robot_id)

# Wrap environment with domain randomization
env = HumanoidEnvWithDR(env, randomizer)

# Create vectorized environment
vec_env = make_vec_env(lambda: env, n_envs=1)

# Create callback for domain randomization
dr_callback = DomainRandomizationCallback(randomizer=randomizer)

# Create and train agent
model = PPO('MlpPolicy', vec_env, verbose=1, tensorboard_log="./ppo_humanoid_dr/")

# Train with domain randomization
model.learn(
total_timesteps=1000000,
callback=dr_callback,
progress_bar=True
)

return model

# Example usage
if __name__ == "__main__":
# model = train_with_domain_randomization()
pass

System Identification and Parameter Estimation​

Robot System Identification​

System identification involves determining the actual parameters of a physical robot to match the simulation:

import numpy as np
from scipy.optimize import least_squares, minimize
from scipy.integrate import solve_ivp

class HumanoidSystemIdentifier:
"""System identification for humanoid robots to bridge sim-to-real gap"""

def __init__(self, robot_interface):
self.robot = robot_interface
self.nominal_params = self.get_nominal_parameters()
self.identification_data = {
'inputs': [],
'outputs': [],
'states': [],
'timestamps': []
}

def get_nominal_parameters(self):
"""Get nominal robot parameters"""
# This would interface with the robot to get initial parameters
# In practice, this could be from URDF or calibration process
params = {
'link_masses': [1.0] * 28, # Example: 28 links
'link_inertias': [0.1] * 28, # Simplified, would be 3x3 matrices in practice
'joint_frictions': [0.1] * 27, # 27 joints for example
'actuator_gains': [1.0] * 27,
'sensor_offsets': [0.0] * 54, # Position and velocity sensors
}
return params

def collect_identification_data(self, excitation_signal, duration=10.0):
"""Collect data for system identification using excitation signal"""
print("Collecting identification data...")

# Reset robot to initial state
self.robot.reset()

# Apply excitation signal over time
dt = 0.01 # Control timestep
time_steps = int(duration / dt)

for i in range(time_steps):
# Get current time
t = i * dt

# Generate control input based on excitation signal
if t < len(excitation_signal):
u = excitation_signal[t]
else:
u = np.zeros(self.robot.action_space.shape[0])

# Apply control input
obs, reward, done, info = self.robot.step(u)

# Store data
self.identification_data['inputs'].append(u.copy())
self.identification_data['outputs'].append(obs.copy())
self.identification_data['states'].append(self.get_robot_state())
self.identification_data['timestamps'].append(t)

if done:
break

print(f"Collected {len(self.identification_data['inputs'])} data points")

def get_robot_state(self):
"""Get full robot state for identification"""
# This would return a comprehensive state vector
# including positions, velocities, and other relevant states
joint_pos = self.robot.get_joint_positions()
joint_vel = self.robot.get_joint_velocities()
base_pos, base_orn = self.robot.get_base_pose()
base_vel, base_angular_vel = self.robot.get_base_velocity()

state = np.concatenate([
joint_pos,
joint_vel,
base_pos,
base_orn, # Could convert to euler for easier optimization
base_vel,
base_angular_vel
])
return state

def dynamics_model(self, t, state, control_input, params):
"""Dynamics model for the humanoid robot"""
# Get dimensions
n_joints = 27 # Example
state_dim = len(state)

# Extract state components
joint_pos = state[:n_joints]
joint_vel = state[n_joints:2*n_joints]
base_pos = state[2*n_joints:2*n_joints+3]
base_orn = state[2*n_joints+3:2*n_joints+7] # quaternion
base_vel = state[2*n_joints+7:2*n_joints+10]
base_angular_vel = state[2*n_joints+10:2*n_joints+13]

# Simplified dynamics model - in practice, this would be much more complex
# and involve the humanoid's full dynamics equations
joint_acc = np.zeros(n_joints)

# Apply simplified model of joint dynamics
# This is a placeholder - real implementation would use full dynamics
for i in range(n_joints):
# tau = I*alpha + friction*vel + spring_offset*pos
# alpha = (tau - friction*vel - spring_offset*pos) / I
inertia = params.get('link_inertias', [1.0]*n_joints)[i]
friction = params.get('joint_frictions', [0.1]*n_joints)[i]
actuator_gain = params.get('actuator_gains', [1.0]*n_joints)[i]

# Calculate joint acceleration
applied_torque = control_input[i] * actuator_gain if i < len(control_input) else 0
joint_acc[i] = (applied_torque - friction * joint_vel[i]) / inertia

# Base acceleration (simplified)
base_acc = np.zeros(3)
base_angular_acc = np.zeros(3)

# Concatenate derivatives
state_derivative = np.concatenate([
joint_vel, # d/dt(joint_pos) = joint_vel
joint_acc, # d/dt(joint_vel) = joint_acc
base_vel, # d/dt(base_pos) = base_vel
np.zeros(4), # d/dt(base_orn) - simplified
base_acc, # d/dt(base_vel) = base_acc
base_angular_acc # d/dt(base_angular_vel) = base_angular_acc
])

return state_derivative

def simulate_robot(self, initial_state, control_inputs, params, dt=0.01):
"""Simulate the robot with given parameters"""
states = [initial_state]
current_state = initial_state.copy()

for control_input in control_inputs:
# Integrate dynamics for one time step
def state_derivative(t, state):
return self.dynamics_model(t, state, control_input, params)

# Use a simple Euler integration for demonstration
# In practice, use more sophisticated integration
derivative = self.dynamics_model(0, current_state, control_input, params)
next_state = current_state + derivative * dt

states.append(next_state)
current_state = next_state

return np.array(states)

def objective_function(self, param_vector):
"""Objective function for parameter estimation"""
# Reshape parameter vector back to dictionary
params = self.param_vector_to_dict(param_vector)

# Extract collected data
inputs = np.array(self.identification_data['inputs'])
real_states = np.array(self.identification_data['states'])

# Simulate with current parameters
initial_state = real_states[0]
simulated_states = self.simulate_robot(initial_state, inputs, params)

# Calculate error between real and simulated states
if len(simulated_states) != len(real_states):
# Pad or truncate as needed
min_len = min(len(simulated_states), len(real_states))
simulated_states = simulated_states[:min_len]
real_states = real_states[:min_len]

# Calculate state prediction error
state_error = np.mean((simulated_states - real_states)**2)

# Add regularization to prevent overfitting
reg_term = 1e-6 * np.sum(param_vector**2)

total_error = state_error + reg_term
return total_error

def param_vector_to_dict(self, param_vector):
"""Convert parameter vector to dictionary"""
# This is a simplified example - real implementation would match actual param structure
n_joints = 27 # Example
params = {
'link_masses': param_vector[:n_joints],
'link_inertias': param_vector[n_joints:2*n_joints],
'joint_frictions': param_vector[2*n_joints:3*n_joints],
'actuator_gains': param_vector[3*n_joints:4*n_joints],
}
return params

def dict_to_param_vector(self, params):
"""Convert parameter dictionary to vector"""
# This is a simplified example
param_list = []
param_list.extend(params['link_masses'])
param_list.extend(params['link_inertias'])
param_list.extend(params['joint_frictions'])
param_list.extend(params['actuator_gains'])
return np.array(param_list)

def identify_parameters(self, bounds=None):
"""Identify robot parameters using collected data"""
if bounds is None:
# Set reasonable bounds for parameters
n_joints = 27
lower_bounds = np.concatenate([
np.ones(n_joints) * 0.1, # Mass bounds
np.ones(n_joints) * 0.01, # Inertia bounds
np.ones(n_joints) * 0.0, # Friction bounds
np.ones(n_joints) * 0.5 # Gain bounds
])

upper_bounds = np.concatenate([
np.ones(n_joints) * 5.0, # Mass bounds
np.ones(n_joints) * 0.5, # Inertia bounds
np.ones(n_joints) * 1.0, # Friction bounds
np.ones(n_joints) * 2.0 # Gain bounds
])

bounds = (lower_bounds, upper_bounds)

# Set initial parameter guess
initial_params = self.dict_to_param_vector(self.nominal_params)

print("Starting parameter identification...")
print(f"Optimizing {len(initial_params)} parameters")

# Perform optimization
result = minimize(
fun=self.objective_function,
x0=initial_params,
method='L-BFGS-B',
bounds=bounds,
options={'maxiter': 1000}
)

if result.success:
print("Parameter identification completed successfully")
print(f"Final objective value: {result.fun:.6f}")
final_params = self.param_vector_to_dict(result.x)

# Update robot model with identified parameters
self.update_robot_parameters(final_params)

return final_params
else:
print(f"Parameter identification failed: {result.message}")
return None

def update_robot_parameters(self, params):
"""Update robot parameters in simulation"""
# In practice, this would update the physics simulation parameters
# to match the identified values
print("Updating robot parameters in simulation...")
for key, value in params.items():
print(f" {key}: {np.mean(value) if hasattr(value, '__len__') else value}")

def generate_excitation_signal(duration=10.0, dt=0.01, n_joints=27):
"""Generate an excitation signal for system identification"""
time_steps = int(duration / dt)

# Generate random trajectory with different frequencies
signal = np.zeros((time_steps, n_joints))

for j in range(n_joints):
# Use different frequencies for different joints
freq = 0.5 + 2.0 * np.random.rand() # 0.5 to 2.5 Hz
amplitude = 0.5 + 0.5 * np.random.rand() # 0.5 to 1.0

time = np.arange(time_steps) * dt
# Add multiple sine waves at different frequencies
signal[:, j] = (
amplitude * np.sin(2*np.pi * freq * time) +
0.3 * amplitude * np.sin(2*np.pi * 2*freq * time) +
0.2 * amplitude * np.sin(2*np.pi * 0.5*freq * time)
)

return signal

def run_system_identification_example():
"""Run an example of the system identification process"""
print("Running system identification example...")

# In practice, you would use a real robot interface
# For this example, we'll simulate the process

# Generate excitation signal
excitation = generate_excitation_signal()
print(f"Generated excitation signal with shape: {excitation.shape}")

# Create identifier
class DummyRobotInterface:
def __init__(self):
self.action_space = type('ActionSpace', (), {'shape': (27,)})()

def reset(self):
pass

def step(self, action):
# Simulated response
obs = np.random.randn(54) # Example observation
reward = 0.0
done = False
info = {}
return obs, reward, done, info

def get_joint_positions(self):
return np.random.randn(27)

def get_joint_velocities(self):
return np.random.randn(27)

def get_base_pose(self):
return np.random.randn(3), np.random.randn(4)

def get_base_velocity(self):
return np.random.randn(3), np.random.randn(3)

robot_interface = DummyRobotInterface()
identifier = HumanoidSystemIdentifier(robot_interface)

# Collect data
identifier.collect_identification_data(excitation)

# Run identification
identified_params = identifier.identify_parameters()

if identified_params:
print("System identification completed successfully!")
for key, value in identified_params.items():
print(f" {key}: mean={np.mean(value):.4f}, std={np.std(value):.4f}")

if __name__ == "__main__":
run_system_identification_example()

Adaptive Control for Real-World Deployment​

Adaptive Control Framework​

import torch
import torch.nn as nn
import numpy as np

class AdaptiveController:
"""Adaptive controller that adjusts parameters based on real-world performance"""

def __init__(self, nominal_controller, adaptation_rate=0.01, history_length=100):
self.nominal_controller = nominal_controller
self.adaptation_rate = adaptation_rate
self.performance_history = []
self.history_length = history_length
self.adaptation_params = None

# Initialize adaptation parameters
self.reset_adaptation()

def reset_adaptation(self):
"""Reset adaptation parameters"""
# For example, initialize controller gains
self.adaptation_params = {
'proportional_gain': 1.0, # For PD controllers
'derivative_gain': 1.0,
'control_scaling': 1.0,
'disturbance_estimate': np.zeros(27) # For 27 joints example
}

def update_adaptation(self, state_error, control_error, time_step):
"""Update adaptation parameters based on errors"""
# Calculate performance metrics
performance = self.calculate_performance(state_error, control_error)
self.performance_history.append(performance)

# Keep history to a fixed length
if len(self.performance_history) > self.history_length:
self.performance_history.pop(0)

# Calculate trend in performance
if len(self.performance_history) >= 2:
performance_trend = (
self.performance_history[-1] - self.performance_history[-2]
)

# Adapt parameters based on performance trend
if performance_trend > 0.1: # Performance is degrading
# Increase robustness parameters
self.adaptation_params['proportional_gain'] *= (1 - self.adaptation_rate)
self.adaptation_params['derivative_gain'] *= (1 + self.adaptation_rate)
elif performance_trend < -0.1: # Performance is improving
# Optimize for better performance
self.adaptation_params['proportional_gain'] *= (1 + self.adaptation_rate * 0.5)
self.adaptation_params['derivative_gain'] *= (1 - self.adaptation_rate * 0.2)

def calculate_performance(self, state_error, control_error):
"""Calculate performance metric"""
# Weighted combination of state tracking and control effort
state_cost = np.mean(np.abs(state_error))
control_cost = np.mean(np.abs(control_error))

# Weight more heavily on tracking error than control effort
performance = 0.8 * (1.0 / (1.0 + state_cost)) + 0.2 * (1.0 / (1.0 + control_cost))
return performance

def get_control(self, state, reference_state):
"""Get adaptive control action"""
# Get nominal control
nominal_control = self.nominal_controller.get_control(state, reference_state)

# Apply adaptation
adapted_control = self.apply_adaptation(nominal_control, state, reference_state)

# Update adaptation based on state error
state_error = state - reference_state
self.update_adaptation(state_error, adapted_control - nominal_control, 0)

return adapted_control

def apply_adaptation(self, nominal_control, state, reference_state):
"""Apply adaptation to nominal control"""
adapted_control = nominal_control.copy()

# Apply gain scaling
adapted_control *= self.adaptation_params['control_scaling']

# Add disturbance compensation
adapted_control += self.adaptation_params['disturbance_estimate']

# Clamp to reasonable bounds
max_control = 100 # N*m example
adapted_control = np.clip(adapted_control, -max_control, max_control)

return adapted_control

class NNAdaptiveController:
"""Neural network-based adaptive controller"""

def __init__(self, state_dim, action_dim, hidden_dim=256):
self.state_dim = state_dim
self.action_dim = action_dim
self.controller_network = self.build_network(hidden_dim)
self.adaptation_network = self.build_network(hidden_dim)

# Separate optimizer for adaptation
self.adaptation_optimizer = torch.optim.Adam(
self.adaptation_network.parameters(), lr=1e-4
)

self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.controller_network.to(self.device)
self.adaptation_network.to(self.device)

def build_network(self, hidden_dim):
"""Build neural network for control adaptation"""
return nn.Sequential(
nn.Linear(self.state_dim + self.action_dim + self.state_dim, hidden_dim), # state + action + ref_state
nn.ReLU(),
nn.Linear(hidden_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, self.action_dim)
)

def get_control(self, state, reference_state, nominal_control):
"""Get adaptive control using neural network"""
state_tensor = torch.FloatTensor(state).to(self.device).unsqueeze(0)
ref_tensor = torch.FloatTensor(reference_state).to(self.device).unsqueeze(0)
nominal_tensor = torch.FloatTensor(nominal_control).to(self.device).unsqueeze(0)

# Combine state, reference, and nominal control
combined_input = torch.cat([state_tensor, ref_tensor, nominal_tensor], dim=1)

# Get adaptation offset
adaptation_offset = self.adaptation_network(combined_input)

# Apply adaptation to nominal control
adapted_control = nominal_control + adaptation_offset.cpu().data.numpy()[0]

return adapted_control


class HumanoidAdaptiveController:
"""Complete adaptive controller for humanoid robots"""

def __init__(self, robot_interface, policy_network):
self.robot_interface = robot_interface
self.policy_network = policy_network
self.adaptive_controller = None

# Initialize adaptive controller
self.setup_adaptive_control()

def setup_adaptive_control(self):
"""Setup the adaptive control system"""
# Create base controller using the policy network
class PolicyController:
def __init__(self, policy_network):
self.policy = policy_network

def get_control(self, state, reference_state):
# This would use the policy network to generate control
# For this example, we'll use a simplified approach
return np.random.randn(27) # Example: 27 joint torques

base_controller = PolicyController(self.policy_network)
self.adaptive_controller = AdaptiveController(base_controller)

def execute_control_step(self, current_state, desired_state):
"""Execute one control step with adaptation"""
# Get adaptive control action
control_action = self.adaptive_controller.get_control(
current_state, desired_state
)

# Apply control to robot
next_state, reward, done, info = self.robot_interface.step(control_action)

return next_state, control_action, done, info

# Example usage
def adaptive_control_example():
"""Example of adaptive control in practice"""
print("Setting up adaptive control system...")

# Simulate with dummy components
class DummyPolicy:
def predict(self, state):
return np.random.randn(27) # 27 joint torques

class DummyRobot:
def step(self, action):
return np.random.randn(54), 0.0, False, {}

policy = DummyPolicy()
robot = DummyRobot()

adaptive_ctrl = HumanoidAdaptiveController(robot, policy)

# Simulate execution
current_state = np.random.randn(54)
desired_state = np.random.randn(54)

for step in range(100):
next_state, control, done, info = adaptive_ctrl.execute_control_step(
current_state, desired_state
)

current_state = next_state

if step % 10 == 0:
print(f"Step {step}: Control magnitude = {np.linalg.norm(control):.4f}")

print("Adaptive control execution completed")

if __name__ == "__main__":
adaptive_control_example()

Practical Techniques for Sim-to-Real Transfer​

Reality Gap Mitigation Strategies​

class RealityGapMitigation:
"""Collection of techniques to mitigate the reality gap"""

def __init__(self):
self.techniques = {
'noise_robust_training': True,
'model_uncertainty': True,
'ensemble_methods': True,
'online_adaptation': True
}

def noise_robust_training(self, env, noise_std=0.05):
"""Add controlled noise during training to improve robustness"""
class NoisyEnvWrapper(gym.Wrapper):
def __init__(self, env, noise_std):
super().__init__(env)
self.noise_std = noise_std

def step(self, action):
# Add noise to action
noisy_action = action + np.random.normal(0, self.noise_std, action.shape)

# Add noise to observation
obs, reward, done, info = self.env.step(action) # Use clean action for sim
noisy_obs = obs + np.random.normal(0, self.noise_std, obs.shape)

return noisy_obs, reward, done, info

return NoisyEnvWrapper(env, noise_std)

def model_uncertainty_wrapper(self, base_model, num_models=5):
"""Create an ensemble of models to represent uncertainty"""
class ModelUncertaintyWrapper:
def __init__(self, base_model, num_models):
self.models = [base_model.copy() for _ in range(num_models)]
self.num_models = num_models

# Add small perturbations to each model
for i, model in enumerate(self.models):
self.perturb_model(model, i)

def perturb_model(self, model, index):
"""Perturb a model to create diversity"""
# This would modify model parameters, for example:
# model.add_perturbation(0.1 * index)
pass

def predict(self, state, action):
"""Get prediction with uncertainty estimate"""
predictions = []
for model in self.models:
pred = model.predict(state, action)
predictions.append(pred)

# Return mean and standard deviation
mean_pred = np.mean(predictions, axis=0)
std_pred = np.std(predictions, axis=0)

return mean_pred, std_pred

return ModelUncertaintyWrapper(base_model, num_models)

def online_adaptation(self, policy, adaptation_rate=0.01):
"""Online adaptation of policy parameters"""
class OnlineAdaptationWrapper:
def __init__(self, policy, adaptation_rate):
self.policy = policy
self.adaptation_rate = adaptation_rate
self.performance_history = []

def get_action(self, state):
# Get action from base policy
action = self.policy.get_action(state)

# Update policy based on recent performance
self.adapt_if_needed()

return action

def update_performance(self, reward):
"""Update performance history"""
self.performance_history.append(reward)
if len(self.performance_history) > 100: # Keep last 100 rewards
self.performance_history.pop(0)

def adapt_if_needed(self):
"""Adapt policy if performance is degrading"""
if len(self.performance_history) >= 10:
recent_perf = np.mean(self.performance_history[-5:])
earlier_perf = np.mean(self.performance_history[-10:-5])

if recent_perf < earlier_perf * 0.9: # Performance degraded significantly
# Apply adaptation (simplified)
self.policy.update_parameters(self.adaptation_rate)

return OnlineAdaptationWrapper(policy, adaptation_rate)

class Sim2RealTrainer:
"""Complete training pipeline with sim-to-real considerations"""

def __init__(self, config):
self.config = config
self.mitigation = RealityGapMitigation()
self.best_real_world_performance = -float('inf')

def train_with_gap_considerations(self, sim_env, real_env, policy_network):
"""Train policy with explicit consideration of sim-to-real gap"""
print("Starting training with sim-to-real considerations...")

# Apply noise robustness during simulation training
noisy_sim_env = self.mitigation.noise_robust_training(
sim_env,
noise_std=self.config.get('noise_std', 0.05)
)

# Create uncertainty-aware model
uncertainty_model = self.mitigation.model_uncertainty_wrapper(
policy_network,
num_models=self.config.get('num_models', 5)
)

# Apply online adaptation
adaptive_policy = self.mitigation.online_adaptation(
policy_network,
adaptation_rate=self.config.get('adaptation_rate', 0.01)
)

# Training loop with periodic real-world evaluation
for iteration in range(self.config.get('training_iterations', 100000)):
# Train in simulation with robustness techniques
self.train_in_simulation(noisy_sim_env, adaptive_policy)

# Evaluate on real robot periodically
if iteration % self.config.get('real_eval_frequency', 1000) == 0:
real_performance = self.evaluate_on_real_robot(
real_env, adaptive_policy
)

print(f"Real world performance at iteration {iteration}: {real_performance}")

# Save best performing policy
if real_performance > self.best_real_world_performance:
self.best_real_world_performance = real_performance
self.save_best_policy(adaptive_policy, iteration)

print("Training completed with sim-to-real considerations")
return adaptive_policy

def train_in_simulation(self, env, policy):
"""Train policy in simulation environment"""
# This would contain your standard RL training loop
# For this example, we'll simulate training
print("Training in simulation...")

# Sample training code structure
state = env.reset()
for step in range(1000): # Example training steps
action = policy.get_action(state)
next_state, reward, done, info = env.step(action)

# Update policy based on experience
policy.update(state, action, reward, next_state, done)

state = next_state if not done else env.reset()

def evaluate_on_real_robot(self, real_env, policy):
"""Evaluate policy performance on real robot"""
print("Evaluating on real robot...")

total_reward = 0
num_episodes = self.config.get('real_evaluation_episodes', 10)

for episode in range(num_episodes):
state = real_env.reset()
episode_reward = 0

for step in range(500): # Fixed horizon evaluation
action = policy.get_action(state)
next_state, reward, done, info = real_env.step(action)

episode_reward += reward
state = next_state

if done:
break

total_reward += episode_reward

avg_reward = total_reward / num_episodes
return avg_reward

def save_best_policy(self, policy, iteration):
"""Save the best performing policy"""
print(f"Saving best policy at iteration {iteration}")
# Implementation would save policy parameters to file
pass

def run_sim2real_training_example():
"""Run example of sim-to-real training"""
config = {
'noise_std': 0.05,
'num_models': 5,
'adaptation_rate': 0.01,
'training_iterations': 5000,
'real_eval_frequency': 500,
'real_evaluation_episodes': 5
}

# Simulate with dummy environments and policy
class DummyEnv:
def reset(self):
return np.random.randn(54)

def step(self, action):
return np.random.randn(54), np.random.rand(), False, {}

class DummyPolicy:
def get_action(self, state):
return np.random.randn(27)

def update(self, state, action, reward, next_state, done):
pass

sim_env = DummyEnv()
real_env = DummyEnv()
policy = DummyPolicy()

trainer = Sim2RealTrainer(config)
trained_policy = trainer.train_with_gap_considerations(sim_env, real_env, policy)

if __name__ == "__main__":
run_sim2real_training_example()

Validation and Evaluation​

Transfer Performance Metrics​

class TransferValidator:
"""Validate and evaluate sim-to-real transfer performance"""

def __init__(self):
self.metrics = {
'success_rate': [],
'tracking_accuracy': [],
'control_effort': [],
'stability': [],
'sim_real_correlation': []
}

def validate_transfer(self, sim_policy, real_robot, num_episodes=50):
"""Validate transfer performance using multiple metrics"""
print("Validating sim-to-real transfer...")

# Collect data from simulation and real robot
sim_results = self.run_policy_in_simulation(sim_policy, num_episodes)
real_results = self.run_policy_on_real_robot(real_robot, num_episodes)

# Calculate validation metrics
validation_metrics = {
'success_rate': self.calculate_success_rate(real_results),
'tracking_accuracy': self.calculate_tracking_accuracy(sim_results, real_results),
'control_effort': self.calculate_control_effort(real_results),
'stability': self.calculate_stability(real_results),
'sim_real_correlation': self.calculate_correlation(sim_results, real_results)
}

self.metrics['success_rate'].append(validation_metrics['success_rate'])
self.metrics['tracking_accuracy'].append(validation_metrics['tracking_accuracy'])
self.metrics['control_effort'].append(validation_metrics['control_effort'])
self.metrics['stability'].append(validation_metrics['stability'])
self.metrics['sim_real_correlation'].append(validation_metrics['sim_real_correlation'])

return validation_metrics

def calculate_success_rate(self, results):
"""Calculate success rate of task completion"""
successful_episodes = sum(1 for r in results if r['completed_task'])
return successful_episodes / len(results) if results else 0.0

def calculate_tracking_accuracy(self, sim_results, real_results):
"""Calculate how well real robot tracks simulated behavior"""
if not sim_results or not real_results:
return 0.0

total_tracking_error = 0.0
for sim_res, real_res in zip(sim_results, real_results):
# Calculate trajectory tracking error
error = np.mean([
np.abs(sim_state - real_state).mean()
for sim_state, real_state in zip(sim_res['states'], real_res['states'])
])
total_tracking_error += error

avg_error = total_tracking_error / len(sim_results)
# Convert to accuracy (higher is better)
accuracy = 1.0 / (1.0 + avg_error)
return accuracy

def calculate_control_effort(self, results):
"""Calculate average control effort"""
if not results:
return 0.0

total_effort = 0.0
for result in results:
# Calculate average control signal magnitude
if 'controls' in result:
avg_control = np.mean([np.linalg.norm(ctrl) for ctrl in result['controls']])
total_effort += avg_control

return total_effort / len(results)

def calculate_stability(self, results):
"""Calculate stability metrics"""
if not results:
return 0.0

stability_scores = []
for result in results:
if 'states' in result and len(result['states']) > 1:
# Calculate stability based on state variations
states = np.array(result['states'])
state_variance = np.var(states, axis=0)
stability = 1.0 / (1.0 + np.mean(state_variance))
stability_scores.append(stability)

return np.mean(stability_scores) if stability_scores else 0.0

def calculate_correlation(self, sim_results, real_results):
"""Calculate correlation between simulation and real performance"""
if not sim_results or not real_results:
return 0.0

# Calculate correlation of performance metrics
sim_performance = [r.get('performance', 0.0) for r in sim_results]
real_performance = [r.get('performance', 0.0) for r in real_results]

if len(sim_performance) > 1 and len(real_performance) > 1:
correlation_matrix = np.corrcoef(sim_performance, real_performance)
return correlation_matrix[0, 1]
else:
return 0.0

def run_policy_in_simulation(self, policy, num_episodes):
"""Run policy in simulation to collect results"""
# This would run the policy in simulation
results = []
for _ in range(num_episodes):
# Simulate episode
result = {
'states': [np.random.randn(54) for _ in range(100)], # Example states
'controls': [np.random.randn(27) for _ in range(100)], # Example controls
'performance': np.random.rand(), # Example performance
'completed_task': np.random.choice([True, False]) # Example task completion
}
results.append(result)
return results

def run_policy_on_real_robot(self, robot, num_episodes):
"""Run policy on real robot to collect results"""
# This would run the policy on the real robot
results = []
for _ in range(num_episodes):
# Execute episode on real robot
result = {
'states': [np.random.randn(54) for _ in range(100)], # Example states
'controls': [np.random.randn(27) for _ in range(100)], # Example controls
'performance': np.random.rand(), # Example performance
'completed_task': np.random.choice([True, False]) # Example task completion
}
results.append(result)
return results

def generate_validation_report(self):
"""Generate comprehensive validation report"""
report = {
'overall_transfer_score': np.mean([
self.metrics['success_rate'][-1] if self.metrics['success_rate'] else 0,
self.metrics['tracking_accuracy'][-1] if self.metrics['tracking_accuracy'] else 0,
self.metrics['stability'][-1] if self.metrics['stability'] else 0,
self.metrics['sim_real_correlation'][-1] if self.metrics['sim_real_correlation'] else 0
]) if any(self.metrics.values()) else 0.0,
'detailed_metrics': {
'success_rate': self.metrics['success_rate'][-1] if self.metrics['success_rate'] else 0,
'tracking_accuracy': self.metrics['tracking_accuracy'][-1] if self.metrics['tracking_accuracy'] else 0,
'average_control_effort': np.mean(self.metrics['control_effort']) if self.metrics['control_effort'] else 0,
'stability': self.metrics['stability'][-1] if self.metrics['stability'] else 0,
'sim_real_correlation': self.metrics['sim_real_correlation'][-1] if self.metrics['sim_real_correlation'] else 0
}
}
return report

def validate_transfer_example():
"""Example of transfer validation"""
validator = TransferValidator()
results = validator.validate_transfer(None, None, num_episodes=10)
report = validator.generate_validation_report()

print("Transfer Validation Report:")
print(f"Overall Transfer Score: {report['overall_transfer_score']:.3f}")
for metric, value in report['detailed_metrics'].items():
print(f" {metric}: {value:.3f}")

if __name__ == "__main__":
validate_transfer_example()

Hands-on Lab: Implementing Sim-to-Real Transfer​

In this lab, you'll implement and validate sim-to-real transfer techniques for a humanoid robot task.

Step 1: Setup Simulation Environment​

  1. Set up a humanoid robot simulation environment (e.g., PyBullet or MuJoCo)
  2. Implement basic control for the simulated robot
  3. Verify that the simulation environment works correctly

Step 2: Implement Domain Randomization​

  1. Create a domain randomization module that randomizes physics parameters
  2. Integrate it with your training environment
  3. Test that randomization affects robot behavior

Step 3: Train a Policy with Domain Randomization​

  1. Train a simple locomotion policy in the randomized simulation
  2. Monitor training progress and convergence
  3. Save the trained policy

Step 4: Validate on Real Robot (or High-Fidelity Simulation)​

  1. Transfer the trained policy to the real robot (or high-fidelity simulation)
  2. Evaluate performance using the metrics discussed
  3. Compare with a policy trained without domain randomization

Troubleshooting Notes​

  1. Excessive Randomization: Avoid making simulation too different from reality; start with small variations and gradually increase.

  2. Training Instability: Domain randomization can cause training instability; use techniques like PPO instead of more sensitive algorithms.

  3. Parameter Identification: Be careful with parameter bounds in system identification to avoid non-physical results.

  4. Adaptation Speed: Balance adaptation speed with stability; too-fast adaptation can cause oscillations.

Summary​

Sim-to-real transfer techniques are essential for applying simulation-trained policies to real humanoid robots. This chapter covered key approaches including domain randomization, system identification, adaptive control, and validation methodologies. By properly applying these techniques, we can significantly reduce the reality gap and enable effective deployment of simulation-trained policies on physical robots.

Next Steps​

The next chapter will focus on a comprehensive mini-project that integrates all the concepts covered in Module 3, implementing a complete perception pipeline for humanoid robots that includes synthetic data generation, Isaac ROS perception, Nav2 navigation, and reinforcement learning control with sim-to-real transfer.

References​

  1. Domain Randomization: https://arxiv.org/abs/1703.06907
  2. Sim-to-Real Transfer in Robotics: https://arxiv.org/abs/2010.06880
  3. System Identification for Robotics: https://ieeexplore.ieee.org/document/9392284
  4. Adaptive Control of Robots: https://www.sciencedirect.com/science/article/pii/S0967066119303135
  5. Reality Gap in Reinforcement Learning: https://arxiv.org/abs/2108.09400