add modified sru-navigation-sim (added go2 code)

This commit is contained in:
MattMa
2026-07-13 15:13:55 +08:00
parent 9e8f17bab0
commit 58b25cb40a
86 changed files with 10524 additions and 0 deletions
@@ -0,0 +1,20 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""MDP components for navigation tasks.
This module provides observations, rewards, terminations, curriculums,
and actions specific to navigation tasks.
"""
from isaaclab.envs.mdp import * # noqa: F401, F403
from .curriculums import * # noqa: F401, F403
from .events import * # noqa: F401, F403
from .rewards import * # noqa: F401, F403
from .terminations import * # noqa: F401, F403
from .observations import * # noqa: F401, F403
from .navigation import * # noqa: F401, F403
from .delay_manager import ObservationDelayManager, ObservationDelayManagerCfg, DelayBufferState # noqa: F401
@@ -0,0 +1,56 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Curriculum functions for navigation tasks.
The functions can be passed to the :class:`isaaclab.managers.CurriculumTermCfg` object to enable
the curriculum introduced by the function.
"""
from __future__ import annotations
from collections.abc import Sequence
from typing import TYPE_CHECKING
import torch
if TYPE_CHECKING:
from isaaclab.envs import ManagerBasedRLEnv
def disable_backward_penalty_after_steps(
env: ManagerBasedRLEnv,
env_ids: Sequence[int],
term_name: str = "backward_movement_penalty",
num_steps: int = 1000
) -> torch.Tensor:
"""Curriculum that disables the backward movement penalty after a certain number of steps.
This helps with early training by preventing backward movement, but removes the constraint
later to allow more natural movement patterns.
Args:
env: The learning environment.
env_ids: Not used since all environments are affected.
term_name: The name of the backward movement penalty term.
num_steps: The number of steps after which the penalty should be disabled.
Returns:
Current step counter as float for logging purposes.
"""
if env.common_step_counter > num_steps:
# Check if the term exists and has a non-zero weight
if hasattr(env.reward_manager, 'get_term_cfg'):
try:
term_cfg = env.reward_manager.get_term_cfg(term_name)
if term_cfg.weight != 0.0:
# Disable the penalty by setting weight to 0
term_cfg.weight = 0.0
env.reward_manager.set_term_cfg(term_name, term_cfg)
print(f"Disabled backward movement penalty at step {env.common_step_counter}")
except KeyError:
# Term doesn't exist, which is fine
pass
return torch.tensor(float(env.common_step_counter))
@@ -0,0 +1,106 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Custom noise configurations for navigation tasks."""
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
from isaaclab.utils import configclass
from isaaclab.utils.math import quat_from_euler_xyz, transform_points
from isaaclab.utils.noise import NoiseCfg
if TYPE_CHECKING:
pass
@torch.jit.script
def goal_to_xyz(goal: torch.Tensor) -> torch.Tensor:
"""Convert goal in (direction, log distance) format to (x, y, z) coordinates."""
direction = goal[:, :3] # Extract directional vector
distance = torch.exp(goal[:, 3]) - 1 # Convert log distance back to distance
return direction * distance.unsqueeze(-1) # Scale direction by distance
@torch.jit.script
def xyz_to_goal(xyz: torch.Tensor) -> torch.Tensor:
"""Convert (x, y, z) coordinates to (direction, log distance) format."""
distance = torch.norm(xyz, dim=1, keepdim=True) + 1e-6 # Calculate distance
direction = xyz / distance # Normalize to get directional vector
distance = torch.log(1 + distance) # Convert distance to log distance
return torch.cat([direction, distance], dim=1) # Concatenate direction and log distance
@torch.inference_mode()
def delta_transformation_noise(data: torch.Tensor, cfg: "DeltaTransformationNoiseCfg") -> torch.Tensor:
"""Delta transformation noise involving random rotation and translation.
The output is returned in a new tensor (instead of modifying 'data' in-place).
"""
# Ensure the data has the shape (..., 3) for 3D coordinates, or (direction, log distance)
if data.shape[-1] not in (3, 4):
raise ValueError(
"Data must have shape (..., 3) for 3D coordinates, or (..., 4) for (direction, log distance)."
)
# Determine whether data is in (direction, log distance) format
unit_vec = data.shape[-1] == 4
# Convert to (x, y, z) if needed
if unit_vec:
coordinate = goal_to_xyz(data)
else:
coordinate = data
# Generate small rotation noise (Rx, Ry, Rz) using uniform distribution
rotation_noise = torch.empty((data.shape[0], 3), device=data.device).uniform_(-cfg.rotation, cfg.rotation)
# Convert Euler angles (Rx, Ry, Rz) to quaternions
quat_noise = quat_from_euler_xyz(rotation_noise[:, 0], rotation_noise[:, 1], rotation_noise[:, 2])
# Generate small translation noise (Tx, Ty, Tz) using uniform distribution
translation_noise = torch.empty((data.shape[0], 3), device=data.device).uniform_(-cfg.translation, cfg.translation)
# Apply random rotation + translation
transformed_data = transform_points(coordinate.unsqueeze(1), translation_noise, quat_noise).squeeze(1)
# If input was in goal format, convert back
if unit_vec:
transformed_data = xyz_to_goal(transformed_data)
# Randomly apply the noise based on the probability
random_mask = torch.rand(data.shape[0], device=data.device) < cfg.noise_prob
# Use torch.where to select transformed values on the mask
random_mask_expanded = random_mask.unsqueeze(-1)
output = torch.where(random_mask_expanded, transformed_data, data)
if cfg.remove_dist:
if unit_vec:
# Zero out the distance component by directly assigning 0
output[..., 3:] = 0
else:
# Normalize the vector by its norm (avoiding division by zero)
norm = torch.norm(output, dim=-1, keepdim=True) + 1e-6
output = output / norm
return output
@configclass
class DeltaTransformationNoiseCfg(NoiseCfg):
"""Configuration for small delta transformation noise involving rotation and translation."""
func = delta_transformation_noise
rotation: float = 0.1
"""The maximum rotation angle in radians. Defaults to 0.1."""
translation: float = 0.5
"""The maximum translation in meters. Defaults to 0.5."""
noise_prob: float = 0.25
"""The probability of applying the noise. Defaults to 0.25."""
remove_dist: bool = False
"""Whether to remove the distance from the output. Defaults to False."""
@@ -0,0 +1,272 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Standalone observation delay manager for simulating sensor delays."""
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass, field
import torch
from isaaclab.utils import DelayBuffer, configclass
@configclass
class ObservationDelayManagerCfg:
"""Configuration for the observation delay manager.
This configuration controls the simulation of sensor delays, where each environment
can have a different random delay sampled from [0, max_delay] at episode reset.
"""
enabled: bool = True
"""Whether to enable delay simulation for observations."""
max_delay_lin_vel: int = 2
"""Maximum delay in timesteps for linear velocity observations."""
max_delay_ang_vel: int = 2
"""Maximum delay in timesteps for angular velocity observations."""
max_delay_projected_gravity: int = 2
"""Maximum delay in timesteps for projected gravity observations."""
max_delay_target_position: int = 2
"""Maximum delay in timesteps for target position/goal observations."""
max_delay_depth: int = 2
"""Maximum delay in timesteps for depth image observations."""
@dataclass
class DelayBufferState:
"""Container for a delay buffer and its associated time lags.
This encapsulates the state needed for delayed observations:
- The buffer storing historical data
- Per-environment time lags (delays)
- Maximum delay configured for this buffer
"""
buffer: DelayBuffer
time_lags: torch.Tensor
max_delay: int
def compute(self, data: torch.Tensor) -> torch.Tensor:
"""Append data and return delayed version."""
return self.buffer.compute(data)
def reset(self, env_ids: Sequence[int] | None = None):
"""Reset buffer for specified environments."""
self.buffer.reset(env_ids)
def randomize_lags(self, env_ids: torch.Tensor, device: str):
"""Randomize time lags for specified environments."""
new_lags = torch.randint(0, self.max_delay + 1, (len(env_ids),), dtype=torch.int, device=device)
self.time_lags[env_ids] = new_lags
env_ids_list = env_ids.tolist() if env_ids is not None else None
self.buffer.set_time_lag(new_lags, env_ids_list)
def set_lags(self, time_lags: torch.Tensor, env_ids: torch.Tensor | None = None):
"""Set time lags for specified environments."""
if env_ids is None:
self.time_lags[:] = time_lags
self.buffer.set_time_lag(time_lags)
else:
self.time_lags[env_ids] = time_lags
self.buffer.set_time_lag(time_lags, env_ids.tolist())
class ObservationDelayManager:
"""Standalone manager for simulating observation delays.
This manager can be added to any environment to simulate sensor delays
without coupling to a specific action term. Each observation type can
have its own delay buffer with per-environment random delays.
Usage:
# In environment config or __init__:
self.delay_manager = ObservationDelayManager(cfg, num_envs, device)
# In observation functions:
delayed_vel = env.delay_manager.compute_delayed_lin_vel(current_vel)
# On episode reset:
env.delay_manager.reset(env_ids)
env.delay_manager.randomize_lags(env_ids)
"""
def __init__(self, cfg: ObservationDelayManagerCfg, num_envs: int, device: str):
"""Initialize the observation delay manager.
Args:
cfg: Configuration for delay buffers.
num_envs: Number of parallel environments.
device: Device for tensor operations.
"""
self.cfg = cfg
self.num_envs = num_envs
self.device = device
self._delay_enabled = cfg.enabled
self._init_delay_buffers()
def _create_delay_buffer_state(self, max_delay: int) -> DelayBufferState:
"""Create a DelayBufferState with initialized buffer and random time lags."""
buffer = DelayBuffer(max_delay, batch_size=self.num_envs, device=self.device)
time_lags = torch.randint(0, max_delay + 1, (self.num_envs,), dtype=torch.int, device=self.device)
buffer.set_time_lag(time_lags)
return DelayBufferState(buffer=buffer, time_lags=time_lags, max_delay=max_delay)
def _init_delay_buffers(self):
"""Initialize all delay buffers based on configuration."""
if not self.cfg.enabled:
# No delays - set all delay states to None
self._delay_lin_vel: DelayBufferState | None = None
self._delay_ang_vel: DelayBufferState | None = None
self._delay_projected_gravity: DelayBufferState | None = None
self._delay_target_position: DelayBufferState | None = None
self._delay_depth_buffers: dict[str, DelayBufferState] = {}
self._max_delay_depth = 0
return
# Initialize delay buffer states for each observation type
self._delay_lin_vel = self._create_delay_buffer_state(self.cfg.max_delay_lin_vel)
self._delay_ang_vel = self._create_delay_buffer_state(self.cfg.max_delay_ang_vel)
self._delay_projected_gravity = self._create_delay_buffer_state(self.cfg.max_delay_projected_gravity)
self._delay_target_position = self._create_delay_buffer_state(self.cfg.max_delay_target_position)
# Depth buffers are created dynamically per camera
self._delay_depth_buffers: dict[str, DelayBufferState] = {}
self._max_delay_depth = self.cfg.max_delay_depth
@property
def enabled(self) -> bool:
"""Whether delay simulation is enabled."""
return self._delay_enabled
def get_or_create_depth_delay_buffer(self, camera_name: str) -> DelayBufferState:
"""Get or create a delay buffer for a specific depth camera.
Args:
camera_name: Name of the depth camera sensor.
Returns:
DelayBufferState for the specified camera.
"""
if camera_name not in self._delay_depth_buffers:
self._delay_depth_buffers[camera_name] = self._create_delay_buffer_state(self._max_delay_depth)
return self._delay_depth_buffers[camera_name]
def reset(self, env_ids: torch.Tensor):
"""Reset all delay buffers for specified environments.
Args:
env_ids: Environment indices to reset.
"""
env_ids_list = env_ids.tolist() if env_ids is not None else None
if self._delay_lin_vel is not None:
self._delay_lin_vel.reset(env_ids_list)
if self._delay_ang_vel is not None:
self._delay_ang_vel.reset(env_ids_list)
if self._delay_projected_gravity is not None:
self._delay_projected_gravity.reset(env_ids_list)
if self._delay_target_position is not None:
self._delay_target_position.reset(env_ids_list)
# Reset all depth buffers
for depth_buffer in self._delay_depth_buffers.values():
depth_buffer.reset(env_ids_list)
def randomize_lags(self, env_ids: torch.Tensor):
"""Randomize time lags for all delay buffers.
Args:
env_ids: Environment indices to randomize.
"""
if self._delay_lin_vel is not None:
self._delay_lin_vel.randomize_lags(env_ids, self.device)
if self._delay_ang_vel is not None:
self._delay_ang_vel.randomize_lags(env_ids, self.device)
if self._delay_projected_gravity is not None:
self._delay_projected_gravity.randomize_lags(env_ids, self.device)
if self._delay_target_position is not None:
self._delay_target_position.randomize_lags(env_ids, self.device)
# Randomize all depth buffers
for depth_buffer in self._delay_depth_buffers.values():
depth_buffer.randomize_lags(env_ids, self.device)
# ============================================================================
# Delayed observation computation methods
# ============================================================================
def compute_delayed_lin_vel(self, lin_vel: torch.Tensor) -> torch.Tensor:
"""Compute delayed linear velocity observation.
Args:
lin_vel: Current linear velocity tensor of shape (num_envs, 3).
Returns:
Delayed linear velocity, or original if delays disabled.
"""
if self._delay_lin_vel is None:
return lin_vel
return self._delay_lin_vel.compute(lin_vel)
def compute_delayed_ang_vel(self, ang_vel: torch.Tensor) -> torch.Tensor:
"""Compute delayed angular velocity observation.
Args:
ang_vel: Current angular velocity tensor of shape (num_envs, 3).
Returns:
Delayed angular velocity, or original if delays disabled.
"""
if self._delay_ang_vel is None:
return ang_vel
return self._delay_ang_vel.compute(ang_vel)
def compute_delayed_projected_gravity(self, projected_gravity: torch.Tensor) -> torch.Tensor:
"""Compute delayed projected gravity observation.
Args:
projected_gravity: Current projected gravity tensor of shape (num_envs, 3).
Returns:
Delayed projected gravity, or original if delays disabled.
"""
if self._delay_projected_gravity is None:
return projected_gravity
return self._delay_projected_gravity.compute(projected_gravity)
def compute_delayed_target_position(self, target_position: torch.Tensor) -> torch.Tensor:
"""Compute delayed target position observation.
Args:
target_position: Current target position tensor.
Returns:
Delayed target position, or original if delays disabled.
"""
if self._delay_target_position is None:
return target_position
return self._delay_target_position.compute(target_position)
def compute_delayed_depth(self, depth_features: torch.Tensor, camera_name: str) -> torch.Tensor:
"""Compute delayed depth observation for a specific camera.
Args:
depth_features: Encoded depth features of shape (num_envs, feature_dim).
camera_name: Name of the camera sensor.
Returns:
Delayed depth features, or original if delays disabled.
"""
if not self._delay_enabled:
return depth_features
delay_buffer = self.get_or_create_depth_delay_buffer(camera_name)
return delay_buffer.compute(depth_features)
@@ -0,0 +1,332 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Depth noise encoder module for visual navigation.
This module provides a VAE-based depth encoder with realistic stereo depth noise simulation.
"""
import os
from collections import OrderedDict
from typing import Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import regnet_x_400mf
from torchvision.ops import Conv2dNormActivation, FeaturePyramidNetwork
from isaaclab_assets import ISAACLAB_ASSETS_DATA_DIR
from .camera_config import CameraConfig
# Default camera configuration (ZedX Camera for b2w and aow d)
DEFAULT_CAMERA_CONFIG = CameraConfig(
focal_length=25.0,
baseline=0.12,
min_depth=0.25,
max_depth=10.0,
depth_encoder_path=os.path.join(str(ISAACLAB_ASSETS_DATA_DIR), "Policies", "RSL-ETHZ/AoW_d/depth_encoder", "vae_pretrain_fuse.pth")
)
class VAESampler(nn.Module):
def __init__(self, input_dim, latent_dim):
super(VAESampler, self).__init__()
self.input_dim = input_dim
self.latent_dim = latent_dim
self.conv = Conv2dNormActivation(input_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False)
# Convolutional Layers for 2D mean and logvar
self.mean_layers = nn.Sequential(
Conv2dNormActivation(latent_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False),
nn.Conv2d(latent_dim, latent_dim, kernel_size=1, stride=1, padding=0)
)
self.logvar_layers = nn.Sequential(
Conv2dNormActivation(latent_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False),
nn.Conv2d(latent_dim, latent_dim, kernel_size=1, stride=1, padding=0)
)
def reparameterize(self, mu, logvar):
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
return mu + eps * std
def forward(self, x):
x = self.conv(x)
x = self.mean_layers(x)
return x
class EncoderFPN(nn.Module):
def __init__(self, in_channel, out_channel):
super(EncoderFPN, self).__init__()
encoder = regnet_x_400mf(weights=None)
# Remove classification head from the encoder
encoder = nn.Sequential(*list(encoder.children())[:-2])
# Modify the first layer to accept the number of channels in the input image
encoder[0][0] = nn.Conv2d(in_channel, 32, kernel_size=3, stride=2, padding=1, bias=False)
self.enc = encoder[0]
self.enc_1 = encoder[1][:2]
self.enc_2 = encoder[1][2]
self.enc_3 = encoder[1][3]
# Feature Pyramid Network
self.fpn = FeaturePyramidNetwork([64, 160, 400], out_channel)
def forward(self, x):
raise NotImplementedError("Forward method must be implemented in the child class.")
class DepthEncoder(EncoderFPN):
"""Depth image encoder using Feature Pyramid Network."""
def __init__(self, out_channel):
super(DepthEncoder, self).__init__(1, out_channel)
def forward(self, x):
# check if depth has channel dimension
if x.dim() == 3:
x = x.unsqueeze(1)
out = OrderedDict()
x = self.enc(x)
out['feat1'] = self.enc_1(x)
out['feat2'] = self.enc_2(out['feat1'])
out['feat3'] = self.enc_3(out['feat2'])
out = self.fpn(out)
return out['feat1']
class VAEDecoder(nn.Module):
def __init__(self, input_dim, out_dim):
super(VAEDecoder, self).__init__()
self.input_dim = input_dim
self.conv = Conv2dNormActivation(input_dim, input_dim, kernel_size=3, stride=1, padding=1, bias=False)
self.decoder = nn.Sequential(
# Layer 0
nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False),
nn.BatchNorm2d(input_dim),
nn.ReLU(inplace=True),
# Layer 1
nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False),
nn.BatchNorm2d(input_dim),
nn.ReLU(inplace=True),
# Layer 2
nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False),
nn.BatchNorm2d(input_dim),
nn.ReLU(inplace=True),
# Final Output Layer
nn.Conv2d(input_dim, out_dim, kernel_size=3, stride=1, padding=1)
) # Expand the spatial dimensions by a factor of 2**4=16
def forward(self, z):
z = self.conv(z)
img = self.decoder(z)
return img
class DepthDecoder(VAEDecoder):
def __init__(self, input_dim):
super(DepthDecoder, self).__init__(input_dim, 1)
class VAENet(nn.Module):
def __init__(self, latent_dim):
super(VAENet, self).__init__()
self.depth_encoder = DepthEncoder(latent_dim)
self.vae_sampler = VAESampler(latent_dim, latent_dim)
self.depth_decoder = DepthDecoder(latent_dim)
def forward(self, x):
x = self.depth_encoder(x)
x = self.vae_sampler(x)
return x
def decode(self, z):
return self.depth_decoder(z)
class DepthNoise(torch.nn.Module):
def __init__(self,
focal_length,
baseline,
min_depth,
max_depth,
filter_size=3,
inlier_thred_range=(0.01, 0.05),
prob_range=(0.4, 0.6),
invalid_disp=1e7
):
"""
A Simply PyTorch module to add realistic noise to depth images.
Args:
focal_length (float): Focal length of the camera (in pixels).
baseline (float): Baseline distance between stereo cameras (in meters).
min_depth (float): Minimum depth value after clamping.
max_depth (float): Maximum depth value after clamping.
filter_size (int): Kernel size for local mean disparity computation. (tuning based on image resolution)
inlier_thred_range (tuple): Threshold range for normalized disparity differences.
prob_range (tuple): Probability range for matching pixels.
invalid_disp (float): Invalid disparity
"""
super().__init__()
self.focal_length = focal_length
self.baseline = baseline
self.min_depth = min_depth
self.max_depth = max_depth
self.invalid_disp = invalid_disp
self.inlier_thred_range = inlier_thred_range
self.prob_range = prob_range
self.filter_size = filter_size
weights, substitutes = self._compute_weights(filter_size)
self.register_buffer('weights', weights.view(1, 1, filter_size, filter_size))
self.register_buffer('substitutes', substitutes.view(1, 1, filter_size, filter_size))
def _compute_weights(self, filter_size):
"""
Compute weights and substitutes for disparity filtering.
Args:
filter_size (int): Kernel size for local mean disparity computation.
"""
center = filter_size // 2
idx = torch.arange(filter_size) - center
x_filter, y_filter = torch.meshgrid(idx, idx, indexing='ij')
sqr_radius = x_filter ** 2 + y_filter ** 2
sqrt_radius = torch.sqrt(sqr_radius)
weights = 1 / torch.where(sqr_radius == 0, torch.ones_like(sqrt_radius), sqrt_radius)
weights = weights / weights.sum()
fill_weights = 1 / (1 + sqrt_radius)
fill_weights = torch.where(sqr_radius > filter_size, -1.0, fill_weights)
substitutes = (fill_weights > 0).float()
return weights, substitutes
def filter_disparity(self, disparity):
"""
Filter the disparity map using local mean disparity.
Args:
disparity (torch.Tensor): Input disparity map tensor of shape (B, C, H, W).
"""
B, _, H, W = disparity.shape
device = disparity.device
center = self.filter_size // 2
output_disparity = torch.full_like(disparity, self.invalid_disp)
prob = torch.rand(B, 1, 1, 1, device=device) * (self.prob_range[1] - self.prob_range[0]) + self.prob_range[0]
random_mask = (torch.rand(B, 1, H, W, device=device) < prob)
# Compute mean disparity
weighted_disparity = F.conv2d(disparity, self.weights, padding=center)
# Compute differences
differences = torch.abs(disparity - weighted_disparity)
# Normalize differences based on current image statistics for consistent thresholding
differences_flat = differences.view(B, -1) # Flatten spatial dimensions
mean_diff = torch.mean(differences_flat, dim=1, keepdim=True)
std_diff = torch.std(differences_flat, dim=1, keepdim=True) + 1e-6 # Add epsilon to avoid division by zero
# Normalize differences: (diff - mean) / std, then shift to [0, 1] range approximately
normalized_differences_flat = (differences_flat - mean_diff) / std_diff
normalized_differences = normalized_differences_flat.view_as(differences)
# Use parameter-based threshold on normalized differences
threshold = torch.rand(B, 1, 1, 1, device=device) * (self.inlier_thred_range[1] - self.inlier_thred_range[0]) + self.inlier_thred_range[0]
update_mask = (normalized_differences < threshold) & random_mask
# Compute output value: round with 1/32 precision
disparity = torch.round(disparity * 32.0) / 32.0
# Update output disparity
output_disparity = torch.where(update_mask, disparity, output_disparity)
# Apply substitutes to fill neighboring pixels
filled_values = F.conv2d(update_mask.float() * disparity, self.substitutes, padding=center)
counts = F.conv2d(update_mask.float(), self.substitutes, padding=center) + 1e-9
average_filled_values = filled_values / counts
output_disparity = torch.where(counts >= 1, average_filled_values, output_disparity)
return output_disparity
def forward(self, depth, add_noise: bool) -> torch.Tensor:
# correct input shape
if len(depth.shape) == 3:
depth = depth.unsqueeze(1) # add channel dimension
# check dimension (B, 1, H, W)
assert depth.shape[1] == 1, "Input depth tensor must have shape (B, 1, H, W)."
assert len(depth.shape) == 4, "Input depth tensor must have shape (B, 1, H, W)."
if add_noise:
# Clamp the depth values
depth = torch.clamp(depth, min=1. / self.invalid_disp)
# Step 1: Convert depth to disparity
disparity = self.focal_length * self.baseline / depth
# Step 2: Filter the disparity map
filtered_disparity = self.filter_disparity(disparity)
# Step 3: Recompute depth from disparity
depth = self.focal_length * self.baseline / filtered_disparity
# Step 4: Clamp the depth values
depth[depth < self.min_depth] = 0.0
# Step 5: Set invalid depth values to 0.0 (values outside valid range are not measurable)
depth[depth > self.max_depth] = 0.0
return depth
class DepthNoiseEncoder(torch.nn.Module):
def __init__(self,
feature_dim,
camera_config: CameraConfig = None
):
"""
A Simply PyTorch module to add realistic noise to depth images.
Args:
feature_dim (int): Number of output channels from the encoder.
camera_config (CameraConfig, optional): Camera configuration parameters.
If None, uses DEFAULT_CAMERA_CONFIG.
"""
super().__init__()
# Use provided config or default
if camera_config is None:
camera_config = DEFAULT_CAMERA_CONFIG
self.camera_config = camera_config
self.depth_noise = DepthNoise(
focal_length=camera_config.focal_length,
baseline=camera_config.baseline,
min_depth=camera_config.min_depth,
max_depth=camera_config.max_depth
)
self.encoder = VAENet(feature_dim)
try:
self.encoder.load_state_dict(torch.load(camera_config.depth_encoder_path, weights_only=True), strict=True)
print('\033[92m' + f'Successfully loaded pre-trained weights from {camera_config.depth_encoder_path}' + '\033[0m')
except Exception as e:
print('\033[91m' + f'Failed to load pre-trained weights: {e}' + '\033[0m')
def forward(self, depth: torch.Tensor, add_noise: bool = True) -> Tuple[torch.Tensor, torch.Tensor]:
noisy_depth = self.depth_noise(depth, add_noise)
encoded_depth = self.encoder(noisy_depth) # (B, 1, H, W) -> (B, C, H//8, W//8)
return encoded_depth, noisy_depth
@torch.jit.export
def decode(self, z: torch.Tensor) -> torch.Tensor:
return self.encoder.decode(z)
@@ -0,0 +1,25 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Depth noise and encoding utilities for navigation tasks."""
from .camera_config import (
CameraConfig,
ZEDX_CAMERA_CONFIG,
DEFAULT_CAMERA_CONFIG,
ROBOT_CAMERA_CONFIGS,
get_camera_config,
)
from .depth_noise_encoder import DepthNoiseEncoder, DepthNoise
__all__ = [
"CameraConfig",
"ZEDX_CAMERA_CONFIG",
"DEFAULT_CAMERA_CONFIG",
"ROBOT_CAMERA_CONFIGS",
"get_camera_config",
"DepthNoiseEncoder",
"DepthNoise",
]
@@ -0,0 +1,146 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Camera configuration parameters for different robots and camera types.
This module provides camera-specific parameters for depth noise generation and encoding.
"""
import os
from typing import Optional
from isaaclab.utils import configclass
# Local assets directory for this extension
# Path: depth_utils -> mdp -> navigation -> assets/data
_ASSETS_DIR = os.path.normpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "assets", "data")
)
def _get_encoder_path(model_filename: str) -> str:
"""Helper function to construct encoder model path.
Args:
model_filename: Name of the encoder model file (e.g., 'vae_pretrain_new.pth')
Returns:
Full path to the encoder model file
"""
return os.path.join(_ASSETS_DIR, "Policies", "depth_encoder", model_filename)
@configclass
class CameraConfig:
"""Configuration class for camera parameters.
This class contains all camera-specific parameters needed for depth noise generation
and depth encoder initialization.
"""
# Camera intrinsic parameters
focal_length: float = 25.0
baseline: float = 0.12
# Depth range parameters
min_depth: float = 0.25
max_depth: float = 10.0
# Camera resolution (width, height)
resolution: tuple[int, int] = (53, 30)
# Depth encoder model path
depth_encoder_path: str = ""
def __post_init__(self):
"""Post-initialization to set default encoder path if not provided."""
if not self.depth_encoder_path:
self.depth_encoder_path = _get_encoder_path("vae_pretrain_fuse.pth")
# Predefined camera configurations
ZEDX_CAMERA_CONFIG = CameraConfig(
focal_length=25.0,
baseline=0.12,
min_depth=0.25,
max_depth=10.0,
resolution=(64, 40),
depth_encoder_path=_get_encoder_path("vae_pretrain_new.pth"),
)
"""Configuration for ZedX camera (used with b2w and aow_d robots)."""
# -----------------------------------------------------------------------------
# Odin1 (LiDAR-aligned depth on Unitree Go2)
# -----------------------------------------------------------------------------
# Real intrinsics @ native 1600x1296 (from ROS calibration):
# fx = 737.357 px, fy = 737.292 px, cx = 794.372 px, cy = 666.259 px
# hFOV = 2*atan(W / 2fx) = 94.67 deg
# vFOV = 2*atan(H / 2fy) = 82.65 deg
#
# Scaled to VAE-fixed 64x40 input (keep FOV identical):
# fx_sim = 737.357 * 64/1600 = 29.49 px
# fy_sim = 737.292 * 40/1296 = 22.76 px
# cx_sim ~= 31.77 px (close to width/2)
# cy_sim ~= 20.56 px (close to height/2)
#
# Noise model caveat: the upstream DepthNoise module simulates *stereo*
# disparity-quantization noise (sigma_d proportional to d^2 / (fx * baseline)).
# Odin1 depth comes from LiDAR-to-image alignment, where the real noise is
# closer to a constant ~1-2 cm regardless of range. We keep the stereo-style
# noise as a coarse proxy (set focal_length=fx_sim, baseline=0.05 m) but if
# sim2real depth fidelity becomes a problem, swap in a constant-sigma noise
# model later.
ODIN1_CAMERA_CONFIG = CameraConfig(
focal_length=29.49, # pixels (NOT mm; matches sim pinhole fx)
baseline=0.05, # fudge: makes per-meter quantization noise sane
min_depth=0.25,
max_depth=10.0,
resolution=(64, 40), # do not change; VAE encoder input is fixed
depth_encoder_path=_get_encoder_path("vae_pretrain_new.pth"),
)
"""Configuration for Odin1 LiDAR-aligned depth (used with Go2)."""
# Default camera configuration
DEFAULT_CAMERA_CONFIG = ZEDX_CAMERA_CONFIG
"""Default camera configuration (ZedX camera settings)."""
# Robot-to-camera mapping. Go2 now uses Odin1 (LiDAR-aligned depth). b2w and
# aow_d keep the original ZedX profile so the upstream paper results stay
# reproducible.
ROBOT_CAMERA_CONFIGS = {
"b2w": ZEDX_CAMERA_CONFIG,
"aow_d": ZEDX_CAMERA_CONFIG,
"go2": ODIN1_CAMERA_CONFIG,
}
"""Dictionary mapping robot names to their camera configurations."""
def get_camera_config(robot_name: str, use_default_fallback: bool = False) -> CameraConfig:
"""Get camera configuration for a specific robot.
Args:
robot_name: Name of the robot (e.g., 'b2w', 'aow_d')
use_default_fallback: If True, return DEFAULT_CAMERA_CONFIG when robot not found
instead of raising an error (default: False)
Returns:
Camera configuration for the specified robot
Raises:
KeyError: If robot_name not found and use_default_fallback is False
"""
if robot_name in ROBOT_CAMERA_CONFIGS:
return ROBOT_CAMERA_CONFIGS[robot_name]
if use_default_fallback:
return DEFAULT_CAMERA_CONFIG
available_robots = ", ".join(sorted(ROBOT_CAMERA_CONFIGS.keys()))
raise KeyError(
f"Robot '{robot_name}' not found in camera configurations. "
f"Available robots: {available_robots}"
)
@@ -0,0 +1,361 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Depth noise generation and encoding for navigation tasks."""
import os
from collections import OrderedDict
from typing import Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import regnet_x_400mf
from torchvision.ops import Conv2dNormActivation, FeaturePyramidNetwork
from isaaclab_assets import ISAACLAB_ASSETS_DATA_DIR
from .camera_config import CameraConfig
# Default camera configuration (ZedX Camera for b2w and aow d)
DEFAULT_CAMERA_CONFIG = CameraConfig(
focal_length=25.0,
baseline=0.12,
min_depth=0.25,
max_depth=10.0,
depth_encoder_path=os.path.join(
str(ISAACLAB_ASSETS_DATA_DIR),
"Policies",
"RSL-ETHZ/AoW_d/depth_encoder",
"vae_pretrain_fuse.pth"
)
)
class VAESampler(nn.Module):
def __init__(self, input_dim, latent_dim):
super(VAESampler, self).__init__()
self.input_dim = input_dim
self.latent_dim = latent_dim
self.conv = Conv2dNormActivation(
input_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False
)
# Convolutional Layers for 2D mean and logvar
self.mean_layers = nn.Sequential(
Conv2dNormActivation(
latent_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False
),
nn.Conv2d(latent_dim, latent_dim, kernel_size=1, stride=1, padding=0)
)
self.logvar_layers = nn.Sequential(
Conv2dNormActivation(
latent_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False
),
nn.Conv2d(latent_dim, latent_dim, kernel_size=1, stride=1, padding=0)
)
def reparameterize(self, mu, logvar):
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
return mu + eps * std
def forward(self, x):
x = self.conv(x)
x = self.mean_layers(x)
return x
class EncoderFPN(nn.Module):
def __init__(self, in_channel, out_channel):
super(EncoderFPN, self).__init__()
encoder = regnet_x_400mf(weights=None)
# Remove classification head from the encoder
encoder = nn.Sequential(*list(encoder.children())[:-2])
# Modify the first layer to accept the number of channels in the input image
encoder[0][0] = nn.Conv2d(in_channel, 32, kernel_size=3, stride=2, padding=1, bias=False)
self.enc = encoder[0]
self.enc_1 = encoder[1][:2]
self.enc_2 = encoder[1][2]
self.enc_3 = encoder[1][3]
# Feature Pyramid Network
self.fpn = FeaturePyramidNetwork([64, 160, 400], out_channel)
def forward(self, x):
raise NotImplementedError("Forward method must be implemented in the child class.")
# Depth image encoder
class DepthEncoder(EncoderFPN):
def __init__(self, out_channel):
super(DepthEncoder, self).__init__(1, out_channel)
def forward(self, x):
# check if depth has channel dimension
if x.dim() == 3:
x = x.unsqueeze(1)
out = OrderedDict()
x = self.enc(x)
out['feat1'] = self.enc_1(x)
out['feat2'] = self.enc_2(out['feat1'])
out['feat3'] = self.enc_3(out['feat2'])
out = self.fpn(out)
return out['feat1']
class VAEDecoder(nn.Module):
def __init__(self, input_dim, out_dim):
super(VAEDecoder, self).__init__()
self.input_dim = input_dim
self.conv = Conv2dNormActivation(
input_dim, input_dim, kernel_size=3, stride=1, padding=1, bias=False
)
self.decoder = nn.Sequential(
# Layer 0
nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False),
nn.BatchNorm2d(input_dim),
nn.ReLU(inplace=True),
# Layer 1
nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False),
nn.BatchNorm2d(input_dim),
nn.ReLU(inplace=True),
# Layer 2
nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False),
nn.BatchNorm2d(input_dim),
nn.ReLU(inplace=True),
# Final Output Layer
nn.Conv2d(input_dim, out_dim, kernel_size=3, stride=1, padding=1)
) # Expand the spatial dimensions by a factor of 2**4=16
def forward(self, z):
z = self.conv(z)
img = self.decoder(z)
return img
class DepthDecoder(VAEDecoder):
def __init__(self, input_dim):
super(DepthDecoder, self).__init__(input_dim, 1)
class VAENet(nn.Module):
def __init__(self, latent_dim):
super(VAENet, self).__init__()
self.depth_encoder = DepthEncoder(latent_dim)
self.vae_sampler = VAESampler(latent_dim, latent_dim)
self.depth_decoder = DepthDecoder(latent_dim)
def forward(self, x):
x = self.depth_encoder(x)
x = self.vae_sampler(x)
return x
def decode(self, z):
return self.depth_decoder(z)
class DepthNoise(torch.nn.Module):
def __init__(
self,
focal_length,
baseline,
min_depth,
max_depth,
filter_size=3,
inlier_thred_range=(0.01, 0.05),
prob_range=(0.4, 0.6),
invalid_disp=1e7
):
"""A Simply PyTorch module to add realistic noise to depth images.
Args:
focal_length (float): Focal length of the camera (in pixels).
baseline (float): Baseline distance between stereo cameras (in meters).
min_depth (float): Minimum depth value after clamping.
max_depth (float): Maximum depth value after clamping.
filter_size (int): Kernel size for local mean disparity computation.
inlier_thred_range (tuple): Threshold range for normalized disparity differences.
prob_range (tuple): Probability range for matching pixels.
invalid_disp (float): Invalid disparity
"""
super().__init__()
self.focal_length = focal_length
self.baseline = baseline
self.min_depth = min_depth
self.max_depth = max_depth
self.invalid_disp = invalid_disp
self.inlier_thred_range = inlier_thred_range
self.prob_range = prob_range
self.filter_size = filter_size
weights, substitutes = self._compute_weights(filter_size)
self.register_buffer('weights', weights.view(1, 1, filter_size, filter_size))
self.register_buffer('substitutes', substitutes.view(1, 1, filter_size, filter_size))
def _compute_weights(self, filter_size):
"""Compute weights and substitutes for disparity filtering.
Args:
filter_size (int): Kernel size for local mean disparity computation.
"""
center = filter_size // 2
idx = torch.arange(filter_size) - center
x_filter, y_filter = torch.meshgrid(idx, idx, indexing='ij')
sqr_radius = x_filter ** 2 + y_filter ** 2
sqrt_radius = torch.sqrt(sqr_radius)
weights = 1 / torch.where(sqr_radius == 0, torch.ones_like(sqrt_radius), sqrt_radius)
weights = weights / weights.sum()
fill_weights = 1 / (1 + sqrt_radius)
fill_weights = torch.where(sqr_radius > filter_size, -1.0, fill_weights)
substitutes = (fill_weights > 0).float()
return weights, substitutes
def filter_disparity(self, disparity):
"""Filter the disparity map using local mean disparity.
Args:
disparity (torch.Tensor): Input disparity map tensor of shape (B, C, H, W).
"""
B, _, H, W = disparity.shape
device = disparity.device
center = self.filter_size // 2
output_disparity = torch.full_like(disparity, self.invalid_disp)
prob = (
torch.rand(B, 1, 1, 1, device=device)
* (self.prob_range[1] - self.prob_range[0])
+ self.prob_range[0]
)
random_mask = (torch.rand(B, 1, H, W, device=device) < prob)
# Compute mean disparity
weighted_disparity = F.conv2d(disparity, self.weights, padding=center)
# Compute differences
differences = torch.abs(disparity - weighted_disparity)
# Normalize differences based on current image statistics
differences_flat = differences.view(B, -1)
mean_diff = torch.mean(differences_flat, dim=1, keepdim=True)
std_diff = torch.std(differences_flat, dim=1, keepdim=True) + 1e-6
normalized_differences_flat = (differences_flat - mean_diff) / std_diff
normalized_differences = normalized_differences_flat.view_as(differences)
# Use parameter-based threshold on normalized differences
threshold = (
torch.rand(B, 1, 1, 1, device=device)
* (self.inlier_thred_range[1] - self.inlier_thred_range[0])
+ self.inlier_thred_range[0]
)
update_mask = (normalized_differences < threshold) & random_mask
# Compute output value: round with 1/32 precision
disparity = torch.round(disparity * 32.0) / 32.0
# Update output disparity
output_disparity = torch.where(update_mask, disparity, output_disparity)
# Apply substitutes to fill neighboring pixels
filled_values = F.conv2d(update_mask.float() * disparity, self.substitutes, padding=center)
counts = F.conv2d(update_mask.float(), self.substitutes, padding=center) + 1e-9
average_filled_values = filled_values / counts
output_disparity = torch.where(counts >= 1, average_filled_values, output_disparity)
return output_disparity
def forward(self, depth, add_noise: bool) -> torch.Tensor:
# correct input shape
if len(depth.shape) == 3:
depth = depth.unsqueeze(1) # add channel dimension
# check dimension (B, 1, H, W)
assert depth.shape[1] == 1, "Input depth tensor must have shape (B, 1, H, W)."
assert len(depth.shape) == 4, "Input depth tensor must have shape (B, 1, H, W)."
if add_noise:
# Clamp the depth values
depth = torch.clamp(depth, min=1. / self.invalid_disp)
# Step 1: Convert depth to disparity
disparity = self.focal_length * self.baseline / depth
# Step 2: Filter the disparity map
filtered_disparity = self.filter_disparity(disparity)
# Step 3: Recompute depth from disparity
depth = self.focal_length * self.baseline / filtered_disparity
# Step 4: Clamp the depth values
depth[depth < self.min_depth] = 0.0
# Step 5: Set invalid depth values to 0.0
depth[depth > self.max_depth] = 0.0
return depth
class DepthNoiseEncoder(torch.nn.Module):
def __init__(
self,
feature_dim,
camera_config: CameraConfig = None
):
"""A Simply PyTorch module to add realistic noise to depth images.
Args:
feature_dim (int): Number of output channels from the encoder.
camera_config (CameraConfig, optional): Camera configuration parameters.
If None, uses DEFAULT_CAMERA_CONFIG.
"""
super().__init__()
# Use provided config or default
if camera_config is None:
camera_config = DEFAULT_CAMERA_CONFIG
self.camera_config = camera_config
self.depth_noise = DepthNoise(
focal_length=camera_config.focal_length,
baseline=camera_config.baseline,
min_depth=camera_config.min_depth,
max_depth=camera_config.max_depth
)
self.encoder = VAENet(feature_dim)
try:
self.encoder.load_state_dict(
torch.load(camera_config.depth_encoder_path, weights_only=True),
strict=True
)
print(
'\033[92m'
+ f'Successfully loaded pre-trained weights from {camera_config.depth_encoder_path}'
+ '\033[0m'
)
except Exception as e:
print('\033[91m' + f'Failed to load pre-trained weights: {e}' + '\033[0m')
def forward(
self, depth: torch.Tensor, add_noise: bool = True
) -> Tuple[torch.Tensor, torch.Tensor]:
noisy_depth = self.depth_noise(depth, add_noise)
encoded_depth = self.encoder(noisy_depth) # (B, 1, H, W) -> (B, C, H//8, W//8)
return encoded_depth, noisy_depth
@torch.jit.export
def decode(self, z: torch.Tensor) -> torch.Tensor:
return self.encoder.decode(z)
@@ -0,0 +1,229 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Custom event functions for navigation tasks.
These functions are ported from the internal Isaac Lab fork and provide
domain randomization and environment events specific to navigation tasks.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from isaaclab.envs import ManagerBasedEnv
from isaaclab.managers import SceneEntityCfg
from isaaclab.utils import math as math_utils
if TYPE_CHECKING:
from isaaclab.sensors import RayCasterCamera
from isaaclab_nav_task.navigation.mdp import PerceptiveNavigationSE2Action
def randomize_camera_height(
env: ManagerBasedEnv,
env_ids: torch.Tensor,
height_range: float,
roll_angle_range: float,
pitch_angle_range: float,
yaw_angle_range: float,
asset_cfg: SceneEntityCfg = SceneEntityCfg("raycast_camera"),
):
"""Randomize the camera's height and orientation around the original values.
The function samples around the original camera offset and orientation:
- height: original height +- height_range (meters)
- roll: original roll +- roll_angle_range (degrees)
- pitch: original pitch +- pitch_angle_range (degrees)
- yaw: original yaw +- yaw_angle_range (degrees)
Args:
env: The environment manager.
env_ids: The environment ids to randomize.
height_range: Range around original height (meters).
roll_angle_range: Range around original roll angle (degrees).
pitch_angle_range: Range around original pitch angle (degrees).
yaw_angle_range: Range around original yaw angle (degrees).
asset_cfg: Scene entity configuration for the camera.
"""
camera: RayCasterCamera = env.scene[asset_cfg.name]
# Get original camera position and orientation
original_camera_pos = camera.cfg.offset.pos
original_camera_quat = camera.cfg.offset.rot
# Sample position around original value
num_envs = env_ids.numel()
pos_delta = torch.zeros((num_envs, 3), device=env.device)
pos_delta[:, 0] = torch.randn(num_envs, device=env.device) * (height_range / 2.0)
pos_delta[:, 1] = torch.randn(num_envs, device=env.device) * (height_range / 2.0)
pos_delta[:, 0] = torch.clamp(pos_delta[:, 0], -height_range, height_range)
pos_delta[:, 1] = torch.clamp(pos_delta[:, 1], -height_range, height_range)
pos_delta[:, 2] = torch.rand(num_envs, device=env.device) * 2.0 * height_range - height_range
camera._offset_pos[env_ids] = torch.tensor(original_camera_pos, device=env.device) + pos_delta
# Convert original quaternion to Euler angles (XYZ convention)
quat_tensor = torch.tensor(original_camera_quat, device=env.device).unsqueeze(0)
original_euler = math_utils.euler_xyz_from_quat(quat_tensor)
original_roll_deg = original_euler[0] * 180.0 / torch.pi
original_pitch_deg = original_euler[1] * 180.0 / torch.pi
original_yaw_deg = original_euler[2] * 180.0 / torch.pi
# Sample angles around original values
roll_delta_deg = torch.randn(num_envs, device=env.device) * (roll_angle_range / 2.0)
roll_delta_deg = torch.clamp(roll_delta_deg, -roll_angle_range, roll_angle_range)
pitch_delta_deg = torch.rand(num_envs, device=env.device) * 2.0 * pitch_angle_range - pitch_angle_range
yaw_delta_deg = torch.randn(num_envs, device=env.device) * (yaw_angle_range / 2.0)
yaw_delta_deg = torch.clamp(yaw_delta_deg, -yaw_angle_range, yaw_angle_range)
# Add deltas to original angles
sampled_roll_deg = original_roll_deg + roll_delta_deg
sampled_pitch_deg = original_pitch_deg + pitch_delta_deg
sampled_yaw_deg = original_yaw_deg + yaw_delta_deg
# Convert to radians and build quaternion (XYZ convention)
sampled_roll_rad = sampled_roll_deg * torch.pi / 180.0
sampled_pitch_rad = sampled_pitch_deg * torch.pi / 180.0
sampled_yaw_rad = sampled_yaw_deg * torch.pi / 180.0
camera._offset_quat[env_ids] = math_utils.quat_from_euler_xyz(sampled_roll_rad, sampled_pitch_rad, sampled_yaw_rad)
def randomize_action_scale(
env: ManagerBasedEnv,
env_ids: torch.Tensor,
scale_range_x: tuple[float, float],
scale_range_y: tuple[float, float],
scale_range_theta: tuple[float, float],
scale_range_xb: float,
scale_range_yb: float,
scale_range_thetab: float,
action_term: str,
):
"""Change the action scale in the scene.
Args:
env: The environment manager.
env_ids: The environment ids to change the action scale in.
scale_range_x: The scale range for x.
scale_range_y: The scale range for y.
scale_range_theta: The scale range for theta.
scale_range_xb: The bias range for x.
scale_range_yb: The bias range for y.
scale_range_thetab: The bias range for theta.
action_term: Name of the action term.
"""
action_term_obj: PerceptiveNavigationSE2Action = env.action_manager._terms[action_term]
action_term_obj._policy_scaling[env_ids] = torch.tensor(
action_term_obj.cfg.policy_scaling, device=action_term_obj.device
).expand(len(env_ids), -1)
random_scales_x = (
torch.rand(len(env_ids), 1, device=env.device) * (scale_range_x[1] - scale_range_x[0]) + scale_range_x[0]
)
random_scales_y = (
torch.rand(len(env_ids), 1, device=env.device) * (scale_range_y[1] - scale_range_y[0]) + scale_range_y[0]
)
random_scales_theta = (
torch.rand(len(env_ids), 1, device=env.device) * (scale_range_theta[1] - scale_range_theta[0])
+ scale_range_theta[0]
)
random_scales_xb = (torch.rand(len(env_ids), 1, device=env.device) * 2 - 1) * scale_range_xb
random_scales_yb = (torch.rand(len(env_ids), 1, device=env.device) * 2 - 1) * scale_range_yb
random_scales_thetab = (torch.rand(len(env_ids), 1, device=env.device) * 2 - 1) * scale_range_thetab
random_scales = torch.cat((random_scales_x, random_scales_y, random_scales_theta), dim=-1)
random_scales_b = torch.cat((random_scales_xb, random_scales_yb, random_scales_thetab), dim=-1)
action_term_obj._policy_scaling[env_ids] *= random_scales
action_term_obj._policy_bias[env_ids, :] = random_scales_b
def reset_and_randomize_delay_buffer(
env: ManagerBasedEnv,
env_ids: torch.Tensor,
):
"""Reset and randomize delay buffers.
This function resets the delay buffers and randomizes the time lags for
all observation types. Requires env.delay_manager to exist.
Args:
env: The environment manager (must have delay_manager attribute).
env_ids: The environment ids to reset.
"""
env.delay_manager.reset(env_ids)
env.delay_manager.randomize_lags(env_ids)
def randomize_low_pass_filter_alpha(
env: ManagerBasedEnv,
env_ids: torch.Tensor,
alpha_range: tuple[float, float],
action_term: str,
per_dimension: bool = True,
alpha_range_vx: tuple[float, float] | None = None,
alpha_range_vy: tuple[float, float] | None = None,
alpha_range_omega: tuple[float, float] | None = None,
):
"""Randomize the low-pass filter alpha parameter for velocity command smoothing.
Args:
env: The environment manager.
env_ids: The environment ids to randomize the alpha parameter for.
alpha_range: Tuple of (min_alpha, max_alpha) values.
action_term: Name of the action term to modify.
per_dimension: Whether to use different alpha for each dimension.
alpha_range_vx: Optional range for vx dimension.
alpha_range_vy: Optional range for vy dimension.
alpha_range_omega: Optional range for omega dimension.
"""
action_term_obj: PerceptiveNavigationSE2Action = env.action_manager._terms[action_term]
if per_dimension:
# Use dimension-specific ranges or fall back to global range
vx_range = alpha_range_vx if alpha_range_vx is not None else alpha_range
vy_range = alpha_range_vy if alpha_range_vy is not None else alpha_range
omega_range = alpha_range_omega if alpha_range_omega is not None else alpha_range
alpha_vx = torch.rand(len(env_ids), device=env.device) * (vx_range[1] - vx_range[0]) + vx_range[0]
alpha_vy = torch.rand(len(env_ids), device=env.device) * (vy_range[1] - vy_range[0]) + vy_range[0]
alpha_omega = torch.rand(len(env_ids), device=env.device) * (omega_range[1] - omega_range[0]) + omega_range[0]
if hasattr(action_term_obj, "_per_env_per_dim_low_pass_alpha"):
action_term_obj._per_env_per_dim_low_pass_alpha[env_ids, 0] = alpha_vx
action_term_obj._per_env_per_dim_low_pass_alpha[env_ids, 1] = alpha_vy
action_term_obj._per_env_per_dim_low_pass_alpha[env_ids, 2] = alpha_omega
else:
random_alpha = (
torch.rand(len(env_ids), device=env.device) * (alpha_range[1] - alpha_range[0]) + alpha_range[0]
)
if hasattr(action_term_obj, "_per_env_per_dim_low_pass_alpha"):
action_term_obj._per_env_per_dim_low_pass_alpha[env_ids] = random_alpha.unsqueeze(-1).expand(-1, 3)
def disable_backward_penalty_after_steps(
env: ManagerBasedEnv,
env_ids: torch.Tensor,
disable_after_steps: int,
action_term: str,
):
"""Disable backward movement penalty after a certain number of steps.
Args:
env: The environment manager.
env_ids: The environment ids.
disable_after_steps: Number of steps after which to disable the penalty.
action_term: Name of the action term.
"""
action_term_obj: PerceptiveNavigationSE2Action = env.action_manager._terms[action_term]
if hasattr(action_term_obj, "disable_backward_penalty"):
# Check which environments have exceeded the step threshold
if hasattr(env, "episode_length_buf"):
exceeded_steps = env.episode_length_buf[env_ids] >= disable_after_steps
action_term_obj.disable_backward_penalty[env_ids[exceeded_steps]] = True
@@ -0,0 +1,10 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Height scan encoder utilities for navigation tasks."""
from .heightscan_encoder import HeightScanFeatEncoder
__all__ = ["HeightScanFeatEncoder"]
@@ -0,0 +1,192 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
import os
import torch
import torch.nn as nn
from typing import Tuple
import torch.nn.functional as F
from collections import OrderedDict
from torchvision.ops import FeaturePyramidNetwork
from torchvision.models import regnet_x_400mf
from torchvision.ops import Conv2dNormActivation
# Local path to the encoder weights (relative to this file's directory)
_ASSETS_DIR = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "assets", "data"))
HEIGHTSCAN_ENCODER_PATH = os.path.join(_ASSETS_DIR, "Policies", "heightscan_encoder", "vae_heightscan3.pth")
class VAESampler(nn.Module):
def __init__(self, input_dim, latent_dim):
super(VAESampler, self).__init__()
self.input_dim = input_dim
self.latent_dim = latent_dim
self.conv = Conv2dNormActivation(input_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False)
# Convolutional Layers for 2D mean and logvar
self.mean_layers = nn.Sequential(
Conv2dNormActivation(latent_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False),
nn.Conv2d(latent_dim, latent_dim, kernel_size=1, stride=1, padding=0)
)
self.logvar_layers = nn.Sequential(
Conv2dNormActivation(latent_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False),
nn.Conv2d(latent_dim, latent_dim, kernel_size=1, stride=1, padding=0)
)
def reparameterize(self, mu, logvar):
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
return mu + eps * std
def forward(self, x):
x = self.conv(x)
x = self.mean_layers(x)
return x
class EncoderFPN(nn.Module):
def __init__(self, in_channel, out_channel):
super(EncoderFPN, self).__init__()
encoder = regnet_x_400mf(weights=None)
# Remove classification head from the encoder
encoder = nn.Sequential(*list(encoder.children())[:-2])
# Modify the first layer to accept the number of channels in the input image
encoder[0][0] = nn.Conv2d(in_channel, 32, kernel_size=3, stride=2, padding=1, bias=False)
self.enc = encoder[0]
self.enc_1 = encoder[1][:2]
self.enc_2 = encoder[1][2]
self.enc_3 = encoder[1][3]
# Feature Pyramid Network
self.fpn = FeaturePyramidNetwork([64, 160, 400], out_channel)
def forward(self, x):
raise NotImplementedError("Forward method must be implemented in the child class.")
# Depth image encoder
class HeightScanEncoder(EncoderFPN):
def __init__(self, out_channel):
super(HeightScanEncoder, self).__init__(1, out_channel)
def forward(self, x):
# check if depth has channel dimension
if x.dim() == 3:
x = x.unsqueeze(1)
out = OrderedDict()
x = self.enc(x)
out['feat1'] = self.enc_1(x)
out['feat2'] = self.enc_2(out['feat1'])
out['feat3'] = self.enc_3(out['feat2'])
out = self.fpn(out)
return out['feat1']
class VAEDecoder(nn.Module):
def __init__(self, input_dim, out_dim):
super(VAEDecoder, self).__init__()
self.input_dim = input_dim
self.conv = Conv2dNormActivation(input_dim, input_dim, kernel_size=3, stride=1, padding=1, bias=False)
self.decoder = nn.Sequential(
# Layer 0
nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False),
nn.BatchNorm2d(input_dim),
nn.ReLU(inplace=True),
# Layer 1
nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False),
nn.BatchNorm2d(input_dim),
nn.ReLU(inplace=True),
# Layer 2
nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False),
nn.BatchNorm2d(input_dim),
nn.ReLU(inplace=True),
# Final Output Layer
nn.Conv2d(input_dim, out_dim, kernel_size=3, stride=1, padding=1)
) # Expand the spatial dimensions by a factor of 2**4=16
def forward(self, z):
z = self.conv(z)
img = self.decoder(z)
return img
class HeightScanDecoder(VAEDecoder):
def __init__(self, input_dim):
super(HeightScanDecoder, self).__init__(input_dim, 1)
class VAENet(nn.Module):
def __init__(self, latent_dim):
super(VAENet, self).__init__()
self.depth_encoder = HeightScanEncoder(latent_dim)
self.vae_sampler = VAESampler(latent_dim, latent_dim)
self.depth_decoder = HeightScanDecoder(latent_dim)
def forward(self, x):
x = self.depth_encoder(x)
x = self.vae_sampler(x)
return x
def decode(self, z):
return self.depth_decoder(z)
class HeightScanFeatEncoder(torch.nn.Module):
def __init__(self,
feature_dim,
):
"""
A Simply PyTorch module to add realistic noise to depth images.
Args:
feature_dim (int): Number of output channels from the encoder.
"""
super().__init__()
self.encoder = VAENet(feature_dim)
try:
self.encoder.load_state_dict(torch.load(HEIGHTSCAN_ENCODER_PATH, weights_only=True), strict=True)
print('\033[92m' + f'Successfully loaded pre-trained weights from {HEIGHTSCAN_ENCODER_PATH}' + '\033[0m')
except Exception as e:
print('\033[91m' + f'Failed to load pre-trained weights: {e}' + '\033[0m')
def forward(self, scan: torch.Tensor) -> torch.Tensor:
encoded_scan = self.encoder(scan) # (B, 1, H, W) -> (B, C, H//8, W//8)
return encoded_scan
@torch.jit.export
def decode(self, z: torch.Tensor) -> torch.Tensor:
return self.encoder.decode(z)
# Example usage
if __name__ == "__main__":
import cv2
import numpy as np
# parameters for the depth noise
feature_dim = 64
# Initialize the DepthNoise class
heightscan_feat_encoder = HeightScanFeatEncoder(feature_dim=feature_dim)
# compile the depth_noise module
compiled_scan_encoder = torch.jit.script(heightscan_feat_encoder)
# random height scan image
scan = np.random.rand(51, 51) * 5
# convert depth to tensor
scan = torch.tensor(scan).unsqueeze(0).unsqueeze(0).float()
clipped_scan = torch.clamp(scan, min=-5, max=5)
# Add noise to the depth image
noisy_scan = compiled_scan_encoder(clipped_scan)
noisy_scan = noisy_scan.numpy().squeeze().squeeze()
# check the min and max values of the noisy depth
print("Min depth: ", noisy_scan.min())
print("Max depth: ", noisy_scan.max())
@@ -0,0 +1,50 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Custom math utilities for navigation tasks."""
from __future__ import annotations
import torch
@torch.jit.script
def vec_to_quat(v: torch.Tensor) -> torch.Tensor:
"""Converts a unit vector to a quaternion representing the rotation from the X-axis to the vector v.
Args:
v (torch.Tensor): A tensor of shape (..., 3) representing the unit vectors.
Returns:
torch.Tensor: A tensor of shape (..., 4) representing the quaternions (w, x, y, z).
"""
# Ensure v is a unit vector
norm_v = v / torch.clamp(torch.norm(v, dim=-1, keepdim=True), min=1e-8)
# Reference vector (X-axis)
a = torch.tensor([1.0, 0.0, 0.0], device=norm_v.device, dtype=norm_v.dtype).expand_as(norm_v)
# Compute dot and cross products
dot = torch.sum(a * norm_v, dim=-1, keepdim=True)
w = torch.cross(a, norm_v, dim=-1)
# Compute quaternion components
s = torch.sqrt((1.0 + dot) * 0.5).clamp(min=1e-8) # Avoid division by zero
q = torch.cat([s, w / (2.0 * s)], dim=-1)
# Handle edge case when dot == -1 (vectors are opposite)
mask = (dot < -0.999999).squeeze(-1)
if mask.any():
# Choose an arbitrary orthogonal vector
orthogonal = torch.cross(
a[mask],
torch.tensor([0.0, 1.0, 0.0], device=norm_v.device, dtype=norm_v.dtype).expand_as(a[mask]),
dim=-1
)
orthogonal = orthogonal / torch.clamp(torch.norm(orthogonal, dim=-1, keepdim=True), min=1e-8)
q[mask] = torch.cat([torch.zeros_like(s[mask]), orthogonal], dim=-1)
# Normalize the quaternion
q = q / torch.clamp(torch.norm(q, dim=-1, keepdim=True), min=1e-8)
return q
@@ -0,0 +1,10 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Navigation-specific MDP components including goal commands and SE2 actions."""
from .goal_commands import * # noqa: F401, F403
from .goal_commands_cfg import * # noqa: F401, F403
from .actions import * # noqa: F401, F403
@@ -0,0 +1,10 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
from .navigation_se2_actions import PerceptiveNavigationSE2Action
from .navigation_se2_actions_cfg import PerceptiveNavigationSE2ActionCfg
__all__ = ["PerceptiveNavigationSE2Action", "PerceptiveNavigationSE2ActionCfg"]
@@ -0,0 +1,249 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Navigation SE2 action term for hierarchical control."""
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from isaaclab.envs import ManagerBasedRLEnv
from isaaclab.managers.action_manager import ActionTerm
from isaaclab.utils.assets import check_file_path, read_file
if TYPE_CHECKING:
from .navigation_se2_actions_cfg import PerceptiveNavigationSE2ActionCfg
class PerceptiveNavigationSE2Action(ActionTerm):
"""Actions to navigate a robot using hierarchical control with a pre-trained locomotion policy."""
cfg: PerceptiveNavigationSE2ActionCfg
_env: ManagerBasedRLEnv
def __init__(self, cfg: PerceptiveNavigationSE2ActionCfg, env: ManagerBasedRLEnv):
super().__init__(cfg, env)
# Check if policy file exists
if not check_file_path(cfg.low_level_policy_file):
raise FileNotFoundError(f"Policy file '{cfg.low_level_policy_file}' does not exist.")
# Load pre-trained locomotion policy
file_bytes = read_file(self.cfg.low_level_policy_file)
self.low_level_policy = torch.jit.load(file_bytes, map_location=self.device)
self.low_level_policy.eval()
# prepare joint position actions
self.low_level_position_action_term: ActionTerm = self.cfg.low_level_position_action.class_type(cfg.low_level_position_action, env)
# Velocity branch is optional (None for legs-only robots like Go2).
if self.cfg.low_level_velocity_action is not None:
self.low_level_velocity_action_term: ActionTerm | None = self.cfg.low_level_velocity_action.class_type(cfg.low_level_velocity_action, env)
else:
self.low_level_velocity_action_term = None
# prepare buffers
self._action_dim = 3 # [vx, vy, omega]
# set up buffers
self._init_buffers()
# Low-pass filter state for velocity commands
self._prev_filtered_velocity_commands = torch.zeros((self.num_envs, self._action_dim), device=self.device)
self._low_pass_alpha = self.cfg.low_pass_filter_alpha if hasattr(self.cfg, 'low_pass_filter_alpha') else 0.8
self._enable_low_pass_filter = self.cfg.enable_low_pass_filter if hasattr(self.cfg, 'enable_low_pass_filter') else True
# Per-environment per-dimension alpha values (initialized to default, can be randomized per episode)
# Shape: [num_envs, action_dim] where action_dim = 3 (vx, vy, omega)
self._per_env_per_dim_low_pass_alpha = torch.full((self.num_envs, self._action_dim), self._low_pass_alpha, device=self.device)
"""
Properties.
"""
@property
def action_dim(self) -> int:
return self._action_dim
@property
def raw_actions(self) -> torch.Tensor:
return self._raw_navigation_velocity_actions
@property
def processed_actions(self) -> torch.Tensor:
return self._processed_navigation_velocity_actions
@property
def filtered_velocity_commands(self) -> torch.Tensor:
"""Get the current filtered (smoothed) velocity commands."""
return self._prev_filtered_velocity_commands
@property
def low_pass_alpha_values(self) -> torch.Tensor:
"""Get the current per-environment per-dimension low-pass filter alpha values.
Returns:
torch.Tensor: Alpha values with shape [num_envs, action_dim] where:
- action_dim = 3 for [vx, vy, omega]
- Each environment can have different alpha values for each command dimension
"""
return self._per_env_per_dim_low_pass_alpha
@property
def low_level_actions(self) -> torch.Tensor:
if self.low_level_velocity_action_term is None:
return self._low_level_position_actions
return torch.cat((self._low_level_position_actions, self._low_level_velocity_actions), dim=1)
@property
def low_level_position_actions(self) -> torch.Tensor:
return self._low_level_position_actions
@property
def prev_low_level_position_actions(self) -> torch.Tensor:
return self._prev_low_level_position_actions
@property
def low_level_velocity_actions(self) -> torch.Tensor:
return self._low_level_velocity_actions
@property
def prev_low_level_velocity_actions(self) -> torch.Tensor:
return self._prev_low_level_velocity_actions
"""
Operations.
"""
def apply_low_pass_filter(self, velocity_commands: torch.Tensor) -> torch.Tensor:
"""Apply low-pass filter to velocity commands for smoother locomotion.
The low-pass filter implements exponential smoothing:
filtered_cmd(t) = alpha * filtered_cmd(t-1) + (1 - alpha) * new_cmd(t)
Where alpha is the smoothing factor:
- alpha = 0.0: No smoothing (pass through)
- alpha = 1.0: Maximum smoothing (no change)
- alpha = 0.8: Good balance for locomotion (default)
This implementation supports per-environment per-dimension alpha values, allowing:
- Different smoothing for vx, vy, and omega in each environment
- Independent control over linear and angular velocity response
Args:
velocity_commands (torch.Tensor): Raw velocity commands [num_envs, 3] (vx, vy, omega)
Returns:
torch.Tensor: Filtered velocity commands with same shape as input
"""
if not self._enable_low_pass_filter:
return velocity_commands
# Use per-environment per-dimension alpha values for filtering
# Shape: [num_envs, action_dim] - already matches velocity_commands shape
alpha_values = self._per_env_per_dim_low_pass_alpha
# Apply exponential smoothing (low-pass filter) with per-environment per-dimension alpha
filtered_commands = (
alpha_values * self._prev_filtered_velocity_commands
+ (1.0 - alpha_values) * velocity_commands
)
# Update previous filtered commands for next iteration
self._prev_filtered_velocity_commands.copy_(filtered_commands)
return filtered_commands
def process_actions(self, actions):
"""Process low-level navigation actions. This function is called with a frequency of 10Hz.
Args:
actions (torch.Tensor): The low-level navigation actions.
"""
# Store the raw low-level navigation actions
self._raw_navigation_velocity_actions[:] = actions
# Apply the affine transformations
if not self.cfg.use_raw_actions:
self._processed_navigation_velocity_actions = (
self._raw_navigation_velocity_actions * self._scale + self._offset
)
else:
self._processed_navigation_velocity_actions[:] = self._raw_navigation_velocity_actions
if self.cfg.policy_distr_type == "gaussian":
# scale the actions to the range [-1, 1] for gaussian distribution
self._processed_navigation_velocity_actions = torch.tanh(self._processed_navigation_velocity_actions)
elif self.cfg.policy_distr_type == "beta":
# scale the actions to the range [-1, 1] for beta distribution
self._processed_navigation_velocity_actions = (self._processed_navigation_velocity_actions - 0.5) * 2.0
else:
raise ValueError(f"Unknown policy distribution type: {self.cfg.policy_distr_type}")
# compute the current speed of the robot to generate low-level actions based on the current speed
observations = self._env.observation_manager.compute_group(group_name=self.cfg.observation_group)
base_lin_vel = observations[:, 0:3]
vel_xyz = base_lin_vel.norm(dim=1, keepdim=True)
# [vx, vy, omega]
self._processed_navigation_velocity_actions = (self._processed_navigation_velocity_actions + vel_xyz * self._policy_bias) * self._policy_scaling
# Apply low-pass filter to smooth velocity commands and add delay effect
self._processed_navigation_velocity_actions = self.apply_low_pass_filter(self._processed_navigation_velocity_actions)
@torch.inference_mode()
def apply_actions(self):
"""Apply low-level actions for the simulator to the physics engine. This functions is called with the
simulation frequency of 200Hz. Since low-level locomotion runs at 50Hz, we need to decimate the actions."""
if self._counter % self.cfg.low_level_decimation == 0:
self._counter = 0
self._prev_low_level_position_actions[:] = self._low_level_position_actions.clone()
if self.low_level_velocity_action_term is not None:
self._prev_low_level_velocity_actions[:] = self._low_level_velocity_actions.clone()
# Get low level actions from low level policy
actions_phase = self.low_level_policy(
self._env.observation_manager.compute_group(group_name=self.cfg.observation_group)
)
# Process actions and bring them in the right order
pos_dim = self.low_level_position_action_term.action_dim
self._low_level_position_actions[:] = actions_phase[:, :pos_dim]
self.low_level_position_action_term.process_actions(self._low_level_position_actions)
if self.low_level_velocity_action_term is not None:
self._low_level_velocity_actions[:] = actions_phase[:, pos_dim:]
self.low_level_velocity_action_term.process_actions(self._low_level_velocity_actions)
# Apply low level actions
self.low_level_position_action_term.apply_actions()
if self.low_level_velocity_action_term is not None:
self.low_level_velocity_action_term.apply_actions()
self._counter += 1
def reset_low_pass_filter(self, env_ids: torch.Tensor):
"""Reset low-pass filter state for specified environments.
Args:
env_ids: Environment indices to reset.
"""
self._prev_filtered_velocity_commands[env_ids] = 0.0
"""
Helper functions
"""
def _init_buffers(self):
# Prepare buffers
self._raw_navigation_velocity_actions = torch.zeros(self.num_envs, self._action_dim, device=self.device)
self._processed_navigation_velocity_actions = torch.zeros((self.num_envs, self._action_dim), device=self.device)
self._low_level_position_actions = torch.zeros(self.num_envs, self.low_level_position_action_term.action_dim, device=self.device)
vel_dim = self.low_level_velocity_action_term.action_dim if self.low_level_velocity_action_term is not None else 0
self._low_level_velocity_actions = torch.zeros(self.num_envs, vel_dim, device=self.device)
self._prev_low_level_position_actions = torch.zeros_like(self._low_level_position_actions)
self._prev_low_level_velocity_actions = torch.zeros_like(self._low_level_velocity_actions)
self._low_level_step_dt = self.cfg.low_level_decimation * self._env.physics_dt
self._counter = 0
self._scale = torch.tensor(self.cfg.scale, device=self.device)
self._offset = torch.tensor(self.cfg.offset, device=self.device)
self._policy_scaling = torch.tensor(self.cfg.policy_scaling, device=self.device).repeat(self.num_envs, 1)
self._policy_bias = torch.zeros(self.num_envs, self._action_dim, device=self.device)
@@ -0,0 +1,52 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
from __future__ import annotations
from dataclasses import MISSING
from isaaclab.managers.action_manager import ActionTerm, ActionTermCfg
from isaaclab.utils import configclass
from .navigation_se2_actions import PerceptiveNavigationSE2Action
@configclass
class PerceptiveNavigationSE2ActionCfg(ActionTermCfg):
class_type: type[ActionTerm] = PerceptiveNavigationSE2Action
""" Class of the action term."""
low_level_decimation: int = 4
"""Decimation factor for the low level action term."""
use_raw_actions: bool = False
"""Whether to use raw actions or not."""
scale: list[float] = [1.0, 1.0, 1.0]
"""Scale for the actions [vx, vy, w]."""
offset: list[float] = [0.0, 0.0, 0.0]
"""Offset for the actions [vx, vy, w]."""
low_level_velocity_action: ActionTermCfg | None = None
"""Configuration of the low level velocity action term.
Set to ``None`` for legs-only quadrupeds (e.g. Go2) whose locomotion policy
only outputs joint position targets. The position-action branch then handles
all 12 leg joints, and the velocity-action branch is fully bypassed."""
low_level_position_action: ActionTermCfg = MISSING
"""Configuration of the low level position action term."""
low_level_policy_file: str = MISSING
"""Path to the low level policy file."""
observation_group: str = "policy"
"""Observation group to use for the low level policy."""
policy_scaling: list[float] = [1.0, 1.0, 1.0]
"""Policy dependent scaling for the actions [vx, vy, w]."""
reorder_joint_list: list[str] | None = None
"""Reorder the joint actions given from the low-level policy to match the Isaac Sim order if policy has been
trained with a different order. Set to None to disable reordering."""
policy_distr_type: str = "gaussian"
"""Policy distribution type: 'gaussian', 'beta'."""
# Low-pass filter parameters
enable_low_pass_filter: bool = True
"""Whether to enable low-pass filtering for velocity commands."""
low_pass_filter_alpha: float = 0.5
"""Low-pass filter smoothing factor (0.0 = no smoothing, 1.0 = maximum smoothing).
Formula: filtered_cmd = alpha * prev_filtered_cmd + (1 - alpha) * new_cmd"""
@@ -0,0 +1,786 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Goal command generator for robot navigation tasks.
Simplified architecture:
1. Terrain generation creates `valid_mask` (boolean mask of valid positions with safety padding)
2. This module samples goal/spawn positions uniformly from valid positions
3. Z-height is looked up from the visual height field
The terrain module handles:
- Height field generation
- Obstacle detection
- Safety padding (dilation)
- Border exclusion
"""
from __future__ import annotations
import math
from collections.abc import Sequence
from typing import TYPE_CHECKING, Tuple, Optional
import torch
import isaaclab.utils.math as math_utils
from isaaclab.assets import Articulation
from isaaclab.managers import CommandTerm
from isaaclab.markers import VisualizationMarkers
from isaaclab.markers.config import (
CUBOID_MARKER_CFG,
GREEN_ARROW_X_MARKER_CFG,
RED_ARROW_X_MARKER_CFG,
)
from isaaclab.utils.math import subtract_frame_transforms, transform_points, yaw_quat
from isaaclab_nav_task.navigation.mdp.math_utils import vec_to_quat
from isaaclab_nav_task.terrains.terrain_constants import VERTICAL_SCALE
if TYPE_CHECKING:
from isaaclab.envs import ManagerBasedRLEnv
from .goal_commands_cfg import RobotNavigationGoalCommandCfg
# =============================================================================
# Position Sampler (Simplified)
# =============================================================================
class PositionSampler:
"""Samples positions uniformly from valid terrain cells.
Uses pre-computed valid_mask from terrain generation (already has safety padding).
For spawn positions, uses spawn_mask with larger padding to account for robot body.
Coordinate System:
- The height field has shape (num_cells_x, num_cells_y), e.g., (299, 299)
- Each cell is horizontal_scale meters (e.g., 0.1m)
- The mesh is generated with a border: border_pixels = int(border_width / horizontal_scale) + 1
- Our valid_mask corresponds to the inner terrain (no border)
- Local coordinates are centered: (-terrain_size/2, -terrain_size/2) to (+terrain_size/2, +terrain_size/2)
- Border pixel offset is computed dynamically from terrain config (not hardcoded)
"""
def __init__(
self,
heights: torch.Tensor,
valid_mask: torch.Tensor,
platform_mask: torch.Tensor,
terrain_size: float,
horizontal_scale: float,
device: torch.device,
platform_repeat_count: int = 10,
spawn_mask: torch.Tensor = None,
border_width: float = 0.0,
):
"""Initialize the sampler.
Args:
heights: Height field (num_terrains, width, height) for Z-lookup.
valid_mask: Boolean mask of valid goal positions (num_terrains, width, height).
platform_mask: Boolean mask of platform positions for curriculum.
terrain_size: Size of each terrain in meters (full mesh size).
horizontal_scale: Resolution of height field in meters per cell.
device: Torch device.
platform_repeat_count: Repetition count for platform positions.
spawn_mask: Boolean mask of valid spawn positions with larger padding.
If None, defaults to valid_mask.
border_width: Border width around terrain in meters (from terrain config).
"""
self.device = device
self.terrain_size = terrain_size
self.horizontal_scale = horizontal_scale
self.heights = heights
self.valid_mask = valid_mask
self.platform_mask = platform_mask
# Use spawn_mask if provided, otherwise fall back to valid_mask
self.spawn_mask = spawn_mask if spawn_mask is not None else valid_mask
# Use horizontal_scale as cell size (correct resolution)
self.cell_size = horizontal_scale
# Compute border pixel offset dynamically based on terrain configuration
# Formula matches patches.py: border_pixels = int(border_width / horizontal_scale) + 1
# This ensures valid_mask indices map correctly to mesh coordinates
self.border_pixels = int(border_width / horizontal_scale) + 1
# Mesh center offset (mesh is centered at origin after transform)
self.mesh_center = terrain_size / 2 # e.g., 30 / 2 = 15m
# Build position tables for both goal and spawn sampling
self._build_position_tables(platform_repeat_count)
def _build_position_tables(self, platform_repeat_count: int):
"""Build pre-computed position tensors for efficient sampling.
Creates two sets of position tables:
- Goal positions: from valid_mask with platform repetition for curriculum
- Spawn positions: from spawn_mask (larger padding for robot body clearance)
"""
num_terrains = self.valid_mask.shape[0]
# =========================
# Build GOAL position table (from valid_mask with platform repetition)
# =========================
valid_indices = self.valid_mask.nonzero(as_tuple=False)
# Build enhanced indices with platform repetition
enhanced_indices = []
for terrain_idx in range(num_terrains):
terrain_valid = valid_indices[valid_indices[:, 0] == terrain_idx]
if len(terrain_valid) == 0:
enhanced_indices.append(terrain_valid)
continue
# Find platform positions
terrain_platform = self.platform_mask[terrain_idx]
platform_positions = terrain_platform.nonzero(as_tuple=False)
if len(platform_positions) > 0:
# Check which valid positions are platforms (vectorized)
valid_xy = terrain_valid[:, 1:] # (num_valid, 2)
plat_xy = platform_positions # (num_platforms, 2)
# Broadcast compare: (num_valid, 1, 2) vs (1, num_platforms, 2)
matches = (valid_xy.unsqueeze(1) == plat_xy.unsqueeze(0)).all(dim=2)
is_platform = matches.any(dim=1)
# Repeat platform positions
platform_valid = terrain_valid[is_platform]
if len(platform_valid) > 0:
repeated = platform_valid.repeat(platform_repeat_count, 1)
terrain_valid = torch.cat([terrain_valid, repeated], dim=0)
enhanced_indices.append(terrain_valid)
# Count positions per terrain for goals
self.count_per_terrain = torch.zeros(num_terrains, dtype=torch.long, device=self.device)
for terrain_idx in range(num_terrains):
self.count_per_terrain[terrain_idx] = len(enhanced_indices[terrain_idx])
# Create padded tensor for goal positions
max_count = max(1, self.count_per_terrain.max().item())
self.positions = torch.full(
(num_terrains, max_count, 3), -1, dtype=torch.long, device=self.device
)
# Fill goal position tables
for terrain_idx in range(num_terrains):
terrain_positions = enhanced_indices[terrain_idx]
num_pos = terrain_positions.shape[0]
if num_pos > 0:
self.positions[terrain_idx, :num_pos] = terrain_positions
# =========================
# Build SPAWN position table (from spawn_mask, no platform repetition)
# =========================
spawn_indices = self.spawn_mask.nonzero(as_tuple=False)
# Count spawn positions per terrain
self.spawn_count_per_terrain = torch.zeros(num_terrains, dtype=torch.long, device=self.device)
spawn_positions_list = []
for terrain_idx in range(num_terrains):
terrain_spawn = spawn_indices[spawn_indices[:, 0] == terrain_idx]
self.spawn_count_per_terrain[terrain_idx] = len(terrain_spawn)
spawn_positions_list.append(terrain_spawn)
# Create padded tensor for spawn positions
max_spawn_count = max(1, self.spawn_count_per_terrain.max().item())
self.spawn_positions = torch.full(
(num_terrains, max_spawn_count, 3), -1, dtype=torch.long, device=self.device
)
# Fill spawn position tables
for terrain_idx in range(num_terrains):
terrain_positions = spawn_positions_list[terrain_idx]
num_pos = terrain_positions.shape[0]
if num_pos > 0:
self.spawn_positions[terrain_idx, :num_pos] = terrain_positions
def sample(self, terrain_indices: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Sample GOAL positions for given terrain indices.
Uses valid_mask with platform repetition for curriculum learning.
Args:
terrain_indices: Tensor of terrain indices to sample from.
Returns:
Tuple of (x, y, z) local coordinates in meters.
"""
return self._sample_from_table(
terrain_indices,
self.positions,
self.count_per_terrain
)
def sample_spawn(self, terrain_indices: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Sample SPAWN positions for given terrain indices.
Uses spawn_mask with larger padding to account for:
- Robot body dimensions with random orientation
- Platform edge safety margins
- Controller startup behavior
Args:
terrain_indices: Tensor of terrain indices to sample from.
Returns:
Tuple of (x, y, z) local coordinates in meters.
"""
return self._sample_from_table(
terrain_indices,
self.spawn_positions,
self.spawn_count_per_terrain
)
def _sample_from_table(
self,
terrain_indices: torch.Tensor,
positions_table: torch.Tensor,
count_per_terrain: torch.Tensor
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Internal method to sample from a position table.
Args:
terrain_indices: Tensor of terrain indices to sample from.
positions_table: Pre-computed position table (num_terrains, max_count, 3).
count_per_terrain: Number of valid positions per terrain.
Returns:
Tuple of (x, y, z) local coordinates in meters.
"""
num_samples = terrain_indices.shape[0]
# Random indices within valid range
valid_counts = count_per_terrain[terrain_indices].float().clamp(min=1)
random_indices = (torch.rand(num_samples, device=self.device) * valid_counts).long()
# Lookup positions
selected = positions_table[terrain_indices, random_indices] # (n, 3)
is_valid = selected[:, 0] >= 0
local_x = torch.zeros(num_samples, device=self.device)
local_y = torch.zeros(num_samples, device=self.device)
local_z = torch.zeros(num_samples, device=self.device)
if is_valid.any():
valid_selected = selected[is_valid]
x_idx = valid_selected[:, 1]
y_idx = valid_selected[:, 2]
# Convert to meters (accounting for border pixel offset)
# The mesh is generated with @height_field_to_mesh which adds a border
# border_pixels = int(border_width / horizontal_scale) + 1 (computed dynamically)
# Mesh vertex at (i, j) has position: (i * h_scale - terrain_size/2, j * h_scale - terrain_size/2)
# Our valid_mask[i, j] corresponds to mesh heights[i + border_pixels, j + border_pixels]
# So the world position for valid_mask[i, j] is:
# x = (i + border_pixels) * h_scale - terrain_size/2
# y = (j + border_pixels) * h_scale - terrain_size/2
local_x[is_valid] = (x_idx.float() + self.border_pixels) * self.cell_size - self.mesh_center
local_y[is_valid] = (y_idx.float() + self.border_pixels) * self.cell_size - self.mesh_center
# Lookup Z from heights (our heights tensor matches valid_mask dimensions, no border offset needed)
height_values = self.heights[valid_selected[:, 0], x_idx, y_idx]
local_z[is_valid] = height_values.float() * VERTICAL_SCALE
return local_x, local_y, local_z
# =============================================================================
# Success Rate Tracker
# =============================================================================
class SuccessRateTracker:
"""Tracks navigation success rates using a rolling buffer."""
def __init__(self, num_envs: int, device: torch.device, buffer_size: int = 10):
self.device = device
self.buffer_size = buffer_size
self.buffer = torch.full((num_envs, buffer_size), -1.0, device=device)
self.write_index = torch.zeros(num_envs, dtype=torch.long, device=device)
def record_result(self, success: torch.Tensor, env_ids: torch.Tensor):
indices = self.write_index[env_ids] % self.buffer_size
self.buffer[env_ids, indices] = success[env_ids].float()
self.write_index[env_ids] += 1
def add(self, results: torch.Tensor, env_ids: torch.Tensor):
"""Legacy alias."""
self.record_result(results, env_ids)
def clear(self, env_ids: torch.Tensor):
self.buffer[env_ids] = -1.0
self.write_index[env_ids] = 0
def get_success_rate(self) -> torch.Tensor:
filled_count = (self.buffer >= 0).sum(dim=1).clamp(min=1)
success_count = (self.buffer > 0).sum(dim=1)
return success_count.float() / filled_count.float()
# =============================================================================
# Main Navigation Goal Command Generator
# =============================================================================
class RobotNavigationGoalCommand(CommandTerm):
"""Command generator for robot navigation goal positions.
Samples goal and spawn positions from terrain-provided valid_mask.
"""
cfg: RobotNavigationGoalCommandCfg
def __init__(self, cfg: RobotNavigationGoalCommandCfg, env: ManagerBasedRLEnv):
super().__init__(cfg, env)
self.env = env
self.robot: Articulation = env.scene[cfg.asset_name]
# Terrain configuration
terrain_cfg = env.scene.terrain.cfg.terrain_generator
self.num_terrain_rows = terrain_cfg.num_rows
self.num_terrain_cols = terrain_cfg.num_cols
self.terrain_size = terrain_cfg.size[0]
# Initialize buffers
self._init_command_buffers()
self._init_tracking_buffers()
self._init_metrics()
# Position sampling (lazy initialization)
self._sampling_initialized = False
self._position_sampler: Optional[PositionSampler] = None
def _init_command_buffers(self):
"""Initialize command state buffers."""
# Goal in body frame: [direction_x, direction_y, direction_z, log_distance]
self.goal_command_body = torch.zeros(self.num_envs, 4, device=self.device)
self.goal_command_body_unscaled = torch.ones(self.num_envs, 3, device=self.device)
# World frame positions
self.goal_position_world = torch.zeros(self.num_envs, 3, device=self.device)
self.goal_position_world[:, 2] = 0.5
self.spawn_position_world = torch.zeros(self.num_envs, 3, device=self.device)
self.spawn_position_world[:, 2] = 0.5
self.spawn_position_world[:, :2] = self.env.scene.env_origins[:, :2]
self.spawn_heading_world = torch.zeros(self.num_envs, device=self.device)
def _init_tracking_buffers(self):
"""Initialize goal tracking buffers."""
self.steps_at_goal = torch.zeros(self.num_envs, device=self.device)
self.time_at_goal = torch.zeros(self.num_envs, device=self.device)
self.required_steps_at_goal = 4.0 / self.env.step_dt
self.initial_distance_to_goal = torch.zeros(self.num_envs, device=self.device)
self.distance_to_goal = torch.zeros(self.num_envs, device=self.device)
self.closest_distance_to_goal = torch.zeros(self.num_envs, device=self.device)
self.total_distance_traveled = torch.zeros(self.num_envs, device=self.device)
self.previous_position = torch.zeros(self.num_envs, 3, device=self.device)
self.goal_reach_count = torch.zeros(self.num_envs, device=self.device)
self.success_tracker = SuccessRateTracker(self.num_envs, self.device, buffer_size=10)
self.success_rate_buffer = torch.full((self.num_envs, 10), -1.0, device=self.device)
def _init_metrics(self):
"""Initialize performance metrics."""
self.metrics["velocity_toward_goal"] = torch.zeros(self.num_envs, device=self.device)
self.metrics["velocity_magnitude"] = torch.zeros(self.num_envs, device=self.device)
self.metrics["success_rate"] = torch.zeros(self.num_envs, device=self.device)
# =========================================================================
# Command Interface
# =========================================================================
def __str__(self) -> str:
return f"NavigationGoalCommand:\n\tCommand dimension: {tuple(self.command.shape[1:])}\n"
@property
def command(self) -> torch.Tensor:
return self.goal_command_body
def _get_unscaled_command(self) -> torch.Tensor:
return self.goal_command_body_unscaled
# =========================================================================
# Position Sampling
# =========================================================================
def _initialize_position_sampling(self):
"""Initialize position sampling from terrain-provided masks."""
if self._sampling_initialized:
return
# Get terrain data from scene.terrain (stored by patches system)
terrain = self.env.scene.terrain
# Check for height field data
heights_raw = getattr(terrain, '_height_field_visual', None)
valid_mask_raw = getattr(terrain, '_height_field_valid_mask', None)
platform_mask_raw = getattr(terrain, '_height_field_platform_mask', None)
spawn_mask_raw = getattr(terrain, '_height_field_spawn_mask', None)
if heights_raw is None or valid_mask_raw is None:
raise ValueError(
"No height field data found on terrain. "
"Ensure add_goal=True is set in terrain configuration and patches are applied."
)
# Move to device
heights = heights_raw.to(self.device)
valid_mask = valid_mask_raw.to(self.device)
# Platform mask defaults to empty if not provided
if platform_mask_raw is not None:
platform_mask = platform_mask_raw.to(self.device)
else:
platform_mask = torch.zeros_like(valid_mask)
# Spawn mask defaults to valid_mask if not provided
if spawn_mask_raw is not None:
spawn_mask = spawn_mask_raw.to(self.device)
else:
spawn_mask = valid_mask # Fall back to goal mask
# Get terrain configuration parameters
terrain_cfg = self.env.scene.terrain.cfg.terrain_generator
horizontal_scale = terrain_cfg.horizontal_scale
# Note: border_width for height_field_to_mesh comes from sub-terrain config (HfTerrainBaseCfg),
# NOT from TerrainGeneratorCfg. Sub-terrain configs default to border_width=0.0.
# TerrainGeneratorCfg.border_width (e.g., 30.0) is for the outer grid border, not per-tile.
sub_terrain_border_width = 0.0 # Default from HfTerrainBaseCfg
# Create sampler with both goal (valid_mask) and spawn (spawn_mask) masks
self._position_sampler = PositionSampler(
heights=heights,
valid_mask=valid_mask,
platform_mask=platform_mask,
terrain_size=self.terrain_size,
horizontal_scale=horizontal_scale,
device=self.device,
spawn_mask=spawn_mask,
border_width=sub_terrain_border_width,
)
self._sampling_initialized = True
def _get_terrain_indices(self, env_ids: torch.Tensor) -> torch.Tensor:
"""Get terrain indices for given environment IDs.
The terrain index formula depends on the generation order:
- curriculum=True: column-major (row + col * num_rows)
- curriculum=False: row-major (row * num_cols + col)
Note: terrain_levels corresponds to row, terrain_types to column.
"""
terrain = self.env.scene.terrain
levels = terrain.terrain_levels[env_ids] # row
types = terrain.terrain_types[env_ids] # col
# Check if curriculum mode
terrain_cfg = self.env.scene.terrain.cfg.terrain_generator
if terrain_cfg.curriculum:
# Column-major order (curriculum mode iterates: for col: for row:)
return levels + types * self.num_terrain_rows
else:
# Row-major order (random mode uses np.unravel_index with (num_rows, num_cols))
return levels * self.num_terrain_cols + types
# =========================================================================
# Command Sampling and Update
# =========================================================================
def _resample_command(self, env_ids: Sequence[int]):
"""Sample new goal and spawn positions.
Goal positions use valid_mask (smaller padding, robot just needs to reach).
Spawn positions use spawn_mask (larger padding for robot body clearance).
"""
self._initialize_position_sampling()
if isinstance(env_ids, torch.Tensor):
env_ids_tensor = env_ids.clone().to(device=self.device, dtype=torch.long)
else:
env_ids_tensor = torch.as_tensor(env_ids, device=self.device, dtype=torch.long)
# Reset tracking
self._reset_tracking_state(env_ids)
# Get terrain indices
terrain_indices = self._get_terrain_indices(env_ids_tensor)
# Sample goal positions (from valid_mask with smaller padding)
goal_x, goal_y, goal_z = self._position_sampler.sample(terrain_indices)
# Sample spawn positions (from spawn_mask with larger padding for robot body)
spawn_x, spawn_y, spawn_z = self._position_sampler.sample_spawn(terrain_indices)
# Convert to world coordinates
terrain = self.env.scene.terrain
levels = terrain.terrain_levels[env_ids]
types = terrain.terrain_types[env_ids]
terrain_origins = terrain.terrain_origins[levels, types]
# Update goal position
self.goal_position_world[env_ids, 0] = terrain_origins[:, 0] + goal_x
self.goal_position_world[env_ids, 1] = terrain_origins[:, 1] + goal_y
h_min, h_max = self.cfg.goal_height_offset_range
height_offset = torch.rand(len(env_ids), device=self.device) * (h_max - h_min) + h_min
self.goal_position_world[env_ids, 2] = goal_z + height_offset
# Small spawn height offset to prevent clipping into terrain
# Note: The robot's default_root_state already includes standing height (~0.5m)
spawn_offset = 0.05
# Update spawn/env origin
terrain.env_origins[env_ids, 0] = terrain_origins[:, 0] + spawn_x
terrain.env_origins[env_ids, 1] = terrain_origins[:, 1] + spawn_y
terrain.env_origins[env_ids, 2] = spawn_z + spawn_offset
# Track spawn position
self.spawn_position_world[env_ids, 0] = terrain_origins[:, 0] + spawn_x
self.spawn_position_world[env_ids, 1] = terrain_origins[:, 1] + spawn_y
self.spawn_position_world[env_ids, 2] = spawn_z + spawn_offset
# Initialize distance metrics
self.initial_distance_to_goal[env_ids] = torch.norm(
self.robot.data.root_pos_w[env_ids] - self.goal_position_world[env_ids], dim=1
)
self.closest_distance_to_goal[env_ids] = self.initial_distance_to_goal[env_ids]
def _reset_tracking_state(self, env_ids: Sequence[int]):
"""Reset tracking state for specified environments."""
self.steps_at_goal[env_ids] = 0
self.time_at_goal[env_ids] = 0
self.total_distance_traveled[env_ids] = 0.0
self.previous_position[env_ids] = self.robot.data.root_pos_w[env_ids].clone()
def _update_command(self):
"""Update command in body frame."""
# Transform goal to body frame
inverse_pos, inverse_rot = subtract_frame_transforms(
self.robot.data.root_pos_w,
self.robot.data.root_quat_w
)
goal_in_body = transform_points(
self.goal_position_world.unsqueeze(1),
inverse_pos,
inverse_rot
).squeeze(1)
self.goal_command_body_unscaled = goal_in_body.clone()
# Normalized direction and log distance
distance = torch.norm(goal_in_body, dim=-1, keepdim=True)
direction = goal_in_body / torch.clamp(distance, min=1e-6)
log_distance = torch.log(distance + 1.0)
self.goal_command_body[:, :3] = direction
self.goal_command_body[:, 3:] = log_distance
self._update_distance_tracking()
def _update_distance_tracking(self):
"""Update distance metrics."""
self.distance_to_goal = torch.norm(
self.robot.data.root_pos_w - self.goal_position_world, dim=1
)
self.closest_distance_to_goal = torch.min(
self.closest_distance_to_goal, self.distance_to_goal
)
step_distance = torch.norm(
self.robot.data.root_pos_w - self.previous_position, dim=1
)
self.total_distance_traveled += step_distance
self.previous_position = self.robot.data.root_pos_w.clone()
def _resample_spawn_positions(self, env_ids: Sequence[int]):
"""Update spawn position tracking."""
self.spawn_position_world[env_ids, :2] = self.env.scene.env_origins[env_ids, :2]
# =========================================================================
# Metrics and Reset
# =========================================================================
def _update_metrics(self):
"""Update performance metrics."""
position_error = self.goal_position_world - self.robot.data.root_pos_w[:, :3]
position_error_2d = position_error[:, :2]
velocity_2d = self.robot.data.root_state_w[:, 7:9]
self.metrics["velocity_magnitude"] = torch.norm(velocity_2d, dim=1)
direction_to_goal = position_error_2d / torch.clamp(torch.norm(position_error_2d, dim=1, keepdim=True), min=1e-6)
self.metrics["velocity_toward_goal"] = (velocity_2d * direction_to_goal).sum(dim=1)
self.metrics["success_rate"] = self.success_tracker.get_success_rate()
def reset(self, env_ids: Sequence[int] | None = None) -> dict[str, float]:
"""Reset command generator and compute episode metrics."""
metrics_obs = self.env.observation_manager.compute_group(group_name="metrics")
success = metrics_obs["in_goal"][env_ids].squeeze(-1)
failed = ~success
# Update legacy success rate buffer
self.success_rate_buffer[env_ids] = torch.roll(
self.success_rate_buffer[env_ids], 1, dims=1
)
rate = success.float() - failed.float()
rate[rate == 0] = -1
self.success_rate_buffer[env_ids, 0] = rate
# Reset command state
if env_ids is None:
env_ids = slice(None)
self.command_counter[env_ids] = 0
self._resample(env_ids)
# Return mean metrics
extras = {}
for name, value in self.metrics.items():
extras[name] = torch.mean(value[env_ids]).item()
value[env_ids] = 0.0
return extras
# =========================================================================
# Success/Failure Tracking
# =========================================================================
def update_success(self, at_goal: torch.Tensor):
self.goal_reach_count += at_goal.int()
def update_failures(self, failed: torch.Tensor):
self.goal_reach_count -= failed.int()
# =========================================================================
# Visualization
# =========================================================================
def _set_debug_vis_impl(self, debug_vis: bool):
if debug_vis:
self._setup_visualizers()
else:
self._hide_visualizers()
def _setup_visualizers(self):
"""Create visualization markers."""
if not hasattr(self, "goal_marker"):
cfg = CUBOID_MARKER_CFG.copy()
cfg.prim_path = "/Visuals/Command/goal_position"
cfg.markers["cuboid"].size = (0.2, 0.2, 0.2)
cfg.markers["cuboid"].visual_material.diffuse_color = (0.0, 0.0, 1.0)
self.goal_marker = VisualizationMarkers(cfg)
if not hasattr(self, "spawn_marker"):
cfg = CUBOID_MARKER_CFG.copy()
cfg.prim_path = "/Visuals/Command/spawn_position"
cfg.markers["cuboid"].size = (0.2, 0.2, 0.2)
cfg.markers["cuboid"].visual_material.diffuse_color = (1.0, 0.5, 0.0)
self.spawn_marker = VisualizationMarkers(cfg)
if not hasattr(self, "desired_velocity_marker"):
cfg = GREEN_ARROW_X_MARKER_CFG.copy()
cfg.prim_path = "/Visuals/Command/desired_velocity"
cfg.markers["arrow"].scale = (0.5, 0.5, 0.5)
self.desired_velocity_marker = VisualizationMarkers(cfg)
if not hasattr(self, "current_velocity_marker"):
cfg = RED_ARROW_X_MARKER_CFG.copy()
cfg.prim_path = "/Visuals/Command/current_velocity"
cfg.markers["arrow"].scale = (0.5, 0.5, 0.5)
self.current_velocity_marker = VisualizationMarkers(cfg)
self.goal_marker.set_visibility(True)
self.spawn_marker.set_visibility(True)
self.desired_velocity_marker.set_visibility(True)
self.current_velocity_marker.set_visibility(True)
def _hide_visualizers(self):
for name in ["goal_marker", "spawn_marker", "desired_velocity_marker", "current_velocity_marker"]:
if hasattr(self, name):
getattr(self, name).set_visibility(False)
def _debug_vis_callback(self, event):
"""Update visualization markers."""
self.goal_marker.visualize(self.goal_position_world)
self.spawn_marker.visualize(self.spawn_position_world)
arrow_position = self.robot.data.root_pos_w.clone()
arrow_position[:, 2] += 0.5
desired_scale, desired_quat = self._compute_velocity_arrow(
self.command[:, :3], is_goal_direction=True
)
self.desired_velocity_marker.visualize(arrow_position, desired_quat, desired_scale)
current_scale, current_quat = self._compute_velocity_arrow(
self.robot.data.root_lin_vel_b, is_goal_direction=False
)
self.current_velocity_marker.visualize(arrow_position, current_quat, current_scale)
def _compute_velocity_arrow(
self,
velocity: torch.Tensor,
is_goal_direction: bool
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Compute arrow visualization parameters."""
base_scale = torch.tensor(
self.desired_velocity_marker.cfg.markers["arrow"].scale,
device=self.device
).repeat(velocity.shape[0], 1)
if not is_goal_direction:
velocity = velocity.clone()
velocity[:, 2] = 0.0
base_scale[:, 0] *= torch.norm(velocity, dim=1) * 3.0
quat = vec_to_quat(velocity)
if is_goal_direction:
quat = math_utils.quat_mul(self.robot.data.root_quat_w, quat)
else:
quat = math_utils.quat_mul(yaw_quat(self.robot.data.root_quat_w), quat)
return base_scale, quat
# =========================================================================
# Utility Methods
# =========================================================================
def _is_position_in_bounds(self, position: torch.Tensor) -> torch.Tensor:
half_side = math.ceil(self.num_envs ** 0.5) * self.env.cfg.scene.env_spacing / 2
return (position[:, :2].abs() < half_side).all(dim=1)
def _clamp_to_bounds(self, position: torch.Tensor) -> torch.Tensor:
origins = self.env.scene.terrain.terrain_origins.view(-1, 3)
bounds_max = origins.max(dim=0)[0][:2]
bounds_min = origins.min(dim=0)[0][:2]
position[:, 0] = position[:, 0].clamp(bounds_min[0], bounds_max[0])
position[:, 1] = position[:, 1].clamp(bounds_min[1], bounds_max[1])
return position
# =============================================================================
# Legacy Aliases
# =============================================================================
RobotNavigationGoalCommand.pos_command_b = property(lambda self: self.goal_command_body)
RobotNavigationGoalCommand.pos_command_w = property(lambda self: self.goal_position_world)
RobotNavigationGoalCommand.pos_spawn_w = property(lambda self: self.spawn_position_world)
RobotNavigationGoalCommand.closes_distance_to_goal = property(
lambda self: self.closest_distance_to_goal
)
RobotNavigationGoalCommand.time_at_goal_in_steps = property(lambda self: self.steps_at_goal)
RobotNavigationGoalCommand.required_time_at_goal_in_steps = property(
lambda self: self.required_steps_at_goal
)
RobotNavigationGoalCommand.goal_reached_buffer = property(lambda self: self.success_tracker)
RobotNavigationGoalCommand.goal_reached_counter = property(lambda self: self.goal_reach_count)
RobotNavigationGoalCommand.distance_traveled = property(lambda self: self.total_distance_traveled)
RobotNavigationGoalCommand.previous_pos_3d = property(lambda self: self.previous_position)
@@ -0,0 +1,45 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
from __future__ import annotations
import math
from dataclasses import MISSING
from typing import TYPE_CHECKING, Literal
from isaaclab.managers import CommandTermCfg
from isaaclab.utils import configclass
from isaaclab.utils.noise import AdditiveUniformNoiseCfg
from .goal_commands import RobotNavigationGoalCommand
"""
Base command generator.
"""
@configclass
class RobotNavigationGoalCommandCfg(CommandTermCfg):
"""Configuration for the robot goal command generator."""
class_type: type = RobotNavigationGoalCommand
asset_name: str = MISSING
"""Name of the asset in the environment for which the commands are generated."""
robot_to_goal_line_vis: bool = True
"""If true, visualize the line from the robot to the goal."""
goal_height_offset_range: tuple[float, float] = (0.2, 0.8)
"""Range (min, max) in meters for the random goal height offset above the ground.
The goal cube is placed at ``terrain_ground_height + U(min, max)``. The default
(0.2, 0.8) is tuned for the B2W body height (~0.5-0.6 m). For shorter robots
such as the Go2 (standing height ~0.3 m), lower this range (e.g. (0.1, 0.4)) so
the goal marker sits near the robot body. Note: success/termination is purely
horizontal (xy), so this offset only affects visualization and the minor 3D
``reach_goal_xy_soft`` reward term.
"""
@@ -0,0 +1,507 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Observation functions for navigation tasks.
These functions can be passed to :class:`isaaclab.managers.ObservationTermCfg`
to specify observations for the policy.
"""
from __future__ import annotations
import os
from typing import TYPE_CHECKING, Optional, cast
import torch
import matplotlib.pyplot as plt
from isaaclab.assets import Articulation, RigidObject
from isaaclab.envs import ManagerBasedEnv, ManagerBasedRLEnv
from isaaclab.managers import SceneEntityCfg
import isaaclab_nav_task.navigation.mdp as mdp
from .depth_utils.camera_config import CameraConfig, DEFAULT_CAMERA_CONFIG, get_camera_config
from .depth_utils.depth_noise_encoder import DepthNoiseEncoder
from .heightscan_utils.heightscan_encoder import HeightScanFeatEncoder
if TYPE_CHECKING:
from isaaclab_nav_task.navigation.mdp import PerceptiveNavigationSE2Action
from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand
# Visualization state
_DEPTH_VIZ_WINDOWS: dict[str, dict] = {}
# Global depth noise generator - will be initialized with camera config
DEPTH_NOISE_GENERATOR: Optional[DepthNoiseEncoder] = None
JIT_DEPTH_NOISE_GENERATOR: Optional[torch.jit.ScriptModule] = None
# Global height scan encoder - initialized once on first use
HEIGHTSCAN_FEAT_ENCODER: Optional[HeightScanFeatEncoder] = None
JIT_HEIGHTSCAN_FEAT_ENCODER: Optional[torch.jit.ScriptModule] = None
# Global flags/params for depth encoding
use_jit = True
min_depth = 0.0
max_depth = 0.0
def _update_depth_window(camera_name: str, depth_tensor: torch.Tensor, height: int, width: int, title: str) -> None:
"""Update (or lazily create) a persistent matplotlib window for a camera.
This enables continuous, non-blocking visualization across steps for one or more cameras.
"""
try:
# Convert to numpy and handle different tensor shapes
if depth_tensor.dim() == 4: # [B, 1, H, W]
depth_np = depth_tensor[0, 0].detach().cpu().numpy()
elif depth_tensor.dim() == 2: # [B, H*W]
depth_np = depth_tensor[0].detach().cpu().numpy().reshape(height, width)
else:
return
# Lazily create window if missing
if camera_name not in _DEPTH_VIZ_WINDOWS:
plt.ion()
fig, ax = plt.subplots(1, 1, figsize=(8, 6))
im = ax.imshow(depth_np, cmap="plasma", aspect="equal")
cbar = plt.colorbar(im, ax=ax, label="Depth (meters)")
ax.set_title(title)
ax.set_xlabel("Width (pixels)")
ax.set_ylabel("Height (pixels)")
_DEPTH_VIZ_WINDOWS[camera_name] = {"fig": fig, "ax": ax, "im": im, "cbar": cbar}
else:
handle = _DEPTH_VIZ_WINDOWS[camera_name]
im = handle["im"]
ax = handle["ax"]
ax.set_title(title)
im.set_data(depth_np)
# Optional: keep consistent color scaling per window
im.set_clim(vmin=depth_np.min(), vmax=depth_np.max())
# Lightweight draw
_DEPTH_VIZ_WINDOWS[camera_name]["fig"].canvas.draw_idle()
plt.pause(0.001)
except Exception as e:
print(f"Error updating depth window for {camera_name}: {e}")
def _ensure_depth_noise_generator_initialized(
camera_config: Optional[CameraConfig] = None,
use_jit_precompiled: bool = True,
feature_dim: int = 64,
):
"""Ensure the depth noise generator is initialized with the correct configuration.
This is called automatically by observation functions that need depth encoding.
If not explicitly initialized via initialize_depth_noise_generator(), it will use defaults.
Args:
camera_config: The camera configuration to use. If None, uses DEFAULT_CAMERA_CONFIG.
use_jit_precompiled: Whether to use JIT compilation for faster inference.
feature_dim: Feature dimension for the encoder output.
"""
global DEPTH_NOISE_GENERATOR, JIT_DEPTH_NOISE_GENERATOR, use_jit, min_depth, max_depth
# Only initialize if not already done
if DEPTH_NOISE_GENERATOR is not None:
return
# Use provided camera config or default
config = camera_config if camera_config is not None else DEFAULT_CAMERA_CONFIG
# Extract camera parameters
min_depth = config.min_depth
max_depth = config.max_depth
resolution = config.resolution
print("=" * 80)
print("Initializing depth noise generator for navigation observation:")
print(f" Resolution: {resolution}")
print(f" Depth range: [{min_depth}, {max_depth}]")
print(f" Feature dim: {feature_dim}")
print(f" Encoder path: {config.depth_encoder_path}")
print(f" Use JIT: {use_jit_precompiled}")
# Initialize encoder with the new simplified API
# The DepthNoiseEncoder now takes camera_config directly
DEPTH_NOISE_GENERATOR = DepthNoiseEncoder(
feature_dim=feature_dim,
camera_config=config,
).to(torch.device("cuda"))
DEPTH_NOISE_GENERATOR.eval()
# Create JIT version for inference (optional optimization)
use_jit = use_jit_precompiled
if use_jit:
# Try to find a JIT compiled version
jit_path = config.depth_encoder_path.replace('.pth', '_jit.pt') if config.depth_encoder_path else None
if jit_path and os.path.exists(jit_path):
print(f" Loading precompiled JIT model from: {jit_path}")
JIT_DEPTH_NOISE_GENERATOR = torch.jit.load(jit_path, map_location="cuda")
JIT_DEPTH_NOISE_GENERATOR = torch.jit.optimize_for_inference(JIT_DEPTH_NOISE_GENERATOR)
else:
print(f" JIT compilation requested but no precompiled model found.")
print(f" Creating JIT model from encoder...")
example_input = torch.randn(1, 1, resolution[1], resolution[0]).cuda() # (B, C, H, W)
JIT_DEPTH_NOISE_GENERATOR = torch.jit.trace(DEPTH_NOISE_GENERATOR, example_input)
JIT_DEPTH_NOISE_GENERATOR = torch.jit.optimize_for_inference(JIT_DEPTH_NOISE_GENERATOR)
else:
JIT_DEPTH_NOISE_GENERATOR = DEPTH_NOISE_GENERATOR
print(" Depth noise generator initialized successfully")
print("=" * 80)
def initialize_depth_noise_generator(
camera_config: Optional[CameraConfig] = None,
robot_name: Optional[str] = None,
use_jit_precompiled: bool = True,
feature_dim: int = 64,
):
"""Initialize the depth noise generator with specific configuration.
This function should be called in the environment's __post_init__() to set up
the depth encoder before any observations are computed.
Args:
camera_config: The camera configuration to use. If None and robot_name is provided,
uses the config for that robot. If both are None, uses DEFAULT_CAMERA_CONFIG.
robot_name: Name of the robot (e.g., 'b2w', 'aow_d'). If provided and
camera_config is None, automatically loads the appropriate camera config.
use_jit_precompiled: Whether to use JIT compilation for faster inference. Defaults to True.
feature_dim: Feature dimension for the encoder output. Defaults to 64.
Examples:
# Using robot name (recommended for multi-robot training)
initialize_depth_noise_generator(robot_name="b2w")
# Using explicit camera config
initialize_depth_noise_generator(camera_config=ZEDX_CAMERA_CONFIG)
"""
# If camera_config not provided, try to get it from robot_name
if camera_config is None and robot_name is not None:
camera_config = get_camera_config(robot_name, use_default_fallback=False)
_ensure_depth_noise_generator_initialized(camera_config, use_jit_precompiled, feature_dim)
# ============================================================================
# Observation Functions
# ============================================================================
def generated_commands_reshaped(
env: ManagerBasedRLEnv, command_name: str, unsqueeze_pos: int = 1, flatten: bool = False
) -> torch.Tensor:
"""The generated command from command term in the command manager with the given name."""
if flatten:
return env.command_manager.get_command(command_name)
return env.command_manager.get_command(command_name).unsqueeze(unsqueeze_pos)
def base_lin_vel_delayed(
env: ManagerBasedEnv,
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
) -> torch.Tensor:
"""Compute delayed root linear velocity.
Requires env.delay_manager to exist. Each environment has a random delay
sampled from [0, max_delay] at episode reset.
Args:
env: The environment object (must have delay_manager attribute).
asset_cfg: The name of the asset.
Returns:
The delayed linear velocity in the asset's root frame.
"""
asset: RigidObject = env.scene[asset_cfg.name]
lin_vel = asset.data.root_lin_vel_b
return env.delay_manager.compute_delayed_lin_vel(lin_vel)
def base_ang_vel_delayed(
env: ManagerBasedEnv,
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
) -> torch.Tensor:
"""Compute delayed root angular velocity.
Requires env.delay_manager to exist. Each environment has a random delay
sampled from [0, max_delay] at episode reset.
Args:
env: The environment object (must have delay_manager attribute).
asset_cfg: The name of the asset.
Returns:
The delayed angular velocity in the asset's root frame.
"""
asset: RigidObject = env.scene[asset_cfg.name]
ang_vel = asset.data.root_ang_vel_b
return env.delay_manager.compute_delayed_ang_vel(ang_vel)
def projected_gravity_delayed(
env: ManagerBasedEnv,
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
) -> torch.Tensor:
"""Compute delayed projected gravity.
Requires env.delay_manager to exist. Each environment has a random delay
sampled from [0, max_delay] at episode reset.
Args:
env: The environment object (must have delay_manager attribute).
asset_cfg: The name of the asset.
Returns:
The delayed projected gravity in the asset's root frame.
"""
asset: RigidObject = env.scene[asset_cfg.name]
projected_gravity = asset.data.projected_gravity_b
return env.delay_manager.compute_delayed_projected_gravity(projected_gravity)
def height_scan_feat(
env: ManagerBasedEnv, sensor_cfg: SceneEntityCfg = SceneEntityCfg("height_scanner_critic"), offset: float = 0.5
) -> torch.Tensor:
"""Height scan feature from a ray caster sensor, encoded using a pre-trained VAE encoder.
The height scan is reshaped to a 51x51 grid and encoded using a VAE encoder that
outputs a 64-channel, 7x7 spatial feature map (64*7*7 = 3136 features).
Args:
env: The environment object.
sensor_cfg: The configuration of the height scanner sensor.
offset: Offset to subtract from the height values. Defaults to 0.5.
Returns:
The encoded height scan features of shape (num_envs, 3136).
"""
global HEIGHTSCAN_FEAT_ENCODER, JIT_HEIGHTSCAN_FEAT_ENCODER
# Initialize the encoder on first call
if HEIGHTSCAN_FEAT_ENCODER is None:
print("Initializing height scan feature encoder...")
HEIGHTSCAN_FEAT_ENCODER = HeightScanFeatEncoder(feature_dim=64).to(torch.device("cuda"))
HEIGHTSCAN_FEAT_ENCODER.eval()
JIT_HEIGHTSCAN_FEAT_ENCODER = torch.jit.script(HEIGHTSCAN_FEAT_ENCODER)
JIT_HEIGHTSCAN_FEAT_ENCODER = torch.jit.optimize_for_inference(JIT_HEIGHTSCAN_FEAT_ENCODER)
# Get height scanner data
height_scanner = env.scene.sensors[sensor_cfg.name]
# Compute height scan: sensor_height - hit_z - offset
scan_data = height_scanner.data.pos_w[:, 2].unsqueeze(1) - height_scanner.data.ray_hits_w[..., 2] - offset
# Clamp the height scan data to the range [-5, 5]
scan_data = torch.clamp(scan_data, min=-5.0, max=5.0)
# Expected grid size for the height scanner (51x51 = 2601 points)
H = W = 51
# Reshape the height scan data to a 2D grid
scan_data = scan_data.view(-1, H, W)
# Encode using the pre-trained encoder
with torch.no_grad():
encoded_scan = JIT_HEIGHTSCAN_FEAT_ENCODER(scan_data)
# Flatten and return: (batch, 64, 7, 7) -> (batch, 3136)
return encoded_scan.view(env.num_envs, -1)
def generated_actions(env: ManagerBasedRLEnv, action_name: str) -> torch.Tensor:
"""The generated action from action term in the action manager with the given name.
Args:
env: The environment object.
action_name: The name of the action term.
Returns:
The processed actions from the action term.
"""
return env.action_manager.get_term(action_name).processed_actions
def generated_commands_reshaped_delayed(
env: ManagerBasedRLEnv,
command_name: str,
unsqueeze_pos: int = 1,
flatten: bool = False,
) -> torch.Tensor:
"""The generated command with delay applied.
Requires env.delay_manager to exist. Each environment has a random delay
sampled from [0, max_delay] at episode reset.
Args:
env: The environment object (must have delay_manager attribute).
command_name: The name of the command term.
unsqueeze_pos: Position to unsqueeze the command.
flatten: Whether to flatten the command.
Returns:
The delayed command.
"""
if flatten:
command = env.command_manager.get_command(command_name)
return env.delay_manager.compute_delayed_target_position(command)
command = env.command_manager.get_command(command_name).unsqueeze(unsqueeze_pos)
return env.delay_manager.compute_delayed_target_position(command)
def last_low_level_action(
env: ManagerBasedEnv, action_term: str, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")
) -> torch.Tensor:
"""The last low-level action.
Args:
env: The environment object.
action_term: The name of the action term.
Returns:
The last low-level action.
"""
action_term: PerceptiveNavigationSE2Action = env.action_manager._terms[action_term]
return action_term.low_level_actions[:, asset_cfg.joint_ids]
@torch.inference_mode()
def depth_image_prefect(env, sensor_cfg):
"""Return the perfect (non-noisy) encoded depth image from the camera.
Args:
env: The environment object.
sensor_cfg: The sensor configuration.
Returns:
The encoded depth image features.
"""
# Ensure encoder is initialized
_ensure_depth_noise_generator_initialized()
depth_camera = env.scene.sensors[sensor_cfg.name]
# Get depth image tensor
depth_tensor = depth_camera.data.output["distance_to_image_plane"].view(env.num_envs, -1)
# Handle NaN values by replacing them with 50.0
depth_tensor = torch.nan_to_num(depth_tensor, nan=50.0, posinf=50.0, neginf=0.0)
# Reshape the tensor to [B, 1, H, W]
H, W = depth_camera.image_shape
depth_tensor = depth_tensor.view(-1, 1, H, W)
assert JIT_DEPTH_NOISE_GENERATOR is not None, (
"Depth encoder JIT model is not initialized. Call initialize_depth_noise_generator first."
)
model = cast(torch.jit.ScriptModule, JIT_DEPTH_NOISE_GENERATOR)
if use_jit:
depth_tensor[depth_tensor > max_depth] = 0.0
encoded_depth_tensor = model(depth_tensor)
else:
encoded_depth_tensor, _ = model(depth_tensor)
return encoded_depth_tensor.view(env.num_envs, -1)
@torch.no_grad()
def depth_image_noisy_delayed(
env, sensor_cfg, visualize: bool = False
):
"""Return the noisy and delayed encoded depth image from the camera.
Requires env.delay_manager to exist. Each environment has a random delay
sampled from [0, max_delay] at episode reset.
Args:
env: The environment object (must have delay_manager attribute).
sensor_cfg: The sensor configuration.
visualize: Whether to visualize the depth image.
Returns:
The delayed encoded depth image features.
"""
# Ensure encoder is initialized
_ensure_depth_noise_generator_initialized()
depth_camera = env.scene.sensors[sensor_cfg.name]
# Get depth image tensor
depth_tensor = depth_camera.data.output["distance_to_image_plane"].view(env.num_envs, -1)
# Handle NaN values by replacing them with 50.0
depth_tensor = torch.nan_to_num(depth_tensor, nan=50.0, posinf=50.0, neginf=0.0)
# Reshape the tensor to [B, 1, H, W]
H, W = depth_camera.image_shape
depth_tensor = depth_tensor.view(-1, 1, H, W)
assert JIT_DEPTH_NOISE_GENERATOR is not None, (
"Depth encoder JIT model is not initialized. Call initialize_depth_noise_generator first."
)
model = cast(torch.jit.ScriptModule, JIT_DEPTH_NOISE_GENERATOR)
if use_jit:
depth_tensor[depth_tensor > max_depth] = 0.0 # depth larger than depth max is invalid
depth_tensor[depth_tensor < min_depth] = 0.0 # depth smaller than depth min is invalid
encoded_depth_tensor = model(depth_tensor)
noisy_depth_tensor = depth_tensor
else:
encoded_depth_tensor, noisy_depth_tensor = model(depth_tensor)
# Continuous visualization (single-env) with persistent windows
if visualize and env.num_envs == 1 and not use_jit:
camera_name = sensor_cfg.name if hasattr(sensor_cfg, "name") else "camera"
_update_depth_window(camera_name, noisy_depth_tensor, H, W, title=f"Depth (Noisy Delayed) - {camera_name}")
encoded_depth_tensor_reshaped = encoded_depth_tensor.view(env.num_envs, -1)
# Apply delay using env's delay manager
camera_name = sensor_cfg.name if hasattr(sensor_cfg, "name") else "depth"
return env.delay_manager.compute_delayed_depth(encoded_depth_tensor_reshaped, camera_name)
def in_goal(
env: ManagerBasedRLEnv,
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
distance_threshold: float = 0.5,
goal_cmd_name: str = "robot_goal",
) -> torch.Tensor:
"""Check if the robot is within the goal distance threshold.
Args:
env: The learning environment.
asset_cfg: The name of the robot asset.
distance_threshold: The distance threshold to the goal.
goal_cmd_name: The name of the goal command.
Returns:
Boolean tensor indicating whether the robot is within the goal.
"""
asset: Articulation = env.scene[asset_cfg.name]
goal_cmd_generator: RobotNavigationGoalCommand = env.command_manager._terms[goal_cmd_name]
distance_goal = torch.norm(asset.data.root_pos_w[:, :2] - goal_cmd_generator.pos_command_w[:, :2], dim=1, p=2, keepdim=True)
return distance_goal < distance_threshold
def time_normalized(env: ManagerBasedRLEnv, command_name: str = "robot_goal") -> torch.Tensor:
"""Time normalized to the maximum episode length.
Args:
env: The learning environment.
command_name: The name of the goal command.
Returns:
The normalized time (current step / max steps).
"""
T_max = env.max_episode_length
if hasattr(env, "episode_length_buf"):
t = env.episode_length_buf.unsqueeze(-1)
else:
t = torch.tensor([0.0]).repeat(env.num_envs, 1).to(env.device)
return t / T_max
@@ -0,0 +1,134 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Reward functions for navigation tasks.
These functions can be passed to :class:`isaaclab.managers.RewardTermCfg`
to specify the reward function and its parameters.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from isaaclab.assets import Articulation
from isaaclab.managers import SceneEntityCfg
from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand
if TYPE_CHECKING:
from isaaclab.envs import ManagerBasedRLEnv
def action_rate_l1(env: "ManagerBasedRLEnv") -> torch.Tensor:
"""Penalize the rate of change of the actions using L1 kernel."""
return torch.sum(torch.abs(env.action_manager.action - env.action_manager.prev_action), dim=1)
def lateral_movement(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Reward the agent for moving laterally using L1-Kernel.
Args:
env: The learning environment.
asset_cfg: The name of the robot asset.
Returns:
Dense reward [0, +1] based on the lateral velocity.
"""
asset: Articulation = env.scene[asset_cfg.name]
# compute the reward
lateral_velocity = asset.data.root_lin_vel_b[:, 1]
reward = torch.abs(lateral_velocity)
return reward
def rot_movement(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Reward the agent for rotating around the z-axis using an L2-Kernel.
Args:
env: The learning environment.
asset_cfg: The name of the robot asset.
Returns:
Dense reward [0, +1] based on the rotational velocity.
"""
asset: Articulation = env.scene[asset_cfg.name]
rot_vel_norm = torch.norm(asset.data.root_ang_vel_b, dim=1)
return rot_vel_norm
def reach_goal_xyz(
env: ManagerBasedRLEnv,
command_name: str,
sigmoid: float,
T_r: float,
probability: float,
flat: bool,
ratio: bool,
) -> torch.Tensor:
"""Reward goal reaching with configurable sigmoid shaping.
Args:
env: The learning environment.
command_name: Name of the goal command.
sigmoid: Sigmoid parameter for shaping.
T_r: Time reward scaling factor.
probability: Probability of random sampling.
flat: Whether to only consider xy error (ignore z).
ratio: Whether to scale by travel distance ratio.
Returns:
Dense reward based on distance to goal.
"""
goal_cmd_generator: RobotNavigationGoalCommand = env.command_manager._terms[command_name]
t = env.episode_length_buf
T = env.max_episode_length
if flat:
xyz_error = torch.norm(goal_cmd_generator._get_unscaled_command()[:, :2], dim=1)
else:
xyz_error = torch.norm(goal_cmd_generator._get_unscaled_command(), dim=1)
reward = 1 / (1 + torch.square(xyz_error / sigmoid)) / T_r
timeup_mask = t > (T - goal_cmd_generator.required_time_at_goal_in_steps)
random_mask = torch.rand_like(t.float()) < probability
timeup_mask = torch.logical_or(timeup_mask, random_mask)
arrive_mask = goal_cmd_generator.time_at_goal > 0.0
reward_mask = torch.logical_or(timeup_mask, arrive_mask)
if ratio:
# Calculate the travel distance ratio relative to the initial goal distance
travel_distance = torch.max(
goal_cmd_generator.distance_traveled, goal_cmd_generator.initial_distance_to_goal
)
travel_distance_ratio = goal_cmd_generator.initial_distance_to_goal / (travel_distance + 1e-6)
else:
travel_distance_ratio = torch.ones_like(reward)
reward = reward * reward_mask.float() * travel_distance_ratio
return reward
def backward_movement_penalty(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor:
"""Small penalty for backward movement as a regularization term.
Args:
env: The learning environment.
asset_cfg: The name of the robot asset.
Returns:
Penalty [0, +1] based on backward velocity (to be used with negative weight).
"""
asset: Articulation = env.scene[asset_cfg.name]
# compute the penalty
forward_velocity = asset.data.root_lin_vel_b[:, 0]
# Only penalize negative forward velocity (backward movement)
backward_velocity = torch.clamp(-forward_velocity, min=0.0, max=1.0)
return backward_velocity
@@ -0,0 +1,211 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Common functions that can be used to activate certain terminations.
The functions can be passed to the :class:`isaaclab.managers.TerminationTermCfg` object to enable
the termination introduced by the function.
"""
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
from isaaclab.assets import Articulation
from isaaclab.managers import SceneEntityCfg
from isaaclab.sensors import ContactSensor
from isaaclab.utils.math import quat_inv, yaw_quat, quat_mul, euler_xyz_from_quat
if TYPE_CHECKING:
from isaaclab.envs import ManagerBasedRLEnv
from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand
def euler_xyz_from_quat_wrapped(quat: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Convert quaternion to Euler angles (XYZ convention) with wrapping to [-pi, pi].
Args:
quat: Quaternion tensor of shape (..., 4) in (w, x, y, z) format.
Returns:
Tuple of (roll, pitch, yaw) tensors.
"""
roll, pitch, yaw = euler_xyz_from_quat(quat)
# Wrap to [-pi, pi]
roll = torch.remainder(roll + torch.pi, 2 * torch.pi) - torch.pi
pitch = torch.remainder(pitch + torch.pi, 2 * torch.pi) - torch.pi
yaw = torch.remainder(yaw + torch.pi, 2 * torch.pi) - torch.pi
return roll, pitch, yaw
def time_out_navigation(
env: "ManagerBasedRLEnv",
goal_cmd_name: str = "robot_goal",
distance_threshold: float = 0.5
) -> torch.Tensor:
"""Terminate the episode when the episode length exceeds the maximum episode length.
This also tracks success metrics by checking if the robot reached the goal before timeout.
"""
from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand
goal_cmd_generator: RobotNavigationGoalCommand = env.command_manager._terms[goal_cmd_name]
termination = env.episode_length_buf >= env.max_episode_length
env_ids = torch.where(termination)[0]
distance_goal = torch.norm(goal_cmd_generator._get_unscaled_command()[:, :2], dim=1)
# update time at goal
goal_cmd_generator.time_at_goal[distance_goal < distance_threshold] += 1 * env.step_dt
if env_ids.numel() > 0: # Check if env_ids is not empty
success_masks = goal_cmd_generator.time_at_goal > 0.0
value_buffer = torch.zeros_like(distance_goal) # init with 0: Fail
value_buffer[success_masks] = 1.0 # Success
goal_cmd_generator.goal_reached_buffer.add(value_buffer, env_ids)
return termination
def illegal_contact_navigation(
env: "ManagerBasedRLEnv",
threshold: float,
sensor_cfg: SceneEntityCfg,
goal_cmd_name: str = "robot_goal",
) -> torch.Tensor:
"""Terminate when the contact force on the sensor exceeds the force threshold."""
from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand
# extract the used quantities (to enable type-hinting)
contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name]
net_contact_forces = contact_sensor.data.net_forces_w_history
goal_cmd_generator: RobotNavigationGoalCommand = env.command_manager._terms[goal_cmd_name]
termination = torch.any(
torch.max(torch.norm(net_contact_forces[:, :, sensor_cfg.body_ids], dim=-1), dim=1)[0] > threshold, dim=1
)
env_ids = torch.where(termination)[0]
if env_ids.numel() > 0: # Check if env_ids is not empty
goal_cmd_generator.goal_reached_buffer.add(torch.zeros_like(termination, dtype=torch.float), env_ids)
return termination
def large_angle_termination_navigation(
env: "ManagerBasedRLEnv",
threshold: float,
goal_cmd_name: str = "robot_goal",
) -> torch.Tensor:
"""Terminate when the robot exceeds a pitch or roll angle threshold."""
from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand
goal_cmd_generator: RobotNavigationGoalCommand = env.command_manager._terms[goal_cmd_name]
# degree to rad
threshold_rad = threshold * torch.pi / 180.0
robot = env.scene["robot"]
yaw_q = yaw_quat(robot.data.root_quat_w)
base_quat_b = quat_mul(quat_inv(yaw_q), robot.data.root_quat_w)
robot_roll, robot_pitch, _ = euler_xyz_from_quat_wrapped(base_quat_b)
termination = torch.logical_or(torch.abs(robot_pitch) > threshold_rad, torch.abs(robot_roll) > threshold_rad)
env_ids = torch.where(termination)[0]
if env_ids.numel() > 0: # Check if env_ids is not empty
goal_cmd_generator.goal_reached_buffer.add(torch.zeros_like(termination, dtype=torch.float), env_ids)
return termination
def at_goal_navigation(
env: "ManagerBasedRLEnv",
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
distance_threshold: float = 0.5,
goal_cmd_name: str = "robot_goal",
) -> torch.Tensor:
"""Terminate the episode when the goal is reached.
Args:
env: The learning environment.
asset_cfg: The name of the robot asset.
distance_threshold: The distance threshold to the goal.
goal_cmd_name: The name of the goal command term.
Returns:
Boolean tensor indicating whether the goal is reached.
"""
from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand
# Extract the used quantities
asset: Articulation = env.scene[asset_cfg.name]
goal_cmd_generator: RobotNavigationGoalCommand = env.command_manager._terms.get(goal_cmd_name)
# Calculate distance to goal
xy_error = torch.norm(goal_cmd_generator._get_unscaled_command()[:, :2], dim=1)
# Check conditions for termination
at_goal = xy_error < distance_threshold
# already at goal
already_at_goal = goal_cmd_generator.time_at_goal > 0.0
at_goal = torch.logical_or(at_goal, already_at_goal)
# Update the time at goal in steps
goal_cmd_generator.time_at_goal_in_steps[at_goal] += 1 # Increment if at goal
# Determine if termination condition is met
termination = goal_cmd_generator.time_at_goal_in_steps > goal_cmd_generator.required_time_at_goal_in_steps
# Update goal reached buffer if termination condition is met
env_ids = torch.where(termination)[0]
if env_ids.numel() > 0: # Check if any environments have met the termination condition
goal_cmd_generator.goal_reached_buffer.add(torch.ones_like(termination, dtype=torch.float), env_ids)
return termination
def terrain_fall(
env: "ManagerBasedRLEnv",
asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"),
fall_height_threshold: float = -1.0,
goal_cmd_name: str = "robot_goal",
) -> torch.Tensor:
"""Terminate when the robot falls below a certain height threshold.
This termination is triggered when the robot's z-position falls below a
specified threshold, indicating that the robot has fallen off the terrain
or into a deep pit.
Args:
env: The learning environment.
asset_cfg: The configuration for the robot asset.
fall_height_threshold: The z-height below which the robot is considered fallen (in meters).
Default is -1.0m to account for pits which can be ~1.5m deep.
goal_cmd_name: The name of the goal command term.
Returns:
Boolean tensor indicating whether the robot has fallen.
"""
# Direct tensor access for z-coordinate (avoids intermediate variable allocation)
termination = env.scene[asset_cfg.name].data.root_pos_w[:, 2] < fall_height_threshold
# Early exit if no terminations (common case - avoids torch.where overhead)
if not termination.any():
return termination
# Update goal reached buffer with failure
goal_cmd = env.command_manager._terms.get(goal_cmd_name)
if goal_cmd is not None:
env_ids = termination.nonzero(as_tuple=False).squeeze(-1)
goal_cmd.goal_reached_buffer.add(torch.zeros(env.num_envs, dtype=torch.float, device=env.device), env_ids)
return termination