omni.isaac.lab.utils

Contents

omni.isaac.lab.utils#

Sub-package containing utilities for common operations and helper functions.

Submodules

io

Submodules for files IO operations.

array

Sub-module containing utilities for working with different array backends.

assets

Sub-module that defines the host-server where assets and resources are stored.

buffers

Sub-module containing different buffers.

dict

Sub-module for utilities for working with dictionaries.

interpolation

Submodule for different interpolation methods.

math

Sub-module containing utilities for various math operations.

modifiers

Sub-module containing different modifiers implementations.

noise

Sub-module containing different noise models implementations.

string

Sub-module containing utilities for transforming strings and regular expressions.

timer

Sub-module for a timer class that can be used for performance measurements.

types

Sub-module for different data types.

warp

Sub-module containing operations based on warp.

Functions

configclass(cls, **kwargs)

Wrapper around dataclass functionality to add extra checks and utilities.

Configuration class#

Sub-module that provides a wrapper around the Python 3.7 onwards dataclasses module.

Functions:

configclass(cls, **kwargs)

Wrapper around dataclass functionality to add extra checks and utilities.

omni.isaac.lab.utils.configclass.configclass(cls, **kwargs)[source]#

Wrapper around dataclass functionality to add extra checks and utilities.

As of Python 3.7, the standard dataclasses have two main issues which makes them non-generic for configuration use-cases. These include:

  1. Requiring a type annotation for all its members.

  2. Requiring explicit usage of field(default_factory=...)() to reinitialize mutable variables.

This function provides a decorator that wraps around Python’s dataclass utility to deal with the above two issues. It also provides additional helper functions for dictionary <-> class conversion and easily copying class instances.

Usage:

from dataclasses import MISSING

from omni.isaac.lab.utils.configclass import configclass


@configclass
class ViewerCfg:
    eye: list = [7.5, 7.5, 7.5]  # field missing on purpose
    lookat: list = field(default_factory=[0.0, 0.0, 0.0])


@configclass
class EnvCfg:
    num_envs: int = MISSING
    episode_length: int = 2000
    viewer: ViewerCfg = ViewerCfg()

# create configuration instance
env_cfg = EnvCfg(num_envs=24)

# print information as a dictionary
print(env_cfg.to_dict())

# create a copy of the configuration
env_cfg_copy = env_cfg.copy()

# replace arbitrary fields using keyword arguments
env_cfg_copy = env_cfg_copy.replace(num_envs=32)
Parameters:
  • cls – The class to wrap around.

  • **kwargs – Additional arguments to pass to dataclass().

Returns:

The wrapped class.

IO operations#

Submodules for files IO operations.

Functions:

dump_pickle(filename, data)

Saves data into a pickle file safely.

load_pickle(filename)

Loads an input PKL file safely.

dump_yaml(filename, data[, sort_keys])

Saves data into a YAML file safely.

load_yaml(filename)

Loads an input PKL file safely.

omni.isaac.lab.utils.io.dump_pickle(filename: str, data: Any)[source]#

Saves data into a pickle file safely.

Note

The function creates any missing directory along the file’s path.

Parameters:
  • filename – The path to save the file at.

  • data – The data to save.

omni.isaac.lab.utils.io.load_pickle(filename: str) Any[source]#

Loads an input PKL file safely.

Parameters:

filename – The path to pickled file.

Raises:

FileNotFoundError – When the specified file does not exist.

Returns:

The data read from the input file.

omni.isaac.lab.utils.io.dump_yaml(filename: str, data: dict | object, sort_keys: bool = False)[source]#

Saves data into a YAML file safely.

Note

The function creates any missing directory along the file’s path.

Parameters:
  • filename – The path to save the file at.

  • data – The data to save either a dictionary or class object.

  • sort_keys – Whether to sort the keys in the output file. Defaults to False.

omni.isaac.lab.utils.io.load_yaml(filename: str) dict[source]#

Loads an input PKL file safely.

Parameters:

filename – The path to pickled file.

Raises:

FileNotFoundError – When the specified file does not exist.

Returns:

The data read from the input file.

Array operations#

Sub-module containing utilities for working with different array backends.

Data:

TENSOR_TYPES

A dictionary containing the types for each backend.

TENSOR_TYPE_CONVERSIONS

A nested dictionary containing the conversion functions for each backend.

Functions:

convert_to_torch(array[, dtype, device])

Converts a given array into a torch tensor.

omni.isaac.lab.utils.array.TensorData(*args, **kwargs)#

Type definition for a tensor data.

Union of numpy, torch, and warp arrays.

alias of Union[ndarray, Tensor, array]

omni.isaac.lab.utils.array.TENSOR_TYPES = {'numpy': numpy.ndarray, 'torch': torch.Tensor, 'warp': warp.array}#

A dictionary containing the types for each backend.

The keys are the name of the backend (“numpy”, “torch”, “warp”) and the values are the corresponding type (np.ndarray, torch.Tensor, wp.array).

omni.isaac.lab.utils.array.TENSOR_TYPE_CONVERSIONS = {'numpy': {warp.array: <function <lambda>>, torch.Tensor: <function <lambda>>}, 'torch': {warp.array: <function <lambda>>, numpy.ndarray: <function <lambda>>}, 'warp': {numpy.array: <function <lambda>>, torch.Tensor: <function <lambda>>}}#

A nested dictionary containing the conversion functions for each backend.

The keys of the outer dictionary are the name of target backend (“numpy”, “torch”, “warp”). The keys of the inner dictionary are the source backend (np.ndarray, torch.Tensor, wp.array).

omni.isaac.lab.utils.array.convert_to_torch(array: TensorData, dtype: torch.dtype = None, device: torch.device | str | None = None) torch.Tensor[source]#

Converts a given array into a torch tensor.

The function tries to convert the array to a torch tensor. If the array is a numpy/warp arrays, or python list/tuples, it is converted to a torch tensor. If the array is already a torch tensor, it is returned directly.

If device is None, then the function deduces the current device of the data. For numpy arrays, this defaults to “cpu”, for torch tensors it is “cpu” or “cuda”, and for warp arrays it is “cuda”.

Note

Since PyTorch does not support unsigned integer types, unsigned integer arrays are converted to signed integer arrays. This is done by casting the array to the corresponding signed integer type.

Parameters:
  • array – The input array. It can be a numpy array, warp array, python list/tuple, or torch tensor.

  • dtype – Target data-type for the tensor.

  • device – The target device for the tensor. Defaults to None.

Returns:

The converted array as torch tensor.

Asset operations#

Sub-module that defines the host-server where assets and resources are stored.

By default, we use the Isaac Sim Nucleus Server for hosting assets and resources. This makes distribution of the assets easier and makes the repository smaller in size code-wise.

For more information, please check information on Omniverse Nucleus.

Data:

NUCLEUS_ASSET_ROOT_DIR

Path to the root directory on the Nucleus Server.

NVIDIA_NUCLEUS_DIR

Path to the root directory on the NVIDIA Nucleus Server.

ISAAC_NUCLEUS_DIR

Path to the Isaac directory on the NVIDIA Nucleus Server.

ISAACLAB_NUCLEUS_DIR

Path to the Isaac/IsaacLab directory on the NVIDIA Nucleus Server.

Functions:

check_file_path(path)

Checks if a file exists on the Nucleus Server or locally.

retrieve_file_path(path[, download_dir, ...])

Retrieves the path to a file on the Nucleus Server or locally.

read_file(path)

Reads a file from the Nucleus Server or locally.

omni.isaac.lab.utils.assets.NUCLEUS_ASSET_ROOT_DIR = '/persistent/isaac/asset_root/cloud'#

Path to the root directory on the Nucleus Server.

omni.isaac.lab.utils.assets.NVIDIA_NUCLEUS_DIR = 'carb.settings.get_settings.get/NVIDIA'#

Path to the root directory on the NVIDIA Nucleus Server.

omni.isaac.lab.utils.assets.ISAAC_NUCLEUS_DIR = 'carb.settings.get_settings.get/Isaac'#

Path to the Isaac directory on the NVIDIA Nucleus Server.

omni.isaac.lab.utils.assets.ISAACLAB_NUCLEUS_DIR = 'carb.settings.get_settings.get/Isaac/IsaacLab'#

Path to the Isaac/IsaacLab directory on the NVIDIA Nucleus Server.

omni.isaac.lab.utils.assets.check_file_path(path: str) Literal[0, 1, 2][source]#

Checks if a file exists on the Nucleus Server or locally.

Parameters:

path – The path to the file.

Returns:

The status of the file. Possible values are listed below.

  • 0 if the file does not exist

  • 1 if the file exists locally

  • 2 if the file exists on the Nucleus Server

omni.isaac.lab.utils.assets.retrieve_file_path(path: str, download_dir: str | None = None, force_download: bool = True) str[source]#

Retrieves the path to a file on the Nucleus Server or locally.

If the file exists locally, then the absolute path to the file is returned. If the file exists on the Nucleus Server, then the file is downloaded to the local machine and the absolute path to the file is returned.

Parameters:
  • path – The path to the file.

  • download_dir – The directory where the file should be downloaded. Defaults to None, in which case the file is downloaded to the system’s temporary directory.

  • force_download – Whether to force download the file from the Nucleus Server. This will overwrite the local file if it exists. Defaults to True.

Returns:

The path to the file on the local machine.

Raises:
  • FileNotFoundError – When the file not found locally or on Nucleus Server.

  • RuntimeError – When the file cannot be copied from the Nucleus Server to the local machine. This can happen when the file already exists locally and force_download is set to False.

omni.isaac.lab.utils.assets.read_file(path: str) BytesIO[source]#

Reads a file from the Nucleus Server or locally.

Parameters:

path – The path to the file.

Raises:

FileNotFoundError – When the file not found locally or on Nucleus Server.

Returns:

The content of the file.

Buffer operations#

Sub-module containing different buffers.

Classes:

CircularBuffer

Circular buffer for storing a history of batched tensor data.

DelayBuffer

Delay buffer that allows retrieving stored data with delays.

TimestampedBuffer

A buffer class containing data and its timestamp.

class omni.isaac.lab.utils.buffers.CircularBuffer[source]#

Bases: object

Circular buffer for storing a history of batched tensor data.

This class implements a circular buffer for storing a history of batched tensor data. The buffer is initialized with a maximum length and a batch size. The data is stored in a circular fashion, and the data can be retrieved in a LIFO (Last-In-First-Out) fashion. The buffer is designed to be used in multi-environment settings, where each environment has its own data.

The shape of the appended data is expected to be (batch_size, …), where the first dimension is the batch dimension. Correspondingly, the shape of the ring buffer is (max_len, batch_size, …).

Methods:

__init__(max_len, batch_size, device)

Initialize the circular buffer.

reset([batch_ids])

Reset the circular buffer at the specified batch indices.

append(data)

Append the data to the circular buffer.

Attributes:

batch_size

The batch size of the ring buffer.

device

The device used for processing.

max_length

The maximum length of the ring buffer.

current_length

The current length of the buffer.

buffer

Complete circular buffer with most recent entry at the end and oldest entry at the beginning.

__init__(max_len: int, batch_size: int, device: str)[source]#

Initialize the circular buffer.

Parameters:
  • max_len – The maximum length of the circular buffer. The minimum allowed value is 1.

  • batch_size – The batch dimension of the data.

  • device – The device used for processing.

Raises:

ValueError – If the buffer size is less than one.

property batch_size: int#

The batch size of the ring buffer.

property device: str#

The device used for processing.

property max_length: int#

The maximum length of the ring buffer.

property current_length: torch.Tensor#

The current length of the buffer. Shape is (batch_size,).

Since the buffer is circular, the current length is the minimum of the number of pushes and the maximum length.

property buffer: torch.Tensor#

Complete circular buffer with most recent entry at the end and oldest entry at the beginning. :returns: ]]. :rtype: Complete circular buffer with most recent entry at the end and oldest entry at the beginning of dimension 1. The shape is [batch_size, max_length, data.shape[1

reset(batch_ids: Sequence[int] | None = None)[source]#

Reset the circular buffer at the specified batch indices.

Parameters:

batch_ids – Elements to reset in the batch dimension. Default is None, which resets all the batch indices.

append(data: torch.Tensor)[source]#

Append the data to the circular buffer.

Parameters:

data – The data to append to the circular buffer. The first dimension should be the batch dimension. Shape is (batch_size, …).

Raises:

ValueError – If the input data has a different batch size than the buffer.

class omni.isaac.lab.utils.buffers.DelayBuffer[source]#

Bases: object

Delay buffer that allows retrieving stored data with delays.

This class uses a batched circular buffer to store input data. Different to a standard circular buffer, which uses the LIFO (last-in-first-out) principle to retrieve the data, the delay buffer class allows retrieving data based on the lag set by the user. For instance, if the delay set inside the buffer is 1, then the second last entry from the stream is retrieved. If it is 2, then the third last entry and so on.

The class supports storing a batched tensor data. This means that the shape of the appended data is expected to be (batch_size, …), where the first dimension is the batch dimension. Correspondingly, the delay can be set separately for each batch index. If the requested delay is larger than the current length of the underlying buffer, the most recent entry is returned.

Note

By default, the delay buffer has no delay, meaning that the data is returned as is.

Methods:

__init__(history_length, batch_size, device)

Initialize the delay buffer.

set_time_lag(time_lag[, batch_ids])

Sets the time lag for the delay buffer across the provided batch indices.

reset([batch_ids])

Reset the data in the delay buffer at the specified batch indices.

compute(data)

Append the input data to the buffer and returns a stale version of the data based on time lag delay.

Attributes:

batch_size

The batch size of the ring buffer.

device

The device used for processing.

history_length

The history length of the delay buffer.

min_time_lag

Minimum amount of time steps that can be delayed.

max_time_lag

Maximum amount of time steps that can be delayed.

time_lags

The time lag across each batch index.

__init__(history_length: int, batch_size: int, device: str)[source]#

Initialize the delay buffer.

Parameters:
  • history_length – The history of the buffer, i.e., the number of time steps in the past that the data will be buffered. It is recommended to set this value equal to the maximum time-step lag that is expected. The minimum acceptable value is zero, which means only the latest data is stored.

  • batch_size – The batch dimension of the data.

  • device – The device used for processing.

property batch_size: int#

The batch size of the ring buffer.

property device: str#

The device used for processing.

property history_length: int#

The history length of the delay buffer.

If zero, only the latest data is stored. If one, the latest and the previous data are stored, and so on.

property min_time_lag: int#

Minimum amount of time steps that can be delayed.

This value cannot be negative or larger than max_time_lag.

property max_time_lag: int#

Maximum amount of time steps that can be delayed.

This value cannot be greater than history_length.

property time_lags: torch.Tensor#

The time lag across each batch index.

The shape of the tensor is (batch_size, ). The value at each index represents the delay for that index. This value is used to retrieve the data from the buffer.

set_time_lag(time_lag: int | torch.Tensor, batch_ids: Sequence[int] | None = None)[source]#

Sets the time lag for the delay buffer across the provided batch indices.

Parameters:
  • time_lag

    The desired delay for the buffer.

    • If an integer is provided, the same delay is set for the provided batch indices.

    • If a tensor is provided, the delay is set for each batch index separately. The shape of the tensor should be (len(batch_ids),).

  • batch_ids – The batch indices for which the time lag is set. Default is None, which sets the time lag for all batch indices.

Raises:
  • TypeError – If the type of the time_lag is not int or integer tensor.

  • ValueError – If the minimum time lag is negative or the maximum time lag is larger than the history length.

reset(batch_ids: Sequence[int] | None = None)[source]#

Reset the data in the delay buffer at the specified batch indices.

Parameters:

batch_ids – Elements to reset in the batch dimension. Default is None, which resets all the batch indices.

compute(data: torch.Tensor) torch.Tensor[source]#

Append the input data to the buffer and returns a stale version of the data based on time lag delay.

If the requested delay is larger than the number of buffered data points since the last reset, the function returns the latest data. For instance, if the delay is set to 2 and only one data point is stored in the buffer, the function will return the latest data. If the delay is set to 2 and three data points are stored, the function will return the first data point.

Parameters:

data – The input data. Shape is (batch_size, …).

Returns:

The delayed version of the data from the stored buffer. Shape is (batch_size, …).

class omni.isaac.lab.utils.buffers.TimestampedBuffer[source]#

Bases: object

A buffer class containing data and its timestamp.

This class is a simple data container that stores a tensor and its timestamp. The timestamp is used to track the last update of the buffer. The timestamp is set to -1.0 by default, indicating that the buffer has not been updated yet. The timestamp should be updated whenever the data in the buffer is updated. This way the buffer can be used to check whether the data is outdated and needs to be refreshed.

The buffer is useful for creating lazy buffers that only update the data when it is outdated. This can be useful when the data is expensive to compute or retrieve. For example usage, refer to the data classes in the omni.isaac.lab.assets module.

Attributes:

data

The data stored in the buffer.

timestamp

Timestamp at the last update of the buffer.

Methods:

__init__([data, timestamp])

data: torch.Tensor = None#

The data stored in the buffer. Default is None, indicating that the buffer is empty.

__init__(data: torch.Tensor | None = None, timestamp: float = -1.0) None#
timestamp: float = -1.0#

Timestamp at the last update of the buffer. Default is -1.0, indicating that the buffer has not been updated.

Dictionary operations#

Sub-module for utilities for working with dictionaries.

Functions:

class_to_dict(obj)

Convert an object into dictionary recursively.

update_class_from_dict(obj, data[, _ns])

Reads a dictionary and sets object variables recursively.

dict_to_md5_hash(data)

Convert a dictionary into a hashable key using MD5 hash.

convert_dict_to_backend(data[, backend, ...])

Convert all arrays or tensors in a dictionary to a given backend.

update_dict(orig_dict, new_dict)

Updates existing dictionary with values from a new dictionary.

replace_slices_with_strings(data)

Replace slice objects with their string representations in a dictionary.

replace_strings_with_slices(data)

Replace string representations of slices with slice objects in a dictionary.

print_dict(val[, nesting, start])

Outputs a nested dictionary.

omni.isaac.lab.utils.dict.class_to_dict(obj: object) dict[str, Any][source]#

Convert an object into dictionary recursively.

Note

Ignores all names starting with “__” (i.e. built-in methods).

Parameters:

obj – An instance of a class to convert.

Raises:

ValueError – When input argument is not an object.

Returns:

Converted dictionary mapping.

omni.isaac.lab.utils.dict.update_class_from_dict(obj, data: dict[str, Any], _ns: str = '') None[source]#

Reads a dictionary and sets object variables recursively.

This function performs in-place update of the class member attributes.

Parameters:
  • obj – An instance of a class to update.

  • data – Input dictionary to update from.

  • _ns – Namespace of the current object. This is useful for nested configuration classes or dictionaries. Defaults to “”.

Raises:
  • TypeError – When input is not a dictionary.

  • ValueError – When dictionary has a value that does not match default config type.

  • KeyError – When dictionary has a key that does not exist in the default config type.

omni.isaac.lab.utils.dict.dict_to_md5_hash(data: object) str[source]#

Convert a dictionary into a hashable key using MD5 hash.

Parameters:

data – Input dictionary or configuration object to convert.

Returns:

A string object of double length containing only hexadecimal digits.

omni.isaac.lab.utils.dict.convert_dict_to_backend(data: dict, backend: str = 'numpy', array_types: Iterable[str] = ('numpy', 'torch', 'warp')) dict[source]#

Convert all arrays or tensors in a dictionary to a given backend.

This function iterates over the dictionary, converts all arrays or tensors with the given types to the desired backend, and stores them in a new dictionary. It also works with nested dictionaries.

Currently supported backends are “numpy”, “torch”, and “warp”.

Note

This function only converts arrays or tensors. Other types of data are left unchanged. Mutable types (e.g. lists) are referenced by the new dictionary, so they are not copied.

Parameters:
  • data – An input dict containing array or tensor data as values.

  • backend – The backend (“numpy”, “torch”, “warp”) to which arrays in this dict should be converted. Defaults to “numpy”.

  • array_types – A list containing the types of arrays that should be converted to the desired backend. Defaults to (“numpy”, “torch”, “warp”).

Raises:

ValueError – If the specified backend or array_types are unknown, i.e. not in the list of supported backends (“numpy”, “torch”, “warp”).

Returns:

The updated dict with the data converted to the desired backend.

omni.isaac.lab.utils.dict.update_dict(orig_dict: dict, new_dict: Mapping) dict[source]#

Updates existing dictionary with values from a new dictionary.

This function mimics the dict.update() function. However, it works for nested dictionaries as well.

Parameters:
  • orig_dict – The original dictionary to insert items to.

  • new_dict – The new dictionary to insert items from.

Returns:

The updated dictionary.

omni.isaac.lab.utils.dict.replace_slices_with_strings(data: dict) dict[source]#

Replace slice objects with their string representations in a dictionary.

Parameters:

data – The dictionary to process.

Returns:

The dictionary with slice objects replaced by their string representations.

omni.isaac.lab.utils.dict.replace_strings_with_slices(data: dict) dict[source]#

Replace string representations of slices with slice objects in a dictionary.

Parameters:

data – The dictionary to process.

Returns:

The dictionary with string representations of slices replaced by slice objects.

omni.isaac.lab.utils.dict.print_dict(val, nesting: int = -4, start: bool = True)[source]#

Outputs a nested dictionary.

Interpolation operations#

Submodule for different interpolation methods.

Classes:

LinearInterpolation

Linearly interpolates a sampled scalar function for arbitrary query points.

class omni.isaac.lab.utils.interpolation.LinearInterpolation[source]#

Bases: object

Linearly interpolates a sampled scalar function for arbitrary query points.

This class implements a linear interpolation for a scalar function. The function maps from real values, x, to real values, y. It expects a set of samples from the function’s domain, x, and the corresponding values, y. The class allows querying the function’s values at any arbitrary point.

The interpolation is done by finding the two closest points in x to the query point and then linearly interpolating between the corresponding y values. For the query points that are outside the input points, the class does a zero-order-hold extrapolation based on the boundary values. This means that the class returns the value of the closest point in x.

Methods:

__init__(x, y, device)

Initializes the linear interpolation.

compute(q)

Calculates a linearly interpolated values for the query points.

__init__(x: torch.Tensor, y: torch.Tensor, device: str)[source]#

Initializes the linear interpolation.

The scalar function maps from real values, x, to real values, y. The input to the class is a set of samples from the function’s domain, x, and the corresponding values, y.

Note

The input tensor x should be sorted in ascending order.

Parameters:
  • x – An vector of samples from the function’s domain. The values should be sorted in ascending order. Shape is (num_samples,)

  • y – The function’s values associated to the input x. Shape is (num_samples,)

  • device – The device used for processing.

Raises:
  • ValueError – If the input tensors are empty or have different sizes.

  • ValueError – If the input tensor x is not sorted in ascending order.

compute(q: torch.Tensor) torch.Tensor[source]#

Calculates a linearly interpolated values for the query points.

Parameters:

q – The query points. It can have any arbitrary shape.

Returns:

The interpolated values at query points. It has the same shape as the input tensor.

Math operations#

Sub-module containing utilities for various math operations.

Functions:

scale_transform

Normalizes a given input tensor to a range of [-1, 1].

unscale_transform

De-normalizes a given input tensor from range of [-1, 1] to (lower, upper).

saturate

Clamps a given input tensor to (lower, upper).

normalize

Normalizes a given input tensor to unit length.

wrap_to_pi

Wraps input angles (in radians) to the range \([-\pi, \pi]\).

copysign

Create a new floating-point tensor with the magnitude of input and the sign of other, element-wise.

matrix_from_quat

Convert rotations given as quaternions to rotation matrices.

convert_quat(quat[, to])

Converts quaternion from one convention to another.

quat_conjugate

Computes the conjugate of a quaternion.

quat_inv

Compute the inverse of a quaternion.

quat_from_euler_xyz

Convert rotations given as Euler angles in radians to Quaternions.

quat_from_matrix

Convert rotations given as rotation matrices to quaternions.

matrix_from_euler(euler_angles, convention)

Convert rotations given as Euler angles in radians to rotation matrices.

euler_xyz_from_quat

Convert rotations given as quaternions to Euler angles in radians.

quat_unique

Convert a unit quaternion to a standard form where the real part is non-negative.

quat_mul

Multiply two quaternions together.

quat_box_minus

The box-minus operator (quaternion difference) between two quaternions.

yaw_quat

Extract the yaw component of a quaternion.

quat_apply

Apply a quaternion rotation to a vector.

quat_apply_yaw

Rotate a vector only around the yaw-direction.

quat_rotate

Rotate a vector by a quaternion along the last dimension of q and v.

quat_rotate_inverse

Rotate a vector by the inverse of a quaternion along the last dimension of q and v.

quat_from_angle_axis

Convert rotations given as angle-axis to quaternions.

axis_angle_from_quat

Convert rotations given as quaternions to axis/angle.

quat_error_magnitude

Computes the rotation difference between two quaternions.

skew_symmetric_matrix

Computes the skew-symmetric matrix of a vector.

is_identity_pose(pos, rot)

Checks if input poses are identity transforms.

combine_frame_transforms

Combine transformations between two reference frames into a stationary frame.

subtract_frame_transforms(t01, q01[, t02, q02])

Subtract transformations between two reference frames into a stationary frame.

compute_pose_error(t01, q01, t02, q02[, ...])

Compute the position and orientation error between source and target frames.

apply_delta_pose

Applies delta pose transformation on source pose.

transform_points(points[, pos, quat])

Transform input points in a given frame to a target frame.

orthogonalize_perspective_depth

Converts perspective depth image to orthogonal depth image.

unproject_depth

Un-project depth image into a pointcloud.

project_points

Projects 3D points into 2D image plane.

default_orientation

Returns identity rotation transform.

random_orientation

Returns sampled rotation in 3D as quaternion.

random_yaw_orientation

Returns sampled rotation around z-axis.

sample_triangle(lower, upper, size, device)

Randomly samples tensor from a triangular distribution.

sample_uniform(lower, upper, size, device)

Sample uniformly within a range.

sample_log_uniform(lower, upper, size, device)

Sample using log-uniform distribution within a range.

sample_gaussian(mean, std, size, device)

Sample using gaussian distribution.

sample_cylinder(radius, h_range, size, device)

Sample 3D points uniformly on a cylinder's surface.

convert_camera_frame_orientation_convention(...)

Converts a quaternion representing a rotation from one convention to another.

create_rotation_matrix_from_view(eyes, targets)

Compute the rotation matrix from world to view coordinates.

omni.isaac.lab.utils.math.scale_transform(x: torch.Tensor, lower: torch.Tensor, upper: torch.Tensor) torch.Tensor#

Normalizes a given input tensor to a range of [-1, 1].

Note

It uses pytorch broadcasting functionality to deal with batched input.

Parameters:
  • x – Input tensor of shape (N, dims).

  • lower – The minimum value of the tensor. Shape is (N, dims) or (dims,).

  • upper – The maximum value of the tensor. Shape is (N, dims) or (dims,).

Returns:

Normalized transform of the tensor. Shape is (N, dims).

omni.isaac.lab.utils.math.unscale_transform(x: torch.Tensor, lower: torch.Tensor, upper: torch.Tensor) torch.Tensor#

De-normalizes a given input tensor from range of [-1, 1] to (lower, upper).

Note

It uses pytorch broadcasting functionality to deal with batched input.

Parameters:
  • x – Input tensor of shape (N, dims).

  • lower – The minimum value of the tensor. Shape is (N, dims) or (dims,).

  • upper – The maximum value of the tensor. Shape is (N, dims) or (dims,).

Returns:

De-normalized transform of the tensor. Shape is (N, dims).

omni.isaac.lab.utils.math.saturate(x: torch.Tensor, lower: torch.Tensor, upper: torch.Tensor) torch.Tensor#

Clamps a given input tensor to (lower, upper).

It uses pytorch broadcasting functionality to deal with batched input.

Parameters:
  • x – Input tensor of shape (N, dims).

  • lower – The minimum value of the tensor. Shape is (N, dims) or (dims,).

  • upper – The maximum value of the tensor. Shape is (N, dims) or (dims,).

Returns:

Clamped transform of the tensor. Shape is (N, dims).

omni.isaac.lab.utils.math.normalize(x: torch.Tensor, eps: float = 1e-09) torch.Tensor#

Normalizes a given input tensor to unit length.

Parameters:
  • x – Input tensor of shape (N, dims).

  • eps – A small value to avoid division by zero. Defaults to 1e-9.

Returns:

Normalized tensor of shape (N, dims).

omni.isaac.lab.utils.math.wrap_to_pi(angles: torch.Tensor) torch.Tensor#

Wraps input angles (in radians) to the range \([-\pi, \pi]\).

This function wraps angles in radians to the range \([-\pi, \pi]\), such that \(\pi\) maps to \(\pi\), and \(-\pi\) maps to \(-\pi\). In general, odd positive multiples of \(\pi\) are mapped to \(\pi\), and odd negative multiples of \(\pi\) are mapped to \(-\pi\).

The function behaves similar to MATLAB’s wrapToPi function.

Parameters:

angles – Input angles of any shape.

Returns:

Angles in the range \([-\pi, \pi]\).

omni.isaac.lab.utils.math.copysign(mag: float, other: torch.Tensor) torch.Tensor#

Create a new floating-point tensor with the magnitude of input and the sign of other, element-wise.

Note

The implementation follows from torch.copysign. The function allows a scalar magnitude.

Parameters:
  • mag – The magnitude scalar.

  • other – The tensor containing values whose signbits are applied to magnitude.

Returns:

The output tensor.

omni.isaac.lab.utils.math.matrix_from_quat(quaternions: torch.Tensor) torch.Tensor#

Convert rotations given as quaternions to rotation matrices.

Parameters:

quaternions – The quaternion orientation in (w, x, y, z). Shape is (…, 4).

Returns:

Rotation matrices. The shape is (…, 3, 3).

Reference:

facebookresearch/pytorch3d

omni.isaac.lab.utils.math.convert_quat(quat: torch.Tensor | np.ndarray, to: Literal['xyzw', 'wxyz'] = 'xyzw') torch.Tensor | np.ndarray[source]#

Converts quaternion from one convention to another.

The convention to convert TO is specified as an optional argument. If to == ‘xyzw’, then the input is in ‘wxyz’ format, and vice-versa.

Parameters:
  • quat – The quaternion of shape (…, 4).

  • to – Convention to convert quaternion to.. Defaults to “xyzw”.

Returns:

The converted quaternion in specified convention.

Raises:
  • ValueError – Invalid input argument to, i.e. not “xyzw” or “wxyz”.

  • ValueError – Invalid shape of input quat, i.e. not (…, 4,).

omni.isaac.lab.utils.math.quat_conjugate(q: torch.Tensor) torch.Tensor#

Computes the conjugate of a quaternion.

Parameters:

q – The quaternion orientation in (w, x, y, z). Shape is (…, 4).

Returns:

The conjugate quaternion in (w, x, y, z). Shape is (…, 4).

omni.isaac.lab.utils.math.quat_inv(q: torch.Tensor) torch.Tensor#

Compute the inverse of a quaternion.

Parameters:

q – The quaternion orientation in (w, x, y, z). Shape is (N, 4).

Returns:

The inverse quaternion in (w, x, y, z). Shape is (N, 4).

omni.isaac.lab.utils.math.quat_from_euler_xyz(roll: torch.Tensor, pitch: torch.Tensor, yaw: torch.Tensor) torch.Tensor#

Convert rotations given as Euler angles in radians to Quaternions.

Note

The euler angles are assumed in XYZ convention.

Parameters:
  • roll – Rotation around x-axis (in radians). Shape is (N,).

  • pitch – Rotation around y-axis (in radians). Shape is (N,).

  • yaw – Rotation around z-axis (in radians). Shape is (N,).

Returns:

The quaternion in (w, x, y, z). Shape is (N, 4).

omni.isaac.lab.utils.math.quat_from_matrix(matrix: torch.Tensor) torch.Tensor#

Convert rotations given as rotation matrices to quaternions.

Parameters:

matrix – The rotation matrices. Shape is (…, 3, 3).

Returns:

The quaternion in (w, x, y, z). Shape is (…, 4).

Reference:

facebookresearch/pytorch3d

omni.isaac.lab.utils.math.matrix_from_euler(euler_angles: torch.Tensor, convention: str) torch.Tensor[source]#

Convert rotations given as Euler angles in radians to rotation matrices.

Parameters:
  • euler_angles – Euler angles in radians. Shape is (…, 3).

  • convention – Convention string of three uppercase letters from {“X”, “Y”, and “Z”}. For example, “XYZ” means that the rotations should be applied first about x, then y, then z.

Returns:

Rotation matrices. Shape is (…, 3, 3).

Reference:

facebookresearch/pytorch3d

omni.isaac.lab.utils.math.euler_xyz_from_quat(quat: torch.Tensor) tuple[torch.Tensor, torch.Tensor, torch.Tensor]#

Convert rotations given as quaternions to Euler angles in radians.

Note

The euler angles are assumed in XYZ convention.

Parameters:

quat – The quaternion orientation in (w, x, y, z). Shape is (N, 4).

Returns:

A tuple containing roll-pitch-yaw. Each element is a tensor of shape (N,).

Reference:

https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles

omni.isaac.lab.utils.math.quat_unique(q: torch.Tensor) torch.Tensor#

Convert a unit quaternion to a standard form where the real part is non-negative.

Quaternion representations have a singularity since q and -q represent the same rotation. This function ensures the real part of the quaternion is non-negative.

Parameters:

q – The quaternion orientation in (w, x, y, z). Shape is (…, 4).

Returns:

Standardized quaternions. Shape is (…, 4).

omni.isaac.lab.utils.math.quat_mul(q1: torch.Tensor, q2: torch.Tensor) torch.Tensor#

Multiply two quaternions together.

Parameters:
  • q1 – The first quaternion in (w, x, y, z). Shape is (…, 4).

  • q2 – The second quaternion in (w, x, y, z). Shape is (…, 4).

Returns:

The product of the two quaternions in (w, x, y, z). Shape is (…, 4).

Raises:

ValueError – Input shapes of q1 and q2 are not matching.

omni.isaac.lab.utils.math.quat_box_minus(q1: torch.Tensor, q2: torch.Tensor) torch.Tensor#

The box-minus operator (quaternion difference) between two quaternions.

Parameters:
  • q1 – The first quaternion in (w, x, y, z). Shape is (N, 4).

  • q2 – The second quaternion in (w, x, y, z). Shape is (N, 4).

Returns:

The difference between the two quaternions. Shape is (N, 3).

omni.isaac.lab.utils.math.yaw_quat(quat: torch.Tensor) torch.Tensor#

Extract the yaw component of a quaternion.

Parameters:

quat – The orientation in (w, x, y, z). Shape is (…, 4)

Returns:

A quaternion with only yaw component.

omni.isaac.lab.utils.math.quat_apply(quat: torch.Tensor, vec: torch.Tensor) torch.Tensor#

Apply a quaternion rotation to a vector.

Parameters:
  • quat – The quaternion in (w, x, y, z). Shape is (…, 4).

  • vec – The vector in (x, y, z). Shape is (…, 3).

Returns:

The rotated vector in (x, y, z). Shape is (…, 3).

omni.isaac.lab.utils.math.quat_apply_yaw(quat: torch.Tensor, vec: torch.Tensor) torch.Tensor#

Rotate a vector only around the yaw-direction.

Parameters:
  • quat – The orientation in (w, x, y, z). Shape is (N, 4).

  • vec – The vector in (x, y, z). Shape is (N, 3).

Returns:

The rotated vector in (x, y, z). Shape is (N, 3).

omni.isaac.lab.utils.math.quat_rotate(q: torch.Tensor, v: torch.Tensor) torch.Tensor#

Rotate a vector by a quaternion along the last dimension of q and v.

Parameters:
  • q – The quaternion in (w, x, y, z). Shape is (…, 4).

  • v – The vector in (x, y, z). Shape is (…, 3).

Returns:

The rotated vector in (x, y, z). Shape is (…, 3).

omni.isaac.lab.utils.math.quat_rotate_inverse(q: torch.Tensor, v: torch.Tensor) torch.Tensor#

Rotate a vector by the inverse of a quaternion along the last dimension of q and v.

Parameters:
  • q – The quaternion in (w, x, y, z). Shape is (…, 4).

  • v – The vector in (x, y, z). Shape is (…, 3).

Returns:

The rotated vector in (x, y, z). Shape is (…, 3).

omni.isaac.lab.utils.math.quat_from_angle_axis(angle: torch.Tensor, axis: torch.Tensor) torch.Tensor#

Convert rotations given as angle-axis to quaternions.

Parameters:
  • angle – The angle turned anti-clockwise in radians around the vector’s direction. Shape is (N,).

  • axis – The axis of rotation. Shape is (N, 3).

Returns:

The quaternion in (w, x, y, z). Shape is (N, 4).

omni.isaac.lab.utils.math.axis_angle_from_quat(quat: torch.Tensor, eps: float = 1e-06) torch.Tensor#

Convert rotations given as quaternions to axis/angle.

Parameters:
  • quat – The quaternion orientation in (w, x, y, z). Shape is (…, 4).

  • eps – The tolerance for Taylor approximation. Defaults to 1.0e-6.

Returns:

Rotations given as a vector in axis angle form. Shape is (…, 3). The vector’s magnitude is the angle turned anti-clockwise in radians around the vector’s direction.

Reference:

facebookresearch/pytorch3d

omni.isaac.lab.utils.math.quat_error_magnitude(q1: torch.Tensor, q2: torch.Tensor) torch.Tensor#

Computes the rotation difference between two quaternions.

Parameters:
  • q1 – The first quaternion in (w, x, y, z). Shape is (…, 4).

  • q2 – The second quaternion in (w, x, y, z). Shape is (…, 4).

Returns:

Angular error between input quaternions in radians.

omni.isaac.lab.utils.math.skew_symmetric_matrix(vec: torch.Tensor) torch.Tensor#

Computes the skew-symmetric matrix of a vector.

Parameters:

vec – The input vector. Shape is (3,) or (N, 3).

Returns:

The skew-symmetric matrix. Shape is (1, 3, 3) or (N, 3, 3).

Raises:

ValueError – If input tensor is not of shape (…, 3).

omni.isaac.lab.utils.math.is_identity_pose(pos: torch.tensor, rot: torch.tensor) bool[source]#

Checks if input poses are identity transforms.

The function checks if the input position and orientation are close to zero and identity respectively using L2-norm. It does NOT check the error in the orientation.

Parameters:
  • pos – The cartesian position. Shape is (N, 3).

  • rot – The quaternion in (w, x, y, z). Shape is (N, 4).

Returns:

True if all the input poses result in identity transform. Otherwise, False.

omni.isaac.lab.utils.math.combine_frame_transforms(t01: torch.Tensor, q01: torch.Tensor, t12: torch.Tensor | None = None, q12: torch.Tensor | None = None) tuple[torch.Tensor, torch.Tensor]#

Combine transformations between two reference frames into a stationary frame.

It performs the following transformation operation: \(T_{02} = T_{01} \times T_{12}\), where \(T_{AB}\) is the homogeneous transformation matrix from frame A to B.

Parameters:
  • t01 – Position of frame 1 w.r.t. frame 0. Shape is (N, 3).

  • q01 – Quaternion orientation of frame 1 w.r.t. frame 0 in (w, x, y, z). Shape is (N, 4).

  • t12 – Position of frame 2 w.r.t. frame 1. Shape is (N, 3). Defaults to None, in which case the position is assumed to be zero.

  • q12 – Quaternion orientation of frame 2 w.r.t. frame 1 in (w, x, y, z). Shape is (N, 4). Defaults to None, in which case the orientation is assumed to be identity.

Returns:

A tuple containing the position and orientation of frame 2 w.r.t. frame 0. Shape of the tensors are (N, 3) and (N, 4) respectively.

omni.isaac.lab.utils.math.subtract_frame_transforms(t01: torch.Tensor, q01: torch.Tensor, t02: torch.Tensor | None = None, q02: torch.Tensor | None = None) tuple[torch.Tensor, torch.Tensor][source]#

Subtract transformations between two reference frames into a stationary frame.

It performs the following transformation operation: \(T_{12} = T_{01}^{-1} \times T_{02}\), where \(T_{AB}\) is the homogeneous transformation matrix from frame A to B.

Parameters:
  • t01 – Position of frame 1 w.r.t. frame 0. Shape is (N, 3).

  • q01 – Quaternion orientation of frame 1 w.r.t. frame 0 in (w, x, y, z). Shape is (N, 4).

  • t02 – Position of frame 2 w.r.t. frame 0. Shape is (N, 3). Defaults to None, in which case the position is assumed to be zero.

  • q02 – Quaternion orientation of frame 2 w.r.t. frame 0 in (w, x, y, z). Shape is (N, 4). Defaults to None, in which case the orientation is assumed to be identity.

Returns:

A tuple containing the position and orientation of frame 2 w.r.t. frame 1. Shape of the tensors are (N, 3) and (N, 4) respectively.

omni.isaac.lab.utils.math.compute_pose_error(t01: torch.Tensor, q01: torch.Tensor, t02: torch.Tensor, q02: torch.Tensor, rot_error_type: Literal['quat', 'axis_angle'] = 'axis_angle') tuple[torch.Tensor, torch.Tensor][source]#

Compute the position and orientation error between source and target frames.

Parameters:
  • t01 – Position of source frame. Shape is (N, 3).

  • q01 – Quaternion orientation of source frame in (w, x, y, z). Shape is (N, 4).

  • t02 – Position of target frame. Shape is (N, 3).

  • q02 – Quaternion orientation of target frame in (w, x, y, z). Shape is (N, 4).

  • rot_error_type – The rotation error type to return: “quat”, “axis_angle”. Defaults to “axis_angle”.

Returns:

A tuple containing position and orientation error. Shape of position error is (N, 3). Shape of orientation error depends on the value of rot_error_type:

  • If rot_error_type is “quat”, the orientation error is returned as a quaternion. Shape is (N, 4).

  • If rot_error_type is “axis_angle”, the orientation error is returned as an axis-angle vector. Shape is (N, 3).

Raises:

ValueError – Invalid rotation error type.

omni.isaac.lab.utils.math.apply_delta_pose(source_pos: torch.Tensor, source_rot: torch.Tensor, delta_pose: torch.Tensor, eps: float = 1e-06) tuple[torch.Tensor, torch.Tensor]#

Applies delta pose transformation on source pose.

The first three elements of delta_pose are interpreted as cartesian position displacement. The remaining three elements of delta_pose are interpreted as orientation displacement in the angle-axis format.

Parameters:
  • source_pos – Position of source frame. Shape is (N, 3).

  • source_rot – Quaternion orientation of source frame in (w, x, y, z). Shape is (N, 4)..

  • delta_pose – Position and orientation displacements. Shape is (N, 6).

  • eps – The tolerance to consider orientation displacement as zero. Defaults to 1.0e-6.

Returns:

A tuple containing the displaced position and orientation frames. Shape of the tensors are (N, 3) and (N, 4) respectively.

omni.isaac.lab.utils.math.transform_points(points: torch.Tensor, pos: torch.Tensor | None = None, quat: torch.Tensor | None = None) torch.Tensor[source]#

Transform input points in a given frame to a target frame.

This function transform points from a source frame to a target frame. The transformation is defined by the position \(t\) and orientation \(R\) of the target frame in the source frame.

\[p_{target} = R_{target} \times p_{source} + t_{target}\]

If the input points is a batch of points, the inputs pos and quat must be either a batch of positions and quaternions or a single position and quaternion. If the inputs pos and quat are a single position and quaternion, the same transformation is applied to all points in the batch.

If either the inputs pos and quat are None, the corresponding transformation is not applied.

Parameters:
  • points – Points to transform. Shape is (N, P, 3) or (P, 3).

  • pos – Position of the target frame. Shape is (N, 3) or (3,). Defaults to None, in which case the position is assumed to be zero.

  • quat – Quaternion orientation of the target frame in (w, x, y, z). Shape is (N, 4) or (4,). Defaults to None, in which case the orientation is assumed to be identity.

Returns:

Transformed points in the target frame. Shape is (N, P, 3) or (P, 3).

Raises:
  • ValueError – If the inputs points is not of shape (N, P, 3) or (P, 3).

  • ValueError – If the inputs pos is not of shape (N, 3) or (3,).

  • ValueError – If the inputs quat is not of shape (N, 4) or (4,).

omni.isaac.lab.utils.math.orthogonalize_perspective_depth(depth: torch.Tensor, intrinsics: torch.Tensor) torch.Tensor#

Converts perspective depth image to orthogonal depth image.

Perspective depth images contain distances measured from the camera’s optical center. Meanwhile, orthogonal depth images provide the distance from the camera’s image plane. This method uses the camera geometry to convert perspective depth to orthogonal depth image.

The function assumes that the width and height are both greater than 1.

Parameters:
  • depth – The perspective depth images. Shape is (H, W) or or (H, W, 1) or (N, H, W) or (N, H, W, 1).

  • intrinsics – The camera’s calibration matrix. If a single matrix is provided, the same calibration matrix is used across all the depth images in the batch. Shape is (3, 3) or (N, 3, 3).

Returns:

The orthogonal depth images. Shape matches the input shape of depth images.

Raises:
  • ValueError – When depth is not of shape (H, W) or (H, W, 1) or (N, H, W) or (N, H, W, 1).

  • ValueError – When intrinsics is not of shape (3, 3) or (N, 3, 3).

omni.isaac.lab.utils.math.unproject_depth(depth: torch.Tensor, intrinsics: torch.Tensor, is_ortho: bool = True) torch.Tensor#

Un-project depth image into a pointcloud.

This function converts orthogonal or perspective depth images into points given the calibration matrix of the camera. It uses the following transformation based on camera geometry:

\[p_{3D} = K^{-1} \times [u, v, 1]^T \times d\]

where \(p_{3D}\) is the 3D point, \(d\) is the depth value (measured from the image plane), \(u\) and \(v\) are the pixel coordinates and \(K\) is the intrinsic matrix.

The function assumes that the width and height are both greater than 1. This makes the function deal with many possible shapes of depth images and intrinsics matrices.

Note

If is_ortho is False, the input depth images are transformed to orthogonal depth images by using the orthogonalize_perspective_depth() method.

Parameters:
  • depth – The depth measurement. Shape is (H, W) or or (H, W, 1) or (N, H, W) or (N, H, W, 1).

  • intrinsics – The camera’s calibration matrix. If a single matrix is provided, the same calibration matrix is used across all the depth images in the batch. Shape is (3, 3) or (N, 3, 3).

  • is_ortho – Whether the input depth image is orthogonal or perspective depth image. If True, the input depth image is considered as the orthogonal type, where the measurements are from the camera’s image plane. If False, the depth image is considered as the perspective type, where the measurements are from the camera’s optical center. Defaults to True.

Returns:

The 3D coordinates of points. Shape is (P, 3) or (N, P, 3).

Raises:
  • ValueError – When depth is not of shape (H, W) or (H, W, 1) or (N, H, W) or (N, H, W, 1).

  • ValueError – When intrinsics is not of shape (3, 3) or (N, 3, 3).

omni.isaac.lab.utils.math.project_points(points: torch.Tensor, intrinsics: torch.Tensor) torch.Tensor#

Projects 3D points into 2D image plane.

This project 3D points into a 2D image plane. The transformation is defined by the intrinsic matrix of the camera.

\[\begin{split}\begin{align} p &= K \times p_{3D} = \\ p_{2D} &= \begin{pmatrix} u \\ v \\ d \end{pmatrix} = \begin{pmatrix} p[0] / p[2] \\ p[1] / p[2] \\ Z \end{pmatrix} \end{align}\end{split}\]

where \(p_{2D} = (u, v, d)\) is the projected 3D point, \(p_{3D} = (X, Y, Z)\) is the 3D point and \(K \in \mathbb{R}^{3 \times 3}\) is the intrinsic matrix.

If points is a batch of 3D points and intrinsics is a single intrinsic matrix, the same calibration matrix is applied to all points in the batch.

Parameters:
  • points – The 3D coordinates of points. Shape is (P, 3) or (N, P, 3).

  • intrinsics – Camera’s calibration matrix. Shape is (3, 3) or (N, 3, 3).

Returns:

Projected 3D coordinates of points. Shape is (P, 3) or (N, P, 3).

omni.isaac.lab.utils.math.default_orientation(num: int, device: str) torch.Tensor#

Returns identity rotation transform.

Parameters:
  • num – The number of rotations to sample.

  • device – Device to create tensor on.

Returns:

Identity quaternion in (w, x, y, z). Shape is (num, 4).

omni.isaac.lab.utils.math.random_orientation(num: int, device: str) torch.Tensor#

Returns sampled rotation in 3D as quaternion.

Parameters:
  • num – The number of rotations to sample.

  • device – Device to create tensor on.

Returns:

Sampled quaternion in (w, x, y, z). Shape is (num, 4).

Reference:

https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.transform.Rotation.random.html

omni.isaac.lab.utils.math.random_yaw_orientation(num: int, device: str) torch.Tensor#

Returns sampled rotation around z-axis.

Parameters:
  • num – The number of rotations to sample.

  • device – Device to create tensor on.

Returns:

Sampled quaternion in (w, x, y, z). Shape is (num, 4).

omni.isaac.lab.utils.math.sample_triangle(lower: float, upper: float, size: int | tuple[int, ...], device: str) torch.Tensor[source]#

Randomly samples tensor from a triangular distribution.

Parameters:
  • lower – The lower range of the sampled tensor.

  • upper – The upper range of the sampled tensor.

  • size – The shape of the tensor.

  • device – Device to create tensor on.

Returns:

Sampled tensor. Shape is based on size.

omni.isaac.lab.utils.math.sample_uniform(lower: torch.Tensor | float, upper: torch.Tensor | float, size: int | tuple[int, ...], device: str) torch.Tensor[source]#

Sample uniformly within a range.

Parameters:
  • lower – Lower bound of uniform range.

  • upper – Upper bound of uniform range.

  • size – The shape of the tensor.

  • device – Device to create tensor on.

Returns:

Sampled tensor. Shape is based on size.

omni.isaac.lab.utils.math.sample_log_uniform(lower: torch.Tensor | float, upper: torch.Tensor | float, size: int | tuple[int, ...], device: str) torch.Tensor[source]#

Sample using log-uniform distribution within a range.

The log-uniform distribution is defined as a uniform distribution in the log-space. It is useful for sampling values that span several orders of magnitude. The sampled values are uniformly distributed in the log-space and then exponentiated to get the final values.

\[x = \exp(\text{uniform}(\log(\text{lower}), \log(\text{upper})))\]
Parameters:
  • lower – Lower bound of uniform range.

  • upper – Upper bound of uniform range.

  • size – The shape of the tensor.

  • device – Device to create tensor on.

Returns:

Sampled tensor. Shape is based on size.

omni.isaac.lab.utils.math.sample_gaussian(mean: torch.Tensor | float, std: torch.Tensor | float, size: int | tuple[int, ...], device: str) torch.Tensor[source]#

Sample using gaussian distribution.

Parameters:
  • mean – Mean of the gaussian.

  • std – Std of the gaussian.

  • size – The shape of the tensor.

  • device – Device to create tensor on.

Returns:

Sampled tensor.

omni.isaac.lab.utils.math.sample_cylinder(radius: float, h_range: tuple[float, float], size: int | tuple[int, ...], device: str) torch.Tensor[source]#

Sample 3D points uniformly on a cylinder’s surface.

The cylinder is centered at the origin and aligned with the z-axis. The height of the cylinder is sampled uniformly from the range h_range, while the radius is fixed to radius.

The sampled points are returned as a tensor of shape (*size, 3), i.e. the last dimension contains the x, y, and z coordinates of the sampled points.

Parameters:
  • radius – The radius of the cylinder.

  • h_range – The minimum and maximum height of the cylinder.

  • size – The shape of the tensor.

  • device – Device to create tensor on.

Returns:

Sampled tensor. Shape is (*size, 3).

omni.isaac.lab.utils.math.convert_camera_frame_orientation_convention(orientation: torch.Tensor, origin: Literal['opengl', 'ros', 'world'] = 'opengl', target: Literal['opengl', 'ros', 'world'] = 'ros') torch.Tensor[source]#

Converts a quaternion representing a rotation from one convention to another.

In USD, the camera follows the "opengl" convention. Thus, it is always in Y up convention. This means that the camera is looking down the -Z axis with the +Y axis pointing up , and +X axis pointing right. However, in ROS, the camera is looking down the +Z axis with the +Y axis pointing down, and +X axis pointing right. Thus, the camera needs to be rotated by \(180^{\circ}\) around the X axis to follow the ROS convention.

\[\begin{split}T_{ROS} = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & -1 & 0 & 0 \\ 0 & 0 & -1 & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix} T_{USD}\end{split}\]

On the other hand, the typical world coordinate system is with +X pointing forward, +Y pointing left, and +Z pointing up. The camera can also be set in this convention by rotating the camera by \(90^{\circ}\) around the X axis and \(-90^{\circ}\) around the Y axis.

\[\begin{split}T_{WORLD} = \begin{bmatrix} 0 & 0 & -1 & 0 \\ -1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix} T_{USD}\end{split}\]

Thus, based on their application, cameras follow different conventions for their orientation. This function converts a quaternion from one convention to another.

Possible conventions are:

  • "opengl" - forward axis: -Z - up axis +Y - Offset is applied in the OpenGL (Usd.Camera) convention

  • "ros" - forward axis: +Z - up axis -Y - Offset is applied in the ROS convention

  • "world" - forward axis: +X - up axis +Z - Offset is applied in the World Frame convention

Parameters:
  • orientation – Quaternion of form (w, x, y, z) with shape (…, 4) in source convention.

  • origin – Convention to convert from. Defaults to “opengl”.

  • target – Convention to convert to. Defaults to “ros”.

Returns:

Quaternion of form (w, x, y, z) with shape (…, 4) in target convention

omni.isaac.lab.utils.math.create_rotation_matrix_from_view(eyes: torch.Tensor, targets: torch.Tensor, up_axis: Literal['Y', 'Z'] = 'Z', device: str = 'cpu') torch.Tensor[source]#

Compute the rotation matrix from world to view coordinates.

This function takes a vector ‘’eyes’’ which specifies the location of the camera in world coordinates and the vector ‘’targets’’ which indicate the position of the object. The output is a rotation matrix representing the transformation from world coordinates -> view coordinates.

The inputs eyes and targets can each be a - 3 element tuple/list - torch tensor of shape (1, 3) - torch tensor of shape (N, 3)

Parameters:
  • eyes – Position of the camera in world coordinates.

  • targets – Position of the object in world coordinates.

  • up_axis – The up axis of the camera. Defaults to “Z”.

  • device – The device to create torch tensors on. Defaults to “cpu”.

The vectors are broadcast against each other so they all have shape (N, 3).

Returns:

(N, 3, 3) batched rotation matrices

Return type:

R

Reference: Based on PyTorch3D (facebookresearch/pytorch3d)

Modifier operations#

Sub-module containing different modifiers implementations.

Modifiers are used to apply stateful or stateless modifications to tensor data. They take in a tensor and a configuration and return a tensor with the modification applied. This way users can define custom operations to apply to a tensor. For instance, a modifier can be used to normalize the input data or to apply a rolling average.

They are primarily used to apply custom operations in the ObservationManager as an alternative to the built-in noise, clip and scale post-processing operations. For more details, see the ObservationTermCfg class.

Usage with a function modifier:

import torch
from omni.isaac.lab.utils import modifiers

# create a random tensor
my_tensor = torch.rand(256, 128, device="cuda")

# create a modifier configuration
cfg = modifiers.ModifierCfg(func=modifiers.clip, params={"bounds": (0.0, torch.inf)})

# apply the modifier
my_modified_tensor = cfg.func(my_tensor, cfg)

Usage with a class modifier:

import torch
from omni.isaac.lab.utils import modifiers

# create a random tensor
my_tensor = torch.rand(256, 128, device="cuda")

# create a modifier configuration
# a digital filter with a simple delay of 1 timestep
cfg = modifiers.DigitalFilter(A=[0.0], B=[0.0, 1.0])

# create the modifier instance
my_modifier = modifiers.DigitalFilter(cfg, my_tensor.shape, "cuda")

# apply the modifier as a callable object
my_modified_tensor = my_modifier(my_tensor)

Classes:

ModifierCfg

Configuration parameters modifiers

ModifierBase

Base class for modifiers implemented as classes.

DigitalFilter

Modifier used to apply digital filtering to the input data.

DigitalFilterCfg

Configuration parameters for a digital filter modifier.

Integrator

Modifier that applies a numerical forward integration based on a middle Reimann sum.

IntegratorCfg

Configuration parameters for an integrator modifier.

Functions:

bias(data, value)

Adds a uniform bias to the data.

clip(data, bounds)

Clips the data to a minimum and maximum value.

scale(data, multiplier)

Scales input data by a multiplier.

class omni.isaac.lab.utils.modifiers.ModifierCfg[source]#

Bases: object

Configuration parameters modifiers

Attributes:

params

The parameters to be passed to the function or callable class as keyword arguments.

params: dict[str, Any]#

The parameters to be passed to the function or callable class as keyword arguments. Defaults to an empty dictionary.

class omni.isaac.lab.utils.modifiers.ModifierBase[source]#

Bases: ABC

Base class for modifiers implemented as classes.

Modifiers implementations can be functions or classes. If a modifier is a class, it should inherit from this class and implement the required methods.

A class implementation of a modifier can be used to store state information between calls. This is useful for modifiers that require stateful operations, such as rolling averages or delays or decaying filters.

Example pseudo-code to create and use the class:

from omni.isaac.lab.utils import modifiers

# define custom keyword arguments to pass to ModifierCfg
kwarg_dict = {"arg_1" : VAL_1, "arg_2" : VAL_2}

# create modifier configuration object
# func is the class name of the modifier and params is the dictionary of arguments
modifier_config = modifiers.ModifierCfg(func=modifiers.ModifierBase, params=kwarg_dict)

# define modifier instance
my_modifier = modifiers.ModifierBase(cfg=modifier_config)

Methods:

reset([env_ids])

Resets the Modifier.

__call__(data)

Abstract method for defining the modification function.

abstract reset(env_ids: Sequence[int] | None = None)[source]#

Resets the Modifier.

Parameters:

env_ids – The environment ids. Defaults to None, in which case all environments are considered.

abstract __call__(data: torch.Tensor) torch.Tensor[source]#

Abstract method for defining the modification function.

Parameters:

data – The data to be modified. Shape should match the data_dim passed during initialization.

Returns:

Modified data. Shape is the same as the input data.

class omni.isaac.lab.utils.modifiers.DigitalFilter[source]#

Bases: ModifierBase

Modifier used to apply digital filtering to the input data.

Digital filters are used to process discrete-time signals to extract useful parts of the signal, such as smoothing, noise reduction, or frequency separation.

The filter can be implemented as a linear difference equation in the time domain. This equation can be used to calculate the output at each time-step based on the current and previous inputs and outputs.

\[y_{i} = X B - Y A = \sum_{j=0}^{N} b_j x_{i-j} - \sum_{j=1}^{M} a_j y_{i-j}\]

where \(y_{i}\) is the current output of the filter. The array \(Y\) contains previous outputs from the filter \(\{y_{i-j}\}_{j=1}^M\) for \(M\) previous time-steps. The array \(X\) contains current \(x_{i}\) and previous inputs to the filter \(\{x_{i-j}\}_{j=1}^N\) for \(N\) previous time-steps respectively. The filter coefficients \(A\) and \(B\) are used to design the filter. They are column vectors of length \(M\) and \(N + 1\) respectively.

Different types of filters can be implemented by choosing different values for \(A\) and \(B\). We provide some examples below.

Examples

Unit Delay Filter

A filter that delays the input signal by a single time-step simply outputs the previous input value.

\[y_{i} = x_{i-1}\]

This can be implemented as a digital filter with the coefficients \(A = [0.0]\) and \(B = [0.0, 1.0]\).

Moving Average Filter

A moving average filter is used to smooth out noise in a signal. It is similar to a low-pass filter but has a finite impulse response (FIR) and is non-recursive.

The filter calculates the average of the input signal over a window of time-steps. The linear difference equation for a moving average filter is:

\[y_{i} = \frac{1}{N} \sum_{j=0}^{N} x_{i-j}\]

This can be implemented as a digital filter with the coefficients \(A = [0.0]\) and \(B = [1/N, 1/N, \cdots, 1/N]\).

First-order recursive low-pass filter

A recursive low-pass filter is used to smooth out high-frequency noise in a signal. It is a first-order infinite impulse response (IIR) filter which means it has a recursive component (previous output) in the linear difference equation.

A first-order low-pass IIR filter has the difference equation:

\[y_{i} = \alpha y_{i-1} + (1-\alpha)x_{i}\]

where \(\alpha\) is a smoothing parameter between 0 and 1. Typically, the value of \(\alpha\) is chosen based on the desired cut-off frequency of the filter.

This filter can be implemented as a digital filter with the coefficients \(A = [\alpha]\) and \(B = [1 - \alpha]\).

Methods:

reset([env_ids])

Resets digital filter history.

__call__(data)

Applies digital filter modification with a rolling history window inputs and outputs.

reset(env_ids: Sequence[int] | None = None)[source]#

Resets digital filter history.

Parameters:

env_ids – The environment ids. Defaults to None, in which case all environments are considered.

__call__(data: torch.Tensor) torch.Tensor[source]#

Applies digital filter modification with a rolling history window inputs and outputs.

Parameters:

data – The data to apply filter to.

Returns:

Filtered data. Shape is the same as data.

class omni.isaac.lab.utils.modifiers.DigitalFilterCfg[source]#

Bases: ModifierCfg

Configuration parameters for a digital filter modifier.

For more information, please check the DigitalFilter class.

Attributes:

A

The coefficients corresponding the the filter's response to past outputs.

params

The parameters to be passed to the function or callable class as keyword arguments.

B

The coefficients corresponding the the filter's response to current and past inputs.

A: list[float]#

The coefficients corresponding the the filter’s response to past outputs.

These correspond to the weights of the past outputs of the filter. The first element is the coefficient for the output at the previous time step, the second element is the coefficient for the output at two time steps ago, and so on.

It is the denominator coefficients of the transfer function of the filter.

params: dict[str, Any]#

The parameters to be passed to the function or callable class as keyword arguments. Defaults to an empty dictionary.

B: list[float]#

The coefficients corresponding the the filter’s response to current and past inputs.

These correspond to the weights of the current and past inputs of the filter. The first element is the coefficient for the current input, the second element is the coefficient for the input at the previous time step, and so on.

It is the numerator coefficients of the transfer function of the filter.

class omni.isaac.lab.utils.modifiers.Integrator[source]#

Bases: ModifierBase

Modifier that applies a numerical forward integration based on a middle Reimann sum.

An integrator is used to calculate the integral of a signal over time. The integral of a signal is the area under the curve of the signal. The integral can be approximated using numerical methods such as the Riemann sum.

The middle Riemann sum is a method to approximate the integral of a function by dividing the area under the curve into rectangles. The height of each rectangle is the value of the function at the midpoint of the interval. The area of each rectangle is the width of the interval multiplied by the height of the rectangle.

This integral method is useful for signals that are sampled at regular intervals. The integral can be written as:

\[\int_{t_0}^{t_n} f(t) dt & \approx \int_{t_0}^{t_{n-1}} f(t) dt + \frac{f(t_{n-1}) + f(t_n)}{2} \Delta t\]

where \(f(t)\) is the signal to integrate, \(t_i\) is the time at the i-th sample, and \(\Delta t\) is the time step between samples.

Methods:

reset([env_ids])

Resets integrator state to zero.

__call__(data)

Applies integral modification to input data.

reset(env_ids: Sequence[int] | None = None)[source]#

Resets integrator state to zero.

Parameters:

env_ids – The environment ids. Defaults to None, in which case all environments are considered.

__call__(data: torch.Tensor) torch.Tensor[source]#

Applies integral modification to input data.

Parameters:

data – The data to integrate.

Returns:

Integral of input signal. Shape is the same as data.

class omni.isaac.lab.utils.modifiers.IntegratorCfg[source]#

Bases: ModifierCfg

Configuration parameters for an integrator modifier.

For more information, please check the Integrator class.

Attributes:

params

The parameters to be passed to the function or callable class as keyword arguments.

dt

The time step of the integrator.

params: dict[str, Any]#

The parameters to be passed to the function or callable class as keyword arguments. Defaults to an empty dictionary.

dt: float#

The time step of the integrator.

omni.isaac.lab.utils.modifiers.bias(data: torch.Tensor, value: float) torch.Tensor[source]#

Adds a uniform bias to the data.

Parameters:
  • data – The data to add bias to.

  • value – Value of bias to add to data.

Returns:

Biased data. Shape is the same as data.

omni.isaac.lab.utils.modifiers.clip(data: torch.Tensor, bounds: tuple[float | None, float | None]) torch.Tensor[source]#

Clips the data to a minimum and maximum value.

Parameters:
  • data – The data to apply the clip to.

  • bounds – A tuple containing the minimum and maximum values to clip data to. If the value is None, that bound is not applied.

Returns:

Clipped data. Shape is the same as data.

omni.isaac.lab.utils.modifiers.scale(data: torch.Tensor, multiplier: float) torch.Tensor[source]#

Scales input data by a multiplier.

Parameters:
  • data – The data to apply the scale to.

  • multiplier – Value to scale input by.

Returns:

Scaled data. Shape is the same as data.

Noise operations#

Sub-module containing different noise models implementations.

The noise models are implemented as functions that take in a tensor and a configuration and return a tensor with the noise applied. These functions are then used in the NoiseCfg configuration class.

Usage:

import torch
from omni.isaac.lab.utils.noise import AdditiveGaussianNoiseCfg

# create a random tensor
my_tensor = torch.rand(128, 128, device="cuda")

# create a noise configuration
cfg = AdditiveGaussianNoiseCfg(mean=0.0, std=1.0)

# apply the noise
my_noisified_tensor = cfg.func(my_tensor, cfg)

Classes:

NoiseCfg

Base configuration for a noise term.

ConstantNoiseCfg

Configuration for an additive constant noise term.

GaussianNoiseCfg

Configuration for an additive gaussian noise term.

NoiseModelCfg

Configuration for a noise model.

NoiseModelWithAdditiveBiasCfg

Configuration for an additive gaussian noise with bias model.

UniformNoiseCfg

Configuration for a additive uniform noise term.

NoiseModel

Base class for noise models.

NoiseModelWithAdditiveBias

Noise model with an additive bias.

ConstantBiasNoiseCfg

alias of ConstantNoiseCfg

AdditiveUniformNoiseCfg

alias of UniformNoiseCfg

AdditiveGaussianNoiseCfg

alias of GaussianNoiseCfg

Functions:

constant_noise(data, cfg)

Applies a constant noise bias to a given data set.

gaussian_noise(data, cfg)

Applies a gaussian noise to a given data set.

uniform_noise(data, cfg)

Applies a uniform noise to a given data set.

class omni.isaac.lab.utils.noise.NoiseCfg[source]#

Bases: object

Base configuration for a noise term.

Attributes:

operation

The operation to apply the noise on the data.

operation: Literal['add', 'scale', 'abs']#

The operation to apply the noise on the data. Defaults to “add”.

class omni.isaac.lab.utils.noise.ConstantNoiseCfg[source]#

Bases: NoiseCfg

Configuration for an additive constant noise term.

Attributes:

bias

The bias to add.

operation

The operation to apply the noise on the data.

bias: torch.Tensor | float#

The bias to add. Defaults to 0.0.

operation: Literal['add', 'scale', 'abs']#

The operation to apply the noise on the data. Defaults to “add”.

class omni.isaac.lab.utils.noise.GaussianNoiseCfg[source]#

Bases: NoiseCfg

Configuration for an additive gaussian noise term.

Attributes:

mean

The mean of the noise.

operation

The operation to apply the noise on the data.

std

The standard deviation of the noise.

mean: torch.Tensor | float#

The mean of the noise. Defaults to 0.0.

operation: Literal['add', 'scale', 'abs']#

The operation to apply the noise on the data. Defaults to “add”.

std: torch.Tensor | float#

The standard deviation of the noise. Defaults to 1.0.

class omni.isaac.lab.utils.noise.NoiseModelCfg[source]#

Bases: object

Configuration for a noise model.

Classes:

Attributes:

noise_cfg

The noise configuration to use.

class_type#

alias of NoiseModel

noise_cfg: NoiseCfg#

The noise configuration to use.

class omni.isaac.lab.utils.noise.NoiseModelWithAdditiveBiasCfg[source]#

Bases: NoiseModelCfg

Configuration for an additive gaussian noise with bias model.

Attributes:

noise_cfg

The noise configuration to use.

bias_noise_cfg

The noise configuration for the bias.

Classes:

noise_cfg: NoiseCfg#

The noise configuration to use.

class_type#

alias of NoiseModelWithAdditiveBias

bias_noise_cfg: NoiseCfg#

The noise configuration for the bias.

Based on this configuration, the bias is sampled at every reset of the noise model.

class omni.isaac.lab.utils.noise.UniformNoiseCfg[source]#

Bases: NoiseCfg

Configuration for a additive uniform noise term.

Attributes:

n_min

The minimum value of the noise.

n_max

The maximum value of the noise.

operation

The operation to apply the noise on the data.

n_min: torch.Tensor | float#

The minimum value of the noise. Defaults to -1.0.

n_max: torch.Tensor | float#

The maximum value of the noise. Defaults to 1.0.

operation: Literal['add', 'scale', 'abs']#

The operation to apply the noise on the data. Defaults to “add”.

class omni.isaac.lab.utils.noise.NoiseModel[source]#

Bases: object

Base class for noise models.

Methods:

reset([env_ids])

Reset the noise model.

apply(data)

Apply the noise to the data.

reset(env_ids: Sequence[int] | None = None)[source]#

Reset the noise model.

This method can be implemented by derived classes to reset the noise model. This is useful when implementing temporal noise models such as random walk.

Parameters:

env_ids – The environment ids to reset the noise model for. Defaults to None, in which case all environments are considered.

apply(data: torch.Tensor) torch.Tensor[source]#

Apply the noise to the data.

Parameters:

data – The data to apply the noise to. Shape is (num_envs, …).

Returns:

The data with the noise applied. Shape is the same as the input data.

class omni.isaac.lab.utils.noise.NoiseModelWithAdditiveBias[source]#

Bases: NoiseModel

Noise model with an additive bias.

The bias term is sampled from a the specified distribution on reset.

Methods:

reset([env_ids])

Reset the noise model.

apply(data)

Apply bias noise to the data.

reset(env_ids: Sequence[int] | None = None)[source]#

Reset the noise model.

This method resets the bias term for the specified environments.

Parameters:

env_ids – The environment ids to reset the noise model for. Defaults to None, in which case all environments are considered.

apply(data: torch.Tensor) torch.Tensor[source]#

Apply bias noise to the data.

Parameters:

data – The data to apply the noise to. Shape is (num_envs, …).

Returns:

The data with the noise applied. Shape is the same as the input data.

omni.isaac.lab.utils.noise.constant_noise(data: torch.Tensor, cfg: noise_cfg.ConstantNoiseCfg) torch.Tensor[source]#

Applies a constant noise bias to a given data set.

Parameters:
  • data – The unmodified data set to apply noise to.

  • cfg – The configuration parameters for constant noise.

Returns:

The data modified by the noise parameters provided.

omni.isaac.lab.utils.noise.gaussian_noise(data: torch.Tensor, cfg: noise_cfg.GaussianNoiseCfg) torch.Tensor[source]#

Applies a gaussian noise to a given data set.

Parameters:
  • data – The unmodified data set to apply noise to.

  • cfg – The configuration parameters for gaussian noise.

Returns:

The data modified by the noise parameters provided.

omni.isaac.lab.utils.noise.uniform_noise(data: torch.Tensor, cfg: noise_cfg.UniformNoiseCfg) torch.Tensor[source]#

Applies a uniform noise to a given data set.

Parameters:
  • data – The unmodified data set to apply noise to.

  • cfg – The configuration parameters for uniform noise.

Returns:

The data modified by the noise parameters provided.

omni.isaac.lab.utils.noise.ConstantBiasNoiseCfg#

alias of ConstantNoiseCfg

omni.isaac.lab.utils.noise.AdditiveUniformNoiseCfg#

alias of UniformNoiseCfg

omni.isaac.lab.utils.noise.AdditiveGaussianNoiseCfg#

alias of GaussianNoiseCfg

String operations#

Sub-module containing utilities for transforming strings and regular expressions.

Functions:

to_camel_case(snake_str[, to])

Converts a string from snake case to camel case.

to_snake_case(camel_str)

Converts a string from camel case to snake case.

string_to_slice(s)

Convert a string representation of a slice to a slice object.

is_lambda_expression(name)

Checks if the input string is a lambda expression.

callable_to_string(value)

Converts a callable object to a string.

string_to_callable(name)

Resolves the module and function names to return the function.

resolve_matching_names(keys, list_of_strings)

Match a list of query regular expressions against a list of strings and return the matched indices and names.

resolve_matching_names_values(data, ...[, ...])

Match a list of regular expressions in a dictionary against a list of strings and return the matched indices, names, and values.

omni.isaac.lab.utils.string.to_camel_case(snake_str: str, to: str = 'cC') str[source]#

Converts a string from snake case to camel case.

Parameters:
  • snake_str – A string in snake case (i.e. with ‘_’)

  • to – Convention to convert string to. Defaults to “cC”.

Raises:

ValueError – Invalid input argument to, i.e. not “cC” or “CC”.

Returns:

A string in camel-case format.

omni.isaac.lab.utils.string.to_snake_case(camel_str: str) str[source]#

Converts a string from camel case to snake case.

Parameters:

camel_str – A string in camel case.

Returns:

A string in snake case (i.e. with ‘_’)

omni.isaac.lab.utils.string.string_to_slice(s: str)[source]#

Convert a string representation of a slice to a slice object.

Parameters:

s – The string representation of the slice.

Returns:

The slice object.

omni.isaac.lab.utils.string.is_lambda_expression(name: str) bool[source]#

Checks if the input string is a lambda expression.

Parameters:

name – The input string.

Returns:

Whether the input string is a lambda expression.

omni.isaac.lab.utils.string.callable_to_string(value: Callable) str[source]#

Converts a callable object to a string.

Parameters:

value – A callable object.

Raises:

ValueError – When the input argument is not a callable object.

Returns:

A string representation of the callable object.

omni.isaac.lab.utils.string.string_to_callable(name: str) Callable[source]#

Resolves the module and function names to return the function.

Parameters:

name – The function name. The format should be ‘module:attribute_name’ or a lambda expression of format: ‘lambda x: x’.

Raises:
  • ValueError – When the resolved attribute is not a function.

  • ValueError – When the module cannot be found.

Returns:

The function loaded from the module.

Return type:

Callable

omni.isaac.lab.utils.string.resolve_matching_names(keys: str | Sequence[str], list_of_strings: Sequence[str], preserve_order: bool = False) tuple[list[int], list[str]][source]#

Match a list of query regular expressions against a list of strings and return the matched indices and names.

When a list of query regular expressions is provided, the function checks each target string against each query regular expression and returns the indices of the matched strings and the matched strings.

If the preserve_order is True, the ordering of the matched indices and names is the same as the order of the provided list of strings. This means that the ordering is dictated by the order of the target strings and not the order of the query regular expressions.

If the preserve_order is False, the ordering of the matched indices and names is the same as the order of the provided list of query regular expressions.

For example, consider the list of strings is [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] and the regular expressions are [‘a|c’, ‘b’]. If preserve_order is False, then the function will return the indices of the matched strings and the strings as: ([0, 1, 2], [‘a’, ‘b’, ‘c’]). When preserve_order is True, it will return them as: ([0, 2, 1], [‘a’, ‘c’, ‘b’]).

Note

The function does not sort the indices. It returns the indices in the order they are found.

Parameters:
  • keys – A regular expression or a list of regular expressions to match the strings in the list.

  • list_of_strings – A list of strings to match.

  • preserve_order – Whether to preserve the order of the query keys in the returned values. Defaults to False.

Returns:

A tuple of lists containing the matched indices and names.

Raises:
  • ValueError – When multiple matches are found for a string in the list.

  • ValueError – When not all regular expressions are matched.

omni.isaac.lab.utils.string.resolve_matching_names_values(data: dict[str, Any], list_of_strings: Sequence[str], preserve_order: bool = False) tuple[list[int], list[str], list[Any]][source]#

Match a list of regular expressions in a dictionary against a list of strings and return the matched indices, names, and values.

If the preserve_order is True, the ordering of the matched indices and names is the same as the order of the provided list of strings. This means that the ordering is dictated by the order of the target strings and not the order of the query regular expressions.

If the preserve_order is False, the ordering of the matched indices and names is the same as the order of the provided list of query regular expressions.

For example, consider the dictionary is {“a|d|e”: 1, “b|c”: 2}, the list of strings is [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]. If preserve_order is False, then the function will return the indices of the matched strings, the matched strings, and the values as: ([0, 1, 2, 3, 4], [‘a’, ‘b’, ‘c’, ‘d’, ‘e’], [1, 2, 2, 1, 1]). When preserve_order is True, it will return them as: ([0, 3, 4, 1, 2], [‘a’, ‘d’, ‘e’, ‘b’, ‘c’], [1, 1, 1, 2, 2]).

Parameters:
  • data – A dictionary of regular expressions and values to match the strings in the list.

  • list_of_strings – A list of strings to match.

  • preserve_order – Whether to preserve the order of the query keys in the returned values. Defaults to False.

Returns:

A tuple of lists containing the matched indices, names, and values.

Raises:
  • TypeError – When the input argument data is not a dictionary.

  • ValueError – When multiple matches are found for a string in the dictionary.

  • ValueError – When not all regular expressions in the data keys are matched.

Timer operations#

Sub-module for a timer class that can be used for performance measurements.

Exceptions:

TimerError

A custom exception used to report errors in use of Timer class.

Classes:

Timer

A timer for performance measurements.

exception omni.isaac.lab.utils.timer.TimerError[source]#

Bases: Exception

A custom exception used to report errors in use of Timer class.

class omni.isaac.lab.utils.timer.Timer[source]#

Bases: ContextDecorator

A timer for performance measurements.

A class to keep track of time for performance measurement. It allows timing via context managers and decorators as well.

It uses the time.perf_counter function to measure time. This function returns the number of seconds since the epoch as a float. It has the highest resolution available on the system.

As a regular object:

import time

from omni.isaac.lab.utils.timer import Timer

timer = Timer()
timer.start()
time.sleep(1)
print(1 <= timer.time_elapsed <= 2)  # Output: True

time.sleep(1)
timer.stop()
print(2 <= stopwatch.total_run_time)  # Output: True

As a context manager:

import time

from omni.isaac.lab.utils.timer import Timer

with Timer() as timer:
    time.sleep(1)
    print(1 <= timer.time_elapsed <= 2)  # Output: True

Reference: https://gist.github.com/sumeet/1123871

Attributes:

timing_info

Dictionary for storing the elapsed time per timer instances globally.

time_elapsed

The number of seconds that have elapsed since this timer started timing.

total_run_time

The number of seconds that elapsed from when the timer started to when it ended.

Methods:

__init__([msg, name])

Initializes the timer.

start()

Start timing.

stop()

Stop timing.

get_timer_info(name)

Retrieves the time logged in the global dictionary

timing_info: ClassVar[dict[str, float]] = {}#

Dictionary for storing the elapsed time per timer instances globally.

This dictionary logs the timer information. The keys are the names given to the timer class at its initialization. If no name is passed to the constructor, no time is recorded in the dictionary.

__init__(msg: str | None = None, name: str | None = None)[source]#

Initializes the timer.

Parameters:
  • msg – The message to display when using the timer class in a context manager. Defaults to None.

  • name – The name to use for logging times in a global dictionary. Defaults to None.

property time_elapsed: float#

The number of seconds that have elapsed since this timer started timing.

Note

This is used for checking how much time has elapsed while the timer is still running.

property total_run_time: float#

The number of seconds that elapsed from when the timer started to when it ended.

start()[source]#

Start timing.

stop()[source]#

Stop timing.

static get_timer_info(name: str) float[source]#
Retrieves the time logged in the global dictionary

based on name.

Parameters:

name – Name of the the entry to be retrieved.

Raises:

TimerError – If name doesn’t exist in the log.

Returns:

A float containing the time logged if the name exists.

Type operations#

Sub-module for different data types.

Classes:

ArticulationActions

Data container to store articulation's joints actions.

class omni.isaac.lab.utils.types.ArticulationActions[source]#

Bases: object

Data container to store articulation’s joints actions.

This class is used to store the actions of the joints of an articulation. It is used to store the joint positions, velocities, efforts, and indices.

If the actions are not provided, the values are set to None.

Attributes:

joint_positions

The joint positions of the articulation.

joint_velocities

The joint velocities of the articulation.

joint_efforts

The joint efforts of the articulation.

joint_indices

The joint indices of the articulation.

Methods:

__init__([joint_positions, ...])

joint_positions: torch.Tensor | None = None#

The joint positions of the articulation. Defaults to None.

joint_velocities: torch.Tensor | None = None#

The joint velocities of the articulation. Defaults to None.

__init__(joint_positions: torch.Tensor | None = None, joint_velocities: torch.Tensor | None = None, joint_efforts: torch.Tensor | None = None, joint_indices: torch.Tensor | Sequence[int] | slice | None = None) None#
joint_efforts: torch.Tensor | None = None#

The joint efforts of the articulation. Defaults to None.

joint_indices: torch.Tensor | Sequence[int] | slice | None = None#

The joint indices of the articulation. Defaults to None.

If the joint indices are a slice, this indicates that the indices are continuous and correspond to all the joints of the articulation. We use a slice to make the indexing more efficient.

Warp operations#

Sub-module containing operations based on warp.

Functions:

convert_to_warp_mesh(points, indices, device)

Create a warp mesh object with a mesh defined from vertices and triangles.

raycast_mesh(ray_starts, ray_directions, mesh)

Performs ray-casting against a mesh.

omni.isaac.lab.utils.warp.convert_to_warp_mesh(points: numpy.ndarray, indices: numpy.ndarray, device: str) warp.Mesh[source]#

Create a warp mesh object with a mesh defined from vertices and triangles.

Parameters:
  • points – The vertices of the mesh. Shape is (N, 3), where N is the number of vertices.

  • indices – The triangles of the mesh as references to vertices for each triangle. Shape is (M, 3), where M is the number of triangles / faces.

  • device – The device to use for the mesh.

Returns:

The warp mesh object.

omni.isaac.lab.utils.warp.raycast_mesh(ray_starts: torch.Tensor, ray_directions: torch.Tensor, mesh: wp.Mesh, max_dist: float = 1000000.0, return_distance: bool = False, return_normal: bool = False, return_face_id: bool = False) tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None, torch.Tensor | None][source]#

Performs ray-casting against a mesh.

Note that the ray_starts and ray_directions, and ray_hits should have compatible shapes and data types to ensure proper execution. Additionally, they all must be in the same frame.

Parameters:
  • ray_starts – The starting position of the rays. Shape (N, 3).

  • ray_directions – The ray directions for each ray. Shape (N, 3).

  • mesh – The warp mesh to ray-cast against.

  • max_dist – The maximum distance to ray-cast. Defaults to 1e6.

  • return_distance – Whether to return the distance of the ray until it hits the mesh. Defaults to False.

  • return_normal – Whether to return the normal of the mesh face the ray hits. Defaults to False.

  • return_face_id – Whether to return the face id of the mesh face the ray hits. Defaults to False.

Returns:

The ray hit position. Shape (N, 3).

The returned tensor contains float('inf') for missed hits.

The ray hit distance. Shape (N,).

Will only return if return_distance is True, else returns None. The returned tensor contains float('inf') for missed hits.

The ray hit normal. Shape (N, 3).

Will only return if return_normal is True else returns None. The returned tensor contains float('inf') for missed hits.

The ray hit face id. Shape (N,).

Will only return if return_face_id is True else returns None. The returned tensor contains int(-1) for missed hits.