file_path
stringlengths 20
207
| content
stringlengths 5
3.85M
| size
int64 5
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab/omni/isaac/lab/assets/asset_base.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import inspect
import re
import weakref
from abc import ABC, abstractmethod
from collections.abc import Sequence
from typing import TYPE_CHECKING, Any
import omni.kit.app
import omni.timeline
import omni.isaac.lab.sim as sim_utils
if TYPE_CHECKING:
from .asset_base_cfg import AssetBaseCfg
class AssetBase(ABC):
"""The base interface class for assets.
An asset corresponds to any physics-enabled object that can be spawned in the simulation. These include
rigid objects, articulated objects, deformable objects etc. The core functionality of an asset is to
provide a set of buffers that can be used to interact with the simulator. The buffers are updated
by the asset class and can be written into the simulator using the their respective ``write`` methods.
This allows a convenient way to perform post-processing operations on the buffers before writing them
into the simulator and obtaining the corresponding simulation results.
The class handles both the spawning of the asset into the USD stage as well as initialization of necessary
physics handles to interact with the asset. Upon construction of the asset instance, the prim corresponding
to the asset is spawned into the USD stage if the spawn configuration is not None. The spawn configuration
is defined in the :attr:`AssetBaseCfg.spawn` attribute. In case the configured :attr:`AssetBaseCfg.prim_path`
is an expression, then the prim is spawned at all the matching paths. Otherwise, a single prim is spawned
at the configured path. For more information on the spawn configuration, see the
:mod:`omni.isaac.lab.sim.spawners` module.
Unlike Isaac Sim interface, where one usually needs to call the
:meth:`omni.isaac.core.prims.XFormPrimView.initialize` method to initialize the PhysX handles, the asset
class automatically initializes and invalidates the PhysX handles when the stage is played/stopped. This
is done by registering callbacks for the stage play/stop events.
Additionally, the class registers a callback for debug visualization of the asset if a debug visualization
is implemented in the asset class. This can be enabled by setting the :attr:`AssetBaseCfg.debug_vis` attribute
to True. The debug visualization is implemented through the :meth:`_set_debug_vis_impl` and
:meth:`_debug_vis_callback` methods.
"""
def __init__(self, cfg: AssetBaseCfg):
"""Initialize the asset base.
Args:
cfg: The configuration class for the asset.
Raises:
RuntimeError: If no prims found at input prim path or prim path expression.
"""
# store inputs
self.cfg = cfg
# flag for whether the asset is initialized
self._is_initialized = False
# check if base asset path is valid
# note: currently the spawner does not work if there is a regex pattern in the leaf
# For example, if the prim path is "/World/Robot_[1,2]" since the spawner will not
# know which prim to spawn. This is a limitation of the spawner and not the asset.
asset_path = self.cfg.prim_path.split("/")[-1]
asset_path_is_regex = re.match(r"^[a-zA-Z0-9/_]+$", asset_path) is None
# spawn the asset
if self.cfg.spawn is not None and not asset_path_is_regex:
self.cfg.spawn.func(
self.cfg.prim_path,
self.cfg.spawn,
translation=self.cfg.init_state.pos,
orientation=self.cfg.init_state.rot,
)
# check that spawn was successful
matching_prims = sim_utils.find_matching_prims(self.cfg.prim_path)
if len(matching_prims) == 0:
raise RuntimeError(f"Could not find prim with path {self.cfg.prim_path}.")
# note: Use weakref on all callbacks to ensure that this object can be deleted when its destructor is called.
# add callbacks for stage play/stop
# The order is set to 10 which is arbitrary but should be lower priority than the default order of 0
timeline_event_stream = omni.timeline.get_timeline_interface().get_timeline_event_stream()
self._initialize_handle = timeline_event_stream.create_subscription_to_pop_by_type(
int(omni.timeline.TimelineEventType.PLAY),
lambda event, obj=weakref.proxy(self): obj._initialize_callback(event),
order=10,
)
self._invalidate_initialize_handle = timeline_event_stream.create_subscription_to_pop_by_type(
int(omni.timeline.TimelineEventType.STOP),
lambda event, obj=weakref.proxy(self): obj._invalidate_initialize_callback(event),
order=10,
)
# add handle for debug visualization (this is set to a valid handle inside set_debug_vis)
self._debug_vis_handle = None
# set initial state of debug visualization
self.set_debug_vis(self.cfg.debug_vis)
def __del__(self):
"""Unsubscribe from the callbacks."""
# clear physics events handles
if self._initialize_handle:
self._initialize_handle.unsubscribe()
self._initialize_handle = None
if self._invalidate_initialize_handle:
self._invalidate_initialize_handle.unsubscribe()
self._invalidate_initialize_handle = None
# clear debug visualization
if self._debug_vis_handle:
self._debug_vis_handle.unsubscribe()
self._debug_vis_handle = None
"""
Properties
"""
@property
@abstractmethod
def num_instances(self) -> int:
"""Number of instances of the asset.
This is equal to the number of asset instances per environment multiplied by the number of environments.
"""
return NotImplementedError
@property
def device(self) -> str:
"""Memory device for computation."""
return self._device
@property
@abstractmethod
def data(self) -> Any:
"""Data related to the asset."""
return NotImplementedError
@property
def has_debug_vis_implementation(self) -> bool:
"""Whether the asset has a debug visualization implemented."""
# check if function raises NotImplementedError
source_code = inspect.getsource(self._set_debug_vis_impl)
return "NotImplementedError" not in source_code
"""
Operations.
"""
def set_debug_vis(self, debug_vis: bool) -> bool:
"""Sets whether to visualize the asset data.
Args:
debug_vis: Whether to visualize the asset data.
Returns:
Whether the debug visualization was successfully set. False if the asset
does not support debug visualization.
"""
# check if debug visualization is supported
if not self.has_debug_vis_implementation:
return False
# toggle debug visualization objects
self._set_debug_vis_impl(debug_vis)
# toggle debug visualization handles
if debug_vis:
# create a subscriber for the post update event if it doesn't exist
if self._debug_vis_handle is None:
app_interface = omni.kit.app.get_app_interface()
self._debug_vis_handle = app_interface.get_post_update_event_stream().create_subscription_to_pop(
lambda event, obj=weakref.proxy(self): obj._debug_vis_callback(event)
)
else:
# remove the subscriber if it exists
if self._debug_vis_handle is not None:
self._debug_vis_handle.unsubscribe()
self._debug_vis_handle = None
# return success
return True
@abstractmethod
def reset(self, env_ids: Sequence[int] | None = None):
"""Resets all internal buffers of selected environments.
Args:
env_ids: The indices of the object to reset. Defaults to None (all instances).
"""
raise NotImplementedError
@abstractmethod
def write_data_to_sim(self):
"""Writes data to the simulator."""
raise NotImplementedError
@abstractmethod
def update(self, dt: float):
"""Update the internal buffers.
The time step ``dt`` is used to compute numerical derivatives of quantities such as joint
accelerations which are not provided by the simulator.
Args:
dt: The amount of time passed from last ``update`` call.
"""
raise NotImplementedError
"""
Implementation specific.
"""
@abstractmethod
def _initialize_impl(self):
"""Initializes the PhysX handles and internal buffers."""
raise NotImplementedError
def _set_debug_vis_impl(self, debug_vis: bool):
"""Set debug visualization into visualization objects.
This function is responsible for creating the visualization objects if they don't exist
and input ``debug_vis`` is True. If the visualization objects exist, the function should
set their visibility into the stage.
"""
raise NotImplementedError(f"Debug visualization is not implemented for {self.__class__.__name__}.")
def _debug_vis_callback(self, event):
"""Callback for debug visualization.
This function calls the visualization objects and sets the data to visualize into them.
"""
raise NotImplementedError(f"Debug visualization is not implemented for {self.__class__.__name__}.")
"""
Internal simulation callbacks.
"""
def _initialize_callback(self, event):
"""Initializes the scene elements.
Note:
PhysX handles are only enabled once the simulator starts playing. Hence, this function needs to be
called whenever the simulator "plays" from a "stop" state.
"""
if not self._is_initialized:
# obtain simulation related information
sim = sim_utils.SimulationContext.instance()
if sim is None:
raise RuntimeError("SimulationContext is not initialized! Please initialize SimulationContext first.")
self._backend = sim.backend
self._device = sim.device
# initialize the asset
self._initialize_impl()
# set flag
self._is_initialized = True
def _invalidate_initialize_callback(self, event):
"""Invalidates the scene elements."""
self._is_initialized = False
| 10,684 |
Python
| 39.782443 | 118 | 0.658929 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab/omni/isaac/lab/assets/rigid_object/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module for rigid object assets."""
from .rigid_object import RigidObject
from .rigid_object_cfg import RigidObjectCfg
from .rigid_object_data import RigidObjectData
| 300 |
Python
| 26.363634 | 60 | 0.776667 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab/omni/isaac/lab/assets/rigid_object/rigid_object_cfg.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.lab.utils import configclass
from ..asset_base_cfg import AssetBaseCfg
from .rigid_object import RigidObject
@configclass
class RigidObjectCfg(AssetBaseCfg):
"""Configuration parameters for a rigid object."""
@configclass
class InitialStateCfg(AssetBaseCfg.InitialStateCfg):
"""Initial state of the rigid body."""
lin_vel: tuple[float, float, float] = (0.0, 0.0, 0.0)
"""Linear velocity of the root in simulation world frame. Defaults to (0.0, 0.0, 0.0)."""
ang_vel: tuple[float, float, float] = (0.0, 0.0, 0.0)
"""Angular velocity of the root in simulation world frame. Defaults to (0.0, 0.0, 0.0)."""
##
# Initialize configurations.
##
class_type: type = RigidObject
init_state: InitialStateCfg = InitialStateCfg()
"""Initial state of the rigid object. Defaults to identity pose with zero velocity."""
| 1,031 |
Python
| 30.272726 | 98 | 0.680892 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab/omni/isaac/lab/assets/rigid_object/rigid_object_data.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import torch
from dataclasses import dataclass
@dataclass
class RigidObjectData:
"""Data container for a rigid object."""
##
# Properties.
##
body_names: list[str] = None
"""Body names in the order parsed by the simulation view."""
##
# Default states.
##
default_root_state: torch.Tensor = None
"""Default root state ``[pos, quat, lin_vel, ang_vel]`` in local environment frame. Shape is (num_instances, 13)."""
##
# Frame states.
##
root_state_w: torch.Tensor = None
"""Root state ``[pos, quat, lin_vel, ang_vel]`` in simulation world frame. Shape is (num_instances, 13)."""
root_vel_b: torch.Tensor = None
"""Root velocity `[lin_vel, ang_vel]` in base frame. Shape is (num_instances, 6)."""
projected_gravity_b: torch.Tensor = None
"""Projection of the gravity direction on base frame. Shape is (num_instances, 3)."""
heading_w: torch.Tensor = None
"""Yaw heading of the base frame (in radians). Shape is (num_instances,).
Note:
This quantity is computed by assuming that the forward-direction of the base
frame is along x-direction, i.e. :math:`(1, 0, 0)`.
"""
body_state_w: torch.Tensor = None
"""State of all bodies `[pos, quat, lin_vel, ang_vel]` in simulation world frame.
Shape is (num_instances, num_bodies, 13)."""
body_acc_w: torch.Tensor = None
"""Acceleration of all bodies. Shape is (num_instances, num_bodies, 6).
Note:
This quantity is computed based on the rigid body state from the last step.
"""
##
# Default rigid body properties
##
default_mass: torch.Tensor = None
""" Default mass provided by simulation. Shape is (num_instances, num_bodies)."""
"""
Properties
"""
@property
def root_pos_w(self) -> torch.Tensor:
"""Root position in simulation world frame. Shape is (num_instances, 3)."""
return self.root_state_w[:, :3]
@property
def root_quat_w(self) -> torch.Tensor:
"""Root orientation (w, x, y, z) in simulation world frame. Shape is (num_instances, 4)."""
return self.root_state_w[:, 3:7]
@property
def root_vel_w(self) -> torch.Tensor:
"""Root velocity in simulation world frame. Shape is (num_instances, 6)."""
return self.root_state_w[:, 7:13]
@property
def root_lin_vel_w(self) -> torch.Tensor:
"""Root linear velocity in simulation world frame. Shape is (num_instances, 3)."""
return self.root_state_w[:, 7:10]
@property
def root_ang_vel_w(self) -> torch.Tensor:
"""Root angular velocity in simulation world frame. Shape is (num_instances, 3)."""
return self.root_state_w[:, 10:13]
@property
def root_lin_vel_b(self) -> torch.Tensor:
"""Root linear velocity in base frame. Shape is (num_instances, 3)."""
return self.root_vel_b[:, 0:3]
@property
def root_ang_vel_b(self) -> torch.Tensor:
"""Root angular velocity in base world frame. Shape is (num_instances, 3)."""
return self.root_vel_b[:, 3:6]
@property
def body_pos_w(self) -> torch.Tensor:
"""Positions of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 3)."""
return self.body_state_w[..., :3]
@property
def body_quat_w(self) -> torch.Tensor:
"""Orientation (w, x, y, z) of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 4)."""
return self.body_state_w[..., 3:7]
@property
def body_vel_w(self) -> torch.Tensor:
"""Velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 6)."""
return self.body_state_w[..., 7:13]
@property
def body_lin_vel_w(self) -> torch.Tensor:
"""Linear velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 3)."""
return self.body_state_w[..., 7:10]
@property
def body_ang_vel_w(self) -> torch.Tensor:
"""Angular velocity of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 3)."""
return self.body_state_w[..., 10:13]
@property
def body_lin_acc_w(self) -> torch.Tensor:
"""Linear acceleration of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 3)."""
return self.body_acc_w[..., 0:3]
@property
def body_ang_acc_w(self) -> torch.Tensor:
"""Angular acceleration of all bodies in simulation world frame. Shape is (num_instances, num_bodies, 3)."""
return self.body_acc_w[..., 3:6]
| 4,738 |
Python
| 32.85 | 120 | 0.622415 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab/omni/isaac/lab/assets/rigid_object/rigid_object.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
import warnings
from collections.abc import Sequence
from typing import TYPE_CHECKING
import carb
import omni.physics.tensors.impl.api as physx
from pxr import UsdPhysics
import omni.isaac.lab.sim as sim_utils
import omni.isaac.lab.utils.math as math_utils
import omni.isaac.lab.utils.string as string_utils
from ..asset_base import AssetBase
from .rigid_object_data import RigidObjectData
if TYPE_CHECKING:
from .rigid_object_cfg import RigidObjectCfg
class RigidObject(AssetBase):
"""A rigid object asset class.
Rigid objects are assets comprising of rigid bodies. They can be used to represent dynamic objects
such as boxes, spheres, etc. A rigid body is described by its pose, velocity and mass distribution.
For an asset to be considered a rigid object, the root prim of the asset must have the `USD RigidBodyAPI`_
applied to it. This API is used to define the simulation properties of the rigid body. On playing the
simulation, the physics engine will automatically register the rigid body and create a corresponding
rigid body handle. This handle can be accessed using the :attr:`root_physx_view` attribute.
.. note::
For users familiar with Isaac Sim, the PhysX view class API is not the exactly same as Isaac Sim view
class API. Similar to Isaac Lab, Isaac Sim wraps around the PhysX view API. However, as of now (2023.1 release),
we see a large difference in initializing the view classes in Isaac Sim. This is because the view classes
in Isaac Sim perform additional USD-related operations which are slow and also not required.
.. _`USD RigidBodyAPI`: https://openusd.org/dev/api/class_usd_physics_rigid_body_a_p_i.html
"""
cfg: RigidObjectCfg
"""Configuration instance for the rigid object."""
def __init__(self, cfg: RigidObjectCfg):
"""Initialize the rigid object.
Args:
cfg: A configuration instance.
"""
super().__init__(cfg)
# container for data access
self._data = RigidObjectData()
"""
Properties
"""
@property
def data(self) -> RigidObjectData:
return self._data
@property
def num_instances(self) -> int:
return self.root_physx_view.count
@property
def num_bodies(self) -> int:
"""Number of bodies in the asset."""
return 1
@property
def body_names(self) -> list[str]:
"""Ordered names of bodies in articulation."""
prim_paths = self.root_physx_view.prim_paths[: self.num_bodies]
return [path.split("/")[-1] for path in prim_paths]
@property
def root_physx_view(self) -> physx.RigidBodyView:
"""Rigid body view for the asset (PhysX).
Note:
Use this view with caution. It requires handling of tensors in a specific way.
"""
return self._root_physx_view
@property
def body_physx_view(self) -> physx.RigidBodyView:
"""Rigid body view for the asset (PhysX).
.. deprecated:: v0.3.0
The attribute 'body_physx_view' will be removed in v0.4.0. Please use :attr:`root_physx_view` instead.
"""
dep_msg = "The attribute 'body_physx_view' will be removed in v0.4.0. Please use 'root_physx_view' instead."
warnings.warn(dep_msg, DeprecationWarning)
carb.log_error(dep_msg)
return self.root_physx_view
"""
Operations.
"""
def reset(self, env_ids: Sequence[int] | None = None):
# resolve all indices
if env_ids is None:
env_ids = slice(None)
# reset external wrench
self._external_force_b[env_ids] = 0.0
self._external_torque_b[env_ids] = 0.0
# reset last body vel
self._last_body_vel_w[env_ids] = 0.0
def write_data_to_sim(self):
"""Write external wrench to the simulation.
Note:
We write external wrench to the simulation here since this function is called before the simulation step.
This ensures that the external wrench is applied at every simulation step.
"""
# write external wrench
if self.has_external_wrench:
self.root_physx_view.apply_forces_and_torques_at_position(
force_data=self._external_force_b.view(-1, 3),
torque_data=self._external_torque_b.view(-1, 3),
position_data=None,
indices=self._ALL_BODY_INDICES,
is_global=False,
)
def update(self, dt: float):
# -- root-state (note: we roll the quaternion to match the convention used in Isaac Sim -- wxyz)
self._data.root_state_w[:, :7] = self.root_physx_view.get_transforms()
self._data.root_state_w[:, 3:7] = math_utils.convert_quat(self._data.root_state_w[:, 3:7], to="wxyz")
self._data.root_state_w[:, 7:] = self.root_physx_view.get_velocities()
# -- body-state (note: for rigid objects, we only have one body so we just copy the root state)
self._data.body_state_w[:] = self._data.root_state_w.view(-1, self.num_bodies, 13)
# -- update common data
self._update_common_data(dt)
def find_bodies(self, name_keys: str | Sequence[str], preserve_order: bool = False) -> tuple[list[int], list[str]]:
"""Find bodies in the articulation based on the name keys.
Please check the :meth:`omni.isaac.lab.utils.string_utils.resolve_matching_names` function for more
information on the name matching.
Args:
name_keys: A regular expression or a list of regular expressions to match the body names.
preserve_order: Whether to preserve the order of the name keys in the output. Defaults to False.
Returns:
A tuple of lists containing the body indices and names.
"""
return string_utils.resolve_matching_names(name_keys, self.body_names, preserve_order)
"""
Operations - Write to simulation.
"""
def write_root_state_to_sim(self, root_state: torch.Tensor, env_ids: Sequence[int] | None = None):
"""Set the root state over selected environment indices into the simulation.
The root state comprises of the cartesian position, quaternion orientation in (w, x, y, z), and linear
and angular velocity. All the quantities are in the simulation frame.
Args:
root_state: Root state in simulation frame. Shape is (len(env_ids), 13).
env_ids: Environment indices. If None, then all indices are used.
"""
# set into simulation
self.write_root_pose_to_sim(root_state[:, :7], env_ids=env_ids)
self.write_root_velocity_to_sim(root_state[:, 7:], env_ids=env_ids)
def write_root_pose_to_sim(self, root_pose: torch.Tensor, env_ids: Sequence[int] | None = None):
"""Set the root pose over selected environment indices into the simulation.
The root pose comprises of the cartesian position and quaternion orientation in (w, x, y, z).
Args:
root_pose: Root poses in simulation frame. Shape is (len(env_ids), 7).
env_ids: Environment indices. If None, then all indices are used.
"""
# resolve all indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
# note: we need to do this here since tensors are not set into simulation until step.
# set into internal buffers
self._data.root_state_w[env_ids, :7] = root_pose.clone()
# convert root quaternion from wxyz to xyzw
root_poses_xyzw = self._data.root_state_w[:, :7].clone()
root_poses_xyzw[:, 3:] = math_utils.convert_quat(root_poses_xyzw[:, 3:], to="xyzw")
# set into simulation
self.root_physx_view.set_transforms(root_poses_xyzw, indices=physx_env_ids)
def write_root_velocity_to_sim(self, root_velocity: torch.Tensor, env_ids: Sequence[int] | None = None):
"""Set the root velocity over selected environment indices into the simulation.
Args:
root_velocity: Root velocities in simulation frame. Shape is (len(env_ids), 6).
env_ids: Environment indices. If None, then all indices are used.
"""
# resolve all indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
# note: we need to do this here since tensors are not set into simulation until step.
# set into internal buffers
self._data.root_state_w[env_ids, 7:] = root_velocity.clone()
# set into simulation
self.root_physx_view.set_velocities(self._data.root_state_w[:, 7:], indices=physx_env_ids)
"""
Operations - Setters.
"""
def set_external_force_and_torque(
self,
forces: torch.Tensor,
torques: torch.Tensor,
body_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Set external force and torque to apply on the asset's bodies in their local frame.
For many applications, we want to keep the applied external force on rigid bodies constant over a period of
time (for instance, during the policy control). This function allows us to store the external force and torque
into buffers which are then applied to the simulation at every step.
.. caution::
If the function is called with empty forces and torques, then this function disables the application
of external wrench to the simulation.
.. code-block:: python
# example of disabling external wrench
asset.set_external_force_and_torque(forces=torch.zeros(0, 3), torques=torch.zeros(0, 3))
.. note::
This function does not apply the external wrench to the simulation. It only fills the buffers with
the desired values. To apply the external wrench, call the :meth:`write_data_to_sim` function
right before the simulation step.
Args:
forces: External forces in bodies' local frame. Shape is (len(env_ids), len(body_ids), 3).
torques: External torques in bodies' local frame. Shape is (len(env_ids), len(body_ids), 3).
body_ids: Body indices to apply external wrench to. Defaults to None (all bodies).
env_ids: Environment indices to apply external wrench to. Defaults to None (all instances).
"""
if forces.any() or torques.any():
self.has_external_wrench = True
# resolve all indices
# -- env_ids
if env_ids is None:
env_ids = self._ALL_INDICES
elif not isinstance(env_ids, torch.Tensor):
env_ids = torch.tensor(env_ids, dtype=torch.long, device=self.device)
# -- body_ids
if body_ids is None:
body_ids = torch.arange(self.num_bodies, dtype=torch.long, device=self.device)
elif isinstance(body_ids, slice):
body_ids = torch.arange(self.num_bodies, dtype=torch.long, device=self.device)[body_ids]
elif not isinstance(body_ids, torch.Tensor):
body_ids = torch.tensor(body_ids, dtype=torch.long, device=self.device)
# note: we need to do this complicated indexing since torch doesn't support multi-indexing
# create global body indices from env_ids and env_body_ids
# (env_id * total_bodies_per_env) + body_id
indices = body_ids.repeat(len(env_ids), 1) + env_ids.unsqueeze(1) * self.num_bodies
indices = indices.view(-1)
# set into internal buffers
# note: these are applied in the write_to_sim function
self._external_force_b.flatten(0, 1)[indices] = forces.flatten(0, 1)
self._external_torque_b.flatten(0, 1)[indices] = torques.flatten(0, 1)
else:
self.has_external_wrench = False
"""
Internal helper.
"""
def _initialize_impl(self):
# create simulation view
self._physics_sim_view = physx.create_simulation_view(self._backend)
self._physics_sim_view.set_subspace_roots("/")
# obtain the first prim in the regex expression (all others are assumed to be a copy of this)
template_prim = sim_utils.find_first_matching_prim(self.cfg.prim_path)
if template_prim is None:
raise RuntimeError(f"Failed to find prim for expression: '{self.cfg.prim_path}'.")
template_prim_path = template_prim.GetPath().pathString
# find rigid root prims
root_prims = sim_utils.get_all_matching_child_prims(
template_prim_path, predicate=lambda prim: prim.HasAPI(UsdPhysics.RigidBodyAPI)
)
if len(root_prims) == 0:
raise RuntimeError(
f"Failed to find a rigid body when resolving '{self.cfg.prim_path}'."
" Please ensure that the prim has 'USD RigidBodyAPI' applied."
)
if len(root_prims) > 1:
raise RuntimeError(
f"Failed to find a single rigid body when resolving '{self.cfg.prim_path}'."
f" Found multiple '{root_prims}' under '{template_prim_path}'."
" Please ensure that there is only one rigid body in the prim path tree."
)
# resolve root prim back into regex expression
root_prim_path = root_prims[0].GetPath().pathString
root_prim_path_expr = self.cfg.prim_path + root_prim_path[len(template_prim_path) :]
# -- object view
self._root_physx_view = self._physics_sim_view.create_rigid_body_view(root_prim_path_expr.replace(".*", "*"))
# log information about the articulation
carb.log_info(f"Rigid body initialized at: {self.cfg.prim_path} with root '{root_prim_path_expr}'.")
carb.log_info(f"Number of instances: {self.num_instances}")
carb.log_info(f"Number of bodies: {self.num_bodies}")
carb.log_info(f"Body names: {self.body_names}")
# create buffers
self._create_buffers()
# process configuration
self._process_cfg()
# update the rigid body data
self.update(0.0)
def _create_buffers(self):
"""Create buffers for storing data."""
# constants
self._ALL_INDICES = torch.arange(self.num_instances, dtype=torch.long, device=self.device)
self._ALL_BODY_INDICES = torch.arange(
self.root_physx_view.count * self.num_bodies, dtype=torch.long, device=self.device
)
self.GRAVITY_VEC_W = torch.tensor((0.0, 0.0, -1.0), device=self.device).repeat(self.num_instances, 1)
self.FORWARD_VEC_B = torch.tensor((1.0, 0.0, 0.0), device=self.device).repeat(self.num_instances, 1)
# external forces and torques
self.has_external_wrench = False
self._external_force_b = torch.zeros((self.num_instances, self.num_bodies, 3), device=self.device)
self._external_torque_b = torch.zeros_like(self._external_force_b)
# asset data
# -- properties
self._data.body_names = self.body_names
# -- root states
self._data.root_state_w = torch.zeros(self.num_instances, 13, device=self.device)
self._data.root_state_w[:, 3] = 1.0 # set default quaternion to (1, 0, 0, 0)
self._data.default_root_state = torch.zeros_like(self._data.root_state_w)
self._data.default_root_state[:, 3] = 1.0 # set default quaternion to (1, 0, 0, 0)
# -- body states
self._data.body_state_w = torch.zeros(self.num_instances, self.num_bodies, 13, device=self.device)
self._data.body_state_w[:, :, 3] = 1.0 # set default quaternion to (1, 0, 0, 0)
# -- post-computed
self._data.root_vel_b = torch.zeros(self.num_instances, 6, device=self.device)
self._data.projected_gravity_b = torch.zeros(self.num_instances, 3, device=self.device)
self._data.heading_w = torch.zeros(self.num_instances, device=self.device)
self._data.body_acc_w = torch.zeros(self.num_instances, self.num_bodies, 6, device=self.device)
# history buffers for quantities
# -- used to compute body accelerations numerically
self._last_body_vel_w = torch.zeros(self.num_instances, self.num_bodies, 6, device=self.device)
# mass
self._data.default_mass = self.root_physx_view.get_masses().clone()
def _process_cfg(self):
"""Post processing of configuration parameters."""
# default state
# -- root state
# note: we cast to tuple to avoid torch/numpy type mismatch.
default_root_state = (
tuple(self.cfg.init_state.pos)
+ tuple(self.cfg.init_state.rot)
+ tuple(self.cfg.init_state.lin_vel)
+ tuple(self.cfg.init_state.ang_vel)
)
default_root_state = torch.tensor(default_root_state, dtype=torch.float, device=self.device)
self._data.default_root_state = default_root_state.repeat(self.num_instances, 1)
def _update_common_data(self, dt: float):
"""Update common quantities related to rigid objects.
Note:
This has been separated from the update function to allow for the child classes to
override the update function without having to worry about updating the common data.
"""
# -- body acceleration
if dt > 0.0:
self._data.body_acc_w[:] = (self._data.body_state_w[..., 7:] - self._last_body_vel_w) / dt
self._last_body_vel_w[:] = self._data.body_state_w[..., 7:]
# -- root state in body frame
self._data.root_vel_b[:, 0:3] = math_utils.quat_rotate_inverse(
self._data.root_quat_w, self._data.root_lin_vel_w
)
self._data.root_vel_b[:, 3:6] = math_utils.quat_rotate_inverse(
self._data.root_quat_w, self._data.root_ang_vel_w
)
self._data.projected_gravity_b[:] = math_utils.quat_rotate_inverse(self._data.root_quat_w, self.GRAVITY_VEC_W)
# -- heading direction of root
forward_w = math_utils.quat_apply(self._data.root_quat_w, self.FORWARD_VEC_B)
self._data.heading_w[:] = torch.atan2(forward_w[:, 1], forward_w[:, 0])
"""
Internal simulation callbacks.
"""
def _invalidate_initialize_callback(self, event):
"""Invalidates the scene elements."""
# call parent
super()._invalidate_initialize_callback(event)
# set all existing views to None to invalidate them
self._physics_sim_view = None
self._root_physx_view = None
| 18,928 |
Python
| 43.538823 | 120 | 0.629808 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab/omni/isaac/lab/assets/articulation/articulation_data.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import torch
from dataclasses import dataclass
from ..rigid_object import RigidObjectData
@dataclass
class ArticulationData(RigidObjectData):
"""Data container for an articulation."""
##
# Properties.
##
joint_names: list[str] = None
"""Joint names in the order parsed by the simulation view."""
##
# Default states.
##
default_joint_pos: torch.Tensor = None
"""Default joint positions of all joints. Shape is (num_instances, num_joints)."""
default_joint_vel: torch.Tensor = None
"""Default joint velocities of all joints. Shape is (num_instances, num_joints)."""
##
# Joint states <- From simulation.
##
joint_pos: torch.Tensor = None
"""Joint positions of all joints. Shape is (num_instances, num_joints)."""
joint_vel: torch.Tensor = None
"""Joint velocities of all joints. Shape is (num_instances, num_joints)."""
joint_acc: torch.Tensor = None
"""Joint acceleration of all joints. Shape is (num_instances, num_joints)."""
##
# Joint commands -- Set into simulation.
##
joint_pos_target: torch.Tensor = None
"""Joint position targets commanded by the user. Shape is (num_instances, num_joints).
For an implicit actuator model, the targets are directly set into the simulation.
For an explicit actuator model, the targets are used to compute the joint torques (see :attr:`applied_torque`),
which are then set into the simulation.
"""
joint_vel_target: torch.Tensor = None
"""Joint velocity targets commanded by the user. Shape is (num_instances, num_joints).
For an implicit actuator model, the targets are directly set into the simulation.
For an explicit actuator model, the targets are used to compute the joint torques (see :attr:`applied_torque`),
which are then set into the simulation.
"""
joint_effort_target: torch.Tensor = None
"""Joint effort targets commanded by the user. Shape is (num_instances, num_joints).
For an implicit actuator model, the targets are directly set into the simulation.
For an explicit actuator model, the targets are used to compute the joint torques (see :attr:`applied_torque`),
which are then set into the simulation.
"""
##
# Joint properties.
##
joint_stiffness: torch.Tensor = None
"""Joint stiffness provided to simulation. Shape is (num_instances, num_joints)."""
joint_damping: torch.Tensor = None
"""Joint damping provided to simulation. Shape is (num_instances, num_joints)."""
joint_armature: torch.Tensor = None
"""Joint armature provided to simulation. Shape is (num_instances, num_joints)."""
joint_friction: torch.Tensor = None
"""Joint friction provided to simulation. Shape is (num_instances, num_joints)."""
joint_limits: torch.Tensor = None
"""Joint limits provided to simulation. Shape is (num_instances, num_joints, 2)."""
##
# Default joint properties
##
default_joint_stiffness: torch.Tensor = None
"""Default joint stiffness of all joints. Shape is (num_instances, num_joints)."""
default_joint_damping: torch.Tensor = None
"""Default joint damping of all joints. Shape is (num_instances, num_joints)."""
default_joint_armature: torch.Tensor = None
"""Default joint armature of all joints. Shape is (num_instances, num_joints)."""
default_joint_friction: torch.Tensor = None
"""Default joint friction of all joints. Shape is (num_instances, num_joints)."""
default_joint_limits: torch.Tensor = None
"""Default joint limits of all joints. Shape is (num_instances, num_joints, 2)."""
##
# Joint commands -- Explicit actuators.
##
computed_torque: torch.Tensor = None
"""Joint torques computed from the actuator model (before clipping). Shape is (num_instances, num_joints).
This quantity is the raw torque output from the actuator mode, before any clipping is applied.
It is exposed for users who want to inspect the computations inside the actuator model.
For instance, to penalize the learning agent for a difference between the computed and applied torques.
Note: The torques are zero for implicit actuator models.
"""
applied_torque: torch.Tensor = None
"""Joint torques applied from the actuator model (after clipping). Shape is (num_instances, num_joints).
These torques are set into the simulation, after clipping the :attr:`computed_torque` based on the
actuator model.
Note: The torques are zero for implicit actuator models.
"""
##
# Fixed tendon properties.
##
fixed_tendon_stiffness: torch.Tensor = None
"""Fixed tendon stiffness provided to simulation. Shape is (num_instances, num_fixed_tendons)."""
fixed_tendon_damping: torch.Tensor = None
"""Fixed tendon damping provided to simulation. Shape is (num_instances, num_fixed_tendons)."""
fixed_tendon_limit_stiffness: torch.Tensor = None
"""Fixed tendon limit stiffness provided to simulation. Shape is (num_instances, num_fixed_tendons)."""
fixed_tendon_rest_length: torch.Tensor = None
"""Fixed tendon rest length provided to simulation. Shape is (num_instances, num_fixed_tendons)."""
fixed_tendon_offset: torch.Tensor = None
"""Fixed tendon offset provided to simulation. Shape is (num_instances, num_fixed_tendons)."""
fixed_tendon_limit: torch.Tensor = None
"""Fixed tendon limits provided to simulation. Shape is (num_instances, num_fixed_tendons, 2)."""
##
# Default fixed tendon properties
##
default_fixed_tendon_stiffness: torch.Tensor = None
"""Default tendon stiffness of all tendons. Shape is (num_instances, num_fixed_tendons)."""
default_fixed_tendon_damping: torch.Tensor = None
"""Default tendon damping of all tendons. Shape is (num_instances, num_fixed_tendons)."""
default_fixed_tendon_limit_stiffness: torch.Tensor = None
"""Default tendon limit stiffness of all tendons. Shape is (num_instances, num_fixed_tendons)."""
default_fixed_tendon_rest_length: torch.Tensor = None
"""Default tendon rest length of all tendons. Shape is (num_instances, num_fixed_tendons)."""
default_fixed_tendon_offset: torch.Tensor = None
"""Default tendon offset of all tendons. Shape is (num_instances, num_fixed_tendons)."""
default_fixed_tendon_limit: torch.Tensor = None
"""Default tendon limits of all tendons. Shape is (num_instances, num_fixed_tendons, 2)."""
##
# Other Data.
##
soft_joint_pos_limits: torch.Tensor = None
"""Joint positions limits for all joints. Shape is (num_instances, num_joints, 2)."""
soft_joint_vel_limits: torch.Tensor = None
"""Joint velocity limits for all joints. Shape is (num_instances, num_joints)."""
gear_ratio: torch.Tensor = None
"""Gear ratio for relating motor torques to applied Joint torques. Shape is (num_instances, num_joints)."""
| 7,088 |
Python
| 36.115183 | 115 | 0.693567 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab/omni/isaac/lab/assets/articulation/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-module for rigid articulated assets."""
from .articulation import Articulation
from .articulation_cfg import ArticulationCfg
from .articulation_data import ArticulationData
| 308 |
Python
| 27.090907 | 60 | 0.792208 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab/omni/isaac/lab/assets/articulation/articulation.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
# Flag for pyright to ignore type errors in this file.
# pyright: reportPrivateUsage=false
from __future__ import annotations
import torch
import warnings
from collections.abc import Sequence
from prettytable import PrettyTable
from typing import TYPE_CHECKING
import carb
import omni.isaac.core.utils.stage as stage_utils
import omni.physics.tensors.impl.api as physx
from omni.isaac.core.utils.types import ArticulationActions
from pxr import PhysxSchema, UsdPhysics
import omni.isaac.lab.sim as sim_utils
import omni.isaac.lab.utils.math as math_utils
import omni.isaac.lab.utils.string as string_utils
from omni.isaac.lab.actuators import ActuatorBase, ActuatorBaseCfg, ImplicitActuator
from ..rigid_object import RigidObject
from .articulation_data import ArticulationData
if TYPE_CHECKING:
from .articulation_cfg import ArticulationCfg
class Articulation(RigidObject):
"""An articulation asset class.
An articulation is a collection of rigid bodies connected by joints. The joints can be either
fixed or actuated. The joints can be of different types, such as revolute, prismatic, D-6, etc.
However, the articulation class has currently been tested with revolute and prismatic joints.
The class supports both floating-base and fixed-base articulations. The type of articulation
is determined based on the root joint of the articulation. If the root joint is fixed, then
the articulation is considered a fixed-base system. Otherwise, it is considered a floating-base
system. This can be checked using the :attr:`Articulation.is_fixed_base` attribute.
For an asset to be considered an articulation, the root prim of the asset must have the
`USD ArticulationRootAPI`_. This API is used to define the sub-tree of the articulation using
the reduced coordinate formulation. On playing the simulation, the physics engine parses the
articulation root prim and creates the corresponding articulation in the physics engine. The
articulation root prim can be specified using the :attr:`AssetBaseCfg.prim_path` attribute.
The articulation class is a subclass of the :class:`RigidObject` class. Therefore, it inherits
all the functionality of the rigid object class. In case of an articulation, the :attr:`root_physx_view`
attribute corresponds to the articulation root view and can be used to access the articulation
related data.
The articulation class also provides the functionality to augment the simulation of an articulated
system with custom actuator models. These models can either be explicit or implicit, as detailed in
the :mod:`omni.isaac.lab.actuators` module. The actuator models are specified using the
:attr:`ArticulationCfg.actuators` attribute. These are then parsed and used to initialize the
corresponding actuator models, when the simulation is played.
During the simulation step, the articulation class first applies the actuator models to compute
the joint commands based on the user-specified targets. These joint commands are then applied
into the simulation. The joint commands can be either position, velocity, or effort commands.
As an example, the following snippet shows how this can be used for position commands:
.. code-block:: python
# an example instance of the articulation class
my_articulation = Articulation(cfg)
# set joint position targets
my_articulation.set_joint_position_target(position)
# propagate the actuator models and apply the computed commands into the simulation
my_articulation.write_data_to_sim()
# step the simulation using the simulation context
sim_context.step()
# update the articulation state, where dt is the simulation time step
my_articulation.update(dt)
.. _`USD ArticulationRootAPI`: https://openusd.org/dev/api/class_usd_physics_articulation_root_a_p_i.html
"""
cfg: ArticulationCfg
"""Configuration instance for the articulations."""
def __init__(self, cfg: ArticulationCfg):
"""Initialize the articulation.
Args:
cfg: A configuration instance.
"""
super().__init__(cfg)
# container for data access
self._data = ArticulationData()
# data for storing actuator group
self.actuators: dict[str, ActuatorBase] = dict.fromkeys(self.cfg.actuators.keys())
"""
Properties
"""
@property
def data(self) -> ArticulationData:
return self._data
@property
def is_fixed_base(self) -> bool:
"""Whether the articulation is a fixed-base or floating-base system."""
return self.root_physx_view.shared_metatype.fixed_base
@property
def num_joints(self) -> int:
"""Number of joints in articulation."""
return self.root_physx_view.shared_metatype.dof_count
@property
def num_fixed_tendons(self) -> int:
"""Number of fixed tendons in articulation."""
return self.root_physx_view.max_fixed_tendons
@property
def num_bodies(self) -> int:
"""Number of bodies in articulation."""
return self.root_physx_view.shared_metatype.link_count
@property
def joint_names(self) -> list[str]:
"""Ordered names of joints in articulation."""
return self.root_physx_view.shared_metatype.dof_names
@property
def body_names(self) -> list[str]:
"""Ordered names of bodies in articulation."""
return self.root_physx_view.shared_metatype.link_names
@property
def root_physx_view(self) -> physx.ArticulationView:
"""Articulation view for the asset (PhysX).
Note:
Use this view with caution. It requires handling of tensors in a specific way.
"""
return self._root_physx_view
@property
def body_physx_view(self) -> physx.RigidBodyView:
"""Rigid body view for the asset (PhysX).
.. deprecated:: v0.3.0
In previous versions, this attribute returned the rigid body view over all the links of the articulation.
However, this led to confusion with the link ordering as they were not ordered in the same way as the
articulation view.
Therefore, this attribute will be removed in v0.4.0. Please use the :attr:`root_physx_view` attribute
instead.
"""
dep_msg = "The attribute 'body_physx_view' will be removed in v0.4.0. Please use 'root_physx_view' instead."
warnings.warn(dep_msg, DeprecationWarning)
carb.log_error(dep_msg)
return self._body_physx_view
"""
Operations.
"""
def reset(self, env_ids: Sequence[int] | None = None):
super().reset(env_ids)
# use ellipses object to skip initial indices.
if env_ids is None:
env_ids = slice(None)
# reset actuators
for actuator in self.actuators.values():
actuator.reset(env_ids)
def write_data_to_sim(self):
"""Write external wrenches and joint commands to the simulation.
If any explicit actuators are present, then the actuator models are used to compute the
joint commands. Otherwise, the joint commands are directly set into the simulation.
"""
# write external wrench
if self.has_external_wrench:
# apply external forces and torques
self._body_physx_view.apply_forces_and_torques_at_position(
force_data=self._external_force_body_view_b.view(-1, 3),
torque_data=self._external_torque_body_view_b.view(-1, 3),
position_data=None,
indices=self._ALL_BODY_INDICES,
is_global=False,
)
# apply actuator models
self._apply_actuator_model()
# write actions into simulation
self.root_physx_view.set_dof_actuation_forces(self._joint_effort_target_sim, self._ALL_INDICES)
# position and velocity targets only for implicit actuators
if self._has_implicit_actuators:
self.root_physx_view.set_dof_position_targets(self._joint_pos_target_sim, self._ALL_INDICES)
self.root_physx_view.set_dof_velocity_targets(self._joint_vel_target_sim, self._ALL_INDICES)
def update(self, dt: float):
# -- root state (note: we roll the quaternion to match the convention used in Isaac Sim -- wxyz)
self._data.root_state_w[:, :7] = self.root_physx_view.get_root_transforms()
self._data.root_state_w[:, 3:7] = math_utils.convert_quat(self._data.root_state_w[:, 3:7], to="wxyz")
self._data.root_state_w[:, 7:] = self.root_physx_view.get_root_velocities()
# -- body-state (note: we roll the quaternion to match the convention used in Isaac Sim -- wxyz)
self._data.body_state_w[..., :7] = self.root_physx_view.get_link_transforms()
self._data.body_state_w[..., 3:7] = math_utils.convert_quat(self._data.body_state_w[..., 3:7], to="wxyz")
self._data.body_state_w[..., 7:] = self.root_physx_view.get_link_velocities()
# -- joint states
self._data.joint_pos[:] = self.root_physx_view.get_dof_positions()
self._data.joint_vel[:] = self.root_physx_view.get_dof_velocities()
if dt > 0.0:
self._data.joint_acc[:] = (self._data.joint_vel - self._previous_joint_vel) / dt
# -- update common data
# note: these are computed in the base class
self._update_common_data(dt)
# -- update history buffers
self._previous_joint_vel[:] = self._data.joint_vel[:]
def find_joints(
self, name_keys: str | Sequence[str], joint_subset: list[str] | None = None, preserve_order: bool = False
) -> tuple[list[int], list[str]]:
"""Find joints in the articulation based on the name keys.
Please see the :func:`omni.isaac.lab.utils.string.resolve_matching_names` function for more information
on the name matching.
Args:
name_keys: A regular expression or a list of regular expressions to match the joint names.
joint_subset: A subset of joints to search for. Defaults to None, which means all joints
in the articulation are searched.
preserve_order: Whether to preserve the order of the name keys in the output. Defaults to False.
Returns:
A tuple of lists containing the joint indices and names.
"""
if joint_subset is None:
joint_subset = self.joint_names
# find joints
return string_utils.resolve_matching_names(name_keys, joint_subset, preserve_order)
def find_fixed_tendons(
self, name_keys: str | Sequence[str], tendon_subsets: list[str] | None = None, preserve_order: bool = False
) -> tuple[list[int], list[str]]:
"""Find fixed tendons in the articulation based on the name keys.
Please see the :func:`omni.isaac.orbit.utils.string.resolve_matching_names` function for more information
on the name matching.
Args:
name_keys: A regular expression or a list of regular expressions to match the joint names with fixed tendons.
tendon_subsets: A subset of joints with fixed tendons to search for. Defaults to None, which means all joints
in the articulation are searched.
preserve_order: Whether to preserve the order of the name keys in the output. Defaults to False.
Returns:
A tuple of lists containing the tendon indices and names.
"""
if tendon_subsets is None:
# tendons follow the joint names they are attached to
tendon_subsets = self.fixed_tendon_names
# find tendons
return string_utils.resolve_matching_names(name_keys, tendon_subsets, preserve_order)
"""
Operations - Setters.
"""
def set_external_force_and_torque(
self,
forces: torch.Tensor,
torques: torch.Tensor,
body_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
# call parent to set the external forces and torques into buffers
super().set_external_force_and_torque(forces, torques, body_ids, env_ids)
# reordering of the external forces and torques to match the body view ordering
if self.has_external_wrench:
self._external_force_body_view_b = self._external_force_b[:, self._body_view_ordering]
self._external_torque_body_view_b = self._external_torque_b[:, self._body_view_ordering]
"""
Operations - Writers.
"""
def write_root_pose_to_sim(self, root_pose: torch.Tensor, env_ids: Sequence[int] | None = None):
# resolve all indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
# note: we need to do this here since tensors are not set into simulation until step.
# set into internal buffers
self._data.root_state_w[env_ids, :7] = root_pose.clone()
# convert root quaternion from wxyz to xyzw
root_poses_xyzw = self._data.root_state_w[:, :7].clone()
root_poses_xyzw[:, 3:] = math_utils.convert_quat(root_poses_xyzw[:, 3:], to="xyzw")
# set into simulation
self.root_physx_view.set_root_transforms(root_poses_xyzw, indices=physx_env_ids)
def write_root_velocity_to_sim(self, root_velocity: torch.Tensor, env_ids: Sequence[int] | None = None):
# resolve all indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
# note: we need to do this here since tensors are not set into simulation until step.
# set into internal buffers
self._data.root_state_w[env_ids, 7:] = root_velocity.clone()
# set into simulation
self.root_physx_view.set_root_velocities(self._data.root_state_w[:, 7:], indices=physx_env_ids)
def write_joint_state_to_sim(
self,
position: torch.Tensor,
velocity: torch.Tensor,
joint_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | slice | None = None,
):
"""Write joint positions and velocities to the simulation.
Args:
position: Joint positions. Shape is (len(env_ids), len(joint_ids)).
velocity: Joint velocities. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the targets for. Defaults to None (all joints).
env_ids: The environment indices to set the targets for. Defaults to None (all environments).
"""
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
if joint_ids is None:
joint_ids = slice(None)
elif env_ids != slice(None):
env_ids = env_ids[:, None]
# set into internal buffers
self._data.joint_pos[env_ids, joint_ids] = position
self._data.joint_vel[env_ids, joint_ids] = velocity
self._previous_joint_vel[env_ids, joint_ids] = velocity
self._data.joint_acc[env_ids, joint_ids] = 0.0
# set into simulation
self.root_physx_view.set_dof_positions(self._data.joint_pos, indices=physx_env_ids)
self.root_physx_view.set_dof_velocities(self._data.joint_vel, indices=physx_env_ids)
def write_joint_stiffness_to_sim(
self,
stiffness: torch.Tensor | float,
joint_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Write joint stiffness into the simulation.
Args:
stiffness: Joint stiffness. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the stiffness for. Defaults to None (all joints).
env_ids: The environment indices to set the stiffness for. Defaults to None (all environments).
"""
# note: This function isn't setting the values for actuator models. (#128)
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
if joint_ids is None:
joint_ids = slice(None)
elif env_ids != slice(None):
env_ids = env_ids[:, None]
# set into internal buffers
self._data.joint_stiffness[env_ids, joint_ids] = stiffness
# set into simulation
self.root_physx_view.set_dof_stiffnesses(self._data.joint_stiffness.cpu(), indices=physx_env_ids.cpu())
def write_joint_damping_to_sim(
self,
damping: torch.Tensor | float,
joint_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Write joint damping into the simulation.
Args:
damping: Joint damping. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the damping for.
Defaults to None (all joints).
env_ids: The environment indices to set the damping for.
Defaults to None (all environments).
"""
# note: This function isn't setting the values for actuator models. (#128)
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
if joint_ids is None:
joint_ids = slice(None)
elif env_ids != slice(None):
env_ids = env_ids[:, None]
# set into internal buffers
self._data.joint_damping[env_ids, joint_ids] = damping
# set into simulation
self.root_physx_view.set_dof_dampings(self._data.joint_damping.cpu(), indices=physx_env_ids.cpu())
def write_joint_effort_limit_to_sim(
self,
limits: torch.Tensor | float,
joint_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Write joint effort limits into the simulation.
Args:
limits: Joint torque limits. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the joint torque limits for. Defaults to None (all joints).
env_ids: The environment indices to set the joint torque limits for. Defaults to None (all environments).
"""
# note: This function isn't setting the values for actuator models. (#128)
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
if joint_ids is None:
joint_ids = slice(None)
elif env_ids != slice(None):
env_ids = env_ids[:, None]
# move tensor to cpu if needed
if isinstance(limits, torch.Tensor):
limits = limits.cpu()
# set into internal buffers
torque_limit_all = self.root_physx_view.get_dof_max_forces()
torque_limit_all[env_ids, joint_ids] = limits
# set into simulation
self.root_physx_view.set_dof_max_forces(torque_limit_all.cpu(), indices=physx_env_ids.cpu())
def write_joint_armature_to_sim(
self,
armature: torch.Tensor | float,
joint_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Write joint armature into the simulation.
Args:
armature: Joint armature. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the joint torque limits for. Defaults to None (all joints).
env_ids: The environment indices to set the joint torque limits for. Defaults to None (all environments).
"""
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
if joint_ids is None:
joint_ids = slice(None)
elif env_ids != slice(None):
env_ids = env_ids[:, None]
# set into internal buffers
self._data.joint_armature[env_ids, joint_ids] = armature
# set into simulation
self.root_physx_view.set_dof_armatures(self._data.joint_armature.cpu(), indices=physx_env_ids.cpu())
def write_joint_friction_to_sim(
self,
joint_friction: torch.Tensor | float,
joint_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Write joint friction into the simulation.
Args:
joint_friction: Joint friction. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the joint torque limits for. Defaults to None (all joints).
env_ids: The environment indices to set the joint torque limits for. Defaults to None (all environments).
"""
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
if joint_ids is None:
joint_ids = slice(None)
elif env_ids != slice(None):
env_ids = env_ids[:, None]
# set into internal buffers
self._data.joint_friction[env_ids, joint_ids] = joint_friction
# set into simulation
self.root_physx_view.set_dof_friction_coefficients(self._data.joint_friction.cpu(), indices=physx_env_ids.cpu())
def write_joint_limits_to_sim(
self,
limits: torch.Tensor | float,
joint_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Write joint limits into the simulation.
Args:
limits: Joint limits. Shape is (len(env_ids), len(joint_ids), 2).
joint_ids: The joint indices to set the limits for. Defaults to None (all joints).
env_ids: The environment indices to set the limits for. Defaults to None (all environments).
"""
# note: This function isn't setting the values for actuator models. (#128)
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
env_ids = slice(None)
physx_env_ids = self._ALL_INDICES
if joint_ids is None:
joint_ids = slice(None)
elif env_ids != slice(None):
env_ids = env_ids[:, None]
# set into internal buffers
self._data.joint_limits[env_ids, joint_ids] = limits
# set into simulation
self.root_physx_view.set_dof_limits(self._data.joint_limits.cpu(), indices=physx_env_ids.cpu())
"""
Operations - State.
"""
def set_joint_position_target(
self, target: torch.Tensor, joint_ids: Sequence[int] | slice | None = None, env_ids: Sequence[int] | None = None
):
"""Set joint position targets into internal buffers.
.. note::
This function does not apply the joint targets to the simulation. It only fills the buffers with
the desired values. To apply the joint targets, call the :meth:`write_data_to_sim` function.
Args:
target: Joint position targets. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the targets for. Defaults to None (all joints).
env_ids: The environment indices to set the targets for. Defaults to None (all environments).
"""
# resolve indices
if env_ids is None:
env_ids = slice(None)
if joint_ids is None:
joint_ids = slice(None)
elif env_ids != slice(None):
env_ids = env_ids[:, None]
# set targets
self._data.joint_pos_target[env_ids, joint_ids] = target
def set_joint_velocity_target(
self, target: torch.Tensor, joint_ids: Sequence[int] | slice | None = None, env_ids: Sequence[int] | None = None
):
"""Set joint velocity targets into internal buffers.
.. note::
This function does not apply the joint targets to the simulation. It only fills the buffers with
the desired values. To apply the joint targets, call the :meth:`write_data_to_sim` function.
Args:
target: Joint velocity targets. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the targets for. Defaults to None (all joints).
env_ids: The environment indices to set the targets for. Defaults to None (all environments).
"""
# resolve indices
if env_ids is None:
env_ids = slice(None)
if joint_ids is None:
joint_ids = slice(None)
elif env_ids != slice(None):
env_ids = env_ids[:, None]
# set targets
self._data.joint_vel_target[env_ids, joint_ids] = target
def set_joint_effort_target(
self, target: torch.Tensor, joint_ids: Sequence[int] | slice | None = None, env_ids: Sequence[int] | None = None
):
"""Set joint efforts into internal buffers.
.. note::
This function does not apply the joint targets to the simulation. It only fills the buffers with
the desired values. To apply the joint targets, call the :meth:`write_data_to_sim` function.
Args:
target: Joint effort targets. Shape is (len(env_ids), len(joint_ids)).
joint_ids: The joint indices to set the targets for. Defaults to None (all joints).
env_ids: The environment indices to set the targets for. Defaults to None (all environments).
"""
# resolve indices
if env_ids is None:
env_ids = slice(None)
if joint_ids is None:
joint_ids = slice(None)
elif env_ids != slice(None):
env_ids = env_ids[:, None]
# set targets
self._data.joint_effort_target[env_ids, joint_ids] = target
def set_fixed_tendon_stiffness(
self,
stiffness: torch.Tensor,
fixed_tendon_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Set fixed tendon stiffness into internal buffers.
.. note::
This function does not apply the tendon stiffness to the simulation. It only fills the buffers with
the desired values. To apply the tendon stiffness, call the :meth:`write_fixed_tendon_properties_to_sim` function.
Args:
stiffness: Fixed tendon stiffness. Shape is (len(env_ids), len(fixed_tendon_ids)).
fixed_tendon_ids: The tendon indices to set the stiffness for. Defaults to None (all fixed tendons).
env_ids: The environment indices to set the stiffness for. Defaults to None (all environments).
"""
# resolve indices
if env_ids is None:
env_ids = slice(None)
if fixed_tendon_ids is None:
fixed_tendon_ids = slice(None)
elif env_ids != slice(None):
env_ids = env_ids[:, None]
# set stiffness
self._data.fixed_tendon_stiffness[env_ids, fixed_tendon_ids] = stiffness
def set_fixed_tendon_damping(
self,
damping: torch.Tensor,
fixed_tendon_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Set fixed tendon damping into internal buffers.
.. note::
This function does not apply the tendon damping to the simulation. It only fills the buffers with
the desired values. To apply the tendon damping, call the :meth:`write_fixed_tendon_properties_to_sim` function.
Args:
damping: Fixed tendon damping. Shape is (len(env_ids), len(fixed_tendon_ids)).
fixed_tendon_ids: The tendon indices to set the damping for. Defaults to None (all fixed tendons).
env_ids: The environment indices to set the damping for. Defaults to None (all environments).
"""
# resolve indices
if env_ids is None:
env_ids = slice(None)
if fixed_tendon_ids is None:
fixed_tendon_ids = slice(None)
elif env_ids != slice(None):
env_ids = env_ids[:, None]
# set damping
self._data.fixed_tendon_damping[env_ids, fixed_tendon_ids] = damping
def set_fixed_tendon_limit_stiffness(
self,
limit_stiffness: torch.Tensor,
fixed_tendon_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Set fixed tendon limit stiffness efforts into internal buffers.
.. note::
This function does not apply the tendon limit stiffness to the simulation. It only fills the buffers with
the desired values. To apply the tendon limit stiffness, call the :meth:`write_fixed_tendon_properties_to_sim` function.
Args:
limit_stiffness: Fixed tendon limit stiffness. Shape is (len(env_ids), len(fixed_tendon_ids)).
fixed_tendon_ids: The tendon indices to set the limit stiffness for. Defaults to None (all fixed tendons).
env_ids: The environment indices to set the limit stiffness for. Defaults to None (all environments).
"""
# resolve indices
if env_ids is None:
env_ids = slice(None)
if fixed_tendon_ids is None:
fixed_tendon_ids = slice(None)
elif env_ids != slice(None):
env_ids = env_ids[:, None]
# set limit_stiffness
self._data.fixed_tendon_limit_stiffness[env_ids, fixed_tendon_ids] = limit_stiffness
def set_fixed_tendon_limit(
self,
limit: torch.Tensor,
fixed_tendon_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Set fixed tendon limit efforts into internal buffers.
.. note::
This function does not apply the tendon limit to the simulation. It only fills the buffers with
the desired values. To apply the tendon limit, call the :meth:`write_fixed_tendon_properties_to_sim` function.
Args:
limit: Fixed tendon limit. Shape is (len(env_ids), len(fixed_tendon_ids)).
fixed_tendon_ids: The tendon indices to set the limit for. Defaults to None (all fixed tendons).
env_ids: The environment indices to set the limit for. Defaults to None (all environments).
"""
# resolve indices
if env_ids is None:
env_ids = slice(None)
if fixed_tendon_ids is None:
fixed_tendon_ids = slice(None)
elif env_ids != slice(None):
env_ids = env_ids[:, None]
# set limit
self._data.fixed_tendon_limit[env_ids, fixed_tendon_ids] = limit
def set_fixed_tendon_rest_length(
self,
rest_length: torch.Tensor,
fixed_tendon_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Set fixed tendon rest length efforts into internal buffers.
.. note::
This function does not apply the tendon rest length to the simulation. It only fills the buffers with
the desired values. To apply the tendon rest length, call the :meth:`write_fixed_tendon_properties_to_sim` function.
Args:
rest_length: Fixed tendon rest length. Shape is (len(env_ids), len(fixed_tendon_ids)).
fixed_tendon_ids: The tendon indices to set the rest length for. Defaults to None (all fixed tendons).
env_ids: The environment indices to set the rest length for. Defaults to None (all environments).
"""
# resolve indices
if env_ids is None:
env_ids = slice(None)
if fixed_tendon_ids is None:
fixed_tendon_ids = slice(None)
elif env_ids != slice(None):
env_ids = env_ids[:, None]
# set rest_length
self._data.fixed_tendon_rest_length[env_ids, fixed_tendon_ids] = rest_length
def set_fixed_tendon_offset(
self,
offset: torch.Tensor,
fixed_tendon_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Set fixed tendon offset efforts into internal buffers.
.. note::
This function does not apply the tendon offset to the simulation. It only fills the buffers with
the desired values. To apply the tendon offset, call the :meth:`write_fixed_tendon_properties_to_sim` function.
Args:
offset: Fixed tendon offset. Shape is (len(env_ids), len(fixed_tendon_ids)).
fixed_tendon_ids: The tendon indices to set the offset for. Defaults to None (all fixed tendons).
env_ids: The environment indices to set the offset for. Defaults to None (all environments).
"""
# resolve indices
if env_ids is None:
env_ids = slice(None)
if fixed_tendon_ids is None:
fixed_tendon_ids = slice(None)
elif env_ids != slice(None):
env_ids = env_ids[:, None]
# set offset
self._data.fixed_tendon_offset[env_ids, fixed_tendon_ids] = offset
def write_fixed_tendon_properties_to_sim(
self,
fixed_tendon_ids: Sequence[int] | slice | None = None,
env_ids: Sequence[int] | None = None,
):
"""Write fixed tendon properties into the simulation.
Args:
fixed_tendon_ids: The fixed tendon indices to set the limits for. Defaults to None (all fixed tendons).
env_ids: The environment indices to set the limits for. Defaults to None (all environments).
"""
# resolve indices
physx_env_ids = env_ids
if env_ids is None:
physx_env_ids = self._ALL_INDICES
if fixed_tendon_ids is None:
fixed_tendon_ids = slice(None)
# set into simulation
self.root_physx_view.set_fixed_tendon_properties(
self._data.fixed_tendon_stiffness,
self._data.fixed_tendon_damping,
self._data.fixed_tendon_limit_stiffness,
self._data.fixed_tendon_limit,
self._data.fixed_tendon_rest_length,
self._data.fixed_tendon_offset,
indices=physx_env_ids,
)
"""
Internal helper.
"""
def _initialize_impl(self):
# create simulation view
self._physics_sim_view = physx.create_simulation_view(self._backend)
self._physics_sim_view.set_subspace_roots("/")
# obtain the first prim in the regex expression (all others are assumed to be a copy of this)
template_prim = sim_utils.find_first_matching_prim(self.cfg.prim_path)
if template_prim is None:
raise RuntimeError(f"Failed to find prim for expression: '{self.cfg.prim_path}'.")
template_prim_path = template_prim.GetPath().pathString
# find articulation root prims
root_prims = sim_utils.get_all_matching_child_prims(
template_prim_path, predicate=lambda prim: prim.HasAPI(UsdPhysics.ArticulationRootAPI)
)
if len(root_prims) == 0:
raise RuntimeError(
f"Failed to find an articulation when resolving '{self.cfg.prim_path}'."
" Please ensure that the prim has 'USD ArticulationRootAPI' applied."
)
if len(root_prims) > 1:
raise RuntimeError(
f"Failed to find a single articulation when resolving '{self.cfg.prim_path}'."
f" Found multiple '{root_prims}' under '{template_prim_path}'."
" Please ensure that there is only one articulation in the prim path tree."
)
# resolve articulation root prim back into regex expression
root_prim_path = root_prims[0].GetPath().pathString
root_prim_path_expr = self.cfg.prim_path + root_prim_path[len(template_prim_path) :]
# -- articulation
self._root_physx_view = self._physics_sim_view.create_articulation_view(root_prim_path_expr.replace(".*", "*"))
# -- link views
# note: we use the root view to get the body names, but we use the body view to get the
# actual data. This is mainly needed to apply external forces to the bodies.
physx_body_names = self.root_physx_view.shared_metatype.link_names
body_names_regex = r"(" + "|".join(physx_body_names) + r")"
body_names_regex = f"{self.cfg.prim_path}/{body_names_regex}"
self._body_physx_view = self._physics_sim_view.create_rigid_body_view(body_names_regex.replace(".*", "*"))
# create ordering from articulation view to body view for body names
# note: we need to do this since the body view is not ordered in the same way as the articulation view
# -- root view
root_view_body_names = self.body_names
# -- body view
prim_paths = self._body_physx_view.prim_paths[: self.num_bodies]
body_view_body_names = [path.split("/")[-1] for path in prim_paths]
# -- mapping from articulation view to body view
self._body_view_ordering = [body_view_body_names.index(name) for name in root_view_body_names]
self._body_view_ordering = torch.tensor(self._body_view_ordering, dtype=torch.long, device=self.device)
# log information about the articulation
carb.log_info(f"Articulation initialized at: {self.cfg.prim_path} with root '{root_prim_path_expr}'.")
carb.log_info(f"Is fixed root: {self.is_fixed_base}")
carb.log_info(f"Number of bodies: {self.num_bodies}")
carb.log_info(f"Body names: {self.body_names}")
carb.log_info(f"Number of joints: {self.num_joints}")
carb.log_info(f"Joint names: {self.joint_names}")
carb.log_info(f"Number of fixed tendons: {self.num_fixed_tendons}")
# -- assert that parsing was successful
if set(physx_body_names) != set(self.body_names):
raise RuntimeError("Failed to parse all bodies properly in the articulation.")
# create buffers
self._create_buffers()
# process configuration
self._process_cfg()
self._process_actuators_cfg()
self._process_fixed_tendons()
# validate configuration
self._validate_cfg()
# update the robot data
self.update(0.0)
# log joint information
self._log_articulation_joint_info()
def _create_buffers(self):
# allocate buffers
super()._create_buffers()
# history buffers
self._previous_joint_vel = torch.zeros(self.num_instances, self.num_joints, device=self.device)
# asset data
# -- properties
self._data.joint_names = self.joint_names
# -- joint states
self._data.joint_pos = torch.zeros(self.num_instances, self.num_joints, device=self.device)
self._data.joint_vel = torch.zeros_like(self._data.joint_pos)
self._data.joint_acc = torch.zeros_like(self._data.joint_pos)
self._data.default_joint_pos = torch.zeros_like(self._data.joint_pos)
self._data.default_joint_vel = torch.zeros_like(self._data.joint_pos)
# -- joint commands
self._data.joint_pos_target = torch.zeros_like(self._data.joint_pos)
self._data.joint_vel_target = torch.zeros_like(self._data.joint_pos)
self._data.joint_effort_target = torch.zeros_like(self._data.joint_pos)
self._data.joint_stiffness = torch.zeros_like(self._data.joint_pos)
self._data.joint_damping = torch.zeros_like(self._data.joint_pos)
self._data.joint_armature = torch.zeros_like(self._data.joint_pos)
self._data.joint_friction = torch.zeros_like(self._data.joint_pos)
self._data.joint_limits = torch.zeros(self.num_instances, self.num_joints, 2, device=self.device)
# -- joint commands (explicit)
self._data.computed_torque = torch.zeros_like(self._data.joint_pos)
self._data.applied_torque = torch.zeros_like(self._data.joint_pos)
# -- tendons
if self.num_fixed_tendons > 0:
self._data.fixed_tendon_stiffness = torch.zeros(
self.num_instances, self.num_fixed_tendons, device=self.device
)
self._data.fixed_tendon_damping = torch.zeros(
self.num_instances, self.num_fixed_tendons, device=self.device
)
self._data.fixed_tendon_limit_stiffness = torch.zeros(
self.num_instances, self.num_fixed_tendons, device=self.device
)
self._data.fixed_tendon_limit = torch.zeros(
self.num_instances, self.num_fixed_tendons, 2, device=self.device
)
self._data.fixed_tendon_rest_length = torch.zeros(
self.num_instances, self.num_fixed_tendons, device=self.device
)
self._data.fixed_tendon_offset = torch.zeros(self.num_instances, self.num_fixed_tendons, device=self.device)
# -- other data
self._data.soft_joint_pos_limits = torch.zeros(self.num_instances, self.num_joints, 2, device=self.device)
self._data.soft_joint_vel_limits = torch.zeros(self.num_instances, self.num_joints, device=self.device)
self._data.gear_ratio = torch.ones(self.num_instances, self.num_joints, device=self.device)
# -- initialize default buffers
self._data.default_joint_stiffness = torch.zeros(self.num_instances, self.num_joints, device=self.device)
self._data.default_joint_damping = torch.zeros(self.num_instances, self.num_joints, device=self.device)
self._data.default_joint_armature = torch.zeros(self.num_instances, self.num_joints, device=self.device)
self._data.default_joint_friction = torch.zeros(self.num_instances, self.num_joints, device=self.device)
self._data.default_joint_limits = torch.zeros(self.num_instances, self.num_joints, 2, device=self.device)
if self.num_fixed_tendons > 0:
self._data.default_fixed_tendon_stiffness = torch.zeros(
self.num_instances, self.num_fixed_tendons, device=self.device
)
self._data.default_fixed_tendon_damping = torch.zeros(
self.num_instances, self.num_fixed_tendons, device=self.device
)
self._data.default_fixed_tendon_limit_stiffness = torch.zeros(
self.num_instances, self.num_fixed_tendons, device=self.device
)
self._data.default_fixed_tendon_limit = torch.zeros(
self.num_instances, self.num_fixed_tendons, 2, device=self.device
)
self._data.default_fixed_tendon_rest_length = torch.zeros(
self.num_instances, self.num_fixed_tendons, device=self.device
)
self._data.default_fixed_tendon_offset = torch.zeros(
self.num_instances, self.num_fixed_tendons, device=self.device
)
# soft joint position limits (recommended not to be too close to limits).
joint_pos_limits = self.root_physx_view.get_dof_limits()
joint_pos_mean = (joint_pos_limits[..., 0] + joint_pos_limits[..., 1]) / 2
joint_pos_range = joint_pos_limits[..., 1] - joint_pos_limits[..., 0]
soft_limit_factor = self.cfg.soft_joint_pos_limit_factor
# add to data
self._data.soft_joint_pos_limits[..., 0] = joint_pos_mean - 0.5 * joint_pos_range * soft_limit_factor
self._data.soft_joint_pos_limits[..., 1] = joint_pos_mean + 0.5 * joint_pos_range * soft_limit_factor
# create buffers to store processed actions from actuator models
self._joint_pos_target_sim = torch.zeros_like(self._data.joint_pos_target)
self._joint_vel_target_sim = torch.zeros_like(self._data.joint_pos_target)
self._joint_effort_target_sim = torch.zeros_like(self._data.joint_pos_target)
def _process_cfg(self):
"""Post processing of configuration parameters."""
# default state
super()._process_cfg()
# -- joint state
# joint pos
indices_list, _, values_list = string_utils.resolve_matching_names_values(
self.cfg.init_state.joint_pos, self.joint_names
)
self._data.default_joint_pos[:, indices_list] = torch.tensor(values_list, device=self.device)
# joint vel
indices_list, _, values_list = string_utils.resolve_matching_names_values(
self.cfg.init_state.joint_vel, self.joint_names
)
self._data.default_joint_vel[:, indices_list] = torch.tensor(values_list, device=self.device)
self._data.default_joint_limits = self.root_physx_view.get_dof_limits().to(device=self.device).clone()
self._data.joint_limits = self._data.default_joint_limits.clone()
"""
Internal helpers -- Actuators.
"""
def _process_actuators_cfg(self):
"""Process and apply articulation joint properties."""
# flag for implicit actuators
# if this is false, we by-pass certain checks when doing actuator-related operations
self._has_implicit_actuators = False
# cache the values coming from the usd
usd_stiffness = self.root_physx_view.get_dof_stiffnesses().clone()
usd_damping = self.root_physx_view.get_dof_dampings().clone()
usd_armature = self.root_physx_view.get_dof_armatures().clone()
usd_friction = self.root_physx_view.get_dof_friction_coefficients().clone()
usd_effort_limit = self.root_physx_view.get_dof_max_forces().clone()
usd_velocity_limit = self.root_physx_view.get_dof_max_velocities().clone()
# iterate over all actuator configurations
for actuator_name, actuator_cfg in self.cfg.actuators.items():
# type annotation for type checkers
actuator_cfg: ActuatorBaseCfg
# create actuator group
joint_ids, joint_names = self.find_joints(actuator_cfg.joint_names_expr)
# check if any joints are found
if len(joint_names) == 0:
raise ValueError(
f"No joints found for actuator group: {actuator_name} with joint name expression:"
f" {actuator_cfg.joint_names_expr}."
)
# create actuator collection
# note: for efficiency avoid indexing when over all indices
actuator: ActuatorBase = actuator_cfg.class_type(
cfg=actuator_cfg,
joint_names=joint_names,
joint_ids=slice(None) if len(joint_names) == self.num_joints else joint_ids,
num_envs=self.num_instances,
device=self.device,
stiffness=usd_stiffness[:, joint_ids],
damping=usd_damping[:, joint_ids],
armature=usd_armature[:, joint_ids],
friction=usd_friction[:, joint_ids],
effort_limit=usd_effort_limit[:, joint_ids],
velocity_limit=usd_velocity_limit[:, joint_ids],
)
# log information on actuator groups
carb.log_info(
f"Actuator collection: {actuator_name} with model '{actuator_cfg.class_type.__name__}' and"
f" joint names: {joint_names} [{joint_ids}]."
)
# store actuator group
self.actuators[actuator_name] = actuator
# set the passed gains and limits into the simulation
if isinstance(actuator, ImplicitActuator):
self._has_implicit_actuators = True
# the gains and limits are set into the simulation since actuator model is implicit
self.write_joint_stiffness_to_sim(actuator.stiffness, joint_ids=actuator.joint_indices)
self.write_joint_damping_to_sim(actuator.damping, joint_ids=actuator.joint_indices)
self.write_joint_effort_limit_to_sim(actuator.effort_limit, joint_ids=actuator.joint_indices)
self.write_joint_armature_to_sim(actuator.armature, joint_ids=actuator.joint_indices)
self.write_joint_friction_to_sim(actuator.friction, joint_ids=actuator.joint_indices)
else:
# the gains and limits are processed by the actuator model
# we set gains to zero, and torque limit to a high value in simulation to avoid any interference
self.write_joint_stiffness_to_sim(0.0, joint_ids=actuator.joint_indices)
self.write_joint_damping_to_sim(0.0, joint_ids=actuator.joint_indices)
self.write_joint_effort_limit_to_sim(1.0e9, joint_ids=actuator.joint_indices)
self.write_joint_armature_to_sim(actuator.armature, joint_ids=actuator.joint_indices)
self.write_joint_friction_to_sim(actuator.friction, joint_ids=actuator.joint_indices)
# set the default joint parameters based on the changes from the actuators
self._data.default_joint_stiffness = self.root_physx_view.get_dof_stiffnesses().to(device=self.device).clone()
self._data.default_joint_damping = self.root_physx_view.get_dof_dampings().to(device=self.device).clone()
self._data.default_joint_armature = self.root_physx_view.get_dof_armatures().to(device=self.device).clone()
self._data.default_joint_friction = (
self.root_physx_view.get_dof_friction_coefficients().to(device=self.device).clone()
)
# perform some sanity checks to ensure actuators are prepared correctly
total_act_joints = sum(actuator.num_joints for actuator in self.actuators.values())
if total_act_joints != (self.num_joints - self.num_fixed_tendons):
carb.log_warn(
"Not all actuators are configured! Total number of actuated joints not equal to number of"
f" joints available: {total_act_joints} != {self.num_joints}."
)
def _process_fixed_tendons(self):
"""Process fixed tendons."""
self.fixed_tendon_names = list()
if self.num_fixed_tendons > 0:
stage = stage_utils.get_current_stage()
for j in range(self.num_joints):
usd_joint_path = self.root_physx_view.dof_paths[0][j]
# check whether joint has tendons - tendon name follows the joint name it is attached to
joint = UsdPhysics.Joint.Get(stage, usd_joint_path)
if joint.GetPrim().HasAPI(PhysxSchema.PhysxTendonAxisRootAPI):
joint_name = usd_joint_path.split("/")[-1]
self.fixed_tendon_names.append(joint_name)
self._data.default_fixed_tendon_stiffness = self.root_physx_view.get_fixed_tendon_stiffnesses().clone()
self._data.default_fixed_tendon_damping = self.root_physx_view.get_fixed_tendon_dampings().clone()
self._data.default_fixed_tendon_limit_stiffness = (
self.root_physx_view.get_fixed_tendon_limit_stiffnesses().clone()
)
self._data.default_fixed_tendon_limit = self.root_physx_view.get_fixed_tendon_limits().clone()
self._data.default_fixed_tendon_rest_length = self.root_physx_view.get_fixed_tendon_rest_lengths().clone()
self._data.default_fixed_tendon_offset = self.root_physx_view.get_fixed_tendon_offsets().clone()
def _apply_actuator_model(self):
"""Processes joint commands for the articulation by forwarding them to the actuators.
The actions are first processed using actuator models. Depending on the robot configuration,
the actuator models compute the joint level simulation commands and sets them into the PhysX buffers.
"""
# process actions per group
for actuator in self.actuators.values():
# prepare input for actuator model based on cached data
# TODO : A tensor dict would be nice to do the indexing of all tensors together
control_action = ArticulationActions(
joint_positions=self._data.joint_pos_target[:, actuator.joint_indices],
joint_velocities=self._data.joint_vel_target[:, actuator.joint_indices],
joint_efforts=self._data.joint_effort_target[:, actuator.joint_indices],
joint_indices=actuator.joint_indices,
)
# compute joint command from the actuator model
control_action = actuator.compute(
control_action,
joint_pos=self._data.joint_pos[:, actuator.joint_indices],
joint_vel=self._data.joint_vel[:, actuator.joint_indices],
)
# update targets (these are set into the simulation)
if control_action.joint_positions is not None:
self._joint_pos_target_sim[:, actuator.joint_indices] = control_action.joint_positions
if control_action.joint_velocities is not None:
self._joint_vel_target_sim[:, actuator.joint_indices] = control_action.joint_velocities
if control_action.joint_efforts is not None:
self._joint_effort_target_sim[:, actuator.joint_indices] = control_action.joint_efforts
# update state of the actuator model
# -- torques
self._data.computed_torque[:, actuator.joint_indices] = actuator.computed_effort
self._data.applied_torque[:, actuator.joint_indices] = actuator.applied_effort
# -- actuator data
self._data.soft_joint_vel_limits[:, actuator.joint_indices] = actuator.velocity_limit
# TODO: find a cleaner way to handle gear ratio. Only needed for variable gear ratio actuators.
if hasattr(actuator, "gear_ratio"):
self._data.gear_ratio[:, actuator.joint_indices] = actuator.gear_ratio
"""
Internal helpers -- Debugging.
"""
def _validate_cfg(self):
"""Validate the configuration after processing.
Note:
This function should be called only after the configuration has been processed and the buffers have been
created. Otherwise, some settings that are altered during processing may not be validated.
For instance, the actuator models may change the joint max velocity limits.
"""
# check that the default values are within the limits
joint_pos_limits = self.root_physx_view.get_dof_limits()[0].to(self.device)
out_of_range = self._data.default_joint_pos[0] < joint_pos_limits[:, 0]
out_of_range |= self._data.default_joint_pos[0] > joint_pos_limits[:, 1]
violated_indices = torch.nonzero(out_of_range, as_tuple=False).squeeze(-1)
# throw error if any of the default joint positions are out of the limits
if len(violated_indices) > 0:
# prepare message for violated joints
msg = "The following joints have default positions out of the limits: \n"
for idx in violated_indices:
joint_name = self.data.joint_names[idx]
joint_limits = joint_pos_limits[idx]
joint_pos = self.data.default_joint_pos[0, idx]
# add to message
msg += f"\t- '{joint_name}': {joint_pos:.3f} not in [{joint_limits[0]:.3f}, {joint_limits[1]:.3f}]\n"
raise ValueError(msg)
# check that the default joint velocities are within the limits
joint_max_vel = self.root_physx_view.get_dof_max_velocities()[0].to(self.device)
out_of_range = torch.abs(self._data.default_joint_vel[0]) > joint_max_vel
violated_indices = torch.nonzero(out_of_range, as_tuple=False).squeeze(-1)
if len(violated_indices) > 0:
# prepare message for violated joints
msg = "The following joints have default velocities out of the limits: \n"
for idx in violated_indices:
joint_name = self.data.joint_names[idx]
joint_limits = [-joint_max_vel[idx], joint_max_vel[idx]]
joint_vel = self.data.default_joint_vel[0, idx]
# add to message
msg += f"\t- '{joint_name}': {joint_vel:.3f} not in [{joint_limits[0]:.3f}, {joint_limits[1]:.3f}]\n"
raise ValueError(msg)
def _log_articulation_joint_info(self):
"""Log information about the articulation's simulated joints."""
# read out all joint parameters from simulation
# -- gains
stiffnesses = self.root_physx_view.get_dof_stiffnesses()[0].tolist()
dampings = self.root_physx_view.get_dof_dampings()[0].tolist()
# -- properties
armatures = self.root_physx_view.get_dof_armatures()[0].tolist()
frictions = self.root_physx_view.get_dof_friction_coefficients()[0].tolist()
# -- limits
position_limits = self.root_physx_view.get_dof_limits()[0].tolist()
velocity_limits = self.root_physx_view.get_dof_max_velocities()[0].tolist()
effort_limits = self.root_physx_view.get_dof_max_forces()[0].tolist()
# create table for term information
table = PrettyTable(float_format=".3f")
table.title = f"Simulation Joint Information (Prim path: {self.cfg.prim_path})"
table.field_names = [
"Index",
"Name",
"Stiffness",
"Damping",
"Armature",
"Friction",
"Position Limits",
"Velocity Limits",
"Effort Limits",
]
# set alignment of table columns
table.align["Name"] = "l"
# add info on each term
for index, name in enumerate(self.joint_names):
table.add_row([
index,
name,
stiffnesses[index],
dampings[index],
armatures[index],
frictions[index],
position_limits[index],
velocity_limits[index],
effort_limits[index],
])
# convert table to string
carb.log_info(f"Simulation parameters for joints in {self.cfg.prim_path}:\n" + table.get_string())
# read out all tendon parameters from simulation
if self.num_fixed_tendons > 0:
# -- gains
ft_stiffnesses = self.root_physx_view.get_fixed_tendon_stiffnesses()[0].tolist()
ft_dampings = self.root_physx_view.get_fixed_tendon_dampings()[0].tolist()
# -- limits
ft_limit_stiffnesses = self.root_physx_view.get_fixed_tendon_limit_stiffnesses()[0].tolist()
ft_limits = self.root_physx_view.get_fixed_tendon_limits()[0].tolist()
ft_rest_lengths = self.root_physx_view.get_fixed_tendon_rest_lengths()[0].tolist()
ft_offsets = self.root_physx_view.get_fixed_tendon_offsets()[0].tolist()
# create table for term information
tendon_table = PrettyTable(float_format=".3f")
tendon_table.title = f"Simulation Tendon Information (Prim path: {self.cfg.prim_path})"
tendon_table.field_names = [
"Index",
"Stiffness",
"Damping",
"Limit Stiffness",
"Limit",
"Rest Length",
"Offset",
]
# add info on each term
for index in range(self.num_fixed_tendons):
tendon_table.add_row([
index,
ft_stiffnesses[index],
ft_dampings[index],
ft_limit_stiffnesses[index],
ft_limits[index],
ft_rest_lengths[index],
ft_offsets[index],
])
# convert table to string
carb.log_info(f"Simulation parameters for tendons in {self.cfg.prim_path}:\n" + tendon_table.get_string())
| 60,258 |
Python
| 47.015139 | 132 | 0.623204 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab/omni/isaac/lab/assets/articulation/articulation_cfg.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from dataclasses import MISSING
from omni.isaac.lab.actuators import ActuatorBaseCfg
from omni.isaac.lab.utils import configclass
from ..rigid_object import RigidObjectCfg
from .articulation import Articulation
@configclass
class ArticulationCfg(RigidObjectCfg):
"""Configuration parameters for an articulation."""
class_type: type = Articulation
@configclass
class InitialStateCfg(RigidObjectCfg.InitialStateCfg):
"""Initial state of the articulation."""
# root position
joint_pos: dict[str, float] = {".*": 0.0}
"""Joint positions of the joints. Defaults to 0.0 for all joints."""
joint_vel: dict[str, float] = {".*": 0.0}
"""Joint velocities of the joints. Defaults to 0.0 for all joints."""
##
# Initialize configurations.
##
init_state: InitialStateCfg = InitialStateCfg()
"""Initial state of the articulated object. Defaults to identity pose with zero velocity and zero joint state."""
soft_joint_pos_limit_factor: float = 1.0
"""Fraction specifying the range of DOF position limits (parsed from the asset) to use.
Defaults to 1.0."""
actuators: dict[str, ActuatorBaseCfg] = MISSING
"""Actuators for the robot with corresponding joint names."""
| 1,391 |
Python
| 32.142856 | 117 | 0.701653 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab/omni/isaac/lab/markers/visualization_markers.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""A class to coordinate groups of visual markers (such as spheres, frames or arrows)
using `UsdGeom.PointInstancer`_ class.
The class :class:`VisualizationMarkers` is used to create a group of visual markers and
visualize them in the viewport. The markers are represented as :class:`UsdGeom.PointInstancer` prims
in the USD stage. The markers are created as prototypes in the :class:`UsdGeom.PointInstancer` prim
and are instanced in the :class:`UsdGeom.PointInstancer` prim. The markers can be visualized by
passing the indices of the marker prototypes and their translations, orientations and scales.
The marker prototypes can be configured with the :class:`VisualizationMarkersCfg` class.
.. _UsdGeom.PointInstancer: https://graphics.pixar.com/usd/dev/api/class_usd_geom_point_instancer.html
"""
# needed to import for allowing type-hinting: np.ndarray | torch.Tensor | None
from __future__ import annotations
import numpy as np
import torch
from dataclasses import MISSING
import omni.isaac.core.utils.stage as stage_utils
import omni.kit.commands
import omni.physx.scripts.utils as physx_utils
from pxr import Gf, PhysxSchema, Sdf, Usd, UsdGeom, UsdPhysics, Vt
import omni.isaac.lab.sim as sim_utils
from omni.isaac.lab.sim.spawners import SpawnerCfg
from omni.isaac.lab.utils.configclass import configclass
from omni.isaac.lab.utils.math import convert_quat
@configclass
class VisualizationMarkersCfg:
"""A class to configure a :class:`VisualizationMarkers`."""
prim_path: str = MISSING
"""The prim path where the :class:`UsdGeom.PointInstancer` will be created."""
markers: dict[str, SpawnerCfg] = MISSING
"""The dictionary of marker configurations.
The key is the name of the marker, and the value is the configuration of the marker.
The key is used to identify the marker in the class.
"""
class VisualizationMarkers:
"""A class to coordinate groups of visual markers (loaded from USD).
This class allows visualization of different UI markers in the scene, such as points and frames.
The class wraps around the `UsdGeom.PointInstancer`_ for efficient handling of objects
in the stage via instancing the created marker prototype prims.
A marker prototype prim is a reusable template prim used for defining variations of objects
in the scene. For example, a sphere prim can be used as a marker prototype prim to create
multiple sphere prims in the scene at different locations. Thus, prototype prims are useful
for creating multiple instances of the same prim in the scene.
The class parses the configuration to create different the marker prototypes into the stage. Each marker
prototype prim is created as a child of the :class:`UsdGeom.PointInstancer` prim. The prim path for the
the marker prim is resolved using the key of the marker in the :attr:`VisualizationMarkersCfg.markers`
dictionary. The marker prototypes are created using the :meth:`omni.isaac.core.utils.create_prim`
function, and then then instanced using :class:`UsdGeom.PointInstancer` prim to allow creating multiple
instances of the marker prims.
Switching between different marker prototypes is possible by calling the :meth:`visualize` method with
the prototype indices corresponding to the marker prototype. The prototype indices are based on the order
in the :attr:`VisualizationMarkersCfg.markers` dictionary. For example, if the dictionary has two markers,
"marker1" and "marker2", then their prototype indices are 0 and 1 respectively. The prototype indices
can be passed as a list or array of integers.
Usage:
The following snippet shows how to create 24 sphere markers with a radius of 1.0 at random translations
within the range [-1.0, 1.0]. The first 12 markers will be colored red and the rest will be colored green.
.. code-block:: python
import omni.isaac.lab.sim as sim_utils
from omni.isaac.lab.markers import VisualizationMarkersCfg, VisualizationMarkers
# Create the markers configuration
# This creates two marker prototypes, "marker1" and "marker2" which are spheres with a radius of 1.0.
# The color of "marker1" is red and the color of "marker2" is green.
cfg = VisualizationMarkersCfg(
prim_path="/World/Visuals/testMarkers",
markers={
"marker1": sim_utils.SphereCfg(
radius=1.0,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)),
),
"marker2": VisualizationMarkersCfg.SphereCfg(
radius=1.0,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)),
),
}
)
# Create the markers instance
# This will create a UsdGeom.PointInstancer prim at the given path along with the marker prototypes.
marker = VisualizationMarkers(cfg)
# Set position of the marker
# -- randomly sample translations between -1.0 and 1.0
marker_translations = np.random.uniform(-1.0, 1.0, (24, 3))
# -- this will create 24 markers at the given translations
# note: the markers will all be `marker1` since the marker indices are not given
marker.visualize(translations=marker_translations)
# alter the markers based on their prototypes indices
# first 12 markers will be marker1 and the rest will be marker2
# 0 -> marker1, 1 -> marker2
marker_indices = [0] * 12 + [1] * 12
# this will change the marker prototypes at the given indices
# note: the translations of the markers will not be changed from the previous call
# since the translations are not given.
marker.visualize(marker_indices=marker_indices)
# alter the markers based on their prototypes indices and translations
marker.visualize(marker_indices=marker_indices, translations=marker_translations)
.. _UsdGeom.PointInstancer: https://graphics.pixar.com/usd/dev/api/class_usd_geom_point_instancer.html
"""
def __init__(self, cfg: VisualizationMarkersCfg):
"""Initialize the class.
When the class is initialized, the :class:`UsdGeom.PointInstancer` is created into the stage
and the marker prims are registered into it.
.. note::
If a prim already exists at the given path, the function will find the next free path
and create the :class:`UsdGeom.PointInstancer` prim there.
Args:
cfg: The configuration for the markers.
Raises:
ValueError: When no markers are provided in the :obj:`cfg`.
"""
# get next free path for the prim
prim_path = stage_utils.get_next_free_path(cfg.prim_path)
# create a new prim
stage = stage_utils.get_current_stage()
self._instancer_manager = UsdGeom.PointInstancer.Define(stage, prim_path)
# store inputs
self.prim_path = prim_path
self.cfg = cfg
# check if any markers is provided
if len(self.cfg.markers) == 0:
raise ValueError(f"The `cfg.markers` cannot be empty. Received: {self.cfg.markers}")
# create a child prim for the marker
self._add_markers_prototypes(self.cfg.markers)
# Note: We need to do this the first time to initialize the instancer.
# Otherwise, the instancer will not be "created" and the function `GetInstanceIndices()` will fail.
self._instancer_manager.GetProtoIndicesAttr().Set(list(range(self.num_prototypes)))
self._instancer_manager.GetPositionsAttr().Set([Gf.Vec3f(0.0)] * self.num_prototypes)
self._count = self.num_prototypes
def __str__(self) -> str:
"""Return: A string representation of the class."""
msg = f"VisualizationMarkers(prim_path={self.prim_path})"
msg += f"\n\tCount: {self.count}"
msg += f"\n\tNumber of prototypes: {self.num_prototypes}"
msg += "\n\tMarkers Prototypes:"
for index, (name, marker) in enumerate(self.cfg.markers.items()):
msg += f"\n\t\t[Index: {index}]: {name}: {marker.to_dict()}"
return msg
"""
Properties.
"""
@property
def num_prototypes(self) -> int:
"""The number of marker prototypes available."""
return len(self.cfg.markers)
@property
def count(self) -> int:
"""The total number of marker instances."""
# TODO: Update this when the USD API is available (Isaac Sim 2023.1)
# return self._instancer_manager.GetInstanceCount()
return self._count
"""
Operations.
"""
def set_visibility(self, visible: bool):
"""Sets the visibility of the markers.
The method does this through the USD API.
Args:
visible: flag to set the visibility.
"""
imageable = UsdGeom.Imageable(self._instancer_manager)
if visible:
imageable.MakeVisible()
else:
imageable.MakeInvisible()
def is_visible(self) -> bool:
"""Checks the visibility of the markers.
Returns:
True if the markers are visible, False otherwise.
"""
return self._instancer_manager.GetVisibilityAttr().Get() != UsdGeom.Tokens.invisible
def visualize(
self,
translations: np.ndarray | torch.Tensor | None = None,
orientations: np.ndarray | torch.Tensor | None = None,
scales: np.ndarray | torch.Tensor | None = None,
marker_indices: list[int] | np.ndarray | torch.Tensor | None = None,
):
"""Update markers in the viewport.
.. note::
If the prim `PointInstancer` is hidden in the stage, the function will simply return
without updating the markers. This helps in unnecessary computation when the markers
are not visible.
Whenever updating the markers, the input arrays must have the same number of elements
in the first dimension. If the number of elements is different, the `UsdGeom.PointInstancer`
will raise an error complaining about the mismatch.
Additionally, the function supports dynamic update of the markers. This means that the
number of markers can change between calls. For example, if you have 24 points that you
want to visualize, you can pass 24 translations, orientations, and scales. If you want to
visualize only 12 points, you can pass 12 translations, orientations, and scales. The
function will automatically update the number of markers in the scene.
The function will also update the marker prototypes based on their prototype indices. For instance,
if you have two marker prototypes, and you pass the following marker indices: [0, 1, 0, 1], the function
will update the first and third markers with the first prototype, and the second and fourth markers
with the second prototype. This is useful when you want to visualize different markers in the same
scene. The list of marker indices must have the same number of elements as the translations, orientations,
or scales. If the number of elements is different, the function will raise an error.
.. caution::
This function will update all the markers instanced from the prototypes. That means
if you have 24 markers, you will need to pass 24 translations, orientations, and scales.
If you want to update only a subset of the markers, you will need to handle the indices
yourself and pass the complete arrays to this function.
Args:
translations: Translations w.r.t. parent prim frame. Shape is (M, 3).
Defaults to None, which means left unchanged.
orientations: Quaternion orientations (w, x, y, z) w.r.t. parent prim frame. Shape is (M, 4).
Defaults to None, which means left unchanged.
scales: Scale applied before any rotation is applied. Shape is (M, 3).
Defaults to None, which means left unchanged.
marker_indices: Decides which marker prototype to visualize. Shape is (M).
Defaults to None, which means left unchanged provided that the total number of markers
is the same as the previous call. If the number of markers is different, the function
will update the number of markers in the scene.
Raises:
ValueError: When input arrays do not follow the expected shapes.
ValueError: When the function is called with all None arguments.
"""
# check if it is visible (if not then let's not waste time)
if not self.is_visible():
return
# check if we have any markers to visualize
num_markers = 0
# resolve inputs
# -- position
if translations is not None:
if isinstance(translations, torch.Tensor):
translations = translations.detach().cpu().numpy()
# check that shape is correct
if translations.shape[1] != 3 or len(translations.shape) != 2:
raise ValueError(f"Expected `translations` to have shape (M, 3). Received: {translations.shape}.")
# apply translations
self._instancer_manager.GetPositionsAttr().Set(Vt.Vec3fArray.FromNumpy(translations))
# update number of markers
num_markers = translations.shape[0]
# -- orientation
if orientations is not None:
if isinstance(orientations, torch.Tensor):
orientations = orientations.detach().cpu().numpy()
# check that shape is correct
if orientations.shape[1] != 4 or len(orientations.shape) != 2:
raise ValueError(f"Expected `orientations` to have shape (M, 4). Received: {orientations.shape}.")
# roll orientations from (w, x, y, z) to (x, y, z, w)
# internally USD expects (x, y, z, w)
orientations = convert_quat(orientations, to="xyzw")
# apply orientations
self._instancer_manager.GetOrientationsAttr().Set(Vt.QuathArray.FromNumpy(orientations))
# update number of markers
num_markers = orientations.shape[0]
# -- scales
if scales is not None:
if isinstance(scales, torch.Tensor):
scales = scales.detach().cpu().numpy()
# check that shape is correct
if scales.shape[1] != 3 or len(scales.shape) != 2:
raise ValueError(f"Expected `scales` to have shape (M, 3). Received: {scales.shape}.")
# apply scales
self._instancer_manager.GetScalesAttr().Set(Vt.Vec3fArray.FromNumpy(scales))
# update number of markers
num_markers = scales.shape[0]
# -- status
if marker_indices is not None or num_markers != self._count:
# apply marker indices
if marker_indices is not None:
if isinstance(marker_indices, torch.Tensor):
marker_indices = marker_indices.detach().cpu().numpy()
elif isinstance(marker_indices, list):
marker_indices = np.array(marker_indices)
# check that shape is correct
if len(marker_indices.shape) != 1:
raise ValueError(f"Expected `marker_indices` to have shape (M,). Received: {marker_indices.shape}.")
# apply proto indices
self._instancer_manager.GetProtoIndicesAttr().Set(Vt.IntArray.FromNumpy(marker_indices))
# update number of markers
num_markers = marker_indices.shape[0]
else:
# check that number of markers is not zero
if num_markers == 0:
raise ValueError("Number of markers cannot be zero! Hint: The function was called with no inputs?")
# set all markers to be the first prototype
self._instancer_manager.GetProtoIndicesAttr().Set([0] * num_markers)
# set number of markers
self._count = num_markers
"""
Helper functions.
"""
def _add_markers_prototypes(self, markers_cfg: dict[str, sim_utils.SpawnerCfg]):
"""Adds markers prototypes to the scene and sets the markers instancer to use them."""
# add markers based on config
for name, cfg in markers_cfg.items():
# resolve prim path
marker_prim_path = f"{self.prim_path}/{name}"
# create a child prim for the marker
prim = cfg.func(prim_path=marker_prim_path, cfg=cfg)
# make the asset uninstanceable (in case it is)
# point instancer defines its own prototypes so if an asset is already instanced, this doesn't work.
self._process_prototype_prim(prim)
# remove any physics on the markers because they are only for visualization!
physx_utils.removeRigidBodySubtree(prim)
# add child reference to point instancer
self._instancer_manager.GetPrototypesRel().AddTarget(marker_prim_path)
# check that we loaded all the prototypes
prototypes = self._instancer_manager.GetPrototypesRel().GetTargets()
if len(prototypes) != len(markers_cfg):
raise RuntimeError(
f"Failed to load all the prototypes. Expected: {len(markers_cfg)}. Received: {len(prototypes)}."
)
def _process_prototype_prim(self, prim: Usd.Prim):
"""Process a prim and its descendants to make them suitable for defining prototypes.
Point instancer defines its own prototypes so if an asset is already instanced, this doesn't work.
This function checks if the prim at the specified prim path and its descendants are instanced.
If so, it makes the respective prim uninstanceable by disabling instancing on the prim.
Additionally, it makes the prim invisible to secondary rays. This is useful when we do not want
to see the marker prims on camera images.
Args:
prim_path: The prim path to check.
stage: The stage where the prim exists.
Defaults to None, in which case the current stage is used.
"""
# check if prim is valid
if not prim.IsValid():
raise ValueError(f"Prim at path '{prim.GetPrimAtPath()}' is not valid.")
# iterate over all prims under prim-path
all_prims = [prim]
while len(all_prims) > 0:
# get current prim
child_prim = all_prims.pop(0)
# check if it is physics body -> if so, remove it
if child_prim.HasAPI(UsdPhysics.ArticulationRootAPI):
child_prim.RemoveAPI(UsdPhysics.ArticulationRootAPI)
child_prim.RemoveAPI(PhysxSchema.PhysxArticulationAPI)
if child_prim.HasAPI(UsdPhysics.RigidBodyAPI):
child_prim.RemoveAPI(UsdPhysics.RigidBodyAPI)
child_prim.RemoveAPI(PhysxSchema.PhysxRigidBodyAPI)
if child_prim.IsA(UsdPhysics.Joint):
child_prim.GetAttribute("physics:jointEnabled").Set(False)
# check if prim is instanced -> if so, make it uninstanceable
if child_prim.IsInstance():
child_prim.SetInstanceable(False)
# check if prim is a mesh -> if so, make it invisible to secondary rays
if child_prim.IsA(UsdGeom.Gprim):
# invisible to secondary rays such as depth images
omni.kit.commands.execute(
"ChangePropertyCommand",
prop_path=Sdf.Path(f"{child_prim.GetPrimPath().pathString}.primvars:invisibleToSecondaryRays"),
value=True,
prev=None,
type_to_create_if_not_exist=Sdf.ValueTypeNames.Bool,
)
# add children to list
all_prims += child_prim.GetChildren()
| 20,433 |
Python
| 48.839024 | 120 | 0.646895 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab/omni/isaac/lab/markers/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Sub-package for marker utilities to simplify creation of UI elements in the GUI.
Currently, the sub-package provides the following classes:
* :class:`VisualizationMarkers` for creating a group of markers using `UsdGeom.PointInstancer
<https://graphics.pixar.com/usd/dev/api/class_usd_geom_point_instancer.html>`_.
.. note::
For some simple use-cases, it may be sufficient to use the debug drawing utilities from Isaac Sim.
The debug drawing API is available in the `omni.isaac.debug_drawing`_ module. It allows drawing of
points and splines efficiently on the UI.
.. _omni.isaac.debug_drawing: https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_debug_drawing.html
"""
from .config import * # noqa: F401, F403
from .visualization_markers import VisualizationMarkers, VisualizationMarkersCfg
| 971 |
Python
| 36.384614 | 127 | 0.762101 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab/omni/isaac/lab/markers/config/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import omni.isaac.lab.sim as sim_utils
from omni.isaac.lab.markers.visualization_markers import VisualizationMarkersCfg
from omni.isaac.lab.utils.assets import ISAAC_NUCLEUS_DIR
##
# Sensors.
##
RAY_CASTER_MARKER_CFG = VisualizationMarkersCfg(
markers={
"hit": sim_utils.SphereCfg(
radius=0.02,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)),
),
},
)
"""Configuration for the ray-caster marker."""
CONTACT_SENSOR_MARKER_CFG = VisualizationMarkersCfg(
markers={
"contact": sim_utils.SphereCfg(
radius=0.02,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)),
),
"no_contact": sim_utils.SphereCfg(
radius=0.02,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)),
visible=False,
),
},
)
"""Configuration for the contact sensor marker."""
##
# Frames.
##
FRAME_MARKER_CFG = VisualizationMarkersCfg(
markers={
"frame": sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/UIElements/frame_prim.usd",
scale=(0.5, 0.5, 0.5),
)
}
)
"""Configuration for the frame marker."""
RED_ARROW_X_MARKER_CFG = VisualizationMarkersCfg(
markers={
"arrow": sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/UIElements/arrow_x.usd",
scale=(1.0, 0.1, 0.1),
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)),
)
}
)
"""Configuration for the red arrow marker (along x-direction)."""
BLUE_ARROW_X_MARKER_CFG = VisualizationMarkersCfg(
markers={
"arrow": sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/UIElements/arrow_x.usd",
scale=(1.0, 0.1, 0.1),
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 0.0, 1.0)),
)
}
)
"""Configuration for the blue arrow marker (along x-direction)."""
GREEN_ARROW_X_MARKER_CFG = VisualizationMarkersCfg(
markers={
"arrow": sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/UIElements/arrow_x.usd",
scale=(1.0, 0.1, 0.1),
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)),
)
}
)
"""Configuration for the green arrow marker (along x-direction)."""
##
# Goals.
##
CUBOID_MARKER_CFG = VisualizationMarkersCfg(
markers={
"cuboid": sim_utils.CuboidCfg(
size=(0.1, 0.1, 0.1),
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)),
),
}
)
"""Configuration for the cuboid marker."""
POSITION_GOAL_MARKER_CFG = VisualizationMarkersCfg(
markers={
"target_far": sim_utils.SphereCfg(
radius=0.01,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(1.0, 0.0, 0.0)),
),
"target_near": sim_utils.SphereCfg(
radius=0.01,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0)),
),
"target_invisible": sim_utils.SphereCfg(
radius=0.01,
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 0.0, 1.0)),
visible=False,
),
}
)
"""Configuration for the end-effector tracking marker."""
| 3,509 |
Python
| 27.536585 | 87 | 0.609005 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab/docs/CHANGELOG.rst
|
Changelog
---------
0.17.11 (2024-05-30)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed :class:`omni.isaac.lab.sensor.ContactSensor` not loading correctly in extension mode.
Earlier, the :attr:`omni.isaac.lab.sensor.ContactSensor.body_physx_view` was not initialized when
:meth:`omni.isaac.lab.sensor.ContactSensor._debug_vis_callback` is called which references it.
0.17.10 (2024-05-30)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed compound classes being directly assigned in ``default_factory`` generator method
:meth:`omni.isaac.lab.utils.configclass._return_f`, which resulted in shared references such that modifications to
compound objects were reflected across all instances generated from the same ``default_factory`` method.
0.17.9 (2024-05-30)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added ``variants`` attribute to the :class:`omni.isaac.lab.sim.from_files.UsdFileCfg` class to select USD
variants when loading assets from USD files.
0.17.8 (2024-05-28)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Implemented the reset methods in the action terms to avoid returning outdated data.
0.17.7 (2024-05-28)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added debug visualization utilities in the :class:`omni.isaac.lab.managers.ActionManager` class.
0.17.6 (2024-05-27)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added ``wp.init()`` call in Warp utils.
0.17.5 (2024-05-22)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Websocket livestreaming is no longer supported. Valid livestream options are {0, 1, 2}.
* WebRTC livestream is now set with livestream=2.
0.17.4 (2024-05-17)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Modified the noise functions to also support add, scale, and abs operations on the data. Added aliases
to ensure backward compatibility with the previous functions.
* Added :attr:`omni.isaac.lab.utils.noise.NoiseCfg.operation` for the different operations.
* Renamed ``constant_bias_noise`` to :func:`omni.isaac.lab.utils.noise.constant_noise`.
* Renamed ``additive_uniform_noise`` to :func:`omni.isaac.lab.utils.noise.uniform_noise`.
* Renamed ``additive_gaussian_noise`` to :func:`omni.isaac.lab.utils.noise.gaussian_noise`.
0.17.3 (2024-05-15)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Set ``hide_ui`` flag in the app launcher for livestream.
* Fix native client livestream extensions.
0.17.2 (2024-05-09)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Renamed ``_range`` to ``distribution_params`` in ``events.py`` for methods that defined a distribution.
* Apply additive/scaling randomization noise on default data instead of current data.
* Changed material bucketing logic to prevent exceeding 64k materials.
Fixed
^^^^^
* Fixed broadcasting issues with indexing when environment and joint IDs are provided.
* Fixed incorrect tensor dimensions when setting a subset of environments.
Added
^^^^^
* Added support for randomization of fixed tendon parameters.
* Added support for randomization of dof limits.
* Added support for randomization of gravity.
* Added support for Gaussian sampling.
* Added default buffers to Articulation/Rigid object data classes for randomization.
0.17.1 (2024-05-10)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added attribute :attr:`omni.isaac.lab.sim.converters.UrdfConverterCfg.override_joint_dynamics` to properly parse
joint dynamics in :class:`omni.isaac.lab.sim.converters.UrdfConverter`.
0.17.0 (2024-05-07)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Renamed ``BaseEnv`` to :class:`omni.isaac.lab.envs.ManagerBasedEnv`.
* Renamed ``base_env.py`` to ``manager_based_env.py``.
* Renamed ``BaseEnvCfg`` to :class:`omni.isaac.lab.envs.ManagerBasedEnvCfg`.
* Renamed ``RLTaskEnv`` to :class:`omni.isaac.lab.envs.ManagerBasedRLEnv`.
* Renamed ``rl_task_env.py`` to ``manager_based_rl_env.py``.
* Renamed ``RLTaskEnvCfg`` to :class:`omni.isaac.lab.envs.ManagerBasedRLEnvCfg`.
* Renamed ``rl_task_env_cfg.py`` to ``rl_env_cfg.py``.
* Renamed ``OIGEEnv`` to :class:`omni.isaac.lab.envs.DirectRLEnv`.
* Renamed ``oige_env.py`` to ``direct_rl_env.py``.
* Renamed ``RLTaskEnvWindow`` to :class:`omni.isaac.lab.envs.ui.ManagerBasedRLEnvWindow`.
* Renamed ``rl_task_env_window.py`` to ``manager_based_rl_env_window.py``.
* Renamed all references of ``BaseEnv``, ``BaseEnvCfg``, ``RLTaskEnv``, ``RLTaskEnvCfg``, ``OIGEEnv``, and ``RLTaskEnvWindow``.
Added
^^^^^
* Added direct workflow base class :class:`omni.isaac.lab.envs.DirectRLEnv`.
0.16.4 (2024-05-06)
~~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Added :class:`omni.isaac.lab.sensors.TiledCamera` to support tiled rendering with RGB and depth.
0.16.3 (2024-04-26)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed parsing of filter prim path expressions in the :class:`omni.isaac.lab.sensors.ContactSensor` class.
Earlier, the filter prim paths given to the physics view was not being parsed since they were specified as
regex expressions instead of glob expressions.
0.16.2 (2024-04-25)
~~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Simplified the installation procedure, isaaclab -e is no longer needed
* Updated torch dependency to 2.2.2
0.16.1 (2024-04-20)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added attribute :attr:`omni.isaac.lab.sim.ArticulationRootPropertiesCfg.fix_root_link` to fix the root link
of an articulation to the world frame.
0.16.0 (2024-04-16)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the function :meth:`omni.isaac.lab.utils.math.quat_unique` to standardize quaternion representations,
i.e. always have a non-negative real part.
* Added events terms for randomizing mass by scale, simulation joint properties (stiffness, damping, armature,
and friction)
Fixed
^^^^^
* Added clamping of joint positions and velocities in event terms for resetting joints. The simulation does not
throw an error if the set values are out of their range. Hence, users are expected to clamp them before setting.
* Fixed :class:`omni.isaac.lab.envs.mdp.EMAJointPositionToLimitsActionCfg` to smoothen the actions
at environment frequency instead of simulation frequency.
* Renamed the following functions in :meth:`omni.isaac.lab.envs.mdp` to avoid confusions:
* Observation: :meth:`joint_pos_norm` -> :meth:`joint_pos_limit_normalized`
* Action: :class:`ExponentialMovingAverageJointPositionAction` -> :class:`EMAJointPositionToLimitsAction`
* Termination: :meth:`base_height` -> :meth:`root_height_below_minimum`
* Termination: :meth:`joint_pos_limit` -> :meth:`joint_pos_out_of_limit`
* Termination: :meth:`joint_pos_manual_limit` -> :meth:`joint_pos_out_of_manual_limit`
* Termination: :meth:`joint_vel_limit` -> :meth:`joint_vel_out_of_limit`
* Termination: :meth:`joint_vel_manual_limit` -> :meth:`joint_vel_out_of_manual_limit`
* Termination: :meth:`joint_torque_limit` -> :meth:`joint_effort_out_of_limit`
Deprecated
^^^^^^^^^^
* Deprecated the function :meth:`omni.isaac.lab.envs.mdp.add_body_mass` in favor of
:meth:`omni.isaac.lab.envs.mdp.randomize_rigid_body_mass`. This supports randomizing the mass based on different
operations (add, scale, or set) and sampling distributions.
0.15.13 (2024-04-16)
~~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Improved startup performance by enabling rendering-based extensions only when necessary and caching of nucleus directory.
* Renamed the flag ``OFFSCREEN_RENDER`` or ``--offscreen_render`` to ``ENABLE_CAMERAS`` or ``--enable_cameras`` respectively.
0.15.12 (2024-04-16)
~~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Replaced calls to the ``check_file_path`` function in the :mod:`omni.isaac.lab.sim.spawners.from_files`
with the USD stage resolve identifier function. This helps speed up the loading of assets from file paths
by avoiding Nucleus server calls.
0.15.11 (2024-04-15)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :meth:`omni.isaac.lab.sim.SimulationContext.has_rtx_sensors` method to check if any
RTX-related sensors such as cameras have been created in the simulation. This is useful to determine
if simulation requires RTX rendering during step or not.
Fixed
^^^^^
* Fixed the rendering of RTX-related sensors such as cameras inside the :class:`omni.isaac.lab.envs.RLTaskEnv` class.
Earlier the rendering did not happen inside the step function, which caused the sensor data to be empty.
0.15.10 (2024-04-11)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed sharing of the same memory address between returned tensors from observation terms
in the :class:`omni.isaac.lab.managers.ObservationManager` class. Earlier, the returned
tensors could map to the same memory address, causing issues when the tensors were modified
during scaling, clipping or other operations.
0.15.9 (2024-04-04)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed assignment of individual termination terms inside the :class:`omni.isaac.lab.managers.TerminationManager`
class. Earlier, the terms were being assigned their values through an OR operation which resulted in incorrect
values. This regression was introduced in version 0.15.1.
0.15.8 (2024-04-02)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added option to define ordering of points for the mesh-grid generation in the
:func:`omni.isaac.lab.sensors.ray_caster.patterns.grid_pattern`. This parameter defaults to 'xy'
for backward compatibility.
0.15.7 (2024-03-28)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Adds option to return indices/data in the specified query keys order in
:class:`omni.isaac.lab.managers.SceneEntityCfg` class, and the respective
:func:`omni.isaac.lab.utils.string.resolve_matching_names_values` and
:func:`omni.isaac.lab.utils.string.resolve_matching_names` functions.
0.15.6 (2024-03-28)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Extended the :class:`omni.isaac.lab.app.AppLauncher` class to support the loading of experience files
from the command line. This allows users to load a specific experience file when running the application
(such as for multi-camera rendering or headless mode).
Changed
^^^^^^^
* Changed default loading of experience files in the :class:`omni.isaac.lab.app.AppLauncher` class from the ones
provided by Isaac Sim to the ones provided in Isaac Lab's ``source/apps`` directory.
0.15.5 (2024-03-23)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the env origins in :meth:`_compute_env_origins_grid` of :class:`omni.isaac.lab.terrain.TerrainImporter`
to match that obtained from the Isaac Sim :class:`omni.isaac.cloner.GridCloner` class.
Added
^^^^^
* Added unit test to ensure consistency between environment origins generated by IsaacSim's Grid Cloner and those
produced by the TerrainImporter.
0.15.4 (2024-03-22)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :class:`omni.isaac.lab.envs.mdp.actions.NonHolonomicActionCfg` class to use
the correct variable when applying actions.
0.15.3 (2024-03-21)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added unit test to check that :class:`omni.isaac.lab.scene.InteractiveScene` entity data is not shared between separate instances.
Fixed
^^^^^
* Moved class variables in :class:`omni.isaac.lab.scene.InteractiveScene` to correctly be assigned as
instance variables.
* Removed custom ``__del__`` magic method from :class:`omni.isaac.lab.scene.InteractiveScene`.
0.15.2 (2024-03-21)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added resolving of relative paths for the main asset USD file when using the
:class:`omni.isaac.lab.sim.converters.UrdfConverter` class. This is to ensure that the material paths are
resolved correctly when the main asset file is moved to a different location.
0.15.1 (2024-03-19)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the imitation learning workflow example script, updating Isaac Lab and Robomimic API calls.
* Removed the resetting of :attr:`_term_dones` in the :meth:`omni.isaac.lab.managers.TerminationManager.reset`.
Previously, the environment cleared out all the terms. However, it impaired reading the specific term's values externally.
0.15.0 (2024-03-17)
~~~~~~~~~~~~~~~~~~~
Deprecated
^^^^^^^^^^
* Renamed :class:`omni.isaac.lab.managers.RandomizationManager` to :class:`omni.isaac.lab.managers.EventManager`
class for clarification as the manager takes care of events such as reset in addition to pure randomizations.
* Renamed :class:`omni.isaac.lab.managers.RandomizationTermCfg` to :class:`omni.isaac.lab.managers.EventTermCfg`
for consistency with the class name change.
0.14.1 (2024-03-16)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added simulation schemas for joint drive and fixed tendons. These can be configured for assets imported
from file formats.
* Added logging of tendon properties to the articulation class (if they are present in the USD prim).
0.14.0 (2024-03-15)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the ordering of body names used in the :class:`omni.isaac.lab.assets.Articulation` class. Earlier,
the body names were not following the same ordering as the bodies in the articulation. This led
to issues when using the body names to access data related to the links from the articulation view
(such as Jacobians, mass matrices, etc.).
Removed
^^^^^^^
* Removed the attribute :attr:`body_physx_view` from the :class:`omni.isaac.lab.assets.RigidObject`
and :class:`omni.isaac.lab.assets.Articulation` classes. These were causing confusions when used
with articulation view since the body names were not following the same ordering.
0.13.1 (2024-03-14)
~~~~~~~~~~~~~~~~~~~
Removed
^^^^^^^
* Removed the :mod:`omni.isaac.lab.compat` module. This module was used to provide compatibility
with older versions of Isaac Sim. It is no longer needed since we have most of the functionality
absorbed into the main classes.
0.13.0 (2024-03-12)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added support for the following data types inside the :class:`omni.isaac.lab.sensors.Camera` class:
``instance_segmentation_fast`` and ``instance_id_segmentation_fast``. These are GPU-supported annotations
and are faster than the regular annotations.
Fixed
^^^^^
* Fixed handling of semantic filtering inside the :class:`omni.isaac.lab.sensors.Camera` class. Earlier,
the annotator was given ``semanticTypes`` as an argument. However, with Isaac Sim 2023.1, the annotator
does not accept this argument. Instead the mapping needs to be set to the synthetic data interface directly.
* Fixed the return shape of colored images for segmentation data types inside the
:class:`omni.isaac.lab.sensors.Camera` class. Earlier, the images were always returned as ``int32``. Now,
they are casted to ``uint8`` 4-channel array before returning if colorization is enabled for the annotation type.
Removed
^^^^^^^
* Dropped support for ``instance_segmentation`` and ``instance_id_segmentation`` annotations in the
:class:`omni.isaac.lab.sensors.Camera` class. Their "fast" counterparts should be used instead.
* Renamed the argument :attr:`omni.isaac.lab.sensors.CameraCfg.semantic_types` to
:attr:`omni.isaac.lab.sensors.CameraCfg.semantic_filter`. This is more aligned with Replicator's terminology
for semantic filter predicates.
* Replaced the argument :attr:`omni.isaac.lab.sensors.CameraCfg.colorize` with separate colorized
arguments for each annotation type (:attr:`~omni.isaac.lab.sensors.CameraCfg.colorize_instance_segmentation`,
:attr:`~omni.isaac.lab.sensors.CameraCfg.colorize_instance_id_segmentation`, and
:attr:`~omni.isaac.lab.sensors.CameraCfg.colorize_semantic_segmentation`).
0.12.4 (2024-03-11)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Adapted randomization terms to deal with ``slice`` for the body indices. Earlier, the terms were not
able to handle the slice object and were throwing an error.
* Added ``slice`` type-hinting to all body and joint related methods in the rigid body and articulation
classes. This is to make it clear that the methods can handle both list of indices and slices.
0.12.3 (2024-03-11)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added signal handler to the :class:`omni.isaac.lab.app.AppLauncher` class to catch the ``SIGINT`` signal
and close the application gracefully. This is to prevent the application from crashing when the user
presses ``Ctrl+C`` to close the application.
0.12.2 (2024-03-10)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added observation terms for states of a rigid object in world frame.
* Added randomization terms to set root state with randomized orientation and joint state within user-specified limits.
* Added reward term for penalizing specific termination terms.
Fixed
^^^^^
* Improved sampling of states inside randomization terms. Earlier, the code did multiple torch calls
for sampling different components of the vector. Now, it uses a single call to sample the entire vector.
0.12.1 (2024-03-09)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added an option to the last actions observation term to get a specific term by name from the action manager.
If None, the behavior remains the same as before (the entire action is returned).
0.12.0 (2024-03-08)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added functionality to sample flat patches on a generated terrain. This can be configured using
:attr:`omni.isaac.lab.terrains.SubTerrainBaseCfg.flat_patch_sampling` attribute.
* Added a randomization function for setting terrain-aware root state. Through this, an asset can be
reset to a randomly sampled flat patches.
Fixed
^^^^^
* Separated normal and terrain-base position commands. The terrain based commands rely on the
terrain to sample flat patches for setting the target position.
* Fixed command resample termination function.
Changed
^^^^^^^
* Added the attribute :attr:`omni.isaac.lab.envs.mdp.commands.UniformVelocityCommandCfg.heading_control_stiffness`
to control the stiffness of the heading control term in the velocity command term. Earlier, this was
hard-coded to 0.5 inside the term.
Removed
^^^^^^^
* Removed the function :meth:`sample_new_targets` in the terrain importer. Instead the attribute
:attr:`omni.isaac.lab.terrains.TerrainImporter.flat_patches` should be used to sample new targets.
0.11.3 (2024-03-04)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Corrects the functions :func:`omni.isaac.lab.utils.math.axis_angle_from_quat` and :func:`omni.isaac.lab.utils.math.quat_error_magnitude`
to accept tensors of the form (..., 4) instead of (N, 4). This brings us in line with our documentation and also upgrades one of our functions
to handle higher dimensions.
0.11.2 (2024-03-04)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added checks for default joint position and joint velocity in the articulation class. This is to prevent
users from configuring values for these quantities that might be outside the valid range from the simulation.
0.11.1 (2024-02-29)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Replaced the default values for ``joint_ids`` and ``body_ids`` from ``None`` to ``slice(None)``
in the :class:`omni.isaac.lab.managers.SceneEntityCfg`.
* Adapted rewards and observations terms so that the users can query a subset of joints and bodies.
0.11.0 (2024-02-27)
~~~~~~~~~~~~~~~~~~~
Removed
^^^^^^^
* Dropped support for Isaac Sim<=2022.2. As part of this, removed the components of :class:`omni.isaac.lab.app.AppLauncher`
which handled ROS extension loading. We no longer need them in Isaac Sim>=2023.1 to control the load order to avoid crashes.
* Upgraded Dockerfile to use ISAACSIM_VERSION=2023.1.1 by default.
0.10.28 (2024-02-29)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Implemented relative and moving average joint position action terms. These allow the user to specify
the target joint positions as relative to the current joint positions or as a moving average of the
joint positions over a window of time.
0.10.27 (2024-02-28)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added UI feature to start and stop animation recording in the stage when running an environment.
To enable this feature, please pass the argument ``--disable_fabric`` to the environment script to allow
USD read/write operations. Be aware that this will slow down the simulation.
0.10.26 (2024-02-26)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added a viewport camera controller class to the :class:`omni.isaac.lab.envs.BaseEnv`. This is useful
for applications where the user wants to render the viewport from different perspectives even when the
simulation is running in headless mode.
0.10.25 (2024-02-26)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Ensures that all path arguments in :mod:`omni.isaac.lab.sim.utils` are cast to ``str``. Previously,
we had handled path types as strings without casting.
0.10.24 (2024-02-26)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added tracking of contact time in the :class:`omni.isaac.lab.sensors.ContactSensor` class. Previously,
only the air time was being tracked.
* Added contact force threshold, :attr:`omni.isaac.lab.sensors.ContactSensorCfg.force_threshold`, to detect
when the contact sensor is in contact. Previously, this was set to hard-coded 1.0 in the sensor class.
0.10.23 (2024-02-21)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixes the order of size arguments in :meth:`omni.isaac.lab.terrains.height_field.random_uniform_terrain`. Previously, the function would crash if the size along x and y were not the same.
0.10.22 (2024-02-14)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed "divide by zero" bug in :class:`~omni.isaac.lab.sim.SimulationContext` when setting gravity vector.
Now, it is correctly disabled when the gravity vector is set to zero.
0.10.21 (2024-02-12)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the printing of articulation joint information when the articulation has only one joint.
Earlier, the function was performing a squeeze operation on the tensor, which caused an error when
trying to index the tensor of shape (1,).
0.10.20 (2024-02-12)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Adds :attr:`omni.isaac.lab.sim.PhysxCfg.enable_enhanced_determinism` to enable improved
determinism from PhysX. Please note this comes at the expense of performance.
0.10.19 (2024-02-08)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed environment closing so that articulations, objects, and sensors are cleared properly.
0.10.18 (2024-02-05)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Pinned :mod:`torch` version to 2.0.1 in the setup.py to keep parity version of :mod:`torch` supplied by
Isaac 2023.1.1, and prevent version incompatibility between :mod:`torch` ==2.2 and
:mod:`typing-extensions` ==3.7.4.3
0.10.17 (2024-02-02)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^^
* Fixed carb setting ``/app/livestream/enabled`` to be set as False unless live-streaming is specified
by :class:`omni.isaac.lab.app.AppLauncher` settings. This fixes the logic of :meth:`SimulationContext.render`,
which depended on the config in previous versions of Isaac defaulting to false for this setting.
0.10.16 (2024-01-29)
~~~~~~~~~~~~~~~~~~~~
Added
^^^^^^
* Added an offset parameter to the height scan observation term. This allows the user to specify the
height offset of the scan from the tracked body. Previously it was hard-coded to be 0.5.
0.10.15 (2024-01-29)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed joint torque computation for implicit actuators. Earlier, the torque was always zero for implicit
actuators. Now, it is computed approximately by applying the PD law.
0.10.14 (2024-01-22)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the tensor shape of :attr:`omni.isaac.lab.sensors.ContactSensorData.force_matrix_w`. Earlier, the reshaping
led to a mismatch with the data obtained from PhysX.
0.10.13 (2024-01-15)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed running of environments with a single instance even if the :attr:`replicate_physics`` flag is set to True.
0.10.12 (2024-01-10)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed indexing of source and target frames in the :class:`omni.isaac.lab.sensors.FrameTransformer` class.
Earlier, it always assumed that the source frame body is at index 0. Now, it uses the body index of the
source frame to compute the transformation.
Deprecated
^^^^^^^^^^
* Renamed quantities in the :class:`omni.isaac.lab.sensors.FrameTransformerData` class to be more
consistent with the terminology used in the asset classes. The following quantities are deprecated:
* ``target_rot_w`` -> ``target_quat_w``
* ``source_rot_w`` -> ``source_quat_w``
* ``target_rot_source`` -> ``target_quat_source``
0.10.11 (2024-01-08)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed attribute error raised when calling the :class:`omni.isaac.lab.envs.mdp.TerrainBasedPositionCommand`
command term.
* Added a dummy function in :class:`omni.isaac.lab.terrain.TerrainImporter` that returns environment
origins as terrain-aware sampled targets. This function should be implemented by child classes based on
the terrain type.
0.10.10 (2023-12-21)
~~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed reliance on non-existent ``Viewport`` in :class:`omni.isaac.lab.sim.SimulationContext` when loading livestreaming
by ensuring that the extension ``omni.kit.viewport.window`` is enabled in :class:`omni.isaac.lab.app.AppLauncher` when
livestreaming is enabled
0.10.9 (2023-12-21)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed invalidation of physics views inside the asset and sensor classes. Earlier, they were left initialized
even when the simulation was stopped. This caused issues when closing the application.
0.10.8 (2023-12-20)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :class:`omni.isaac.lab.envs.mdp.actions.DifferentialInverseKinematicsAction` class
to account for the offset pose of the end-effector.
0.10.7 (2023-12-19)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added a check to ray-cast and camera sensor classes to ensure that the sensor prim path does not
have a regex expression at its leaf. For instance, ``/World/Robot/camera_.*`` is not supported
for these sensor types. This behavior needs to be fixed in the future.
0.10.6 (2023-12-19)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added support for using articulations as visualization markers. This disables all physics APIs from
the articulation and allows the user to use it as a visualization marker. It is useful for creating
visualization markers for the end-effectors or base of the robot.
Fixed
^^^^^
* Fixed hiding of debug markers from secondary images when using the
:class:`omni.isaac.lab.markers.VisualizationMarkers` class. Earlier, the properties were applied on
the XForm prim instead of the Mesh prim.
0.10.5 (2023-12-18)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed test ``check_base_env_anymal_locomotion.py``, which
previously called :func:`torch.jit.load` with the path to a policy (which would work
for a local file), rather than calling
:func:`omni.isaac.lab.utils.assets.read_file` on the path to get the file itself.
0.10.4 (2023-12-14)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed potentially breaking import of omni.kit.widget.toolbar by ensuring that
if live-stream is enabled, then the :mod:`omni.kit.widget.toolbar`
extension is loaded.
0.10.3 (2023-12-12)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the attribute :attr:`omni.isaac.lab.actuators.ActuatorNetMLPCfg.input_order`
to specify the order of the input tensors to the MLP network.
Fixed
^^^^^
* Fixed computation of metrics for the velocity command term. Earlier, the norm was being computed
over the entire batch instead of the last dimension.
* Fixed the clipping inside the :class:`omni.isaac.lab.actuators.DCMotor` class. Earlier, it was
not able to handle the case when configured saturation limit was set to None.
0.10.2 (2023-12-12)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added a check in the simulation stop callback in the :class:`omni.isaac.lab.sim.SimulationContext` class
to not render when an exception is raised. The while loop in the callback was preventing the application
from closing when an exception was raised.
0.10.1 (2023-12-06)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added command manager class with terms defined by :class:`omni.isaac.lab.managers.CommandTerm`. This
allow for multiple types of command generators to be used in the same environment.
0.10.0 (2023-12-04)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Modified the sensor and asset base classes to use the underlying PhysX views instead of Isaac Sim views.
Using Isaac Sim classes led to a very high load time (of the order of minutes) when using a scene with
many assets. This is because Isaac Sim supports USD paths which are slow and not required.
Added
^^^^^
* Added faster implementation of USD stage traversal methods inside the :class:`omni.isaac.lab.sim.utils` module.
* Added properties :attr:`omni.isaac.lab.assets.AssetBase.num_instances` and
:attr:`omni.isaac.lab.sensor.SensorBase.num_instances` to obtain the number of instances of the asset
or sensor in the simulation respectively.
Removed
^^^^^^^
* Removed dependencies on Isaac Sim view classes. It is no longer possible to use :attr:`root_view` and
:attr:`body_view`. Instead use :attr:`root_physx_view` and :attr:`body_physx_view` to access the underlying
PhysX views.
0.9.55 (2023-12-03)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the Nucleus directory path in the :attr:`omni.isaac.lab.utils.assets.NVIDIA_NUCLEUS_DIR`.
Earlier, it was referring to the ``NVIDIA/Assets`` directory instead of ``NVIDIA``.
0.9.54 (2023-11-29)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed pose computation in the :class:`omni.isaac.lab.sensors.Camera` class to obtain them from XFormPrimView
instead of using ``UsdGeomCamera.ComputeLocalToWorldTransform`` method. The latter is not updated correctly
during GPU simulation.
* Fixed initialization of the annotator info in the class :class:`omni.isaac.lab.sensors.Camera`. Previously
all dicts had the same memory address which caused all annotators to have the same info.
* Fixed the conversion of ``uint32`` warp arrays inside the :meth:`omni.isaac.lab.utils.array.convert_to_torch`
method. PyTorch does not support this type, so it is converted to ``int32`` before converting to PyTorch tensor.
* Added render call inside :meth:`omni.isaac.lab.sim.SimulationContext.reset` to initialize Replicator
buffers when the simulation is reset.
0.9.53 (2023-11-29)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Changed the behavior of passing :obj:`None` to the :class:`omni.isaac.lab.actuators.ActuatorBaseCfg`
class. Earlier, they were resolved to fixed default values. Now, they imply that the values are loaded
from the USD joint drive configuration.
Added
^^^^^
* Added setting of joint armature and friction quantities to the articulation class.
0.9.52 (2023-11-29)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Changed the warning print in :meth:`omni.isaac.lab.sim.utils.apply_nested` method
to be more descriptive. Earlier, it was printing a warning for every instanced prim.
Now, it only prints a warning if it could not apply the attribute to any of the prims.
Added
^^^^^
* Added the method :meth:`omni.isaac.lab.utils.assets.retrieve_file_path` to
obtain the absolute path of a file on the Nucleus server or locally.
Fixed
^^^^^
* Fixed hiding of STOP button in the :class:`AppLauncher` class when running the
simulation in headless mode.
* Fixed a bug with :meth:`omni.isaac.lab.sim.utils.clone` failing when the input prim path
had no parent (example: "/Table").
0.9.51 (2023-11-29)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Changed the :meth:`omni.isaac.lab.sensor.SensorBase.update` method to always recompute the buffers if
the sensor is in visualization mode.
Added
^^^^^
* Added available entities to the error message when accessing a non-existent entity in the
:class:`InteractiveScene` class.
* Added a warning message when the user tries to reference an invalid prim in the :class:`FrameTransformer` sensor.
0.9.50 (2023-11-28)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Hid the ``STOP`` button in the UI when running standalone Python scripts. This is to prevent
users from accidentally clicking the button and stopping the simulation. They should only be able to
play and pause the simulation from the UI.
Removed
^^^^^^^
* Removed :attr:`omni.isaac.lab.sim.SimulationCfg.shutdown_app_on_stop`. The simulation is always rendering
if it is stopped from the UI. The user needs to close the window or press ``Ctrl+C`` to close the simulation.
0.9.49 (2023-11-27)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added an interface class, :class:`omni.isaac.lab.managers.ManagerTermBase`, to serve as the parent class
for term implementations that are functional classes.
* Adapted all managers to support terms that are classes and not just functions clearer. This allows the user to
create more complex terms that require additional state information.
0.9.48 (2023-11-24)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed initialization of drift in the :class:`omni.isaac.lab.sensors.RayCasterCamera` class.
0.9.47 (2023-11-24)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Automated identification of the root prim in the :class:`omni.isaac.lab.assets.RigidObject` and
:class:`omni.isaac.lab.assets.Articulation` classes. Earlier, the root prim was hard-coded to
the spawn prim path. Now, the class searches for the root prim under the spawn prim path.
0.9.46 (2023-11-24)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed a critical issue in the asset classes with writing states into physics handles.
Earlier, the states were written over all the indices instead of the indices of the
asset that were being updated. This caused the physics handles to refresh the states
of all the assets in the scene, which is not desirable.
0.9.45 (2023-11-24)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added :class:`omni.isaac.lab.command_generators.UniformPoseCommandGenerator` to generate
poses in the asset's root frame by uniformly sampling from a given range.
0.9.44 (2023-11-16)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added methods :meth:`reset` and :meth:`step` to the :class:`omni.isaac.lab.envs.BaseEnv`. This unifies
the environment interface for simple standalone applications with the class.
0.9.43 (2023-11-16)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Replaced subscription of physics play and stop events in the :class:`omni.isaac.lab.assets.AssetBase` and
:class:`omni.isaac.lab.sensors.SensorBase` classes with subscription to time-line play and stop events.
This is to prevent issues in cases where physics first needs to perform mesh cooking and handles are not
available immediately. For instance, with deformable meshes.
0.9.42 (2023-11-16)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed setting of damping values from the configuration for :class:`ActuatorBase` class. Earlier,
the stiffness values were being set into damping when a dictionary configuration was passed to the
actuator model.
* Added dealing with :class:`int` and :class:`float` values in the configurations of :class:`ActuatorBase`.
Earlier, a type-error was thrown when integer values were passed to the actuator model.
0.9.41 (2023-11-16)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the naming and shaping issues in the binary joint action term.
0.9.40 (2023-11-09)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Simplified the manual initialization of Isaac Sim :class:`ArticulationView` class. Earlier, we basically
copied the code from the Isaac Sim source code. Now, we just call their initialize method.
Changed
^^^^^^^
* Changed the name of attribute :attr:`default_root_state_w` to :attr:`default_root_state`. The latter is
more correct since the data is actually in the local environment frame and not the simulation world frame.
0.9.39 (2023-11-08)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Changed the reference of private ``_body_view`` variable inside the :class:`RigidObject` class
to the public ``body_view`` property. For a rigid object, the private variable is not defined.
0.9.38 (2023-11-07)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Upgraded the :class:`omni.isaac.lab.envs.RLTaskEnv` class to support Gym 0.29.0 environment definition.
Added
^^^^^
* Added computation of ``time_outs`` and ``terminated`` signals inside the termination manager. These follow the
definition mentioned in `Gym 0.29.0 <https://gymnasium.farama.org/tutorials/gymnasium_basics/handling_time_limits/>`_.
* Added proper handling of observation and action spaces in the :class:`omni.isaac.lab.envs.RLTaskEnv` class.
These now follow closely to how Gym VecEnv handles the spaces.
0.9.37 (2023-11-06)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed broken visualization in :mod:`omni.isaac.lab.sensors.FrameTramsformer` class by overwriting the
correct ``_debug_vis_callback`` function.
* Moved the visualization marker configurations of sensors to their respective sensor configuration classes.
This allows users to set these configurations from the configuration object itself.
0.9.36 (2023-11-03)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added explicit deleting of different managers in the :class:`omni.isaac.lab.envs.BaseEnv` and
:class:`omni.isaac.lab.envs.RLTaskEnv` classes. This is required since deleting the managers
is order-sensitive (many managers need to be deleted before the scene is deleted).
0.9.35 (2023-11-02)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the error: ``'str' object has no attribute '__module__'`` introduced by adding the future import inside the
:mod:`omni.isaac.lab.utils.warp.kernels` module. Warp language does not support the ``__future__`` imports.
0.9.34 (2023-11-02)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added missing import of ``from __future__ import annotations`` in the :mod:`omni.isaac.lab.utils.warp`
module. This is needed to have a consistent behavior across Python versions.
0.9.33 (2023-11-02)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :class:`omni.isaac.lab.command_generators.NullCommandGenerator` class. Earlier,
it was having a runtime error due to infinity in the resampling time range. Now, the class just
overrides the parent methods to perform no operations.
0.9.32 (2023-11-02)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Renamed the :class:`omni.isaac.lab.envs.RLEnv` class to :class:`omni.isaac.lab.envs.RLTaskEnv` to
avoid confusions in terminologies between environments and tasks.
0.9.31 (2023-11-02)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :class:`omni.isaac.lab.sensors.RayCasterCamera` class, as a ray-casting based camera for
"distance_to_camera", "distance_to_image_plane" and "normals" annotations. It has the same interface and
functionalities as the USD Camera while it is on average 30% faster.
0.9.30 (2023-11-01)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added skipping of None values in the :class:`InteractiveScene` class when creating the scene from configuration
objects. Earlier, it was throwing an error when the user passed a None value for a scene element.
* Added ``kwargs`` to the :class:`RLEnv` class to allow passing additional arguments from gym registry function.
This is now needed since the registry function passes args beyond the ones specified in the constructor.
0.9.29 (2023-11-01)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the material path resolution inside the :class:`omni.isaac.lab.sim.converters.UrdfConverter` class.
With Isaac Sim 2023.1, the material paths from the importer are always saved as absolute paths. This caused
issues when the generated USD file was moved to a different location. The fix now resolves the material paths
relative to the USD file location.
0.9.28 (2023-11-01)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Changed the way the :func:`omni.isaac.lab.sim.spawners.from_files.spawn_ground_plane` function sets the
height of the ground. Earlier, it was reading the height from the configuration object. Now, it expects the
desired transformation as inputs to the function. This makes it consistent with the other spawner functions.
0.9.27 (2023-10-31)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Removed the default value of the argument ``camel_case`` in setters of USD attributes. This is to avoid
confusion with the naming of the attributes in the USD file.
Fixed
^^^^^
* Fixed the selection of material prim in the :class:`omni.isaac.lab.sim.spawners.materials.spawn_preview_surface`
method. Earlier, the created prim was being selected in the viewport which interfered with the selection of
prims by the user.
* Updated :class:`omni.isaac.lab.sim.converters.MeshConverter` to use a different stage than the default stage
for the conversion. This is to avoid the issue of the stage being closed when the conversion is done.
0.9.26 (2023-10-31)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the sensor implementation for :class:`omni.isaac.lab.sensors.FrameTransformer` class. Currently,
it handles obtaining the transformation between two frames in the same articulation.
0.9.25 (2023-10-27)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :mod:`omni.isaac.lab.envs.ui` module to put all the UI-related classes in one place. This currently
implements the :class:`omni.isaac.lab.envs.ui.BaseEnvWindow` and :class:`omni.isaac.lab.envs.ui.RLEnvWindow`
classes. Users can inherit from these classes to create their own UI windows.
* Added the attribute :attr:`omni.isaac.lab.envs.BaseEnvCfg.ui_window_class_type` to specify the UI window class
to be used for the environment. This allows the user to specify their own UI window class to be used for the
environment.
0.9.24 (2023-10-27)
~~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Changed the behavior of setting up debug visualization for assets, sensors and command generators.
Earlier it was raising an error if debug visualization was not enabled in the configuration object.
Now it checks whether debug visualization is implemented and only sets up the callback if it is
implemented.
0.9.23 (2023-10-27)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed a typo in the :class:`AssetBase` and :class:`SensorBase` that effected the class destructor.
Earlier, a tuple was being created in the constructor instead of the actual object.
0.9.22 (2023-10-26)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added a :class:`omni.isaac.lab.command_generators.NullCommandGenerator` class for no command environments.
This is easier to work with than having checks for :obj:`None` in the command generator.
Fixed
^^^^^
* Moved the randomization manager to the :class:`omni.isaac.lab.envs.BaseEnv` class with the default
settings to reset the scene to the defaults specified in the configurations of assets.
* Moved command generator to the :class:`omni.isaac.lab.envs.RlEnv` class to have all task-specification
related classes in the same place.
0.9.21 (2023-10-26)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Decreased the priority of callbacks in asset and sensor base classes. This may help in preventing
crashes when warm starting the simulation.
* Fixed no rendering mode when running the environment from the GUI. Earlier the function
:meth:`SimulationContext.set_render_mode` was erroring out.
0.9.20 (2023-10-25)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Changed naming in :class:`omni.isaac.lab.sim.SimulationContext.RenderMode` to use ``NO_GUI_OR_RENDERING``
and ``NO_RENDERING`` instead of ``HEADLESS`` for clarity.
* Changed :class:`omni.isaac.lab.sim.SimulationContext` to be capable of handling livestreaming and
offscreen rendering.
* Changed :class:`omni.isaac.lab.app.AppLauncher` envvar ``VIEWPORT_RECORD`` to the more descriptive
``OFFSCREEN_RENDER``.
0.9.19 (2023-10-25)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added Gym observation and action spaces for the :class:`omni.isaac.lab.envs.RLEnv` class.
0.9.18 (2023-10-23)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Created :class:`omni.isaac.lab.sim.converters.asset_converter.AssetConverter` to serve as a base
class for all asset converters.
* Added :class:`omni.isaac.lab.sim.converters.mesh_converter.MeshConverter` to handle loading and conversion
of mesh files (OBJ, STL and FBX) into USD format.
* Added script ``convert_mesh.py`` to ``source/tools`` to allow users to convert a mesh to USD via command line arguments.
Changed
^^^^^^^
* Renamed the submodule :mod:`omni.isaac.lab.sim.loaders` to :mod:`omni.isaac.lab.sim.converters` to be more
general with the functionality of the module.
* Updated ``check_instanceable.py`` script to convert relative paths to absolute paths.
0.9.17 (2023-10-22)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added setters and getters for term configurations in the :class:`RandomizationManager`, :class:`RewardManager`
and :class:`TerminationManager` classes. This allows the user to modify the term configurations after the
manager has been created.
* Added the method :meth:`compute_group` to the :class:`omni.isaac.lab.managers.ObservationManager` class to
compute the observations for only a given group.
* Added the curriculum term for modifying reward weights after certain environment steps.
0.9.16 (2023-10-22)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added support for keyword arguments for terms in the :class:`omni.isaac.lab.managers.ManagerBase`.
Fixed
^^^^^
* Fixed resetting of buffers in the :class:`TerminationManager` class. Earlier, the values were being set
to ``0.0`` instead of ``False``.
0.9.15 (2023-10-22)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added base yaw heading and body acceleration into :class:`omni.isaac.lab.assets.RigidObjectData` class.
These quantities are computed inside the :class:`RigidObject` class.
Fixed
^^^^^
* Fixed the :meth:`omni.isaac.lab.assets.RigidObject.set_external_force_and_torque` method to correctly
deal with the body indices.
* Fixed a bug in the :meth:`omni.isaac.lab.utils.math.wrap_to_pi` method to prevent self-assignment of
the input tensor.
0.9.14 (2023-10-21)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added 2-D drift (i.e. along x and y) to the :class:`omni.isaac.lab.sensors.RayCaster` class.
* Added flags to the :class:`omni.isaac.lab.sensors.ContactSensorCfg` to optionally obtain the
sensor origin and air time information. Since these are not required by default, they are
disabled by default.
Fixed
^^^^^
* Fixed the handling of contact sensor history buffer in the :class:`omni.isaac.lab.sensors.ContactSensor` class.
Earlier, the buffer was not being updated correctly.
0.9.13 (2023-10-20)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the issue with double :obj:`Ellipsis` when indexing tensors with multiple dimensions.
The fix now uses :obj:`slice(None)` instead of :obj:`Ellipsis` to index the tensors.
0.9.12 (2023-10-18)
~~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed bugs in actuator model implementation for actuator nets. Earlier the DC motor clipping was not working.
* Fixed bug in applying actuator model in the :class:`omni.isaac.lab.asset.Articulation` class. The new
implementation caches the outputs from explicit actuator model into the ``joint_pos_*_sim`` buffer to
avoid feedback loops in the tensor operation.
0.9.11 (2023-10-17)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the support for semantic tags into the :class:`omni.isaac.lab.sim.spawner.SpawnerCfg` class. This allows
the user to specify the semantic tags for a prim when spawning it into the scene. It follows the same format as
Omniverse Replicator.
0.9.10 (2023-10-16)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added ``--livestream`` and ``--ros`` CLI args to :class:`omni.isaac.lab.app.AppLauncher` class.
* Added a static function :meth:`omni.isaac.lab.app.AppLauncher.add_app_launcher_args`, which
appends the arguments needed for :class:`omni.isaac.lab.app.AppLauncher` to the argument parser.
Changed
^^^^^^^
* Within :class:`omni.isaac.lab.app.AppLauncher`, removed ``REMOTE_DEPLOYMENT`` env-var processing
in the favor of ``HEADLESS`` and ``LIVESTREAM`` env-vars. These have clearer uses and better parity
with the CLI args.
0.9.9 (2023-10-12)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the property :attr:`omni.isaac.lab.assets.Articulation.is_fixed_base` to the articulation class to
check if the base of the articulation is fixed or floating.
* Added the task-space action term corresponding to the differential inverse-kinematics controller.
Fixed
^^^^^
* Simplified the :class:`omni.isaac.lab.controllers.DifferentialIKController` to assume that user provides the
correct end-effector poses and Jacobians. Earlier it was doing internal frame transformations which made the
code more complicated and error-prone.
0.9.8 (2023-09-30)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the boundedness of class objects that register callbacks into the simulator.
These include devices, :class:`AssetBase`, :class:`SensorBase` and :class:`CommandGenerator`.
The fix ensures that object gets deleted when the user deletes the object.
0.9.7 (2023-09-26)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Modified the :class:`omni.isaac.lab.markers.VisualizationMarkers` to use the
:class:`omni.isaac.lab.sim.spawner.SpawnerCfg` class instead of their
own configuration objects. This makes it consistent with the other ways to spawn assets in the scene.
Added
^^^^^
* Added the method :meth:`copy` to configclass to allow copying of configuration objects.
0.9.6 (2023-09-26)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Changed class-level configuration classes to refer to class types using ``class_type`` attribute instead
of ``cls`` or ``cls_name``.
0.9.5 (2023-09-25)
~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Added future import of ``annotations`` to have a consistent behavior across Python versions.
* Removed the type-hinting from docstrings to simplify maintenance of the documentation. All type-hints are
now in the code itself.
0.9.4 (2023-08-29)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added :class:`omni.isaac.lab.scene.InteractiveScene`, as the central scene unit that contains all entities
that are part of the simulation. These include the terrain, sensors, articulations, rigid objects etc.
The scene groups the common operations of these entities and allows to access them via their unique names.
* Added :mod:`omni.isaac.lab.envs` module that contains environment definitions that encapsulate the different
general (scene, action manager, observation manager) and RL-specific (reward and termination manager) managers.
* Added :class:`omni.isaac.lab.managers.SceneEntityCfg` to handle which scene elements are required by the
manager's terms. This allows the manager to parse useful information from the scene elements, such as the
joint and body indices, and pass them to the term.
* Added :class:`omni.isaac.lab.sim.SimulationContext.RenderMode` to handle different rendering modes based on
what the user wants to update (viewport, cameras, or UI elements).
Fixed
^^^^^
* Fixed the :class:`omni.isaac.lab.command_generators.CommandGeneratorBase` to register a debug visualization
callback similar to how sensors and robots handle visualization.
0.9.3 (2023-08-23)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Enabled the `faulthander <https://docs.python.org/3/library/faulthandler.html>`_ to catch segfaults and print
the stack trace. This is enabled by default in the :class:`omni.isaac.lab.app.AppLauncher` class.
Fixed
^^^^^
* Re-added the :mod:`omni.isaac.lab.utils.kit` to the ``compat`` directory and fixed all the references to it.
* Fixed the deletion of Replicator nodes for the :class:`omni.isaac.lab.sensors.Camera` class. Earlier, the
Replicator nodes were not being deleted when the camera was deleted. However, this does not prevent the random
crashes that happen when the camera is deleted.
* Fixed the :meth:`omni.isaac.lab.utils.math.convert_quat` to support both numpy and torch tensors.
Changed
^^^^^^^
* Renamed all the scripts inside the ``test`` directory to follow the convention:
* ``test_<module_name>.py``: Tests for the module ``<module_name>`` using unittest.
* ``check_<module_name>``: Check for the module ``<module_name>`` using python main function.
0.9.2 (2023-08-22)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the ability to color meshes in the :class:`omni.isaac.lab.terrain.TerrainGenerator` class. Currently,
it only supports coloring the mesh randomly (``"random"``), based on the terrain height (``"height"``), and
no coloring (``"none"``).
Fixed
^^^^^
* Modified the :class:`omni.isaac.lab.terrain.TerrainImporter` class to configure visual and physics materials
based on the configuration object.
0.9.1 (2023-08-18)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Introduced three different rotation conventions in the :class:`omni.isaac.lab.sensors.Camera` class. These
conventions are:
* ``opengl``: the camera is looking down the -Z axis with the +Y axis pointing up
* ``ros``: the camera is looking down the +Z axis with the +Y axis pointing down
* ``world``: the camera is looking along the +X axis with the -Z axis pointing down
These can be used to declare the camera offset in :class:`omni.isaac.lab.sensors.CameraCfg.OffsetCfg` class
and in :meth:`omni.isaac.lab.sensors.Camera.set_world_pose` method. Additionally, all conventions are
saved to :class:`omni.isaac.lab.sensors.CameraData` class for easy access.
Changed
^^^^^^^
* Adapted all the sensor classes to follow a structure similar to the :class:`omni.isaac.lab.assets.AssetBase`.
Hence, the spawning and initialization of sensors manually by the users is avoided.
* Removed the :meth:`debug_vis` function since that this functionality is handled by a render callback automatically
(based on the passed configuration for the :class:`omni.isaac.lab.sensors.SensorBaseCfg.debug_vis` flag).
0.9.0 (2023-08-18)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Introduces a new set of asset interfaces. These interfaces simplify the spawning of assets into the scene
and initializing the physics handle by putting that inside post-startup physics callbacks. With this, users
no longer need to worry about the :meth:`spawn` and :meth:`initialize` calls.
* Added utility methods to :mod:`omni.isaac.lab.utils.string` module that resolve regex expressions based
on passed list of target keys.
Changed
^^^^^^^
* Renamed all references of joints in an articulation from "dof" to "joint". This makes it consistent with the
terminology used in robotics.
Deprecated
^^^^^^^^^^
* Removed the previous modules for objects and robots. Instead the :class:`Articulation` and :class:`RigidObject`
should be used.
0.8.12 (2023-08-18)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added other properties provided by ``PhysicsScene`` to the :class:`omni.isaac.lab.sim.SimulationContext`
class to allow setting CCD, solver iterations, etc.
* Added commonly used functions to the :class:`SimulationContext` class itself to avoid having additional
imports from Isaac Sim when doing simple tasks such as setting camera view or retrieving the simulation settings.
Fixed
^^^^^
* Switched the notations of default buffer values in :class:`omni.isaac.lab.sim.PhysxCfg` from multiplication
to scientific notation to avoid confusion with the values.
0.8.11 (2023-08-18)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Adds utility functions and configuration objects in the :mod:`omni.isaac.lab.sim.spawners`
to create the following prims in the scene:
* :mod:`omni.isaac.lab.sim.spawners.from_file`: Create a prim from a USD/URDF file.
* :mod:`omni.isaac.lab.sim.spawners.shapes`: Create USDGeom prims for shapes (box, sphere, cylinder, capsule, etc.).
* :mod:`omni.isaac.lab.sim.spawners.materials`: Create a visual or physics material prim.
* :mod:`omni.isaac.lab.sim.spawners.lights`: Create a USDLux prim for different types of lights.
* :mod:`omni.isaac.lab.sim.spawners.sensors`: Create a USD prim for supported sensors.
Changed
^^^^^^^
* Modified the :class:`SimulationContext` class to take the default physics material using the material spawn
configuration object.
0.8.10 (2023-08-17)
~~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added methods for defining different physics-based schemas in the :mod:`omni.isaac.lab.sim.schemas` module.
These methods allow creating the schema if it doesn't exist at the specified prim path and modify
its properties based on the configuration object.
0.8.9 (2023-08-09)
~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Moved the :class:`omni.isaac.lab.asset_loader.UrdfLoader` class to the :mod:`omni.isaac.lab.sim.loaders`
module to make it more accessible to the user.
0.8.8 (2023-08-09)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added configuration classes and functions for setting different physics-based schemas in the
:mod:`omni.isaac.lab.sim.schemas` module. These allow modifying properties of the physics solver
on the asset using configuration objects.
0.8.7 (2023-08-03)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added support for `__post_init__ <https://docs.python.org/3/library/dataclasses.html#post-init-processing>`_ in
the :class:`omni.isaac.lab.utils.configclass` decorator.
0.8.6 (2023-08-03)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added support for callable classes in the :class:`omni.isaac.lab.managers.ManagerBase`.
0.8.5 (2023-08-03)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :class:`omni.isaac.lab.markers.Visualizationmarkers` class so that the markers are not visible in camera rendering mode.
Changed
^^^^^^^
* Simplified the creation of the point instancer in the :class:`omni.isaac.lab.markers.Visualizationmarkers` class. It now creates a new
prim at the next available prim path if a prim already exists at the given path.
0.8.4 (2023-08-02)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :class:`omni.isaac.lab.sim.SimulationContext` class to the :mod:`omni.isaac.lab.sim` module.
This class inherits from the :class:`omni.isaac.core.simulation_context.SimulationContext` class and adds
the ability to create a simulation context from a configuration object.
0.8.3 (2023-08-02)
~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Moved the :class:`ActuatorBase` class to the :mod:`omni.isaac.lab.actuators.actuator_base` module.
* Renamed the :mod:`omni.isaac.lab.actuators.actuator` module to :mod:`omni.isaac.lab.actuators.actuator_pd`
to make it more explicit that it contains the PD actuator models.
0.8.2 (2023-08-02)
~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Cleaned up the :class:`omni.isaac.lab.terrain.TerrainImporter` class to take all the parameters from the configuration
object. This makes it consistent with the other classes in the package.
* Moved the configuration classes for terrain generator and terrain importer into separate files to resolve circular
dependency issues.
0.8.1 (2023-08-02)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added a hack into :class:`omni.isaac.lab.app.AppLauncher` class to remove Isaac Lab packages from the path before launching
the simulation application. This prevents the warning messages that appears when the user launches the ``SimulationApp``.
Added
^^^^^
* Enabled necessary viewport extensions in the :class:`omni.isaac.lab.app.AppLauncher` class itself if ``VIEWPORT_ENABLED``
flag is true.
0.8.0 (2023-07-26)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :class:`ActionManager` class to the :mod:`omni.isaac.lab.managers` module to handle actions in the
environment through action terms.
* Added contact force history to the :class:`omni.isaac.lab.sensors.ContactSensor` class. The history is stored
in the ``net_forces_w_history`` attribute of the sensor data.
Changed
^^^^^^^
* Implemented lazy update of buffers in the :class:`omni.isaac.lab.sensors.SensorBase` class. This allows the user
to update the sensor data only when required, i.e. when the data is requested by the user. This helps avoid double
computation of sensor data when a reset is called in the environment.
Deprecated
^^^^^^^^^^
* Removed the support for different backends in the sensor class. We only use Pytorch as the backend now.
* Removed the concept of actuator groups. They are now handled by the :class:`omni.isaac.lab.managers.ActionManager`
class. The actuator models are now directly handled by the robot class itself.
0.7.4 (2023-07-26)
~~~~~~~~~~~~~~~~~~
Changed
^^^^^^^
* Changed the behavior of the :class:`omni.isaac.lab.terrains.TerrainImporter` class. It now expects the terrain
type to be specified in the configuration object. This allows the user to specify everything in the configuration
object and not have to do an explicit call to import a terrain.
Fixed
^^^^^
* Fixed setting of quaternion orientations inside the :class:`omni.isaac.lab.markers.Visualizationmarkers` class.
Earlier, the orientation was being set into the point instancer in the wrong order (``wxyz`` instead of ``xyzw``).
0.7.3 (2023-07-25)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the issue with multiple inheritance in the :class:`omni.isaac.lab.utils.configclass` decorator.
Earlier, if the inheritance tree was more than one level deep and the lowest level configuration class was
not updating its values from the middle level classes.
0.7.2 (2023-07-24)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the method :meth:`replace` to the :class:`omni.isaac.lab.utils.configclass` decorator to allow
creating a new configuration object with values replaced from keyword arguments. This function internally
calls the `dataclasses.replace <https://docs.python.org/3/library/dataclasses.html#dataclasses.replace>`_.
Fixed
^^^^^
* Fixed the handling of class types as member values in the :meth:`omni.isaac.lab.utils.configclass`. Earlier it was
throwing an error since class types were skipped in the if-else block.
0.7.1 (2023-07-22)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :class:`TerminationManager`, :class:`CurriculumManager`, and :class:`RandomizationManager` classes
to the :mod:`omni.isaac.lab.managers` module to handle termination, curriculum, and randomization respectively.
0.7.0 (2023-07-22)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Created a new :mod:`omni.isaac.lab.managers` module for all the managers related to the environment / scene.
This includes the :class:`omni.isaac.lab.managers.ObservationManager` and :class:`omni.isaac.lab.managers.RewardManager`
classes that were previously in the :mod:`omni.isaac.lab.utils.mdp` module.
* Added the :class:`omni.isaac.lab.managers.ManagerBase` class to handle the creation of managers.
* Added configuration classes for :class:`ObservationTermCfg` and :class:`RewardTermCfg` to allow easy creation of
observation and reward terms.
Changed
^^^^^^^
* Changed the behavior of :class:`ObservationManager` and :class:`RewardManager` classes to accept the key ``func``
in each configuration term to be a callable. This removes the need to inherit from the base class
and allows more reusability of the functions across different environments.
* Moved the old managers to the :mod:`omni.isaac.lab.compat.utils.mdp` module.
* Modified the necessary scripts to use the :mod:`omni.isaac.lab.compat.utils.mdp` module.
0.6.2 (2023-07-21)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :mod:`omni.isaac.lab.command_generators` to generate different commands based on the desired task.
It allows the user to generate commands for different tasks in the same environment without having to write
custom code for each task.
0.6.1 (2023-07-16)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :meth:`omni.isaac.lab.utils.math.quat_apply_yaw` to compute the yaw quaternion correctly.
Added
^^^^^
* Added functions to convert string and callable objects in :mod:`omni.isaac.lab.utils.string`.
0.6.0 (2023-07-16)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the argument :attr:`sort_keys` to the :meth:`omni.isaac.lab.utils.io.yaml.dump_yaml` method to allow
enabling/disabling of sorting of keys in the output yaml file.
Fixed
^^^^^
* Fixed the ordering of terms in :mod:`omni.isaac.lab.utils.configclass` to be consistent in the order in which
they are defined. Previously, the ordering was done alphabetically which made it inconsistent with the order in which
the parameters were defined.
Changed
^^^^^^^
* Changed the default value of the argument :attr:`sort_keys` in the :meth:`omni.isaac.lab.utils.io.yaml.dump_yaml`
method to ``False``.
* Moved the old config classes in :mod:`omni.isaac.lab.utils.configclass` to
:mod:`omni.isaac.lab.compat.utils.configclass` so that users can still run their old code where alphabetical
ordering was used.
0.5.0 (2023-07-04)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added a generalized :class:`omni.isaac.lab.sensors.SensorBase` class that leverages the ideas of views to
handle multiple sensors in a single class.
* Added the classes :class:`omni.isaac.lab.sensors.RayCaster`, :class:`omni.isaac.lab.sensors.ContactSensor`,
and :class:`omni.isaac.lab.sensors.Camera` that output a batched tensor of sensor data.
Changed
^^^^^^^
* Renamed the parameter ``sensor_tick`` to ``update_freq`` to make it more intuitive.
* Moved the old sensors in :mod:`omni.isaac.lab.sensors` to :mod:`omni.isaac.lab.compat.sensors`.
* Modified the standalone scripts to use the :mod:`omni.isaac.lab.compat.sensors` module.
0.4.4 (2023-07-05)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :meth:`omni.isaac.lab.terrains.trimesh.utils.make_plane` method to handle the case when the
plane origin does not need to be centered.
* Added the :attr:`omni.isaac.lab.terrains.TerrainGeneratorCfg.seed` to make generation of terrains reproducible.
The default value is ``None`` which means that the seed is not set.
Changed
^^^^^^^
* Changed the saving of ``origins`` in :class:`omni.isaac.lab.terrains.TerrainGenerator` class to be in CSV format
instead of NPY format.
0.4.3 (2023-06-28)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :class:`omni.isaac.lab.markers.PointInstancerMarker` class that wraps around
`UsdGeom.PointInstancer <https://graphics.pixar.com/usd/dev/api/class_usd_geom_point_instancer.html>`_
to directly work with torch and numpy arrays.
Changed
^^^^^^^
* Moved the old markers in :mod:`omni.isaac.lab.markers` to :mod:`omni.isaac.lab.compat.markers`.
* Modified the standalone scripts to use the :mod:`omni.isaac.lab.compat.markers` module.
0.4.2 (2023-06-28)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the sub-module :mod:`omni.isaac.lab.terrains` to allow procedural generation of terrains and supporting
importing of terrains from different sources (meshes, usd files or default ground plane).
0.4.1 (2023-06-27)
~~~~~~~~~~~~~~~~~~
* Added the :class:`omni.isaac.lab.app.AppLauncher` class to allow controlled instantiation of
the `SimulationApp <https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.isaac.kit/docs/index.html>`_
and extension loading for remote deployment and ROS bridges.
Changed
^^^^^^^
* Modified all standalone scripts to use the :class:`omni.isaac.lab.app.AppLauncher` class.
0.4.0 (2023-05-27)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added a helper class :class:`omni.isaac.lab.asset_loader.UrdfLoader` that converts a URDF file to instanceable USD
file based on the input configuration object.
0.3.2 (2023-04-27)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added safe-printing of functions while using the :meth:`omni.isaac.lab.utils.dict.print_dict` function.
0.3.1 (2023-04-23)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added a modified version of ``lula_franka_gen.urdf`` which includes an end-effector frame.
* Added a standalone script ``play_rmpflow.py`` to show RMPFlow controller.
Fixed
^^^^^
* Fixed the splitting of commands in the :meth:`ActuatorGroup.compute` method. Earlier it was reshaping the
commands to the shape ``(num_actuators, num_commands)`` which was causing the commands to be split incorrectly.
* Fixed the processing of actuator command in the :meth:`RobotBase._process_actuators_cfg` to deal with multiple
command types when using "implicit" actuator group.
0.3.0 (2023-04-20)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Added the destructor to the keyboard devices to unsubscribe from carb.
Added
^^^^^
* Added the :class:`Se2Gamepad` and :class:`Se3Gamepad` for gamepad teleoperation support.
0.2.8 (2023-04-10)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed bugs in :meth:`axis_angle_from_quat` in the ``omni.isaac.lab.utils.math`` to handle quaternion with negative w component.
* Fixed bugs in :meth:`subtract_frame_transforms` in the ``omni.isaac.lab.utils.math`` by adding the missing final rotation.
0.2.7 (2023-04-07)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed repetition in applying mimic multiplier for "p_abs" in the :class:`GripperActuatorGroup` class.
* Fixed bugs in :meth:`reset_buffers` in the :class:`RobotBase` and :class:`LeggedRobot` classes.
0.2.6 (2023-03-16)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added the :class:`CollisionPropertiesCfg` to rigid/articulated object and robot base classes.
* Added the :class:`PhysicsMaterialCfg` to the :class:`SingleArm` class for tool sites.
Changed
^^^^^^^
* Changed the default control mode of the :obj:`PANDA_HAND_MIMIC_GROUP_CFG` to be from ``"v_abs"`` to ``"p_abs"``.
Using velocity control for the mimic group can cause the hand to move in a jerky manner.
0.2.5 (2023-03-08)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the indices used for the Jacobian and dynamics quantities in the :class:`MobileManipulator` class.
0.2.4 (2023-03-04)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added :meth:`apply_nested_physics_material` to the ``omni.isaac.lab.utils.kit``.
* Added the :meth:`sample_cylinder` to sample points from a cylinder's surface.
* Added documentation about the issue in using instanceable asset as markers.
Fixed
^^^^^
* Simplified the physics material application in the rigid object and legged robot classes.
Removed
^^^^^^^
* Removed the ``geom_prim_rel_path`` argument in the :class:`RigidObjectCfg.MetaInfoCfg` class.
0.2.3 (2023-02-24)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the end-effector body index used for getting the Jacobian in the :class:`SingleArm` and :class:`MobileManipulator` classes.
0.2.2 (2023-01-27)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :meth:`set_world_pose_ros` and :meth:`set_world_pose_from_view` in the :class:`Camera` class.
Deprecated
^^^^^^^^^^
* Removed the :meth:`set_world_pose_from_ypr` method from the :class:`Camera` class.
0.2.1 (2023-01-26)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed the :class:`Camera` class to support different fisheye projection types.
0.2.0 (2023-01-25)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Added support for warp backend in camera utilities.
* Extended the ``play_camera.py`` with ``--gpu`` flag to use GPU replicator backend.
0.1.1 (2023-01-24)
~~~~~~~~~~~~~~~~~~
Fixed
^^^^^
* Fixed setting of physics material on the ground plane when using :meth:`omni.isaac.lab.utils.kit.create_ground_plane` function.
0.1.0 (2023-01-17)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Initial release of the extension with experimental API.
* Available robot configurations:
* **Quadrupeds:** Unitree A1, ANYmal B, ANYmal C
* **Single-arm manipulators:** Franka Emika arm, UR5
* **Mobile manipulators:** Clearpath Ridgeback with Franka Emika arm or UR5
| 70,832 |
reStructuredText
| 29.544631 | 189 | 0.70982 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab/docs/README.md
|
# Isaac Lab: Framework
Isaac Lab includes its own set of interfaces and wrappers around Isaac Sim classes. One of the main goals behind this
decision is to have a unified description for different systems. While isaac Sim tries to be general for a wider
variety of simulation requires, our goal has been to specialize these for learning requirements. These include
features such as augmenting simulators with non-ideal actuator models, managing different observation and reward
settings, integrate different sensors, as well as provide interfaces to features that are currently not available in
Isaac Sim but are available from the physics side (such as deformable bodies).
We recommend the users to try out the demo scripts present in `standalone/demos` that display how different parts
of the framework can be integrated together.
| 835 |
Markdown
| 68.666661 | 117 | 0.821557 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/pyproject.toml
|
[build-system]
requires = ["setuptools", "wheel", "toml"]
build-backend = "setuptools.build_meta"
| 98 |
TOML
| 23.749994 | 42 | 0.704082 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/setup.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Installation script for the 'omni.isaac.lab_tasks' python package."""
import itertools
import os
import platform
import toml
from setuptools import setup
# Obtain the extension data from the extension.toml file
EXTENSION_PATH = os.path.dirname(os.path.realpath(__file__))
# Read the extension.toml file
EXTENSION_TOML_DATA = toml.load(os.path.join(EXTENSION_PATH, "config", "extension.toml"))
# Minimum dependencies required prior to installation
INSTALL_REQUIRES = [
# generic
"numpy",
"torch>=2.2.2",
"torchvision>=0.14.1", # ensure compatibility with torch 1.13.1
# 5.26.0 introduced a breaking change, so we restricted it for now.
# See issue https://github.com/tensorflow/tensorboard/issues/6808 for details.
"protobuf>=3.20.2, < 5.0.0",
# data collection
"h5py",
# basic logger
"tensorboard",
# video recording
"moviepy",
]
# Extra dependencies for RL agents
EXTRAS_REQUIRE = {
"sb3": ["stable-baselines3>=2.1"],
"skrl": ["skrl>=1.1.0"],
"rl-games": ["rl-games==1.6.1", "gym"], # rl-games still needs gym :(
"rsl-rl": ["rsl-rl@git+https://github.com/leggedrobotics/rsl_rl.git"],
"robomimic": [],
}
# Check if the platform is Linux and add the dependency
if platform.system() == "Linux":
EXTRAS_REQUIRE["robomimic"].append("robomimic@git+https://github.com/ARISE-Initiative/robomimic.git")
# cumulation of all extra-requires
EXTRAS_REQUIRE["all"] = list(itertools.chain.from_iterable(EXTRAS_REQUIRE.values()))
# Installation operation
setup(
name="omni-isaac-lab_tasks",
author="Isaac Lab Project Developers",
maintainer="Isaac Lab Project Developers",
url=EXTENSION_TOML_DATA["package"]["repository"],
version=EXTENSION_TOML_DATA["package"]["version"],
description=EXTENSION_TOML_DATA["package"]["description"],
keywords=EXTENSION_TOML_DATA["package"]["keywords"],
include_package_data=True,
python_requires=">=3.10",
install_requires=INSTALL_REQUIRES,
extras_require=EXTRAS_REQUIRE,
packages=["omni.isaac.lab_tasks"],
classifiers=[
"Natural Language :: English",
"Programming Language :: Python :: 3.10",
"Isaac Sim :: 4.0.0",
"Isaac Sim :: 2023.1.1",
],
zip_safe=False,
)
| 2,389 |
Python
| 30.447368 | 105 | 0.678527 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/test/test_environments.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Launch Isaac Sim Simulator first."""
from omni.isaac.lab.app import AppLauncher, run_tests
# launch the simulator
app_launcher = AppLauncher(headless=True, enable_cameras=True)
simulation_app = app_launcher.app
"""Rest everything follows."""
import gymnasium as gym
import torch
import unittest
import omni.usd
from omni.isaac.lab.envs import ManagerBasedRLEnv, ManagerBasedRLEnvCfg
import omni.isaac.lab_tasks # noqa: F401
from omni.isaac.lab_tasks.utils.parse_cfg import parse_env_cfg
class TestEnvironments(unittest.TestCase):
"""Test cases for all registered environments."""
@classmethod
def setUpClass(cls):
# acquire all Isaac environments names
cls.registered_tasks = list()
for task_spec in gym.registry.values():
if "Isaac" in task_spec.id and not task_spec.id.endswith("Play-v0"):
cls.registered_tasks.append(task_spec.id)
# sort environments by name
cls.registered_tasks.sort()
# print all existing task names
print(">>> All registered environments:", cls.registered_tasks)
"""
Test fixtures.
"""
def test_multiple_instances_gpu(self):
"""Run all environments with multiple instances and check environments return valid signals."""
# common parameters
num_envs = 32
use_gpu = True
# iterate over all registered environments
for task_name in self.registered_tasks:
with self.subTest(task_name=task_name):
print(f">>> Running test for environment: {task_name}")
# check environment
self._check_random_actions(task_name, use_gpu, num_envs, num_steps=100)
# close the environment
print(f">>> Closing environment: {task_name}")
print("-" * 80)
def test_single_instance_gpu(self):
"""Run all environments with single instance and check environments return valid signals."""
# common parameters
num_envs = 1
use_gpu = True
# iterate over all registered environments
for task_name in self.registered_tasks:
with self.subTest(task_name=task_name):
print(f">>> Running test for environment: {task_name}")
# check environment
self._check_random_actions(task_name, use_gpu, num_envs, num_steps=100)
# close the environment
print(f">>> Closing environment: {task_name}")
print("-" * 80)
"""
Helper functions.
"""
def _check_random_actions(self, task_name: str, use_gpu: bool, num_envs: int, num_steps: int = 1000):
"""Run random actions and check environments return valid signals."""
# create a new stage
omni.usd.get_context().new_stage()
# parse configuration
env_cfg: ManagerBasedRLEnvCfg = parse_env_cfg(task_name, use_gpu=use_gpu, num_envs=num_envs)
# create environment
env: ManagerBasedRLEnv = gym.make(task_name, cfg=env_cfg)
# reset environment
obs, _ = env.reset()
# check signal
self.assertTrue(self._check_valid_tensor(obs))
# simulate environment for num_steps steps
with torch.inference_mode():
for _ in range(num_steps):
# sample actions from -1 to 1
actions = 2 * torch.rand(env.action_space.shape, device=env.unwrapped.device) - 1
# apply actions
transition = env.step(actions)
# check signals
for data in transition:
self.assertTrue(self._check_valid_tensor(data), msg=f"Invalid data: {data}")
# close the environment
env.close()
@staticmethod
def _check_valid_tensor(data: torch.Tensor | dict) -> bool:
"""Checks if given data does not have corrupted values.
Args:
data: Data buffer.
Returns:
True if the data is valid.
"""
if isinstance(data, torch.Tensor):
return not torch.any(torch.isnan(data))
elif isinstance(data, dict):
valid_tensor = True
for value in data.values():
if isinstance(value, dict):
valid_tensor &= TestEnvironments._check_valid_tensor(value)
elif isinstance(value, torch.Tensor):
valid_tensor &= not torch.any(torch.isnan(value))
return valid_tensor
else:
raise ValueError(f"Input data of invalid type: {type(data)}.")
if __name__ == "__main__":
run_tests()
| 4,769 |
Python
| 34.333333 | 105 | 0.604949 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/test/test_data_collector.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Launch Isaac Sim Simulator first."""
from omni.isaac.lab.app import AppLauncher, run_tests
# launch the simulator
app_launcher = AppLauncher(headless=True)
simulation_app = app_launcher.app
"""Rest everything follows."""
import os
import torch
import unittest
from omni.isaac.lab_tasks.utils.data_collector import RobomimicDataCollector
class TestRobomimicDataCollector(unittest.TestCase):
"""Test dataset flushing behavior of robomimic data collector."""
def test_basic_flushing(self):
"""Adds random data into the collector and checks saving of the data."""
# name of the environment (needed by robomimic)
task_name = "My-Task-v0"
# specify directory for logging experiments
test_dir = os.path.dirname(os.path.abspath(__file__))
log_dir = os.path.join(test_dir, "output", "demos")
# name of the file to save data
filename = "hdf_dataset.hdf5"
# number of episodes to collect
num_demos = 10
# number of environments to simulate
num_envs = 4
# create data-collector
collector_interface = RobomimicDataCollector(task_name, log_dir, filename, num_demos)
# reset the collector
collector_interface.reset()
while not collector_interface.is_stopped():
# generate random data to store
# -- obs
obs = {"joint_pos": torch.randn(num_envs, 7), "joint_vel": torch.randn(num_envs, 7)}
# -- actions
actions = torch.randn(num_envs, 7)
# -- next obs
next_obs = {"joint_pos": torch.randn(num_envs, 7), "joint_vel": torch.randn(num_envs, 7)}
# -- rewards
rewards = torch.randn(num_envs)
# -- dones
dones = torch.rand(num_envs) > 0.5
# store signals
# -- obs
for key, value in obs.items():
collector_interface.add(f"obs/{key}", value)
# -- actions
collector_interface.add("actions", actions)
# -- next_obs
for key, value in next_obs.items():
collector_interface.add(f"next_obs/{key}", value.cpu().numpy())
# -- rewards
collector_interface.add("rewards", rewards)
# -- dones
collector_interface.add("dones", dones)
# flush data from collector for successful environments
# note: in this case we flush all the time
reset_env_ids = dones.nonzero(as_tuple=False).squeeze(-1)
collector_interface.flush(reset_env_ids)
# close collector
collector_interface.close()
# TODO: Add inspection of the saved dataset as part of the test.
if __name__ == "__main__":
run_tests()
| 2,906 |
Python
| 32.802325 | 101 | 0.602202 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/test/test_record_video.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Launch Isaac Sim Simulator first."""
from omni.isaac.lab.app import AppLauncher, run_tests
# launch the simulator
app_launcher = AppLauncher(headless=True, enable_cameras=True)
simulation_app = app_launcher.app
"""Rest everything follows."""
import gymnasium as gym
import os
import torch
import unittest
import omni.usd
from omni.isaac.lab.envs import ManagerBasedRLEnvCfg
import omni.isaac.lab_tasks # noqa: F401
from omni.isaac.lab_tasks.utils import parse_env_cfg
class TestRecordVideoWrapper(unittest.TestCase):
"""Test recording videos using the RecordVideo wrapper."""
@classmethod
def setUpClass(cls):
# acquire all Isaac environments names
cls.registered_tasks = list()
for task_spec in gym.registry.values():
if "Isaac" in task_spec.id:
cls.registered_tasks.append(task_spec.id)
# sort environments by name
cls.registered_tasks.sort()
# print all existing task names
print(">>> All registered environments:", cls.registered_tasks)
# directory to save videos
cls.videos_dir = os.path.join(os.path.dirname(__file__), "output", "videos")
def setUp(self) -> None:
# common parameters
self.num_envs = 16
self.use_gpu = True
# video parameters
self.step_trigger = lambda step: step % 225 == 0
self.video_length = 200
def test_record_video(self):
"""Run random actions agent with recording of videos."""
for task_name in self.registered_tasks:
with self.subTest(task_name=task_name):
print(f">>> Running test for environment: {task_name}")
# create a new stage
omni.usd.get_context().new_stage()
# parse configuration
env_cfg: ManagerBasedRLEnvCfg = parse_env_cfg(task_name, use_gpu=self.use_gpu, num_envs=self.num_envs)
# create environment
env = gym.make(task_name, cfg=env_cfg, render_mode="rgb_array")
# directory to save videos
videos_dir = os.path.join(self.videos_dir, task_name)
# wrap environment to record videos
env = gym.wrappers.RecordVideo(
env,
videos_dir,
step_trigger=self.step_trigger,
video_length=self.video_length,
disable_logger=True,
)
# reset environment
env.reset()
# simulate environment
with torch.inference_mode():
for _ in range(500):
# compute zero actions
actions = 2 * torch.rand(env.action_space.shape, device=env.unwrapped.device) - 1
# apply actions
_ = env.step(actions)
# close the simulator
env.close()
if __name__ == "__main__":
run_tests()
| 3,137 |
Python
| 32.031579 | 118 | 0.58081 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/test/wrappers/test_rsl_rl_wrapper.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Launch Isaac Sim Simulator first."""
from omni.isaac.lab.app import AppLauncher, run_tests
# launch the simulator
app_launcher = AppLauncher(headless=True, enable_cameras=True)
simulation_app = app_launcher.app
"""Rest everything follows."""
import gymnasium as gym
import torch
import unittest
import omni.usd
from omni.isaac.lab.envs import ManagerBasedRLEnvCfg
import omni.isaac.lab_tasks # noqa: F401
from omni.isaac.lab_tasks.utils.parse_cfg import parse_env_cfg
from omni.isaac.lab_tasks.utils.wrappers.rsl_rl import RslRlVecEnvWrapper
class TestRslRlVecEnvWrapper(unittest.TestCase):
"""Test that RSL-RL VecEnv wrapper works as expected."""
@classmethod
def setUpClass(cls):
# acquire all Isaac environments names
cls.registered_tasks = list()
for task_spec in gym.registry.values():
if "Isaac" in task_spec.id:
cfg_entry_point = gym.spec(task_spec.id).kwargs.get("rsl_rl_cfg_entry_point")
if cfg_entry_point is not None:
cls.registered_tasks.append(task_spec.id)
# sort environments by name
cls.registered_tasks.sort()
cls.registered_tasks = cls.registered_tasks[:4]
# print all existing task names
print(">>> All registered environments:", cls.registered_tasks)
def setUp(self) -> None:
# common parameters
self.num_envs = 64
self.use_gpu = True
def test_random_actions(self):
"""Run random actions and check environments return valid signals."""
for task_name in self.registered_tasks:
with self.subTest(task_name=task_name):
print(f">>> Running test for environment: {task_name}")
# create a new stage
omni.usd.get_context().new_stage()
# parse configuration
env_cfg: ManagerBasedRLEnvCfg = parse_env_cfg(task_name, use_gpu=self.use_gpu, num_envs=self.num_envs)
# create environment
env = gym.make(task_name, cfg=env_cfg)
# wrap environment
env = RslRlVecEnvWrapper(env)
# reset environment
obs, extras = env.reset()
# check signal
self.assertTrue(self._check_valid_tensor(obs))
self.assertTrue(self._check_valid_tensor(extras))
# simulate environment for 1000 steps
with torch.inference_mode():
for _ in range(1000):
# sample actions from -1 to 1
actions = 2 * torch.rand(env.action_space.shape, device=env.unwrapped.device) - 1
# apply actions
transition = env.step(actions)
# check signals
for data in transition:
self.assertTrue(self._check_valid_tensor(data), msg=f"Invalid data: {data}")
# close the environment
print(f">>> Closing environment: {task_name}")
env.close()
def test_no_time_outs(self):
"""Check that environments with finite horizon do not send time-out signals."""
for task_name in self.registered_tasks:
with self.subTest(task_name=task_name):
print(f">>> Running test for environment: {task_name}")
# create a new stage
omni.usd.get_context().new_stage()
# parse configuration
env_cfg: ManagerBasedRLEnvCfg = parse_env_cfg(task_name, use_gpu=self.use_gpu, num_envs=self.num_envs)
# change to finite horizon
env_cfg.is_finite_horizon = True
# create environment
env = gym.make(task_name, cfg=env_cfg)
# wrap environment
env = RslRlVecEnvWrapper(env)
# reset environment
_, extras = env.reset()
# check signal
self.assertNotIn("time_outs", extras, msg="Time-out signal found in finite horizon environment.")
# simulate environment for 10 steps
with torch.inference_mode():
for _ in range(10):
# sample actions from -1 to 1
actions = 2 * torch.rand(env.action_space.shape, device=env.unwrapped.device) - 1
# apply actions
extras = env.step(actions)[-1]
# check signals
self.assertNotIn(
"time_outs", extras, msg="Time-out signal found in finite horizon environment."
)
# close the environment
print(f">>> Closing environment: {task_name}")
env.close()
"""
Helper functions.
"""
@staticmethod
def _check_valid_tensor(data: torch.Tensor | dict) -> bool:
"""Checks if given data does not have corrupted values.
Args:
data: Data buffer.
Returns:
True if the data is valid.
"""
if isinstance(data, torch.Tensor):
return not torch.any(torch.isnan(data))
elif isinstance(data, dict):
valid_tensor = True
for value in data.values():
if isinstance(value, dict):
valid_tensor &= TestRslRlVecEnvWrapper._check_valid_tensor(value)
elif isinstance(value, torch.Tensor):
valid_tensor &= not torch.any(torch.isnan(value))
return valid_tensor
else:
raise ValueError(f"Input data of invalid type: {type(data)}.")
if __name__ == "__main__":
run_tests()
| 5,925 |
Python
| 36.745223 | 118 | 0.56 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/test/wrappers/test_rl_games_wrapper.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Launch Isaac Sim Simulator first."""
from omni.isaac.lab.app import AppLauncher, run_tests
# launch the simulator
app_launcher = AppLauncher(headless=True, enable_cameras=True)
simulation_app = app_launcher.app
"""Rest everything follows."""
import gymnasium as gym
import torch
import unittest
import omni.usd
from omni.isaac.lab.envs import ManagerBasedRLEnvCfg
import omni.isaac.lab_tasks # noqa: F401
from omni.isaac.lab_tasks.utils.parse_cfg import parse_env_cfg
from omni.isaac.lab_tasks.utils.wrappers.rl_games import RlGamesVecEnvWrapper
class TestRlGamesVecEnvWrapper(unittest.TestCase):
"""Test that RL-Games VecEnv wrapper works as expected."""
@classmethod
def setUpClass(cls):
# acquire all Isaac environments names
cls.registered_tasks = list()
for task_spec in gym.registry.values():
if "Isaac" in task_spec.id:
cfg_entry_point = gym.spec(task_spec.id).kwargs.get("rl_games_cfg_entry_point")
if cfg_entry_point is not None:
cls.registered_tasks.append(task_spec.id)
# sort environments by name
cls.registered_tasks.sort()
cls.registered_tasks = cls.registered_tasks[:4]
# print all existing task names
print(">>> All registered environments:", cls.registered_tasks)
def setUp(self) -> None:
# common parameters
self.num_envs = 64
self.use_gpu = True
def test_random_actions(self):
"""Run random actions and check environments return valid signals."""
for task_name in self.registered_tasks:
with self.subTest(task_name=task_name):
print(f">>> Running test for environment: {task_name}")
# create a new stage
omni.usd.get_context().new_stage()
# parse configuration
env_cfg: ManagerBasedRLEnvCfg = parse_env_cfg(task_name, use_gpu=self.use_gpu, num_envs=self.num_envs)
# create environment
env = gym.make(task_name, cfg=env_cfg)
# wrap environment
env = RlGamesVecEnvWrapper(env, "cuda:0", 100, 100)
# reset environment
obs = env.reset()
# check signal
self.assertTrue(self._check_valid_tensor(obs))
# simulate environment for 100 steps
with torch.inference_mode():
for _ in range(100):
# sample actions from -1 to 1
actions = 2 * torch.rand(env.num_envs, *env.action_space.shape, device=env.device) - 1
# apply actions
transition = env.step(actions)
# check signals
for data in transition:
self.assertTrue(self._check_valid_tensor(data), msg=f"Invalid data: {data}")
# close the environment
print(f">>> Closing environment: {task_name}")
env.close()
"""
Helper functions.
"""
@staticmethod
def _check_valid_tensor(data: torch.Tensor | dict) -> bool:
"""Checks if given data does not have corrupted values.
Args:
data: Data buffer.
Returns:
True if the data is valid.
"""
if isinstance(data, torch.Tensor):
return not torch.any(torch.isnan(data))
elif isinstance(data, dict):
valid_tensor = True
for value in data.values():
if isinstance(value, dict):
valid_tensor &= TestRlGamesVecEnvWrapper._check_valid_tensor(value)
elif isinstance(value, torch.Tensor):
valid_tensor &= not torch.any(torch.isnan(value))
return valid_tensor
else:
raise ValueError(f"Input data of invalid type: {type(data)}.")
if __name__ == "__main__":
run_tests()
| 4,120 |
Python
| 33.923729 | 118 | 0.583495 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/test/wrappers/test_sb3_wrapper.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Launch Isaac Sim Simulator first."""
from omni.isaac.lab.app import AppLauncher, run_tests
# launch the simulator
app_launcher = AppLauncher(headless=True, enable_cameras=True)
simulation_app = app_launcher.app
"""Rest everything follows."""
import gymnasium as gym
import numpy as np
import torch
import unittest
import omni.usd
from omni.isaac.lab.envs import ManagerBasedRLEnvCfg
import omni.isaac.lab_tasks # noqa: F401
from omni.isaac.lab_tasks.utils.parse_cfg import parse_env_cfg
from omni.isaac.lab_tasks.utils.wrappers.sb3 import Sb3VecEnvWrapper
class TestStableBaselines3VecEnvWrapper(unittest.TestCase):
"""Test that SB3 VecEnv wrapper works as expected."""
@classmethod
def setUpClass(cls):
# acquire all Isaac environments names
cls.registered_tasks = list()
for task_spec in gym.registry.values():
if "Isaac" in task_spec.id:
cfg_entry_point = gym.spec(task_spec.id).kwargs.get("sb3_cfg_entry_point")
if cfg_entry_point is not None:
cls.registered_tasks.append(task_spec.id)
# sort environments by name
cls.registered_tasks.sort()
cls.registered_tasks = cls.registered_tasks[:4]
# print all existing task names
print(">>> All registered environments:", cls.registered_tasks)
def setUp(self) -> None:
# common parameters
self.num_envs = 64
self.use_gpu = True
def test_random_actions(self):
"""Run random actions and check environments return valid signals."""
for task_name in self.registered_tasks:
with self.subTest(task_name=task_name):
print(f">>> Running test for environment: {task_name}")
# create a new stage
omni.usd.get_context().new_stage()
# parse configuration
env_cfg: ManagerBasedRLEnvCfg = parse_env_cfg(task_name, use_gpu=self.use_gpu, num_envs=self.num_envs)
# create environment
env = gym.make(task_name, cfg=env_cfg)
# wrap environment
env = Sb3VecEnvWrapper(env)
# reset environment
obs = env.reset()
# check signal
self.assertTrue(self._check_valid_array(obs))
# simulate environment for 1000 steps
with torch.inference_mode():
for _ in range(1000):
# sample actions from -1 to 1
actions = 2 * np.random.rand(env.num_envs, *env.action_space.shape) - 1
# apply actions
transition = env.step(actions)
# check signals
for data in transition:
self.assertTrue(self._check_valid_array(data), msg=f"Invalid data: {data}")
# close the environment
print(f">>> Closing environment: {task_name}")
env.close()
"""
Helper functions.
"""
@staticmethod
def _check_valid_array(data: np.ndarray | dict | list) -> bool:
"""Checks if given data does not have corrupted values.
Args:
data: Data buffer.
Returns:
True if the data is valid.
"""
if isinstance(data, np.ndarray):
return not np.any(np.isnan(data))
elif isinstance(data, dict):
valid_array = True
for value in data.values():
if isinstance(value, dict):
valid_array &= TestStableBaselines3VecEnvWrapper._check_valid_array(value)
elif isinstance(value, np.ndarray):
valid_array &= not np.any(np.isnan(value))
return valid_array
elif isinstance(data, list):
valid_array = True
for value in data:
valid_array &= TestStableBaselines3VecEnvWrapper._check_valid_array(value)
return valid_array
else:
raise ValueError(f"Input data of invalid type: {type(data)}.")
if __name__ == "__main__":
run_tests()
| 4,303 |
Python
| 33.709677 | 118 | 0.581687 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/test/wrappers/test_skrl_wrapper.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Launch Isaac Sim Simulator first."""
from omni.isaac.lab.app import AppLauncher, run_tests
# launch the simulator
app_launcher = AppLauncher(headless=True, enable_cameras=True)
simulation_app = app_launcher.app
"""Rest everything follows."""
import gymnasium as gym
import torch
import unittest
import omni.usd
from omni.isaac.lab.envs import ManagerBasedRLEnvCfg
import omni.isaac.lab_tasks # noqa: F401
from omni.isaac.lab_tasks.utils.parse_cfg import parse_env_cfg
from omni.isaac.lab_tasks.utils.wrappers.skrl import SkrlVecEnvWrapper
class TestSKRLVecEnvWrapper(unittest.TestCase):
"""Test that SKRL VecEnv wrapper works as expected."""
@classmethod
def setUpClass(cls):
# acquire all Isaac environments names
cls.registered_tasks = list()
for task_spec in gym.registry.values():
if "Isaac" in task_spec.id:
cfg_entry_point = gym.spec(task_spec.id).kwargs.get("skrl_cfg_entry_point")
if cfg_entry_point is not None:
cls.registered_tasks.append(task_spec.id)
# sort environments by name
cls.registered_tasks.sort()
cls.registered_tasks = cls.registered_tasks[:4]
# print all existing task names
print(">>> All registered environments:", cls.registered_tasks)
def setUp(self) -> None:
# common parameters
self.num_envs = 64
self.use_gpu = True
def test_random_actions(self):
"""Run random actions and check environments return valid signals."""
for task_name in self.registered_tasks:
with self.subTest(task_name=task_name):
print(f">>> Running test for environment: {task_name}")
# create a new stage
omni.usd.get_context().new_stage()
# parse configuration
env_cfg: ManagerBasedRLEnvCfg = parse_env_cfg(task_name, use_gpu=self.use_gpu, num_envs=self.num_envs)
# create environment
env = gym.make(task_name, cfg=env_cfg)
# wrap environment
env = SkrlVecEnvWrapper(env)
# reset environment
obs, extras = env.reset()
# check signal
self.assertTrue(self._check_valid_tensor(obs))
self.assertTrue(self._check_valid_tensor(extras))
# simulate environment for 1000 steps
with torch.inference_mode():
for _ in range(1000):
# sample actions from -1 to 1
actions = (
2 * torch.rand(self.num_envs, *env.action_space.shape, device=env.unwrapped.device) - 1
)
# apply actions
transition = env.step(actions)
# check signals
for data in transition:
self.assertTrue(self._check_valid_tensor(data), msg=f"Invalid data: {data}")
# close the environment
print(f">>> Closing environment: {task_name}")
env.close()
"""
Helper functions.
"""
@staticmethod
def _check_valid_tensor(data: torch.Tensor | dict) -> bool:
"""Checks if given data does not have corrupted values.
Args:
data: Data buffer.
Returns:
True if the data is valid.
"""
if isinstance(data, torch.Tensor):
return not torch.any(torch.isnan(data))
elif isinstance(data, dict):
valid_tensor = True
for value in data.values():
if isinstance(value, dict):
valid_tensor &= TestSKRLVecEnvWrapper._check_valid_tensor(value)
elif isinstance(value, torch.Tensor):
valid_tensor &= not torch.any(torch.isnan(value))
return valid_tensor
else:
raise ValueError(f"Input data of invalid type: {type(data)}.")
if __name__ == "__main__":
run_tests()
| 4,219 |
Python
| 33.876033 | 118 | 0.575966 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/config/extension.toml
|
[package]
# Note: Semantic Versioning is used: https://semver.org/
version = "0.7.5"
# Description
title = "Isaac Lab Environments"
description="Extension containing suite of environments for robot learning."
readme = "docs/README.md"
repository = "https://github.com/isaac-sim/IsaacLab"
category = "robotics"
keywords = ["robotics", "rl", "il", "learning"]
[dependencies]
"omni.isaac.lab" = {}
"omni.isaac.lab_assets" = {}
"omni.isaac.core" = {}
"omni.isaac.gym" = {}
"omni.replicator.isaac" = {}
[[python.module]]
name = "omni.isaac.lab_tasks"
| 551 |
TOML
| 22.999999 | 76 | 0.69147 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Package containing task implementations for various robotic environments."""
import os
import toml
# Conveniences to other module directories via relative paths
ISAACLAB_TASKS_EXT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))
"""Path to the extension source directory."""
ISAACLAB_TASKS_METADATA = toml.load(os.path.join(ISAACLAB_TASKS_EXT_DIR, "config", "extension.toml"))
"""Extension metadata dictionary parsed from the extension.toml file."""
# Configure the module-level variables
__version__ = ISAACLAB_TASKS_METADATA["package"]["version"]
##
# Register Gym environments.
##
from .utils import import_packages
# The blacklist is used to prevent importing configs from sub-packages
_BLACKLIST_PKGS = ["utils"]
# Import all configs in this package
import_packages(__name__, _BLACKLIST_PKGS)
| 962 |
Python
| 30.064515 | 101 | 0.745322 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Direct workflow environments.
"""
import gymnasium as gym
| 190 |
Python
| 16.363635 | 60 | 0.736842 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/ant/ant_env.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from omni.isaac.lab_assets.ant import ANT_CFG
import omni.isaac.lab.sim as sim_utils
from omni.isaac.lab.assets import ArticulationCfg
from omni.isaac.lab.envs import DirectRLEnvCfg
from omni.isaac.lab.scene import InteractiveSceneCfg
from omni.isaac.lab.sim import SimulationCfg
from omni.isaac.lab.terrains import TerrainImporterCfg
from omni.isaac.lab.utils import configclass
from omni.isaac.lab_tasks.direct.locomotion.locomotion_env import LocomotionEnv
@configclass
class AntEnvCfg(DirectRLEnvCfg):
# simulation
sim: SimulationCfg = SimulationCfg(dt=1 / 120)
terrain = TerrainImporterCfg(
prim_path="/World/ground",
terrain_type="plane",
collision_group=-1,
physics_material=sim_utils.RigidBodyMaterialCfg(
friction_combine_mode="average",
restitution_combine_mode="average",
static_friction=1.0,
dynamic_friction=1.0,
restitution=0.0,
),
debug_vis=False,
)
# scene
scene: InteractiveSceneCfg = InteractiveSceneCfg(num_envs=4096, env_spacing=4.0, replicate_physics=True)
# robot
robot: ArticulationCfg = ANT_CFG.replace(prim_path="/World/envs/env_.*/Robot")
joint_gears: list = [15, 15, 15, 15, 15, 15, 15, 15]
# env
episode_length_s = 15.0
decimation = 2
action_scale = 0.5
num_actions = 8
num_observations = 36
num_states = 0
heading_weight: float = 0.5
up_weight: float = 0.1
energy_cost_scale: float = 0.05
actions_cost_scale: float = 0.005
alive_reward_scale: float = 0.5
dof_vel_scale: float = 0.2
death_cost: float = -2.0
termination_height: float = 0.31
angular_velocity_scale: float = 1.0
contact_force_scale: float = 0.1
class AntEnv(LocomotionEnv):
cfg: AntEnvCfg
def __init__(self, cfg: AntEnvCfg, render_mode: str | None = None, **kwargs):
super().__init__(cfg, render_mode, **kwargs)
| 2,110 |
Python
| 27.527027 | 108 | 0.674408 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/ant/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Ant locomotion environment.
"""
import gymnasium as gym
from . import agents
from .ant_env import AntEnv, AntEnvCfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Ant-Direct-v0",
entry_point="omni.isaac.lab_tasks.direct.ant:AntEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": AntEnvCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.AntPPORunnerCfg,
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
},
)
| 707 |
Python
| 22.599999 | 79 | 0.666195 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/ant/agents/rsl_rl_ppo_cfg.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.lab.utils import configclass
from omni.isaac.lab_tasks.utils.wrappers.rsl_rl import (
RslRlOnPolicyRunnerCfg,
RslRlPpoActorCriticCfg,
RslRlPpoAlgorithmCfg,
)
@configclass
class AntPPORunnerCfg(RslRlOnPolicyRunnerCfg):
num_steps_per_env = 32
max_iterations = 1000
save_interval = 50
experiment_name = "ant_direct"
empirical_normalization = False
policy = RslRlPpoActorCriticCfg(
init_noise_std=1.0,
actor_hidden_dims=[400, 200, 100],
critic_hidden_dims=[400, 200, 100],
activation="elu",
)
algorithm = RslRlPpoAlgorithmCfg(
value_loss_coef=1.0,
use_clipped_value_loss=True,
clip_param=0.2,
entropy_coef=0.0,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=5.0e-4,
schedule="adaptive",
gamma=0.99,
lam=0.95,
desired_kl=0.01,
max_grad_norm=1.0,
)
| 1,075 |
Python
| 24.619047 | 60 | 0.64186 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/ant/agents/skrl_ppo_cfg.yaml
|
seed: 42
# Models are instantiated using skrl's model instantiator utility
# https://skrl.readthedocs.io/en/latest/api/utils/model_instantiators.html
models:
separate: False
policy: # see skrl.utils.model_instantiators.torch.gaussian_model for parameter details
clip_actions: True
clip_log_std: True
initial_log_std: 0
min_log_std: -20.0
max_log_std: 2.0
input_shape: "Shape.STATES"
hiddens: [256, 128, 64]
hidden_activation: ["elu", "elu", "elu"]
output_shape: "Shape.ACTIONS"
output_activation: "tanh"
output_scale: 1.0
value: # see skrl.utils.model_instantiators.torch.deterministic_model for parameter details
clip_actions: False
input_shape: "Shape.STATES"
hiddens: [256, 128, 64]
hidden_activation: ["elu", "elu", "elu"]
output_shape: "Shape.ONE"
output_activation: ""
output_scale: 1.0
# PPO agent configuration (field names are from PPO_DEFAULT_CONFIG)
# https://skrl.readthedocs.io/en/latest/api/agents/ppo.html
agent:
rollouts: 16
learning_epochs: 8
mini_batches: 4
discount_factor: 0.99
lambda: 0.95
learning_rate: 3.e-4
learning_rate_scheduler: "KLAdaptiveLR"
learning_rate_scheduler_kwargs:
kl_threshold: 0.008
state_preprocessor: "RunningStandardScaler"
state_preprocessor_kwargs: null
value_preprocessor: "RunningStandardScaler"
value_preprocessor_kwargs: null
random_timesteps: 0
learning_starts: 0
grad_norm_clip: 1.0
ratio_clip: 0.2
value_clip: 0.2
clip_predicted_values: True
entropy_loss_scale: 0.0
value_loss_scale: 1.0
kl_threshold: 0
rewards_shaper_scale: 0.6
# logging and checkpoint
experiment:
directory: "ant_direct"
experiment_name: ""
write_interval: 40
checkpoint_interval: 400
# Sequential trainer
# https://skrl.readthedocs.io/en/latest/api/trainers/sequential.html
trainer:
timesteps: 8000
environment_info: "log"
| 1,904 |
YAML
| 27.014705 | 94 | 0.709034 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/ant/agents/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from . import rsl_rl_ppo_cfg
| 156 |
Python
| 21.428568 | 60 | 0.737179 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/ant/agents/rl_games_ppo_cfg.yaml
|
params:
seed: 42
# environment wrapper clipping
env:
clip_actions: 1.0
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [256, 128, 64]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: False # flag which sets whether to load the checkpoint
load_path: '' # path to the checkpoint to load
config:
name: ant_direct
env_name: rlgpu
device: 'cuda:0'
device_name: 'cuda:0'
multi_gpu: False
ppo: True
mixed_precision: True
normalize_input: True
normalize_value: True
value_bootstrap: True
num_actors: -1 # configured from the script (based on num_envs)
reward_shaper:
scale_value: 0.6
normalize_advantage: True
gamma: 0.99
tau: 0.95
learning_rate: 3e-4
lr_schedule: adaptive
schedule_type: legacy
kl_threshold: 0.008
score_to_win: 20000
max_epochs: 500
save_best_after: 100
save_frequency: 50
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 16
minibatch_size: 32768
mini_epochs: 4
critic_coef: 2
clip_value: True
seq_length: 4
bounds_loss_coef: 0.0001
| 1,559 |
YAML
| 19.25974 | 73 | 0.606799 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/quadcopter/quadcopter_env.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
import omni.isaac.lab.sim as sim_utils
from omni.isaac.lab.assets import Articulation, ArticulationCfg
from omni.isaac.lab.envs import DirectRLEnv, DirectRLEnvCfg
from omni.isaac.lab.envs.ui import BaseEnvWindow
from omni.isaac.lab.markers import VisualizationMarkers
from omni.isaac.lab.scene import InteractiveSceneCfg
from omni.isaac.lab.sim import SimulationCfg
from omni.isaac.lab.terrains import TerrainImporterCfg
from omni.isaac.lab.utils import configclass
from omni.isaac.lab.utils.math import subtract_frame_transforms
##
# Pre-defined configs
##
from omni.isaac.lab_assets import CRAZYFLIE_CFG # isort: skip
from omni.isaac.lab.markers import CUBOID_MARKER_CFG # isort: skip
class QuadcopterEnvWindow(BaseEnvWindow):
"""Window manager for the Quadcopter environment."""
def __init__(self, env: QuadcopterEnv, window_name: str = "IsaacLab"):
"""Initialize the window.
Args:
env: The environment object.
window_name: The name of the window. Defaults to "IsaacLab".
"""
# initialize base window
super().__init__(env, window_name)
# add custom UI elements
with self.ui_window_elements["main_vstack"]:
with self.ui_window_elements["debug_frame"]:
with self.ui_window_elements["debug_vstack"]:
# add command manager visualization
self._create_debug_vis_ui_element("targets", self.env)
@configclass
class QuadcopterEnvCfg(DirectRLEnvCfg):
ui_window_class_type = QuadcopterEnvWindow
# simulation
sim: SimulationCfg = SimulationCfg(
dt=1 / 100,
disable_contact_processing=True,
physics_material=sim_utils.RigidBodyMaterialCfg(
friction_combine_mode="multiply",
restitution_combine_mode="multiply",
static_friction=1.0,
dynamic_friction=1.0,
restitution=0.0,
),
)
terrain = TerrainImporterCfg(
prim_path="/World/ground",
terrain_type="plane",
collision_group=-1,
physics_material=sim_utils.RigidBodyMaterialCfg(
friction_combine_mode="multiply",
restitution_combine_mode="multiply",
static_friction=1.0,
dynamic_friction=1.0,
restitution=0.0,
),
debug_vis=False,
)
# scene
scene: InteractiveSceneCfg = InteractiveSceneCfg(num_envs=4096, env_spacing=2.5, replicate_physics=True)
# robot
robot: ArticulationCfg = CRAZYFLIE_CFG.replace(prim_path="/World/envs/env_.*/Robot")
thrust_to_weight = 1.9
moment_scale = 0.01
# env
episode_length_s = 10.0
decimation = 2
num_actions = 4
num_observations = 12
num_states = 0
debug_vis = True
# reward scales
lin_vel_reward_scale = -0.05
ang_vel_reward_scale = -0.01
distance_to_goal_reward_scale = 15.0
class QuadcopterEnv(DirectRLEnv):
cfg: QuadcopterEnvCfg
def __init__(self, cfg: QuadcopterEnvCfg, render_mode: str | None = None, **kwargs):
super().__init__(cfg, render_mode, **kwargs)
# Total thrust and moment applied to the base of the quadcopter
self._actions = torch.zeros(self.num_envs, self.cfg.num_actions, device=self.device)
self._thrust = torch.zeros(self.num_envs, 1, 3, device=self.device)
self._moment = torch.zeros(self.num_envs, 1, 3, device=self.device)
# Goal position
self._desired_pos_w = torch.zeros(self.num_envs, 3, device=self.device)
# Logging
self._episode_sums = {
key: torch.zeros(self.num_envs, dtype=torch.float, device=self.device)
for key in [
"lin_vel",
"ang_vel",
"distance_to_goal",
]
}
# Get specific body indices
self._body_id = self._robot.find_bodies("body")[0]
self._robot_mass = self._robot.root_physx_view.get_masses()[0].sum()
self._gravity_magnitude = torch.tensor(self.sim.cfg.gravity, device=self.device).norm()
self._robot_weight = (self._robot_mass * self._gravity_magnitude).item()
# add handle for debug visualization (this is set to a valid handle inside set_debug_vis)
self.set_debug_vis(self.cfg.debug_vis)
def _setup_scene(self):
self._robot = Articulation(self.cfg.robot)
self.scene.articulations["robot"] = self._robot
self.cfg.terrain.num_envs = self.scene.cfg.num_envs
self.cfg.terrain.env_spacing = self.scene.cfg.env_spacing
self._terrain = self.cfg.terrain.class_type(self.cfg.terrain)
# clone, filter, and replicate
self.scene.clone_environments(copy_from_source=False)
self.scene.filter_collisions(global_prim_paths=[self.cfg.terrain.prim_path])
# add lights
light_cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75))
light_cfg.func("/World/Light", light_cfg)
def _pre_physics_step(self, actions: torch.Tensor):
self._actions = actions.clone().clamp(-1.0, 1.0)
self._thrust[:, 0, 2] = self.cfg.thrust_to_weight * self._robot_weight * (self._actions[:, 0] + 1.0) / 2.0
self._moment[:, 0, :] = self.cfg.moment_scale * self._actions[:, 1:]
def _apply_action(self):
self._robot.set_external_force_and_torque(self._thrust, self._moment, body_ids=self._body_id)
def _get_observations(self) -> dict:
desired_pos_b, _ = subtract_frame_transforms(
self._robot.data.root_state_w[:, :3], self._robot.data.root_state_w[:, 3:7], self._desired_pos_w
)
obs = torch.cat(
[
self._robot.data.root_lin_vel_b,
self._robot.data.root_ang_vel_b,
self._robot.data.projected_gravity_b,
desired_pos_b,
],
dim=-1,
)
observations = {"policy": obs}
return observations
def _get_rewards(self) -> torch.Tensor:
lin_vel = torch.sum(torch.square(self._robot.data.root_lin_vel_b), dim=1)
ang_vel = torch.sum(torch.square(self._robot.data.root_ang_vel_b), dim=1)
distance_to_goal = torch.linalg.norm(self._desired_pos_w - self._robot.data.root_pos_w, dim=1)
distance_to_goal_mapped = 1 - torch.tanh(distance_to_goal / 0.8)
rewards = {
"lin_vel": lin_vel * self.cfg.lin_vel_reward_scale * self.step_dt,
"ang_vel": ang_vel * self.cfg.ang_vel_reward_scale * self.step_dt,
"distance_to_goal": distance_to_goal_mapped * self.cfg.distance_to_goal_reward_scale * self.step_dt,
}
reward = torch.sum(torch.stack(list(rewards.values())), dim=0)
# Logging
for key, value in rewards.items():
self._episode_sums[key] += value
return reward
def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]:
time_out = self.episode_length_buf >= self.max_episode_length - 1
died = torch.logical_or(self._robot.data.root_pos_w[:, 2] < 0.1, self._robot.data.root_pos_w[:, 2] > 2.0)
return died, time_out
def _reset_idx(self, env_ids: torch.Tensor | None):
if env_ids is None or len(env_ids) == self.num_envs:
env_ids = self._robot._ALL_INDICES
# Logging
final_distance_to_goal = torch.linalg.norm(
self._desired_pos_w[env_ids] - self._robot.data.root_pos_w[env_ids], dim=1
).mean()
extras = dict()
for key in self._episode_sums.keys():
episodic_sum_avg = torch.mean(self._episode_sums[key][env_ids])
extras["Episode Reward/" + key] = episodic_sum_avg / self.max_episode_length_s
self._episode_sums[key][env_ids] = 0.0
self.extras["log"] = dict()
self.extras["log"].update(extras)
extras = dict()
extras["Episode Termination/died"] = torch.count_nonzero(self.reset_terminated[env_ids]).item()
extras["Episode Termination/time_out"] = torch.count_nonzero(self.reset_time_outs[env_ids]).item()
extras["Metrics/final_distance_to_goal"] = final_distance_to_goal.item()
self.extras["log"].update(extras)
self._robot.reset(env_ids)
super()._reset_idx(env_ids)
if len(env_ids) == self.num_envs:
# Spread out the resets to avoid spikes in training when many environments reset at a similar time
self.episode_length_buf = torch.randint_like(self.episode_length_buf, high=int(self.max_episode_length))
self._actions[env_ids] = 0.0
# Sample new commands
self._desired_pos_w[env_ids, :2] = torch.zeros_like(self._desired_pos_w[env_ids, :2]).uniform_(-2.0, 2.0)
self._desired_pos_w[env_ids, :2] += self._terrain.env_origins[env_ids, :2]
self._desired_pos_w[env_ids, 2] = torch.zeros_like(self._desired_pos_w[env_ids, 2]).uniform_(0.5, 1.5)
# Reset robot state
joint_pos = self._robot.data.default_joint_pos[env_ids]
joint_vel = self._robot.data.default_joint_vel[env_ids]
default_root_state = self._robot.data.default_root_state[env_ids]
default_root_state[:, :3] += self._terrain.env_origins[env_ids]
self._robot.write_root_pose_to_sim(default_root_state[:, :7], env_ids)
self._robot.write_root_velocity_to_sim(default_root_state[:, 7:], env_ids)
self._robot.write_joint_state_to_sim(joint_pos, joint_vel, None, env_ids)
def _set_debug_vis_impl(self, debug_vis: bool):
# create markers if necessary for the first tome
if debug_vis:
if not hasattr(self, "goal_pos_visualizer"):
marker_cfg = CUBOID_MARKER_CFG.copy()
marker_cfg.markers["cuboid"].size = (0.05, 0.05, 0.05)
# -- goal pose
marker_cfg.prim_path = "/Visuals/Command/goal_position"
self.goal_pos_visualizer = VisualizationMarkers(marker_cfg)
# set their visibility to true
self.goal_pos_visualizer.set_visibility(True)
else:
if hasattr(self, "goal_pos_visualizer"):
self.goal_pos_visualizer.set_visibility(False)
def _debug_vis_callback(self, event):
# update the markers
self.goal_pos_visualizer.visualize(self._desired_pos_w)
| 10,494 |
Python
| 41.148594 | 116 | 0.621307 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/quadcopter/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Quacopter environment.
"""
import gymnasium as gym
from . import agents
from .quadcopter_env import QuadcopterEnv, QuadcopterEnvCfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Quadcopter-Direct-v0",
entry_point="omni.isaac.lab_tasks.direct.quadcopter:QuadcopterEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": QuadcopterEnvCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.QuadcopterPPORunnerCfg,
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
},
)
| 758 |
Python
| 24.299999 | 79 | 0.689974 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/quadcopter/agents/rsl_rl_ppo_cfg.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.lab.utils import configclass
from omni.isaac.lab_tasks.utils.wrappers.rsl_rl import (
RslRlOnPolicyRunnerCfg,
RslRlPpoActorCriticCfg,
RslRlPpoAlgorithmCfg,
)
@configclass
class QuadcopterPPORunnerCfg(RslRlOnPolicyRunnerCfg):
num_steps_per_env = 24
max_iterations = 200
save_interval = 50
experiment_name = "quadcopter_direct"
empirical_normalization = False
policy = RslRlPpoActorCriticCfg(
init_noise_std=1.0,
actor_hidden_dims=[64, 64],
critic_hidden_dims=[64, 64],
activation="elu",
)
algorithm = RslRlPpoAlgorithmCfg(
value_loss_coef=1.0,
use_clipped_value_loss=True,
clip_param=0.2,
entropy_coef=0.0,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=5.0e-4,
schedule="adaptive",
gamma=0.99,
lam=0.95,
desired_kl=0.01,
max_grad_norm=1.0,
)
| 1,074 |
Python
| 24.595238 | 60 | 0.645251 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/quadcopter/agents/skrl_ppo_cfg.yaml
|
seed: 42
# Models are instantiated using skrl's model instantiator utility
# https://skrl.readthedocs.io/en/latest/api/utils/model_instantiators.html
models:
separate: False
policy: # see skrl.utils.model_instantiators.torch.gaussian_model for parameter details
clip_actions: True
clip_log_std: True
initial_log_std: 0
min_log_std: -20.0
max_log_std: 2.0
input_shape: "Shape.STATES"
hiddens: [64, 64]
hidden_activation: ["elu", "elu", "elu"]
output_shape: "Shape.ACTIONS"
output_activation: "tanh"
output_scale: 1.0
value: # see skrl.utils.model_instantiators.torch.deterministic_model for parameter details
clip_actions: False
input_shape: "Shape.STATES"
hiddens: [64, 64]
hidden_activation: ["elu", "elu", "elu"]
output_shape: "Shape.ONE"
output_activation: ""
output_scale: 1.0
# PPO agent configuration (field names are from PPO_DEFAULT_CONFIG)
# https://skrl.readthedocs.io/en/latest/api/agents/ppo.html
agent:
rollouts: 24
learning_epochs: 5
mini_batches: 4
discount_factor: 0.99
lambda: 0.95
learning_rate: 5.e-4
learning_rate_scheduler: "KLAdaptiveLR"
learning_rate_scheduler_kwargs:
kl_threshold: 0.016
state_preprocessor: "RunningStandardScaler"
state_preprocessor_kwargs: null
value_preprocessor: "RunningStandardScaler"
value_preprocessor_kwargs: null
random_timesteps: 0
learning_starts: 0
grad_norm_clip: 1.0
ratio_clip: 0.2
value_clip: 0.2
clip_predicted_values: True
entropy_loss_scale: 0.0
value_loss_scale: 1.0
kl_threshold: 0
rewards_shaper_scale: 0.01
# logging and checkpoint
experiment:
directory: "quadcopter_direct"
experiment_name: ""
write_interval: 24
checkpoint_interval: 240
# Sequential trainer
# https://skrl.readthedocs.io/en/latest/api/trainers/sequential.html
trainer:
timesteps: 4800
environment_info: "log"
| 1,900 |
YAML
| 26.955882 | 94 | 0.710526 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/quadcopter/agents/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from . import rsl_rl_ppo_cfg
| 156 |
Python
| 21.428568 | 60 | 0.737179 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/quadcopter/agents/rl_games_ppo_cfg.yaml
|
params:
seed: 42
# environment wrapper clipping
env:
clip_actions: 1.0
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [64, 64]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: False # flag which sets whether to load the checkpoint
load_path: '' # path to the checkpoint to load
config:
name: quadcopter_direct
env_name: rlgpu
device: 'cuda:0'
device_name: 'cuda:0'
multi_gpu: False
ppo: True
mixed_precision: False
normalize_input: True
normalize_value: True
value_bootstrap: True
num_actors: -1 # configured from the script (based on num_envs)
reward_shaper:
scale_value: 0.01
normalize_advantage: True
gamma: 0.99
tau: 0.95
learning_rate: 5e-4
lr_schedule: adaptive
schedule_type: legacy
kl_threshold: 0.016
score_to_win: 20000
max_epochs: 200
save_best_after: 100
save_frequency: 25
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 24
minibatch_size: 24576
mini_epochs: 5
critic_coef: 2
clip_value: True
seq_length: 4
bounds_loss_coef: 0.0001
| 1,562 |
YAML
| 19.298701 | 73 | 0.608835 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/cartpole/cartpole_camera_env.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import gymnasium as gym
import math
import numpy as np
import torch
from collections.abc import Sequence
from omni.isaac.lab_assets.cartpole import CARTPOLE_CFG
import omni.isaac.lab.sim as sim_utils
from omni.isaac.lab.assets import Articulation, ArticulationCfg
from omni.isaac.lab.envs import DirectRLEnv, DirectRLEnvCfg, ViewerCfg
from omni.isaac.lab.scene import InteractiveSceneCfg
from omni.isaac.lab.sensors import TiledCamera, TiledCameraCfg
from omni.isaac.lab.sim import SimulationCfg
from omni.isaac.lab.sim.spawners.from_files import GroundPlaneCfg, spawn_ground_plane
from omni.isaac.lab.utils import configclass
from omni.isaac.lab.utils.math import sample_uniform
@configclass
class CartpoleRGBCameraEnvCfg(DirectRLEnvCfg):
# simulation
sim: SimulationCfg = SimulationCfg(dt=1 / 120)
# robot
robot_cfg: ArticulationCfg = CARTPOLE_CFG.replace(prim_path="/World/envs/env_.*/Robot")
cart_dof_name = "slider_to_cart"
pole_dof_name = "cart_to_pole"
# camera
tiled_camera: TiledCameraCfg = TiledCameraCfg(
prim_path="/World/envs/env_.*/Camera",
offset=TiledCameraCfg.OffsetCfg(pos=(-7.0, 0.0, 3.0), rot=(0.9945, 0.0, 0.1045, 0.0), convention="world"),
data_types=["rgb"],
spawn=sim_utils.PinholeCameraCfg(
focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 20.0)
),
width=80,
height=80,
)
# change viewer settings
viewer = ViewerCfg(eye=(20.0, 20.0, 20.0))
# scene
scene: InteractiveSceneCfg = InteractiveSceneCfg(num_envs=256, env_spacing=20.0, replicate_physics=True)
# env
decimation = 2
episode_length_s = 5.0
action_scale = 100.0 # [N]
num_actions = 1
num_channels = 3
num_observations = num_channels * tiled_camera.height * tiled_camera.width
num_states = 0
# reset
max_cart_pos = 3.0 # the cart is reset if it exceeds that position [m]
initial_pole_angle_range = [-0.125, 0.125] # the range in which the pole angle is sampled from on reset [rad]
# reward scales
rew_scale_alive = 1.0
rew_scale_terminated = -2.0
rew_scale_pole_pos = -1.0
rew_scale_cart_vel = -0.01
rew_scale_pole_vel = -0.005
class CartpoleDepthCameraEnvCfg(CartpoleRGBCameraEnvCfg):
# camera
tiled_camera: TiledCameraCfg = TiledCameraCfg(
prim_path="/World/envs/env_.*/Camera",
offset=TiledCameraCfg.OffsetCfg(pos=(-7.0, 0.0, 3.0), rot=(0.9945, 0.0, 0.1045, 0.0), convention="world"),
data_types=["depth"],
spawn=sim_utils.PinholeCameraCfg(
focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 20.0)
),
width=80,
height=80,
)
# env
num_channels = 1
num_observations = num_channels * tiled_camera.height * tiled_camera.width
class CartpoleCameraEnv(DirectRLEnv):
cfg: CartpoleRGBCameraEnvCfg | CartpoleDepthCameraEnvCfg
def __init__(
self, cfg: CartpoleRGBCameraEnvCfg | CartpoleDepthCameraEnvCfg, render_mode: str | None = None, **kwargs
):
super().__init__(cfg, render_mode, **kwargs)
self._cart_dof_idx, _ = self._cartpole.find_joints(self.cfg.cart_dof_name)
self._pole_dof_idx, _ = self._cartpole.find_joints(self.cfg.pole_dof_name)
self.action_scale = self.cfg.action_scale
self.joint_pos = self._cartpole.data.joint_pos
self.joint_vel = self._cartpole.data.joint_vel
if len(self.cfg.tiled_camera.data_types) != 1:
raise ValueError(
"The Cartpole camera environment only supports one image type at a time but the following were"
f" provided: {self.cfg.tiled_camera.data_types}"
)
def close(self):
"""Cleanup for the environment."""
super().close()
def _configure_gym_env_spaces(self):
"""Configure the action and observation spaces for the Gym environment."""
# observation space (unbounded since we don't impose any limits)
self.num_actions = self.cfg.num_actions
self.num_observations = self.cfg.num_observations
self.num_states = self.cfg.num_states
# set up spaces
self.single_observation_space = gym.spaces.Dict()
self.single_observation_space["policy"] = gym.spaces.Box(
low=-np.inf,
high=np.inf,
shape=(self.cfg.tiled_camera.height, self.cfg.tiled_camera.width, self.cfg.num_channels),
)
if self.num_states > 0:
self.single_observation_space["critic"] = gym.spaces.Box(
low=-np.inf,
high=np.inf,
shape=(self.cfg.tiled_camera.height, self.cfg.tiled_camera.width, self.cfg.num_channels),
)
self.single_action_space = gym.spaces.Box(low=-np.inf, high=np.inf, shape=(self.num_actions,))
# batch the spaces for vectorized environments
self.observation_space = gym.vector.utils.batch_space(self.single_observation_space, self.num_envs)
self.action_space = gym.vector.utils.batch_space(self.single_action_space, self.num_envs)
# RL specifics
self.actions = torch.zeros(self.num_envs, self.num_actions, device=self.sim.device)
def _setup_scene(self):
"""Setup the scene with the cartpole and camera."""
self._cartpole = Articulation(self.cfg.robot_cfg)
self._tiled_camera = TiledCamera(self.cfg.tiled_camera)
# add ground plane
spawn_ground_plane(prim_path="/World/ground", cfg=GroundPlaneCfg(size=(500, 500)))
# clone, filter, and replicate
self.scene.clone_environments(copy_from_source=False)
self.scene.filter_collisions(global_prim_paths=[])
# add articultion and sensors to scene
self.scene.articulations["cartpole"] = self._cartpole
self.scene.sensors["tiled_camera"] = self._tiled_camera
# add lights
light_cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75))
light_cfg.func("/World/Light", light_cfg)
def _pre_physics_step(self, actions: torch.Tensor) -> None:
self.actions = self.action_scale * actions.clone()
def _apply_action(self) -> None:
self._cartpole.set_joint_effort_target(self.actions, joint_ids=self._cart_dof_idx)
def _get_observations(self) -> dict:
data_type = "rgb" if "rgb" in self.cfg.tiled_camera.data_types else "depth"
observations = {"policy": self._tiled_camera.data.output[data_type].clone()}
return observations
def _get_rewards(self) -> torch.Tensor:
total_reward = compute_rewards(
self.cfg.rew_scale_alive,
self.cfg.rew_scale_terminated,
self.cfg.rew_scale_pole_pos,
self.cfg.rew_scale_cart_vel,
self.cfg.rew_scale_pole_vel,
self.joint_pos[:, self._pole_dof_idx[0]],
self.joint_vel[:, self._pole_dof_idx[0]],
self.joint_pos[:, self._cart_dof_idx[0]],
self.joint_vel[:, self._cart_dof_idx[0]],
self.reset_terminated,
)
return total_reward
def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]:
self.joint_pos = self._cartpole.data.joint_pos
self.joint_vel = self._cartpole.data.joint_vel
time_out = self.episode_length_buf >= self.max_episode_length - 1
out_of_bounds = torch.any(torch.abs(self.joint_pos[:, self._cart_dof_idx]) > self.cfg.max_cart_pos, dim=1)
out_of_bounds = out_of_bounds | torch.any(torch.abs(self.joint_pos[:, self._pole_dof_idx]) > math.pi / 2, dim=1)
return out_of_bounds, time_out
def _reset_idx(self, env_ids: Sequence[int] | None):
if env_ids is None:
env_ids = self._cartpole._ALL_INDICES
super()._reset_idx(env_ids)
joint_pos = self._cartpole.data.default_joint_pos[env_ids]
joint_pos[:, self._pole_dof_idx] += sample_uniform(
self.cfg.initial_pole_angle_range[0] * math.pi,
self.cfg.initial_pole_angle_range[1] * math.pi,
joint_pos[:, self._pole_dof_idx].shape,
joint_pos.device,
)
joint_vel = self._cartpole.data.default_joint_vel[env_ids]
default_root_state = self._cartpole.data.default_root_state[env_ids]
default_root_state[:, :3] += self.scene.env_origins[env_ids]
self.joint_pos[env_ids] = joint_pos
self.joint_vel[env_ids] = joint_vel
self._cartpole.write_root_pose_to_sim(default_root_state[:, :7], env_ids)
self._cartpole.write_root_velocity_to_sim(default_root_state[:, 7:], env_ids)
self._cartpole.write_joint_state_to_sim(joint_pos, joint_vel, None, env_ids)
@torch.jit.script
def compute_rewards(
rew_scale_alive: float,
rew_scale_terminated: float,
rew_scale_pole_pos: float,
rew_scale_cart_vel: float,
rew_scale_pole_vel: float,
pole_pos: torch.Tensor,
pole_vel: torch.Tensor,
cart_pos: torch.Tensor,
cart_vel: torch.Tensor,
reset_terminated: torch.Tensor,
):
rew_alive = rew_scale_alive * (1.0 - reset_terminated.float())
rew_termination = rew_scale_terminated * reset_terminated.float()
rew_pole_pos = rew_scale_pole_pos * torch.sum(torch.square(pole_pos).unsqueeze(dim=1), dim=-1)
rew_cart_vel = rew_scale_cart_vel * torch.sum(torch.abs(cart_vel).unsqueeze(dim=1), dim=-1)
rew_pole_vel = rew_scale_pole_vel * torch.sum(torch.abs(pole_vel).unsqueeze(dim=1), dim=-1)
total_reward = rew_alive + rew_termination + rew_pole_pos + rew_cart_vel + rew_pole_vel
return total_reward
| 9,829 |
Python
| 38.959349 | 120 | 0.64676 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/cartpole/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Cartpole balancing environment.
"""
import gymnasium as gym
from . import agents
from .cartpole_camera_env import CartpoleCameraEnv, CartpoleDepthCameraEnvCfg, CartpoleRGBCameraEnvCfg
from .cartpole_env import CartpoleEnv, CartpoleEnvCfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Cartpole-Direct-v0",
entry_point="omni.isaac.lab_tasks.direct.cartpole:CartpoleEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": CartpoleEnvCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.CartpolePPORunnerCfg,
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
"sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml",
},
)
gym.register(
id="Isaac-Cartpole-RGB-Camera-Direct-v0",
entry_point="omni.isaac.lab_tasks.direct.cartpole:CartpoleCameraEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": CartpoleRGBCameraEnvCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_camera_ppo_cfg.yaml",
},
)
gym.register(
id="Isaac-Cartpole-Depth-Camera-Direct-v0",
entry_point="omni.isaac.lab_tasks.direct.cartpole:CartpoleCameraEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": CartpoleDepthCameraEnvCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_camera_ppo_cfg.yaml",
},
)
| 1,588 |
Python
| 29.557692 | 102 | 0.688287 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/cartpole/cartpole_env.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import math
import torch
from collections.abc import Sequence
from omni.isaac.lab_assets.cartpole import CARTPOLE_CFG
import omni.isaac.lab.sim as sim_utils
from omni.isaac.lab.assets import Articulation, ArticulationCfg
from omni.isaac.lab.envs import DirectRLEnv, DirectRLEnvCfg
from omni.isaac.lab.scene import InteractiveSceneCfg
from omni.isaac.lab.sim import SimulationCfg
from omni.isaac.lab.sim.spawners.from_files import GroundPlaneCfg, spawn_ground_plane
from omni.isaac.lab.utils import configclass
from omni.isaac.lab.utils.math import sample_uniform
@configclass
class CartpoleEnvCfg(DirectRLEnvCfg):
# simulation
sim: SimulationCfg = SimulationCfg(dt=1 / 120)
# robot
robot_cfg: ArticulationCfg = CARTPOLE_CFG.replace(prim_path="/World/envs/env_.*/Robot")
cart_dof_name = "slider_to_cart"
pole_dof_name = "cart_to_pole"
# scene
scene: InteractiveSceneCfg = InteractiveSceneCfg(num_envs=4096, env_spacing=4.0, replicate_physics=True)
# env
decimation = 2
episode_length_s = 5.0
action_scale = 100.0 # [N]
num_actions = 1
num_observations = 4
num_states = 0
# reset
max_cart_pos = 3.0 # the cart is reset if it exceeds that position [m]
initial_pole_angle_range = [-0.25, 0.25] # the range in which the pole angle is sampled from on reset [rad]
# reward scales
rew_scale_alive = 1.0
rew_scale_terminated = -2.0
rew_scale_pole_pos = -1.0
rew_scale_cart_vel = -0.01
rew_scale_pole_vel = -0.005
class CartpoleEnv(DirectRLEnv):
cfg: CartpoleEnvCfg
def __init__(self, cfg: CartpoleEnvCfg, render_mode: str | None = None, **kwargs):
super().__init__(cfg, render_mode, **kwargs)
self._cart_dof_idx, _ = self.cartpole.find_joints(self.cfg.cart_dof_name)
self._pole_dof_idx, _ = self.cartpole.find_joints(self.cfg.pole_dof_name)
self.action_scale = self.cfg.action_scale
self.joint_pos = self.cartpole.data.joint_pos
self.joint_vel = self.cartpole.data.joint_vel
def _setup_scene(self):
self.cartpole = Articulation(self.cfg.robot_cfg)
# add ground plane
spawn_ground_plane(prim_path="/World/ground", cfg=GroundPlaneCfg())
# clone, filter, and replicate
self.scene.clone_environments(copy_from_source=False)
self.scene.filter_collisions(global_prim_paths=[])
# add articultion to scene
self.scene.articulations["cartpole"] = self.cartpole
# add lights
light_cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75))
light_cfg.func("/World/Light", light_cfg)
def _pre_physics_step(self, actions: torch.Tensor) -> None:
self.actions = self.action_scale * actions.clone()
def _apply_action(self) -> None:
self.cartpole.set_joint_effort_target(self.actions, joint_ids=self._cart_dof_idx)
def _get_observations(self) -> dict:
obs = torch.cat(
(
self.joint_pos[:, self._pole_dof_idx[0]].unsqueeze(dim=1),
self.joint_vel[:, self._pole_dof_idx[0]].unsqueeze(dim=1),
self.joint_pos[:, self._cart_dof_idx[0]].unsqueeze(dim=1),
self.joint_vel[:, self._cart_dof_idx[0]].unsqueeze(dim=1),
),
dim=-1,
)
observations = {"policy": obs}
return observations
def _get_rewards(self) -> torch.Tensor:
total_reward = compute_rewards(
self.cfg.rew_scale_alive,
self.cfg.rew_scale_terminated,
self.cfg.rew_scale_pole_pos,
self.cfg.rew_scale_cart_vel,
self.cfg.rew_scale_pole_vel,
self.joint_pos[:, self._pole_dof_idx[0]],
self.joint_vel[:, self._pole_dof_idx[0]],
self.joint_pos[:, self._cart_dof_idx[0]],
self.joint_vel[:, self._cart_dof_idx[0]],
self.reset_terminated,
)
return total_reward
def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]:
self.joint_pos = self.cartpole.data.joint_pos
self.joint_vel = self.cartpole.data.joint_vel
time_out = self.episode_length_buf >= self.max_episode_length - 1
out_of_bounds = torch.any(torch.abs(self.joint_pos[:, self._cart_dof_idx]) > self.cfg.max_cart_pos, dim=1)
out_of_bounds = out_of_bounds | torch.any(torch.abs(self.joint_pos[:, self._pole_dof_idx]) > math.pi / 2, dim=1)
return out_of_bounds, time_out
def _reset_idx(self, env_ids: Sequence[int] | None):
if env_ids is None:
env_ids = self.cartpole._ALL_INDICES
super()._reset_idx(env_ids)
joint_pos = self.cartpole.data.default_joint_pos[env_ids]
joint_pos[:, self._pole_dof_idx] += sample_uniform(
self.cfg.initial_pole_angle_range[0] * math.pi,
self.cfg.initial_pole_angle_range[1] * math.pi,
joint_pos[:, self._pole_dof_idx].shape,
joint_pos.device,
)
joint_vel = self.cartpole.data.default_joint_vel[env_ids]
default_root_state = self.cartpole.data.default_root_state[env_ids]
default_root_state[:, :3] += self.scene.env_origins[env_ids]
self.joint_pos[env_ids] = joint_pos
self.joint_vel[env_ids] = joint_vel
self.cartpole.write_root_pose_to_sim(default_root_state[:, :7], env_ids)
self.cartpole.write_root_velocity_to_sim(default_root_state[:, 7:], env_ids)
self.cartpole.write_joint_state_to_sim(joint_pos, joint_vel, None, env_ids)
@torch.jit.script
def compute_rewards(
rew_scale_alive: float,
rew_scale_terminated: float,
rew_scale_pole_pos: float,
rew_scale_cart_vel: float,
rew_scale_pole_vel: float,
pole_pos: torch.Tensor,
pole_vel: torch.Tensor,
cart_pos: torch.Tensor,
cart_vel: torch.Tensor,
reset_terminated: torch.Tensor,
):
rew_alive = rew_scale_alive * (1.0 - reset_terminated.float())
rew_termination = rew_scale_terminated * reset_terminated.float()
rew_pole_pos = rew_scale_pole_pos * torch.sum(torch.square(pole_pos).unsqueeze(dim=1), dim=-1)
rew_cart_vel = rew_scale_cart_vel * torch.sum(torch.abs(cart_vel).unsqueeze(dim=1), dim=-1)
rew_pole_vel = rew_scale_pole_vel * torch.sum(torch.abs(pole_vel).unsqueeze(dim=1), dim=-1)
total_reward = rew_alive + rew_termination + rew_pole_pos + rew_cart_vel + rew_pole_vel
return total_reward
| 6,598 |
Python
| 37.590643 | 120 | 0.642316 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/cartpole/agents/rsl_rl_ppo_cfg.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.lab.utils import configclass
from omni.isaac.lab_tasks.utils.wrappers.rsl_rl import (
RslRlOnPolicyRunnerCfg,
RslRlPpoActorCriticCfg,
RslRlPpoAlgorithmCfg,
)
@configclass
class CartpolePPORunnerCfg(RslRlOnPolicyRunnerCfg):
num_steps_per_env = 16
max_iterations = 150
save_interval = 50
experiment_name = "cartpole_direct"
empirical_normalization = False
policy = RslRlPpoActorCriticCfg(
init_noise_std=1.0,
actor_hidden_dims=[32, 32],
critic_hidden_dims=[32, 32],
activation="elu",
)
algorithm = RslRlPpoAlgorithmCfg(
value_loss_coef=1.0,
use_clipped_value_loss=True,
clip_param=0.2,
entropy_coef=0.005,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=1.0e-3,
schedule="adaptive",
gamma=0.99,
lam=0.95,
desired_kl=0.01,
max_grad_norm=1.0,
)
| 1,072 |
Python
| 24.547618 | 60 | 0.64459 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/cartpole/agents/rl_games_camera_ppo_cfg.yaml
|
params:
seed: 42
# environment wrapper clipping
env:
# added to the wrapper
clip_observations: 5.0
# can make custom wrapper?
clip_actions: 1.0
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
# doesn't have this fine grained control but made it close
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
cnn:
type: conv2d
activation: relu
initializer:
name: default
regularizer:
name: None
convs:
- filters: 32
kernel_size: 8
strides: 4
padding: 0
- filters: 64
kernel_size: 4
strides: 2
padding: 0
- filters: 64
kernel_size: 3
strides: 1
padding: 0
mlp:
units: [512]
activation: elu
initializer:
name: default
load_checkpoint: False # flag which sets whether to load the checkpoint
load_path: '' # path to the checkpoint to load
config:
name: cartpole_camera_direct
env_name: rlgpu
device: 'cuda:0'
device_name: 'cuda:0'
multi_gpu: False
ppo: True
mixed_precision: False
normalize_input: False
normalize_value: True
num_actors: -1 # configured from the script (based on num_envs)
reward_shaper:
scale_value: 1.0
normalize_advantage: True
gamma: 0.99
tau : 0.95
learning_rate: 1e-4
lr_schedule: adaptive
kl_threshold: 0.008
score_to_win: 20000
max_epochs: 500
save_best_after: 50
save_frequency: 25
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 64
minibatch_size: 2048
mini_epochs: 4
critic_coef: 2
clip_value: True
seq_length: 4
bounds_loss_coef: 0.0001
| 2,015 |
YAML
| 20 | 73 | 0.580645 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/cartpole/agents/skrl_ppo_cfg.yaml
|
seed: 42
# Models are instantiated using skrl's model instantiator utility
# https://skrl.readthedocs.io/en/latest/api/utils/model_instantiators.html
models:
separate: False
policy: # see skrl.utils.model_instantiators.torch.gaussian_model for parameter details
clip_actions: True
clip_log_std: True
initial_log_std: 0
min_log_std: -20.0
max_log_std: 2.0
input_shape: "Shape.STATES"
hiddens: [32, 32]
hidden_activation: ["elu", "elu"]
output_shape: "Shape.ACTIONS"
output_activation: "tanh"
output_scale: 1.0
value: # see skrl.utils.model_instantiators.torch.deterministic_model for parameter details
clip_actions: False
input_shape: "Shape.STATES"
hiddens: [32, 32]
hidden_activation: ["elu", "elu"]
output_shape: "Shape.ONE"
output_activation: ""
output_scale: 1.0
# PPO agent configuration (field names are from PPO_DEFAULT_CONFIG)
# https://skrl.readthedocs.io/en/latest/api/agents/ppo.html
agent:
rollouts: 16
learning_epochs: 8
mini_batches: 1
discount_factor: 0.99
lambda: 0.95
learning_rate: 3.e-4
learning_rate_scheduler: "KLAdaptiveLR"
learning_rate_scheduler_kwargs:
kl_threshold: 0.008
state_preprocessor: "RunningStandardScaler"
state_preprocessor_kwargs: null
value_preprocessor: "RunningStandardScaler"
value_preprocessor_kwargs: null
random_timesteps: 0
learning_starts: 0
grad_norm_clip: 1.0
ratio_clip: 0.2
value_clip: 0.2
clip_predicted_values: True
entropy_loss_scale: 0.0
value_loss_scale: 2.0
kl_threshold: 0
rewards_shaper_scale: 1.0
# logging and checkpoint
experiment:
directory: "cartpole_direct"
experiment_name: ""
write_interval: 16
checkpoint_interval: 80
# Sequential trainer
# https://skrl.readthedocs.io/en/latest/api/trainers/sequential.html
trainer:
timesteps: 1600
environment_info: "log"
| 1,882 |
YAML
| 26.691176 | 94 | 0.712009 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/cartpole/agents/sb3_ppo_cfg.yaml
|
# Reference: https://github.com/DLR-RM/rl-baselines3-zoo/blob/master/hyperparams/ppo.yml#L32
seed: 42
n_timesteps: !!float 1e6
policy: 'MlpPolicy'
n_steps: 16
batch_size: 4096
gae_lambda: 0.95
gamma: 0.99
n_epochs: 20
ent_coef: 0.01
learning_rate: !!float 3e-4
clip_range: !!float 0.2
policy_kwargs: "dict(
activation_fn=nn.ELU,
net_arch=[32, 32],
squash_output=False,
)"
vf_coef: 1.0
max_grad_norm: 1.0
device: "cuda:0"
| 492 |
YAML
| 21.40909 | 92 | 0.611789 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/cartpole/agents/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from . import rsl_rl_ppo_cfg # noqa: F401, F403
| 176 |
Python
| 24.285711 | 60 | 0.721591 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/cartpole/agents/rl_games_ppo_cfg.yaml
|
params:
seed: 42
# environment wrapper clipping
env:
# added to the wrapper
clip_observations: 5.0
# can make custom wrapper?
clip_actions: 1.0
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
# doesn't have this fine grained control but made it close
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [32, 32]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: False # flag which sets whether to load the checkpoint
load_path: '' # path to the checkpoint to load
config:
name: cartpole_direct
env_name: rlgpu
device: 'cuda:0'
device_name: 'cuda:0'
multi_gpu: False
ppo: True
mixed_precision: False
normalize_input: True
normalize_value: True
num_actors: -1 # configured from the script (based on num_envs)
reward_shaper:
scale_value: 0.1
normalize_advantage: True
gamma: 0.99
tau : 0.95
learning_rate: 5e-4
lr_schedule: adaptive
kl_threshold: 0.008
score_to_win: 20000
max_epochs: 150
save_best_after: 50
save_frequency: 25
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 32
minibatch_size: 16384
mini_epochs: 8
critic_coef: 4
clip_value: True
seq_length: 4
bounds_loss_coef: 0.0001
| 1,653 |
YAML
| 19.936709 | 73 | 0.61222 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/humanoid/humanoid_env.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from omni.isaac.lab_assets import HUMANOID_CFG
import omni.isaac.lab.sim as sim_utils
from omni.isaac.lab.assets import ArticulationCfg
from omni.isaac.lab.envs import DirectRLEnvCfg
from omni.isaac.lab.scene import InteractiveSceneCfg
from omni.isaac.lab.sim import SimulationCfg
from omni.isaac.lab.terrains import TerrainImporterCfg
from omni.isaac.lab.utils import configclass
from omni.isaac.lab_tasks.direct.locomotion.locomotion_env import LocomotionEnv
@configclass
class HumanoidEnvCfg(DirectRLEnvCfg):
# simulation
sim: SimulationCfg = SimulationCfg(dt=1 / 120)
terrain = TerrainImporterCfg(
prim_path="/World/ground",
terrain_type="plane",
collision_group=-1,
physics_material=sim_utils.RigidBodyMaterialCfg(
friction_combine_mode="average",
restitution_combine_mode="average",
static_friction=1.0,
dynamic_friction=1.0,
restitution=0.0,
),
debug_vis=False,
)
# scene
scene: InteractiveSceneCfg = InteractiveSceneCfg(num_envs=4096, env_spacing=4.0, replicate_physics=True)
# robot
robot: ArticulationCfg = HUMANOID_CFG.replace(prim_path="/World/envs/env_.*/Robot")
joint_gears: list = [
67.5000, # lower_waist
67.5000, # lower_waist
67.5000, # right_upper_arm
67.5000, # right_upper_arm
67.5000, # left_upper_arm
67.5000, # left_upper_arm
67.5000, # pelvis
45.0000, # right_lower_arm
45.0000, # left_lower_arm
45.0000, # right_thigh: x
135.0000, # right_thigh: y
45.0000, # right_thigh: z
45.0000, # left_thigh: x
135.0000, # left_thigh: y
45.0000, # left_thigh: z
90.0000, # right_knee
90.0000, # left_knee
22.5, # right_foot
22.5, # right_foot
22.5, # left_foot
22.5, # left_foot
]
# env
episode_length_s = 15.0
decimation = 2
action_scale = 1.0
num_actions = 21
num_observations = 75
num_states = 0
heading_weight: float = 0.5
up_weight: float = 0.1
energy_cost_scale: float = 0.05
actions_cost_scale: float = 0.01
alive_reward_scale: float = 2.0
dof_vel_scale: float = 0.1
death_cost: float = -1.0
termination_height: float = 0.8
angular_velocity_scale: float = 0.25
contact_force_scale: float = 0.01
class HumanoidEnv(LocomotionEnv):
cfg: HumanoidEnvCfg
def __init__(self, cfg: HumanoidEnvCfg, render_mode: str | None = None, **kwargs):
super().__init__(cfg, render_mode, **kwargs)
| 2,796 |
Python
| 28.135416 | 108 | 0.631617 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/humanoid/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Humanoid locomotion environment.
"""
import gymnasium as gym
from . import agents
from .humanoid_env import HumanoidEnv, HumanoidEnvCfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Humanoid-Direct-v0",
entry_point="omni.isaac.lab_tasks.direct.humanoid:HumanoidEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": HumanoidEnvCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.HumanoidPPORunnerCfg,
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
},
)
| 752 |
Python
| 24.099999 | 79 | 0.68617 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/humanoid/agents/rsl_rl_ppo_cfg.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.lab.utils import configclass
from omni.isaac.lab_tasks.utils.wrappers.rsl_rl import (
RslRlOnPolicyRunnerCfg,
RslRlPpoActorCriticCfg,
RslRlPpoAlgorithmCfg,
)
@configclass
class HumanoidPPORunnerCfg(RslRlOnPolicyRunnerCfg):
num_steps_per_env = 32
max_iterations = 1000
save_interval = 50
experiment_name = "humanoid_direct"
empirical_normalization = True
policy = RslRlPpoActorCriticCfg(
init_noise_std=1.0,
actor_hidden_dims=[400, 200, 100],
critic_hidden_dims=[400, 200, 100],
activation="elu",
)
algorithm = RslRlPpoAlgorithmCfg(
value_loss_coef=1.0,
use_clipped_value_loss=True,
clip_param=0.2,
entropy_coef=0.0,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=1.0e-4,
schedule="adaptive",
gamma=0.99,
lam=0.95,
desired_kl=0.008,
max_grad_norm=1.0,
)
| 1,085 |
Python
| 24.857142 | 60 | 0.645161 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/humanoid/agents/skrl_ppo_cfg.yaml
|
seed: 42
# Models are instantiated using skrl's model instantiator utility
# https://skrl.readthedocs.io/en/latest/api/utils/model_instantiators.html
models:
separate: False
policy: # see skrl.utils.model_instantiators.torch.gaussian_model for parameter details
clip_actions: True
clip_log_std: True
initial_log_std: 0
min_log_std: -20.0
max_log_std: 2.0
input_shape: "Shape.STATES"
hiddens: [400, 200, 100]
hidden_activation: ["elu", "elu", "elu"]
output_shape: "Shape.ACTIONS"
output_activation: "tanh"
output_scale: 1.0
value: # see skrl.utils.model_instantiators.torch.deterministic_model for parameter details
clip_actions: False
input_shape: "Shape.STATES"
hiddens: [400, 200, 100]
hidden_activation: ["elu", "elu", "elu"]
output_shape: "Shape.ONE"
output_activation: ""
output_scale: 1.0
# PPO agent configuration (field names are from PPO_DEFAULT_CONFIG)
# https://skrl.readthedocs.io/en/latest/api/agents/ppo.html
agent:
rollouts: 32
learning_epochs: 5
mini_batches: 4
discount_factor: 0.99
lambda: 0.95
learning_rate: 1.e-4
learning_rate_scheduler: "KLAdaptiveLR"
learning_rate_scheduler_kwargs:
kl_threshold: 0.008
state_preprocessor: "RunningStandardScaler"
state_preprocessor_kwargs: null
value_preprocessor: "RunningStandardScaler"
value_preprocessor_kwargs: null
random_timesteps: 0
learning_starts: 0
grad_norm_clip: 1.0
ratio_clip: 0.2
value_clip: 0.2
clip_predicted_values: True
entropy_loss_scale: 0.0
value_loss_scale: 2.0
kl_threshold: 0
rewards_shaper_scale: 0.01
# logging and checkpoint
experiment:
directory: "humanoid_direct"
experiment_name: ""
write_interval: 160
checkpoint_interval: 1600
# Sequential trainer
# https://skrl.readthedocs.io/en/latest/api/trainers/sequential.html
trainer:
timesteps: 32000
environment_info: "log"
| 1,915 |
YAML
| 27.17647 | 94 | 0.710705 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/humanoid/agents/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from . import rsl_rl_ppo_cfg
| 156 |
Python
| 21.428568 | 60 | 0.737179 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/humanoid/agents/rl_games_ppo_cfg.yaml
|
params:
seed: 42
# environment wrapper clipping
env:
clip_actions: 1.0
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [400, 200, 100]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: False # flag which sets whether to load the checkpoint
load_path: '' # path to the checkpoint to load
config:
name: humanoid_direct
env_name: rlgpu
device: 'cuda:0'
device_name: 'cuda:0'
multi_gpu: False
ppo: True
mixed_precision: True
normalize_input: True
normalize_value: True
value_bootstrap: True
num_actors: -1 # configured from the script (based on num_envs)
reward_shaper:
scale_value: 0.01
normalize_advantage: True
gamma: 0.99
tau: 0.95
learning_rate: 5e-4
lr_schedule: adaptive
kl_threshold: 0.008
score_to_win: 20000
max_epochs: 1000
save_best_after: 100
save_frequency: 50
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 32
minibatch_size: 32768
mini_epochs: 5
critic_coef: 4
clip_value: True
seq_length: 4
bounds_loss_coef: 0.0001
| 1,541 |
YAML
| 19.289473 | 73 | 0.607398 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/shadow_hand/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Cartpole balancing environment.
"""
import gymnasium as gym
from . import agents
from .shadow_hand_env import ShadowHandEnv
from .shadow_hand_env_cfg import ShadowHandEnvCfg, ShadowHandOpenAIEnvCfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Shadow-Hand-Direct-v0",
entry_point="omni.isaac.lab_tasks.direct.shadow_hand:ShadowHandEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": ShadowHandEnvCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.ShadowHandPPORunnerCfg,
},
)
gym.register(
id="Isaac-Shadow-Hand-OpenAI-FF-Direct-v0",
entry_point="omni.isaac.lab_tasks.direct.shadow_hand:ShadowHandEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": ShadowHandOpenAIEnvCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_ff_cfg.yaml",
"rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.ShadowHandAsymFFPPORunnerCfg,
},
)
gym.register(
id="Isaac-Shadow-Hand-OpenAI-LSTM-Direct-v0",
entry_point="omni.isaac.lab_tasks.direct.shadow_hand:ShadowHandEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": ShadowHandOpenAIEnvCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_lstm_cfg.yaml",
},
)
| 1,496 |
Python
| 28.352941 | 85 | 0.691176 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/shadow_hand/shadow_hand_env.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import numpy as np
import torch
from collections.abc import Sequence
import omni.isaac.lab.sim as sim_utils
from omni.isaac.lab.assets import Articulation, RigidObject
from omni.isaac.lab.envs import DirectRLEnv
from omni.isaac.lab.markers import VisualizationMarkers
from omni.isaac.lab.sim.spawners.from_files import GroundPlaneCfg, spawn_ground_plane
from omni.isaac.lab.utils.math import quat_conjugate, quat_from_angle_axis, quat_mul, sample_uniform, saturate
from .shadow_hand_env_cfg import ShadowHandEnvCfg
class ShadowHandEnv(DirectRLEnv):
cfg: ShadowHandEnvCfg
def __init__(self, cfg: ShadowHandEnvCfg, render_mode: str | None = None, **kwargs):
super().__init__(cfg, render_mode, **kwargs)
self.num_hand_dofs = self.hand.num_joints
# buffers for position targets
self.hand_dof_targets = torch.zeros((self.num_envs, self.num_hand_dofs), dtype=torch.float, device=self.device)
self.prev_targets = torch.zeros((self.num_envs, self.num_hand_dofs), dtype=torch.float, device=self.device)
self.cur_targets = torch.zeros((self.num_envs, self.num_hand_dofs), dtype=torch.float, device=self.device)
# list of actuated joints
self.actuated_dof_indices = list()
for joint_name in cfg.actuated_joint_names:
self.actuated_dof_indices.append(self.hand.joint_names.index(joint_name))
self.actuated_dof_indices.sort()
# finger bodies
self.finger_bodies = list()
for body_name in self.cfg.fingertip_body_names:
self.finger_bodies.append(self.hand.body_names.index(body_name))
self.finger_bodies.sort()
self.num_fingertips = len(self.finger_bodies)
# joint limits
joint_pos_limits = self.hand.root_physx_view.get_dof_limits().to(self.device)
self.hand_dof_lower_limits = joint_pos_limits[..., 0]
self.hand_dof_upper_limits = joint_pos_limits[..., 1]
# track goal resets
self.reset_goal_buf = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device)
# used to compare object position
self.in_hand_pos = self.object.data.default_root_state[:, 0:3].clone()
self.in_hand_pos[:, 2] -= 0.04
# default goal positions
self.goal_rot = torch.zeros((self.num_envs, 4), dtype=torch.float, device=self.device)
self.goal_rot[:, 0] = 1.0
self.goal_pos = torch.zeros((self.num_envs, 3), dtype=torch.float, device=self.device)
self.goal_pos[:, :] = torch.tensor([-0.2, -0.45, 0.68], device=self.device)
# initialize goal marker
self.goal_markers = VisualizationMarkers(self.cfg.goal_object_cfg)
# track successes
self.successes = torch.zeros(self.num_envs, dtype=torch.float, device=self.device)
self.consecutive_successes = torch.zeros(1, dtype=torch.float, device=self.device)
# unit tensors
self.x_unit_tensor = torch.tensor([1, 0, 0], dtype=torch.float, device=self.device).repeat((self.num_envs, 1))
self.y_unit_tensor = torch.tensor([0, 1, 0], dtype=torch.float, device=self.device).repeat((self.num_envs, 1))
self.z_unit_tensor = torch.tensor([0, 0, 1], dtype=torch.float, device=self.device).repeat((self.num_envs, 1))
def _setup_scene(self):
# add hand, in-hand object, and goal object
self.hand = Articulation(self.cfg.robot_cfg)
self.object = RigidObject(self.cfg.object_cfg)
# add ground plane
spawn_ground_plane(prim_path="/World/ground", cfg=GroundPlaneCfg())
# clone and replicate (no need to filter for this environment)
self.scene.clone_environments(copy_from_source=False)
# add articultion to scene - we must register to scene to randomize with EventManager
self.scene.articulations["robot"] = self.hand
self.scene.rigid_objects["object"] = self.object
# add lights
light_cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75))
light_cfg.func("/World/Light", light_cfg)
def _pre_physics_step(self, actions: torch.Tensor) -> None:
self.actions = actions.clone()
def _apply_action(self) -> None:
self.cur_targets[:, self.actuated_dof_indices] = scale(
self.actions,
self.hand_dof_lower_limits[:, self.actuated_dof_indices],
self.hand_dof_upper_limits[:, self.actuated_dof_indices],
)
self.cur_targets[:, self.actuated_dof_indices] = (
self.cfg.act_moving_average * self.cur_targets[:, self.actuated_dof_indices]
+ (1.0 - self.cfg.act_moving_average) * self.prev_targets[:, self.actuated_dof_indices]
)
self.cur_targets[:, self.actuated_dof_indices] = saturate(
self.cur_targets[:, self.actuated_dof_indices],
self.hand_dof_lower_limits[:, self.actuated_dof_indices],
self.hand_dof_upper_limits[:, self.actuated_dof_indices],
)
self.prev_targets[:, self.actuated_dof_indices] = self.cur_targets[:, self.actuated_dof_indices]
self.hand.set_joint_position_target(
self.cur_targets[:, self.actuated_dof_indices], joint_ids=self.actuated_dof_indices
)
def _get_observations(self) -> dict:
if self.cfg.asymmetric_obs:
self.fingertip_force_sensors = self.hand.root_physx_view.get_link_incoming_joint_force()[
:, self.finger_bodies
]
if self.cfg.obs_type == "openai":
obs = self.compute_reduced_observations()
elif self.cfg.obs_type == "full":
obs = self.compute_full_observations()
else:
print("Unknown observations type!")
if self.cfg.asymmetric_obs:
states = self.compute_full_state()
observations = {"policy": obs}
if self.cfg.asymmetric_obs:
observations = {"policy": obs, "critic": states}
return observations
def _get_rewards(self) -> torch.Tensor:
(
total_reward,
self.reset_goal_buf,
self.successes[:],
self.consecutive_successes[:],
) = compute_rewards(
self.reset_buf,
self.reset_goal_buf,
self.successes,
self.consecutive_successes,
self.max_episode_length,
self.object_pos,
self.object_rot,
self.in_hand_pos,
self.goal_rot,
self.cfg.dist_reward_scale,
self.cfg.rot_reward_scale,
self.cfg.rot_eps,
self.actions,
self.cfg.action_penalty_scale,
self.cfg.success_tolerance,
self.cfg.reach_goal_bonus,
self.cfg.fall_dist,
self.cfg.fall_penalty,
self.cfg.av_factor,
)
if "log" not in self.extras:
self.extras["log"] = dict()
self.extras["log"]["consecutive_successes"] = self.consecutive_successes.mean()
# reset goals if the goal has been reached
goal_env_ids = self.reset_goal_buf.nonzero(as_tuple=False).squeeze(-1)
if len(goal_env_ids) > 0:
self._reset_target_pose(goal_env_ids)
return total_reward
def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]:
self._compute_intermediate_values()
# reset when cube has fallen
goal_dist = torch.norm(self.object_pos - self.in_hand_pos, p=2, dim=-1)
out_of_reach = goal_dist >= self.cfg.fall_dist
if self.cfg.max_consecutive_success > 0:
# Reset progress (episode length buf) on goal envs if max_consecutive_success > 0
rot_dist = rotation_distance(self.object_rot, self.goal_rot)
self.episode_length_buf = torch.where(
torch.abs(rot_dist) <= self.cfg.success_tolerance,
torch.zeros_like(self.episode_length_buf),
self.episode_length_buf,
)
max_success_reached = self.successes >= self.cfg.max_consecutive_success
time_out = self.episode_length_buf >= self.max_episode_length - 1
if self.cfg.max_consecutive_success > 0:
time_out = time_out | max_success_reached
return out_of_reach, time_out
def _reset_idx(self, env_ids: Sequence[int] | None):
if env_ids is None:
env_ids = self.hand._ALL_INDICES
# resets articulation and rigid body attributes
super()._reset_idx(env_ids)
# reset goals
self._reset_target_pose(env_ids)
# reset object
object_default_state = self.object.data.default_root_state.clone()[env_ids]
pos_noise = sample_uniform(-1.0, 1.0, (len(env_ids), 3), device=self.device)
# global object positions
object_default_state[:, 0:3] = (
object_default_state[:, 0:3] + self.cfg.reset_position_noise * pos_noise + self.scene.env_origins[env_ids]
)
rot_noise = sample_uniform(-1.0, 1.0, (len(env_ids), 2), device=self.device) # noise for X and Y rotation
object_default_state[:, 3:7] = randomize_rotation(
rot_noise[:, 0], rot_noise[:, 1], self.x_unit_tensor[env_ids], self.y_unit_tensor[env_ids]
)
object_default_state[:, 7:] = torch.zeros_like(self.object.data.default_root_state[env_ids, 7:])
self.object.write_root_state_to_sim(object_default_state, env_ids)
# reset hand
delta_max = self.hand_dof_upper_limits[env_ids] - self.hand.data.default_joint_pos[env_ids]
delta_min = self.hand_dof_lower_limits[env_ids] - self.hand.data.default_joint_pos[env_ids]
dof_pos_noise = sample_uniform(-1.0, 1.0, (len(env_ids), self.num_hand_dofs), device=self.device)
rand_delta = delta_min + (delta_max - delta_min) * 0.5 * dof_pos_noise
dof_pos = self.hand.data.default_joint_pos[env_ids] + self.cfg.reset_dof_pos_noise * rand_delta
dof_vel_noise = sample_uniform(-1.0, 1.0, (len(env_ids), self.num_hand_dofs), device=self.device)
dof_vel = self.hand.data.default_joint_vel[env_ids] + self.cfg.reset_dof_vel_noise * dof_vel_noise
self.prev_targets[env_ids] = dof_pos
self.cur_targets[env_ids] = dof_pos
self.hand_dof_targets[env_ids] = dof_pos
self.hand.set_joint_position_target(dof_pos, env_ids=env_ids)
self.hand.write_joint_state_to_sim(dof_pos, dof_vel, env_ids=env_ids)
self.successes[env_ids] = 0
self._compute_intermediate_values()
def _reset_target_pose(self, env_ids):
# reset goal rotation
rand_floats = sample_uniform(-1.0, 1.0, (len(env_ids), 2), device=self.device)
new_rot = randomize_rotation(
rand_floats[:, 0], rand_floats[:, 1], self.x_unit_tensor[env_ids], self.y_unit_tensor[env_ids]
)
# update goal pose and markers
self.goal_rot[env_ids] = new_rot
goal_pos = self.goal_pos + self.scene.env_origins
self.goal_markers.visualize(goal_pos, self.goal_rot)
self.reset_goal_buf[env_ids] = 0
def _compute_intermediate_values(self):
# data for hand
self.fingertip_pos = self.hand.data.body_pos_w[:, self.finger_bodies]
self.fingertip_rot = self.hand.data.body_quat_w[:, self.finger_bodies]
self.fingertip_pos -= self.scene.env_origins.repeat((1, self.num_fingertips)).reshape(
self.num_envs, self.num_fingertips, 3
)
self.fingertip_velocities = self.hand.data.body_vel_w[:, self.finger_bodies]
self.hand_dof_pos = self.hand.data.joint_pos
self.hand_dof_vel = self.hand.data.joint_vel
# data for object
self.object_pos = self.object.data.root_pos_w - self.scene.env_origins
self.object_rot = self.object.data.root_quat_w
self.object_velocities = self.object.data.root_vel_w
self.object_linvel = self.object.data.root_lin_vel_w
self.object_angvel = self.object.data.root_ang_vel_w
def compute_reduced_observations(self):
# Per https://arxiv.org/pdf/1808.00177.pdf Table 2
# Fingertip positions
# Object Position, but not orientation
# Relative target orientation
obs = torch.cat(
(
self.fingertip_pos.view(self.num_envs, self.num_fingertips * 3), # 0:15
self.object_pos, # 15:18
quat_mul(self.object_rot, quat_conjugate(self.goal_rot)), # 18:22
self.actions, # 22:42
),
dim=-1,
)
return obs
def compute_full_observations(self):
obs = torch.cat(
(
# hand
unscale(self.hand_dof_pos, self.hand_dof_lower_limits, self.hand_dof_upper_limits), # 0:24
self.cfg.vel_obs_scale * self.hand_dof_vel, # 24:48
# object
self.object_pos, # 48:51
self.object_rot, # 51:55
self.object_linvel, # 55:58
self.cfg.vel_obs_scale * self.object_angvel, # 58:61
# goal
self.in_hand_pos, # 61:64
self.goal_rot, # 64:68
quat_mul(self.object_rot, quat_conjugate(self.goal_rot)), # 68:72
# fingertips
self.fingertip_pos.view(self.num_envs, self.num_fingertips * 3), # 72:87
self.fingertip_rot.view(self.num_envs, self.num_fingertips * 4), # 87:107
self.fingertip_velocities.view(self.num_envs, self.num_fingertips * 6), # 107:137
# actions
self.actions, # 137:157
),
dim=-1,
)
return obs
def compute_full_state(self):
states = torch.cat(
(
# hand
unscale(self.hand_dof_pos, self.hand_dof_lower_limits, self.hand_dof_upper_limits), # 0:24
self.cfg.vel_obs_scale * self.hand_dof_vel, # 24:48
# object
self.object_pos, # 48:51
self.object_rot, # 51:55
self.object_linvel, # 55:58
self.cfg.vel_obs_scale * self.object_angvel, # 58:61
# goal
self.in_hand_pos, # 61:64
self.goal_rot, # 64:68
quat_mul(self.object_rot, quat_conjugate(self.goal_rot)), # 68:72
# fingertips
self.fingertip_pos.view(self.num_envs, self.num_fingertips * 3), # 72:87
self.fingertip_rot.view(self.num_envs, self.num_fingertips * 4), # 87:107
self.fingertip_velocities.view(self.num_envs, self.num_fingertips * 6), # 107:137
self.cfg.force_torque_obs_scale
* self.fingertip_force_sensors.view(self.num_envs, self.num_fingertips * 6), # 137:167
# actions
self.actions, # 167:187
),
dim=-1,
)
return states
@torch.jit.script
def scale(x, lower, upper):
return 0.5 * (x + 1.0) * (upper - lower) + lower
@torch.jit.script
def unscale(x, lower, upper):
return (2.0 * x - upper - lower) / (upper - lower)
@torch.jit.script
def randomize_rotation(rand0, rand1, x_unit_tensor, y_unit_tensor):
return quat_mul(
quat_from_angle_axis(rand0 * np.pi, x_unit_tensor), quat_from_angle_axis(rand1 * np.pi, y_unit_tensor)
)
@torch.jit.script
def rotation_distance(object_rot, target_rot):
# Orientation alignment for the cube in hand and goal cube
quat_diff = quat_mul(object_rot, quat_conjugate(target_rot))
return 2.0 * torch.asin(torch.clamp(torch.norm(quat_diff[:, 1:4], p=2, dim=-1), max=1.0)) # changed quat convention
@torch.jit.script
def compute_rewards(
reset_buf: torch.Tensor,
reset_goal_buf: torch.Tensor,
successes: torch.Tensor,
consecutive_successes: torch.Tensor,
max_episode_length: float,
object_pos: torch.Tensor,
object_rot: torch.Tensor,
target_pos: torch.Tensor,
target_rot: torch.Tensor,
dist_reward_scale: float,
rot_reward_scale: float,
rot_eps: float,
actions: torch.Tensor,
action_penalty_scale: float,
success_tolerance: float,
reach_goal_bonus: float,
fall_dist: float,
fall_penalty: float,
av_factor: float,
):
goal_dist = torch.norm(object_pos - target_pos, p=2, dim=-1)
rot_dist = rotation_distance(object_rot, target_rot)
dist_rew = goal_dist * dist_reward_scale
rot_rew = 1.0 / (torch.abs(rot_dist) + rot_eps) * rot_reward_scale
action_penalty = torch.sum(actions**2, dim=-1)
# Total reward is: position distance + orientation alignment + action regularization + success bonus + fall penalty
reward = dist_rew + rot_rew + action_penalty * action_penalty_scale
# Find out which envs hit the goal and update successes count
goal_resets = torch.where(torch.abs(rot_dist) <= success_tolerance, torch.ones_like(reset_goal_buf), reset_goal_buf)
successes = successes + goal_resets
# Success bonus: orientation is within `success_tolerance` of goal orientation
reward = torch.where(goal_resets == 1, reward + reach_goal_bonus, reward)
# Fall penalty: distance to the goal is larger than a threshold
reward = torch.where(goal_dist >= fall_dist, reward + fall_penalty, reward)
# Check env termination conditions, including maximum success number
resets = torch.where(goal_dist >= fall_dist, torch.ones_like(reset_buf), reset_buf)
num_resets = torch.sum(resets)
finished_cons_successes = torch.sum(successes * resets.float())
cons_successes = torch.where(
num_resets > 0,
av_factor * finished_cons_successes / num_resets + (1.0 - av_factor) * consecutive_successes,
consecutive_successes,
)
return reward, goal_resets, successes, cons_successes
| 18,039 |
Python
| 40.953488 | 120 | 0.613615 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/shadow_hand/shadow_hand_env_cfg.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.lab_assets.shadow_hand import SHADOW_HAND_CFG
import omni.isaac.lab.envs.mdp as mdp
import omni.isaac.lab.sim as sim_utils
from omni.isaac.lab.assets import ArticulationCfg, RigidObjectCfg
from omni.isaac.lab.envs import DirectRLEnvCfg
from omni.isaac.lab.managers import EventTermCfg as EventTerm
from omni.isaac.lab.managers import SceneEntityCfg
from omni.isaac.lab.markers import VisualizationMarkersCfg
from omni.isaac.lab.scene import InteractiveSceneCfg
from omni.isaac.lab.sim import PhysxCfg, SimulationCfg
from omni.isaac.lab.sim.spawners.materials.physics_materials_cfg import RigidBodyMaterialCfg
from omni.isaac.lab.utils import configclass
from omni.isaac.lab.utils.assets import ISAAC_NUCLEUS_DIR
from omni.isaac.lab.utils.noise import GaussianNoiseCfg, NoiseModelWithAdditiveBiasCfg
@configclass
class EventCfg:
"""Configuration for randomization."""
# -- robot
robot_physics_material = EventTerm(
func=mdp.randomize_rigid_body_material,
mode="reset",
params={
"asset_cfg": SceneEntityCfg("robot", body_names=".*"),
"static_friction_range": (0.7, 1.3),
"dynamic_friction_range": (1.0, 1.0),
"restitution_range": (1.0, 1.0),
"num_buckets": 250,
},
)
robot_joint_stiffness_and_damping = EventTerm(
func=mdp.randomize_actuator_gains,
mode="reset",
params={
"asset_cfg": SceneEntityCfg("robot", joint_names=".*"),
"stiffness_distribution_params": (0.75, 1.5),
"damping_distribution_params": (0.3, 3.0),
"operation": "scale",
"distribution": "log_uniform",
},
)
robot_joint_limits = EventTerm(
func=mdp.randomize_joint_parameters,
mode="reset",
params={
"asset_cfg": SceneEntityCfg("robot", joint_names=".*"),
"lower_limit_distribution_params": (0.00, 0.01),
"upper_limit_distribution_params": (0.00, 0.01),
"operation": "add",
"distribution": "gaussian",
},
)
robot_tendon_properties = EventTerm(
func=mdp.randomize_fixed_tendon_parameters,
mode="reset",
params={
"asset_cfg": SceneEntityCfg("robot", fixed_tendon_names=".*"),
"stiffness_distribution_params": (0.75, 1.5),
"damping_distribution_params": (0.3, 3.0),
"operation": "scale",
"distribution": "log_uniform",
},
)
# -- object
object_physics_material = EventTerm(
func=mdp.randomize_rigid_body_material,
mode="reset",
params={
"asset_cfg": SceneEntityCfg("object", body_names=".*"),
"static_friction_range": (0.7, 1.3),
"dynamic_friction_range": (1.0, 1.0),
"restitution_range": (1.0, 1.0),
"num_buckets": 250,
},
)
object_scale_mass = EventTerm(
func=mdp.randomize_rigid_body_mass,
mode="reset",
params={
"asset_cfg": SceneEntityCfg("object"),
"mass_distribution_params": (0.5, 1.5),
"operation": "scale",
"distribution": "uniform",
},
)
# -- scene
reset_gravity = EventTerm(
func=mdp.randomize_physics_scene_gravity,
mode="interval",
is_global_time=True,
interval_range_s=(36.0, 36.0), # time_s = num_steps * (decimation * dt)
params={
"gravity_distribution_params": ([0.0, 0.0, 0.0], [0.0, 0.0, 0.4]),
"operation": "add",
"distribution": "gaussian",
},
)
@configclass
class ShadowHandEnvCfg(DirectRLEnvCfg):
# simulation
sim: SimulationCfg = SimulationCfg(
dt=1 / 120,
physics_material=RigidBodyMaterialCfg(
static_friction=1.0,
dynamic_friction=1.0,
),
physx=PhysxCfg(
bounce_threshold_velocity=0.2,
),
)
# robot
robot_cfg: ArticulationCfg = SHADOW_HAND_CFG.replace(prim_path="/World/envs/env_.*/Robot").replace(
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 0.5),
rot=(1.0, 0.0, 0.0, 0.0),
joint_pos={".*": 0.0},
)
)
actuated_joint_names = [
"robot0_WRJ1",
"robot0_WRJ0",
"robot0_FFJ3",
"robot0_FFJ2",
"robot0_FFJ1",
"robot0_MFJ3",
"robot0_MFJ2",
"robot0_MFJ1",
"robot0_RFJ3",
"robot0_RFJ2",
"robot0_RFJ1",
"robot0_LFJ4",
"robot0_LFJ3",
"robot0_LFJ2",
"robot0_LFJ1",
"robot0_THJ4",
"robot0_THJ3",
"robot0_THJ2",
"robot0_THJ1",
"robot0_THJ0",
]
fingertip_body_names = [
"robot0_ffdistal",
"robot0_mfdistal",
"robot0_rfdistal",
"robot0_lfdistal",
"robot0_thdistal",
]
# in-hand object
object_cfg: RigidObjectCfg = RigidObjectCfg(
prim_path="/World/envs/env_.*/object",
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Blocks/DexCube/dex_cube_instanceable.usd",
rigid_props=sim_utils.RigidBodyPropertiesCfg(
kinematic_enabled=False,
disable_gravity=False,
enable_gyroscopic_forces=True,
solver_position_iteration_count=8,
solver_velocity_iteration_count=0,
sleep_threshold=0.005,
stabilization_threshold=0.0025,
max_depenetration_velocity=1000.0,
),
mass_props=sim_utils.MassPropertiesCfg(density=567.0),
),
init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, -0.39, 0.6), rot=(1.0, 0.0, 0.0, 0.0)),
)
# goal object
goal_object_cfg: VisualizationMarkersCfg = VisualizationMarkersCfg(
prim_path="/Visuals/goal_marker",
markers={
"goal": sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Blocks/DexCube/dex_cube_instanceable.usd",
scale=(1.0, 1.0, 1.0),
)
},
)
# scene
scene: InteractiveSceneCfg = InteractiveSceneCfg(num_envs=8192, env_spacing=0.75, replicate_physics=True)
# env
decimation = 2
episode_length_s = 10.0
num_actions = 20
num_observations = 157 # (full)
num_states = 0
asymmetric_obs = False
obs_type = "full"
# reset
reset_position_noise = 0.01 # range of position at reset
reset_dof_pos_noise = 0.2 # range of dof pos at reset
reset_dof_vel_noise = 0.0 # range of dof vel at reset
# reward scales
dist_reward_scale = -10.0
rot_reward_scale = 1.0
rot_eps = 0.1
action_penalty_scale = -0.0002
reach_goal_bonus = 250
fall_penalty = 0
fall_dist = 0.24
vel_obs_scale = 0.2
success_tolerance = 0.1
max_consecutive_success = 0
av_factor = 0.1
act_moving_average = 1.0
force_torque_obs_scale = 10.0
@configclass
class ShadowHandOpenAIEnvCfg(ShadowHandEnvCfg):
# simulation
sim: SimulationCfg = SimulationCfg(
dt=1 / 60,
physics_material=RigidBodyMaterialCfg(
static_friction=1.0,
dynamic_friction=1.0,
),
physx=PhysxCfg(
bounce_threshold_velocity=0.2,
gpu_max_rigid_contact_count=2**23,
gpu_max_rigid_patch_count=2**23,
),
)
# env
decimation = 3
episode_length_s = 8.0
num_actions = 20
num_observations = 42
num_states = 187
asymmetric_obs = True
obs_type = "openai"
# reset
reset_position_noise = 0.01 # range of position at reset
reset_dof_pos_noise = 0.2 # range of dof pos at reset
reset_dof_vel_noise = 0.0 # range of dof vel at reset
# reward scales
dist_reward_scale = -10.0
rot_reward_scale = 1.0
rot_eps = 0.1
action_penalty_scale = -0.0002
reach_goal_bonus = 250
fall_penalty = -50
fall_dist = 0.24
vel_obs_scale = 0.2
success_tolerance = 0.4
max_consecutive_success = 50
av_factor = 0.1
act_moving_average = 0.3
force_torque_obs_scale = 10.0
# domain randomization config
events: EventCfg = EventCfg()
# at every time-step add gaussian noise + bias. The bias is a gaussian sampled at reset
action_noise_model: NoiseModelWithAdditiveBiasCfg = NoiseModelWithAdditiveBiasCfg(
noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.05, operation="add"),
bias_noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.015, operation="abs"),
)
# at every time-step add gaussian noise + bias. The bias is a gaussian sampled at reset
observation_noise_model: NoiseModelWithAdditiveBiasCfg = NoiseModelWithAdditiveBiasCfg(
noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.002, operation="add"),
bias_noise_cfg=GaussianNoiseCfg(mean=0.0, std=0.0001, operation="abs"),
)
| 9,087 |
Python
| 32.167883 | 109 | 0.592165 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/shadow_hand/agents/rsl_rl_ppo_cfg.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.lab.utils import configclass
from omni.isaac.lab_tasks.utils.wrappers.rsl_rl import (
RslRlOnPolicyRunnerCfg,
RslRlPpoActorCriticCfg,
RslRlPpoAlgorithmCfg,
)
@configclass
class ShadowHandPPORunnerCfg(RslRlOnPolicyRunnerCfg):
num_steps_per_env = 16
max_iterations = 10000
save_interval = 250
experiment_name = "shadow_hand"
empirical_normalization = True
policy = RslRlPpoActorCriticCfg(
init_noise_std=1.0,
actor_hidden_dims=[512, 512, 256, 128],
critic_hidden_dims=[512, 512, 256, 128],
activation="elu",
)
algorithm = RslRlPpoAlgorithmCfg(
value_loss_coef=1.0,
use_clipped_value_loss=True,
clip_param=0.2,
entropy_coef=0.005,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=5.0e-4,
schedule="adaptive",
gamma=0.99,
lam=0.95,
desired_kl=0.016,
max_grad_norm=1.0,
)
@configclass
class ShadowHandAsymFFPPORunnerCfg(RslRlOnPolicyRunnerCfg):
num_steps_per_env = 16
max_iterations = 10000
save_interval = 250
experiment_name = "shadow_hand_openai_ff"
empirical_normalization = True
policy = RslRlPpoActorCriticCfg(
init_noise_std=1.0,
actor_hidden_dims=[400, 400, 200, 100],
critic_hidden_dims=[512, 512, 256, 128],
activation="elu",
)
algorithm = RslRlPpoAlgorithmCfg(
value_loss_coef=1.0,
use_clipped_value_loss=True,
clip_param=0.2,
entropy_coef=0.005,
num_learning_epochs=4,
num_mini_batches=4,
learning_rate=5.0e-4,
schedule="adaptive",
gamma=0.99,
lam=0.95,
desired_kl=0.01,
max_grad_norm=1.0,
)
| 1,895 |
Python
| 25.704225 | 60 | 0.626913 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/shadow_hand/agents/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from . import rsl_rl_ppo_cfg
| 156 |
Python
| 21.428568 | 60 | 0.737179 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/shadow_hand/agents/rl_games_ppo_lstm_cfg.yaml
|
params:
seed: 42
# environment wrapper clipping
env:
# added to the wrapper
clip_observations: 5.0
# can make custom wrapper?
clip_actions: 1.0
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [512]
activation: relu
d2rl: False
initializer:
name: default
regularizer:
name: None
rnn:
name: lstm
units: 1024
layers: 1
before_mlp: True
layer_norm: True
load_checkpoint: False # flag which sets whether to load the checkpoint
load_path: '' # path to the checkpoint to load
config:
name: shadow_hand_openai_lstm
env_name: rlgpu
device: 'cuda:0'
device_name: 'cuda:0'
multi_gpu: False
ppo: True
mixed_precision: False
normalize_input: True
normalize_value: True
num_actors: -1 # configured from the script (based on num_envs)
reward_shaper:
scale_value: 0.01
normalize_advantage: True
gamma: 0.998
tau: 0.95
learning_rate: 1e-4
lr_schedule: adaptive
schedule_type: standard
kl_threshold: 0.016
score_to_win: 100000
max_epochs: 10000
save_best_after: 100
save_frequency: 200
print_stats: True
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 16
minibatch_size: 16384
mini_epochs: 4
critic_coef: 4
clip_value: True
seq_length: 4
bounds_loss_coef: 0.0001
central_value_config:
minibatch_size: 32768
mini_epochs: 4
learning_rate: 1e-4
kl_threshold: 0.016
clip_value: True
normalize_input: True
truncate_grads: True
network:
name: actor_critic
central_value: True
mlp:
units: [512]
activation: relu
d2rl: False
initializer:
name: default
regularizer:
name: None
rnn:
name: lstm
units: 1024
layers: 1
before_mlp: True
layer_norm: True
zero_rnn_on_done: False
player:
deterministic: True
games_num: 100000
print_stats: True
| 2,468 |
YAML
| 19.747899 | 73 | 0.577796 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/shadow_hand/agents/rl_games_ppo_cfg.yaml
|
params:
seed: 42
# environment wrapper clipping
env:
# added to the wrapper
clip_observations: 5.0
# can make custom wrapper?
clip_actions: 1.0
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
# doesn't have this fine grained control but made it close
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [512, 512, 256, 128]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: False # flag which sets whether to load the checkpoint
load_path: '' # path to the checkpoint to load
config:
name: shadow_hand
env_name: rlgpu
device: 'cuda:0'
device_name: 'cuda:0'
multi_gpu: False
ppo: True
mixed_precision: False
normalize_input: True
normalize_value: True
value_bootstrap: True
num_actors: -1 # configured from the script (based on num_envs)
reward_shaper:
scale_value: 0.01
normalize_advantage: True
gamma: 0.99
tau : 0.95
learning_rate: 5e-4
lr_schedule: adaptive
schedule_type: standard
kl_threshold: 0.016
score_to_win: 100000
max_epochs: 5000
save_best_after: 100
save_frequency: 200
print_stats: True
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 16
minibatch_size: 32768
mini_epochs: 5
critic_coef: 4
clip_value: True
seq_length: 4
bounds_loss_coef: 0.0001
player:
deterministic: True
games_num: 100000
print_stats: True
| 1,829 |
YAML
| 20.034483 | 73 | 0.614543 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/shadow_hand/agents/rl_games_ppo_ff_cfg.yaml
|
params:
seed: 42
# environment wrapper clipping
env:
# added to the wrapper
clip_observations: 5.0
# can make custom wrapper?
clip_actions: 1.0
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [400, 400, 200, 100]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: False # flag which sets whether to load the checkpoint
load_path: '' # path to the checkpoint to load
config:
name: shadow_hand_openai_ff
env_name: rlgpu
device: 'cuda:0'
device_name: 'cuda:0'
multi_gpu: False
ppo: True
mixed_precision: False
normalize_input: True
normalize_value: True
num_actors: -1
reward_shaper:
scale_value: 0.01
normalize_advantage: True
gamma: 0.998
tau: 0.95
learning_rate: 5e-4
lr_schedule: adaptive
schedule_type: standard
kl_threshold: 0.016
score_to_win: 100000
max_epochs: 10000
save_best_after: 100
save_frequency: 200
print_stats: True
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 16
minibatch_size: 16384
mini_epochs: 4
critic_coef: 4
clip_value: True
seq_length: 4
bounds_loss_coef: 0.0001
central_value_config:
minibatch_size: 32864
mini_epochs: 4
learning_rate: 5e-4
lr_schedule: adaptive
schedule_type: standard
kl_threshold: 0.016
clip_value: True
normalize_input: True
truncate_grads: True
network:
name: actor_critic
central_value: True
mlp:
units: [512, 512, 256, 128]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
player:
deterministic: True
games_num: 100000
print_stats: True
| 2,232 |
YAML
| 19.675926 | 73 | 0.590054 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/franka_cabinet/franka_cabinet_env.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from omni.isaac.core.utils.stage import get_current_stage
from omni.isaac.core.utils.torch.transformations import tf_combine, tf_inverse, tf_vector
from pxr import UsdGeom
import omni.isaac.lab.sim as sim_utils
from omni.isaac.lab.actuators.actuator_cfg import ImplicitActuatorCfg
from omni.isaac.lab.assets import Articulation, ArticulationCfg
from omni.isaac.lab.envs import DirectRLEnv, DirectRLEnvCfg
from omni.isaac.lab.scene import InteractiveSceneCfg
from omni.isaac.lab.sim import SimulationCfg
from omni.isaac.lab.terrains import TerrainImporterCfg
from omni.isaac.lab.utils import configclass
from omni.isaac.lab.utils.assets import ISAAC_NUCLEUS_DIR
from omni.isaac.lab.utils.math import sample_uniform
@configclass
class FrankaCabinetEnvCfg(DirectRLEnvCfg):
# env
episode_length_s = 8.3333 # 500 timesteps
decimation = 2
num_actions = 9
num_observations = 23
num_states = 0
action_scale = 7.5
dof_velocity_scale = 0.1
# simulation
sim: SimulationCfg = SimulationCfg(
dt=1 / 120,
disable_contact_processing=True,
physics_material=sim_utils.RigidBodyMaterialCfg(
friction_combine_mode="multiply",
restitution_combine_mode="multiply",
static_friction=1.0,
dynamic_friction=1.0,
restitution=0.0,
),
)
# scene
scene: InteractiveSceneCfg = InteractiveSceneCfg(num_envs=4096, env_spacing=3.0, replicate_physics=True)
# robot
robot = ArticulationCfg(
prim_path="/World/envs/env_.*/Robot",
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/Franka/franka_instanceable.usd",
activate_contact_sensors=False,
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
max_depenetration_velocity=5.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=False, solver_position_iteration_count=12, solver_velocity_iteration_count=1
),
),
init_state=ArticulationCfg.InitialStateCfg(
joint_pos={
"panda_joint1": 1.157,
"panda_joint2": -1.066,
"panda_joint3": -0.155,
"panda_joint4": -2.239,
"panda_joint5": -1.841,
"panda_joint6": 1.003,
"panda_joint7": 0.469,
"panda_finger_joint.*": 0.035,
},
pos=(1.0, 0.0, 0.0),
rot=(0.0, 0.0, 0.0, 1.0),
),
actuators={
"panda_shoulder": ImplicitActuatorCfg(
joint_names_expr=["panda_joint[1-4]"],
effort_limit=87.0,
velocity_limit=2.175,
stiffness=80.0,
damping=4.0,
),
"panda_forearm": ImplicitActuatorCfg(
joint_names_expr=["panda_joint[5-7]"],
effort_limit=12.0,
velocity_limit=2.61,
stiffness=80.0,
damping=4.0,
),
"panda_hand": ImplicitActuatorCfg(
joint_names_expr=["panda_finger_joint.*"],
effort_limit=200.0,
velocity_limit=0.2,
stiffness=2e3,
damping=1e2,
),
},
)
# cabinet
cabinet = ArticulationCfg(
prim_path="/World/envs/env_.*/Cabinet",
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Sektion_Cabinet/sektion_cabinet_instanceable.usd",
activate_contact_sensors=False,
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0, 0.4),
rot=(0.1, 0.0, 0.0, 0.0),
joint_pos={
"door_left_joint": 0.0,
"door_right_joint": 0.0,
"drawer_bottom_joint": 0.0,
"drawer_top_joint": 0.0,
},
),
actuators={
"drawers": ImplicitActuatorCfg(
joint_names_expr=["drawer_top_joint", "drawer_bottom_joint"],
effort_limit=87.0,
velocity_limit=100.0,
stiffness=10.0,
damping=1.0,
),
"doors": ImplicitActuatorCfg(
joint_names_expr=["door_left_joint", "door_right_joint"],
effort_limit=87.0,
velocity_limit=100.0,
stiffness=10.0,
damping=2.5,
),
},
)
# ground plane
terrain = TerrainImporterCfg(
prim_path="/World/ground",
terrain_type="plane",
collision_group=-1,
physics_material=sim_utils.RigidBodyMaterialCfg(
friction_combine_mode="multiply",
restitution_combine_mode="multiply",
static_friction=1.0,
dynamic_friction=1.0,
restitution=0.0,
),
)
# reward scales
dist_reward_scale = 2.0
rot_reward_scale = 0.5
around_handle_reward_scale = 0.0
open_reward_scale = 7.5
action_penalty_scale = 0.01
finger_dist_reward_scale = 0.0
finger_close_reward_scale = 10.0
class FrankaCabinetEnv(DirectRLEnv):
# pre-physics step calls
# |-- _pre_physics_step(action)
# |-- _apply_action()
# post-physics step calls
# |-- _get_dones()
# |-- _get_rewards()
# |-- _reset_idx(env_ids)
# |-- _get_observations()
cfg: FrankaCabinetEnvCfg
def __init__(self, cfg: FrankaCabinetEnvCfg, render_mode: str | None = None, **kwargs):
super().__init__(cfg, render_mode, **kwargs)
def get_env_local_pose(env_pos: torch.Tensor, xformable: UsdGeom.Xformable, device: torch.device):
"""Compute pose in env-local coordinates"""
world_transform = xformable.ComputeLocalToWorldTransform(0)
world_pos = world_transform.ExtractTranslation()
world_quat = world_transform.ExtractRotationQuat()
px = world_pos[0] - env_pos[0]
py = world_pos[1] - env_pos[1]
pz = world_pos[2] - env_pos[2]
qx = world_quat.imaginary[0]
qy = world_quat.imaginary[1]
qz = world_quat.imaginary[2]
qw = world_quat.real
return torch.tensor([px, py, pz, qw, qx, qy, qz], device=device)
self.dt = self.cfg.sim.dt * self.cfg.decimation
# create auxiliary variables for computing applied action, observations and rewards
self.robot_dof_lower_limits = self._robot.data.soft_joint_pos_limits[0, :, 0].to(device=self.device)
self.robot_dof_upper_limits = self._robot.data.soft_joint_pos_limits[0, :, 1].to(device=self.device)
self.robot_dof_speed_scales = torch.ones_like(self.robot_dof_lower_limits)
self.robot_dof_speed_scales[self._robot.find_joints("panda_finger_joint1")[0]] = 0.1
self.robot_dof_speed_scales[self._robot.find_joints("panda_finger_joint2")[0]] = 0.1
self.robot_dof_targets = torch.zeros((self.num_envs, self._robot.num_joints), device=self.device)
stage = get_current_stage()
hand_pose = get_env_local_pose(
self.scene.env_origins[0],
UsdGeom.Xformable(stage.GetPrimAtPath("/World/envs/env_0/Robot/panda_link7")),
self.device,
)
lfinger_pose = get_env_local_pose(
self.scene.env_origins[0],
UsdGeom.Xformable(stage.GetPrimAtPath("/World/envs/env_0/Robot/panda_leftfinger")),
self.device,
)
rfinger_pose = get_env_local_pose(
self.scene.env_origins[0],
UsdGeom.Xformable(stage.GetPrimAtPath("/World/envs/env_0/Robot/panda_rightfinger")),
self.device,
)
finger_pose = torch.zeros(7, device=self.device)
finger_pose[0:3] = (lfinger_pose[0:3] + rfinger_pose[0:3]) / 2.0
finger_pose[3:7] = lfinger_pose[3:7]
hand_pose_inv_rot, hand_pose_inv_pos = tf_inverse(hand_pose[3:7], hand_pose[0:3])
robot_local_grasp_pose_rot, robot_local_pose_pos = tf_combine(
hand_pose_inv_rot, hand_pose_inv_pos, finger_pose[3:7], finger_pose[0:3]
)
robot_local_pose_pos += torch.tensor([0, 0.04, 0], device=self.device)
self.robot_local_grasp_pos = robot_local_pose_pos.repeat((self.num_envs, 1))
self.robot_local_grasp_rot = robot_local_grasp_pose_rot.repeat((self.num_envs, 1))
drawer_local_grasp_pose = torch.tensor([0.3, 0.01, 0.0, 1.0, 0.0, 0.0, 0.0], device=self.device)
self.drawer_local_grasp_pos = drawer_local_grasp_pose[0:3].repeat((self.num_envs, 1))
self.drawer_local_grasp_rot = drawer_local_grasp_pose[3:7].repeat((self.num_envs, 1))
self.gripper_forward_axis = torch.tensor([0, 0, 1], device=self.device, dtype=torch.float32).repeat(
(self.num_envs, 1)
)
self.drawer_inward_axis = torch.tensor([-1, 0, 0], device=self.device, dtype=torch.float32).repeat(
(self.num_envs, 1)
)
self.gripper_up_axis = torch.tensor([0, 1, 0], device=self.device, dtype=torch.float32).repeat(
(self.num_envs, 1)
)
self.drawer_up_axis = torch.tensor([0, 0, 1], device=self.device, dtype=torch.float32).repeat(
(self.num_envs, 1)
)
self.hand_link_idx = self._robot.find_bodies("panda_link7")[0][0]
self.left_finger_link_idx = self._robot.find_bodies("panda_leftfinger")[0][0]
self.right_finger_link_idx = self._robot.find_bodies("panda_rightfinger")[0][0]
self.drawer_link_idx = self._cabinet.find_bodies("drawer_top")[0][0]
self.robot_grasp_rot = torch.zeros((self.num_envs, 4), device=self.device)
self.robot_grasp_pos = torch.zeros((self.num_envs, 3), device=self.device)
self.drawer_grasp_rot = torch.zeros((self.num_envs, 4), device=self.device)
self.drawer_grasp_pos = torch.zeros((self.num_envs, 3), device=self.device)
def _setup_scene(self):
self._robot = Articulation(self.cfg.robot)
self._cabinet = Articulation(self.cfg.cabinet)
self.scene.articulations["robot"] = self._robot
self.scene.articulations["cabinet"] = self._cabinet
self.cfg.terrain.num_envs = self.scene.cfg.num_envs
self.cfg.terrain.env_spacing = self.scene.cfg.env_spacing
self._terrain = self.cfg.terrain.class_type(self.cfg.terrain)
# clone, filter, and replicate
self.scene.clone_environments(copy_from_source=False)
self.scene.filter_collisions(global_prim_paths=[self.cfg.terrain.prim_path])
# add lights
light_cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75))
light_cfg.func("/World/Light", light_cfg)
# pre-physics step calls
def _pre_physics_step(self, actions: torch.Tensor):
self.actions = actions.clone().clamp(-1.0, 1.0)
targets = self.robot_dof_targets + self.robot_dof_speed_scales * self.dt * self.actions * self.cfg.action_scale
self.robot_dof_targets[:] = torch.clamp(targets, self.robot_dof_lower_limits, self.robot_dof_upper_limits)
def _apply_action(self):
self._robot.set_joint_position_target(self.robot_dof_targets)
# post-physics step calls
def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]:
terminated = self._cabinet.data.joint_pos[:, 3] > 0.39
truncated = self.episode_length_buf >= self.max_episode_length - 1
return terminated, truncated
def _get_rewards(self) -> torch.Tensor:
# Refresh the intermediate values after the physics steps
self._compute_intermediate_values()
robot_left_finger_pos = self._robot.data.body_pos_w[:, self.left_finger_link_idx]
robot_right_finger_pos = self._robot.data.body_pos_w[:, self.right_finger_link_idx]
return self._compute_rewards(
self.actions,
self._cabinet.data.joint_pos,
self.robot_grasp_pos,
self.drawer_grasp_pos,
self.robot_grasp_rot,
self.drawer_grasp_rot,
robot_left_finger_pos,
robot_right_finger_pos,
self.gripper_forward_axis,
self.drawer_inward_axis,
self.gripper_up_axis,
self.drawer_up_axis,
self.num_envs,
self.cfg.dist_reward_scale,
self.cfg.rot_reward_scale,
self.cfg.around_handle_reward_scale,
self.cfg.open_reward_scale,
self.cfg.finger_dist_reward_scale,
self.cfg.action_penalty_scale,
self._robot.data.joint_pos,
self.cfg.finger_close_reward_scale,
)
def _reset_idx(self, env_ids: torch.Tensor | None):
super()._reset_idx(env_ids)
# robot state
joint_pos = self._robot.data.default_joint_pos[env_ids] + sample_uniform(
-0.125,
0.125,
(len(env_ids), self._robot.num_joints),
self.device,
)
joint_pos = torch.clamp(joint_pos, self.robot_dof_lower_limits, self.robot_dof_upper_limits)
joint_vel = torch.zeros_like(joint_pos)
self._robot.set_joint_position_target(joint_pos, env_ids=env_ids)
self._robot.write_joint_state_to_sim(joint_pos, joint_vel, env_ids=env_ids)
# cabinet state
zeros = torch.zeros((len(env_ids), self._cabinet.num_joints), device=self.device)
self._cabinet.write_joint_state_to_sim(zeros, zeros, env_ids=env_ids)
# Need to refresh the intermediate values so that _get_observations() can use the latest values
self._compute_intermediate_values(env_ids)
def _get_observations(self) -> dict:
dof_pos_scaled = (
2.0
* (self._robot.data.joint_pos - self.robot_dof_lower_limits)
/ (self.robot_dof_upper_limits - self.robot_dof_lower_limits)
- 1.0
)
to_target = self.drawer_grasp_pos - self.robot_grasp_pos
obs = torch.cat(
(
dof_pos_scaled,
self._robot.data.joint_vel * self.cfg.dof_velocity_scale,
to_target,
self._cabinet.data.joint_pos[:, 3].unsqueeze(-1),
self._cabinet.data.joint_vel[:, 3].unsqueeze(-1),
),
dim=-1,
)
return {"policy": torch.clamp(obs, -5.0, 5.0)}
# auxiliary methods
def _compute_intermediate_values(self, env_ids: torch.Tensor | None = None):
if env_ids is None:
env_ids = self._robot._ALL_INDICES
hand_pos = self._robot.data.body_pos_w[env_ids, self.hand_link_idx]
hand_rot = self._robot.data.body_quat_w[env_ids, self.hand_link_idx]
drawer_pos = self._cabinet.data.body_pos_w[env_ids, self.drawer_link_idx]
drawer_rot = self._cabinet.data.body_quat_w[env_ids, self.drawer_link_idx]
(
self.robot_grasp_rot[env_ids],
self.robot_grasp_pos[env_ids],
self.drawer_grasp_rot[env_ids],
self.drawer_grasp_pos[env_ids],
) = self._compute_grasp_transforms(
hand_rot,
hand_pos,
self.robot_local_grasp_rot[env_ids],
self.robot_local_grasp_pos[env_ids],
drawer_rot,
drawer_pos,
self.drawer_local_grasp_rot[env_ids],
self.drawer_local_grasp_pos[env_ids],
)
def _compute_rewards(
self,
actions,
cabinet_dof_pos,
franka_grasp_pos,
drawer_grasp_pos,
franka_grasp_rot,
drawer_grasp_rot,
franka_lfinger_pos,
franka_rfinger_pos,
gripper_forward_axis,
drawer_inward_axis,
gripper_up_axis,
drawer_up_axis,
num_envs,
dist_reward_scale,
rot_reward_scale,
around_handle_reward_scale,
open_reward_scale,
finger_dist_reward_scale,
action_penalty_scale,
joint_positions,
finger_close_reward_scale,
):
# distance from hand to the drawer
d = torch.norm(franka_grasp_pos - drawer_grasp_pos, p=2, dim=-1)
dist_reward = 1.0 / (1.0 + d**2)
dist_reward *= dist_reward
dist_reward = torch.where(d <= 0.02, dist_reward * 2, dist_reward)
axis1 = tf_vector(franka_grasp_rot, gripper_forward_axis)
axis2 = tf_vector(drawer_grasp_rot, drawer_inward_axis)
axis3 = tf_vector(franka_grasp_rot, gripper_up_axis)
axis4 = tf_vector(drawer_grasp_rot, drawer_up_axis)
dot1 = (
torch.bmm(axis1.view(num_envs, 1, 3), axis2.view(num_envs, 3, 1)).squeeze(-1).squeeze(-1)
) # alignment of forward axis for gripper
dot2 = (
torch.bmm(axis3.view(num_envs, 1, 3), axis4.view(num_envs, 3, 1)).squeeze(-1).squeeze(-1)
) # alignment of up axis for gripper
# reward for matching the orientation of the hand to the drawer (fingers wrapped)
rot_reward = 0.5 * (torch.sign(dot1) * dot1**2 + torch.sign(dot2) * dot2**2)
# bonus if left finger is above the drawer handle and right below
around_handle_reward = torch.zeros_like(rot_reward)
around_handle_reward = torch.where(
franka_lfinger_pos[:, 2] > drawer_grasp_pos[:, 2],
torch.where(
franka_rfinger_pos[:, 2] < drawer_grasp_pos[:, 2], around_handle_reward + 0.5, around_handle_reward
),
around_handle_reward,
)
# reward for distance of each finger from the drawer
finger_dist_reward = torch.zeros_like(rot_reward)
lfinger_dist = torch.abs(franka_lfinger_pos[:, 2] - drawer_grasp_pos[:, 2])
rfinger_dist = torch.abs(franka_rfinger_pos[:, 2] - drawer_grasp_pos[:, 2])
finger_dist_reward = torch.where(
franka_lfinger_pos[:, 2] > drawer_grasp_pos[:, 2],
torch.where(
franka_rfinger_pos[:, 2] < drawer_grasp_pos[:, 2],
(0.04 - lfinger_dist) + (0.04 - rfinger_dist),
finger_dist_reward,
),
finger_dist_reward,
)
finger_close_reward = torch.zeros_like(rot_reward)
finger_close_reward = torch.where(
d <= 0.03, (0.04 - joint_positions[:, 7]) + (0.04 - joint_positions[:, 8]), finger_close_reward
)
# regularization on the actions (summed for each environment)
action_penalty = torch.sum(actions**2, dim=-1)
# how far the cabinet has been opened out
open_reward = cabinet_dof_pos[:, 3] * around_handle_reward + cabinet_dof_pos[:, 3] # drawer_top_joint
rewards = (
dist_reward_scale * dist_reward
+ rot_reward_scale * rot_reward
+ around_handle_reward_scale * around_handle_reward
+ open_reward_scale * open_reward
+ finger_dist_reward_scale * finger_dist_reward
- action_penalty_scale * action_penalty
+ finger_close_reward * finger_close_reward_scale
)
self.extras["log"] = {
"dist_reward": (dist_reward_scale * dist_reward).mean(),
"rot_reward": (rot_reward_scale * rot_reward).mean(),
"around_handle_reward": (around_handle_reward_scale * around_handle_reward).mean(),
"open_reward": (open_reward_scale * open_reward).mean(),
"finger_dist_reward": (finger_dist_reward_scale * finger_dist_reward).mean(),
"action_penalty": (action_penalty_scale * action_penalty).mean(),
"finger_close_reward": (finger_close_reward * finger_close_reward_scale).mean(),
}
# bonus for opening drawer properly
rewards = torch.where(cabinet_dof_pos[:, 3] > 0.01, rewards + 0.5, rewards)
rewards = torch.where(cabinet_dof_pos[:, 3] > 0.2, rewards + around_handle_reward, rewards)
rewards = torch.where(cabinet_dof_pos[:, 3] > 0.39, rewards + (2.0 * around_handle_reward), rewards)
return rewards
def _compute_grasp_transforms(
self,
hand_rot,
hand_pos,
franka_local_grasp_rot,
franka_local_grasp_pos,
drawer_rot,
drawer_pos,
drawer_local_grasp_rot,
drawer_local_grasp_pos,
):
global_franka_rot, global_franka_pos = tf_combine(
hand_rot, hand_pos, franka_local_grasp_rot, franka_local_grasp_pos
)
global_drawer_rot, global_drawer_pos = tf_combine(
drawer_rot, drawer_pos, drawer_local_grasp_rot, drawer_local_grasp_pos
)
return global_franka_rot, global_franka_pos, global_drawer_rot, global_drawer_pos
| 20,965 |
Python
| 39.087954 | 119 | 0.587455 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/franka_cabinet/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Franka-Cabinet environment.
"""
import gymnasium as gym
from . import agents
from .franka_cabinet_env import FrankaCabinetEnv, FrankaCabinetEnvCfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Franka-Cabinet-Direct-v0",
entry_point="omni.isaac.lab_tasks.direct.franka_cabinet:FrankaCabinetEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": FrankaCabinetEnvCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.FrankaCabinetPPORunnerCfg,
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
},
)
| 789 |
Python
| 26.241378 | 82 | 0.698352 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/franka_cabinet/agents/rsl_rl_ppo_cfg.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.lab.utils import configclass
from omni.isaac.lab_tasks.utils.wrappers.rsl_rl import (
RslRlOnPolicyRunnerCfg,
RslRlPpoActorCriticCfg,
RslRlPpoAlgorithmCfg,
)
@configclass
class FrankaCabinetPPORunnerCfg(RslRlOnPolicyRunnerCfg):
num_steps_per_env = 16
max_iterations = 1500
save_interval = 50
experiment_name = "franka_cabinet_direct"
empirical_normalization = False
policy = RslRlPpoActorCriticCfg(
init_noise_std=1.0,
actor_hidden_dims=[256, 128, 64],
critic_hidden_dims=[256, 128, 64],
activation="elu",
)
algorithm = RslRlPpoAlgorithmCfg(
value_loss_coef=1.0,
use_clipped_value_loss=True,
clip_param=0.2,
entropy_coef=0.0,
num_learning_epochs=8,
num_mini_batches=8,
learning_rate=5.0e-4,
schedule="adaptive",
gamma=0.99,
lam=0.95,
desired_kl=0.008,
max_grad_norm=1.0,
)
| 1,095 |
Python
| 25.095237 | 60 | 0.647489 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/franka_cabinet/agents/skrl_ppo_cfg.yaml
|
seed: 42
# Models are instantiated using skrl's model instantiator utility
# https://skrl.readthedocs.io/en/develop/api/utils/model_instantiators.html
models:
separate: False
policy: # see 'skrl.utils.model_instantiators.torch.gaussian_model' for parameter details
clip_actions: False
clip_log_std: True
initial_log_std: 0
min_log_std: -20.0
max_log_std: 2.0
input_shape: "Shape.STATES"
hiddens: [256, 128, 64]
hidden_activation: ["elu", "elu", "elu"]
output_shape: "Shape.ACTIONS"
output_activation: ""
output_scale: 1.0
value: # see 'skrl.utils.model_instantiators.torch.deterministic_model' for parameter details
clip_actions: False
input_shape: "Shape.STATES"
hiddens: [256, 128, 64]
hidden_activation: ["elu", "elu", "elu"]
output_shape: "Shape.ONE"
output_activation: ""
output_scale: 1.0
# PPO agent configuration (field names are from PPO_DEFAULT_CONFIG)
# https://skrl.readthedocs.io/en/latest/api/agents/ppo.html
agent:
rollouts: 16
learning_epochs: 8
mini_batches: 8
discount_factor: 0.99
lambda: 0.95
learning_rate: 5.e-4
learning_rate_scheduler: "KLAdaptiveLR"
learning_rate_scheduler_kwargs:
kl_threshold: 0.008
state_preprocessor: "RunningStandardScaler"
state_preprocessor_kwargs: null
value_preprocessor: "RunningStandardScaler"
value_preprocessor_kwargs: null
random_timesteps: 0
learning_starts: 0
grad_norm_clip: 1.0
ratio_clip: 0.2
value_clip: 0.2
clip_predicted_values: True
entropy_loss_scale: 0.0
value_loss_scale: 2.0
kl_threshold: 0
rewards_shaper_scale: 0.01
# logging and checkpoint
experiment:
directory: "franka_cabinet_direct"
experiment_name: ""
write_interval: 120
checkpoint_interval: 1200
# Sequential trainer
# https://skrl.readthedocs.io/en/latest/api/trainers/sequential.html
trainer:
timesteps: 24000
environment_info: "log"
| 1,921 |
YAML
| 27.264705 | 96 | 0.709006 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/franka_cabinet/agents/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from . import rsl_rl_ppo_cfg
| 156 |
Python
| 21.428568 | 60 | 0.737179 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/franka_cabinet/agents/rl_games_ppo_cfg.yaml
|
params:
seed: 42
# environment wrapper clipping
env:
clip_actions: 1.0
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [256, 128, 64]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: False # flag which sets whether to load the checkpoint
load_path: '' # path to the checkpoint to load
config:
name: franka_cabinet_direct
env_name: rlgpu
device: 'cuda:0'
device_name: 'cuda:0'
multi_gpu: False
ppo: True
mixed_precision: False
normalize_input: True
normalize_value: True
# value_bootstrap: True
num_actors: -1 # configured from the script (based on num_envs)
reward_shaper:
scale_value: 0.01
normalize_advantage: True
gamma: 0.99
tau: 0.95
learning_rate: 5e-4
lr_schedule: adaptive
kl_threshold: 0.008
score_to_win: 100000000
max_epochs: 1500
save_best_after: 200
save_frequency: 100
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 16
minibatch_size: 8192
mini_epochs: 8
critic_coef: 4
clip_value: True
seq_length: 4
bounds_loss_coef: 0.0001
| 1,553 |
YAML
| 19.447368 | 73 | 0.6085 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/locomotion/locomotion_env.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
import omni.isaac.core.utils.torch as torch_utils
from omni.isaac.core.utils.torch.rotations import compute_heading_and_up, compute_rot, quat_conjugate
import omni.isaac.lab.sim as sim_utils
from omni.isaac.lab.assets import Articulation
from omni.isaac.lab.envs import DirectRLEnv, DirectRLEnvCfg
def normalize_angle(x):
return torch.atan2(torch.sin(x), torch.cos(x))
class LocomotionEnv(DirectRLEnv):
cfg: DirectRLEnvCfg
def __init__(self, cfg: DirectRLEnvCfg, render_mode: str | None = None, **kwargs):
super().__init__(cfg, render_mode, **kwargs)
self.action_scale = self.cfg.action_scale
self.joint_gears = torch.tensor(self.cfg.joint_gears, dtype=torch.float32, device=self.sim.device)
self.motor_effort_ratio = torch.ones_like(self.joint_gears, device=self.sim.device)
self._joint_dof_idx, _ = self.robot.find_joints(".*")
self.potentials = torch.zeros(self.num_envs, dtype=torch.float32, device=self.sim.device)
self.prev_potentials = torch.zeros_like(self.potentials)
self.targets = torch.tensor([1000, 0, 0], dtype=torch.float32, device=self.sim.device).repeat(
(self.num_envs, 1)
)
self.targets += self.scene.env_origins
self.start_rotation = torch.tensor([1, 0, 0, 0], device=self.sim.device, dtype=torch.float32)
self.up_vec = torch.tensor([0, 0, 1], dtype=torch.float32, device=self.sim.device).repeat((self.num_envs, 1))
self.heading_vec = torch.tensor([1, 0, 0], dtype=torch.float32, device=self.sim.device).repeat(
(self.num_envs, 1)
)
self.inv_start_rot = quat_conjugate(self.start_rotation).repeat((self.num_envs, 1))
self.basis_vec0 = self.heading_vec.clone()
self.basis_vec1 = self.up_vec.clone()
def _setup_scene(self):
self.robot = Articulation(self.cfg.robot)
# add ground plane
self.cfg.terrain.num_envs = self.scene.cfg.num_envs
self.cfg.terrain.env_spacing = self.scene.cfg.env_spacing
self.terrain = self.cfg.terrain.class_type(self.cfg.terrain)
# clone, filter, and replicate
self.scene.clone_environments(copy_from_source=False)
self.scene.filter_collisions(global_prim_paths=[self.cfg.terrain.prim_path])
# add articultion to scene
self.scene.articulations["robot"] = self.robot
# add lights
light_cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75))
light_cfg.func("/World/Light", light_cfg)
def _pre_physics_step(self, actions: torch.Tensor):
self.actions = actions.clone()
def _apply_action(self):
forces = self.action_scale * self.joint_gears * self.actions
self.robot.set_joint_effort_target(forces, joint_ids=self._joint_dof_idx)
def _compute_intermediate_values(self):
self.torso_position, self.torso_rotation = self.robot.data.root_pos_w, self.robot.data.root_quat_w
self.velocity, self.ang_velocity = self.robot.data.root_lin_vel_w, self.robot.data.root_ang_vel_w
self.dof_pos, self.dof_vel = self.robot.data.joint_pos, self.robot.data.joint_vel
(
self.up_proj,
self.heading_proj,
self.up_vec,
self.heading_vec,
self.vel_loc,
self.angvel_loc,
self.roll,
self.pitch,
self.yaw,
self.angle_to_target,
self.dof_pos_scaled,
self.prev_potentials,
self.potentials,
) = compute_intermediate_values(
self.targets,
self.torso_position,
self.torso_rotation,
self.velocity,
self.ang_velocity,
self.dof_pos,
self.robot.data.soft_joint_pos_limits[0, :, 0],
self.robot.data.soft_joint_pos_limits[0, :, 1],
self.inv_start_rot,
self.basis_vec0,
self.basis_vec1,
self.potentials,
self.prev_potentials,
self.cfg.sim.dt,
)
def _get_observations(self) -> dict:
obs = torch.cat(
(
self.torso_position[:, 2].view(-1, 1),
self.vel_loc,
self.angvel_loc * self.cfg.angular_velocity_scale,
normalize_angle(self.yaw).unsqueeze(-1),
normalize_angle(self.roll).unsqueeze(-1),
normalize_angle(self.angle_to_target).unsqueeze(-1),
self.up_proj.unsqueeze(-1),
self.heading_proj.unsqueeze(-1),
self.dof_pos_scaled,
self.dof_vel * self.cfg.dof_vel_scale,
self.actions,
),
dim=-1,
)
observations = {"policy": obs}
return observations
def _get_rewards(self) -> torch.Tensor:
total_reward = compute_rewards(
self.actions,
self.reset_terminated,
self.cfg.up_weight,
self.cfg.heading_weight,
self.heading_proj,
self.up_proj,
self.dof_vel,
self.dof_pos_scaled,
self.potentials,
self.prev_potentials,
self.cfg.actions_cost_scale,
self.cfg.energy_cost_scale,
self.cfg.dof_vel_scale,
self.cfg.death_cost,
self.cfg.alive_reward_scale,
self.motor_effort_ratio,
)
return total_reward
def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]:
self._compute_intermediate_values()
time_out = self.episode_length_buf >= self.max_episode_length - 1
died = self.torso_position[:, 2] < self.cfg.termination_height
return died, time_out
def _reset_idx(self, env_ids: torch.Tensor | None):
if env_ids is None or len(env_ids) == self.num_envs:
env_ids = self.robot._ALL_INDICES
self.robot.reset(env_ids)
super()._reset_idx(env_ids)
joint_pos = self.robot.data.default_joint_pos[env_ids]
joint_vel = self.robot.data.default_joint_vel[env_ids]
default_root_state = self.robot.data.default_root_state[env_ids]
default_root_state[:, :3] += self.scene.env_origins[env_ids]
self.robot.write_root_pose_to_sim(default_root_state[:, :7], env_ids)
self.robot.write_root_velocity_to_sim(default_root_state[:, 7:], env_ids)
self.robot.write_joint_state_to_sim(joint_pos, joint_vel, None, env_ids)
to_target = self.targets[env_ids] - default_root_state[:, :3]
to_target[:, 2] = 0.0
self.potentials[env_ids] = -torch.norm(to_target, p=2, dim=-1) / self.cfg.sim.dt
self._compute_intermediate_values()
@torch.jit.script
def compute_rewards(
actions: torch.Tensor,
reset_terminated: torch.Tensor,
up_weight: float,
heading_weight: float,
heading_proj: torch.Tensor,
up_proj: torch.Tensor,
dof_vel: torch.Tensor,
dof_pos_scaled: torch.Tensor,
potentials: torch.Tensor,
prev_potentials: torch.Tensor,
actions_cost_scale: float,
energy_cost_scale: float,
dof_vel_scale: float,
death_cost: float,
alive_reward_scale: float,
motor_effort_ratio: torch.Tensor,
):
heading_weight_tensor = torch.ones_like(heading_proj) * heading_weight
heading_reward = torch.where(heading_proj > 0.8, heading_weight_tensor, heading_weight * heading_proj / 0.8)
# aligning up axis of robot and environment
up_reward = torch.zeros_like(heading_reward)
up_reward = torch.where(up_proj > 0.93, up_reward + up_weight, up_reward)
# energy penalty for movement
actions_cost = torch.sum(actions**2, dim=-1)
electricity_cost = torch.sum(
torch.abs(actions * dof_vel * dof_vel_scale) * motor_effort_ratio.unsqueeze(0),
dim=-1,
)
# dof at limit cost
dof_at_limit_cost = torch.sum(dof_pos_scaled > 0.98, dim=-1)
# reward for duration of staying alive
alive_reward = torch.ones_like(potentials) * alive_reward_scale
progress_reward = potentials - prev_potentials
total_reward = (
progress_reward
+ alive_reward
+ up_reward
+ heading_reward
- actions_cost_scale * actions_cost
- energy_cost_scale * electricity_cost
- dof_at_limit_cost
)
# adjust reward for fallen agents
total_reward = torch.where(reset_terminated, torch.ones_like(total_reward) * death_cost, total_reward)
return total_reward
@torch.jit.script
def compute_intermediate_values(
targets: torch.Tensor,
torso_position: torch.Tensor,
torso_rotation: torch.Tensor,
velocity: torch.Tensor,
ang_velocity: torch.Tensor,
dof_pos: torch.Tensor,
dof_lower_limits: torch.Tensor,
dof_upper_limits: torch.Tensor,
inv_start_rot: torch.Tensor,
basis_vec0: torch.Tensor,
basis_vec1: torch.Tensor,
potentials: torch.Tensor,
prev_potentials: torch.Tensor,
dt: float,
):
to_target = targets - torso_position
to_target[:, 2] = 0.0
torso_quat, up_proj, heading_proj, up_vec, heading_vec = compute_heading_and_up(
torso_rotation, inv_start_rot, to_target, basis_vec0, basis_vec1, 2
)
vel_loc, angvel_loc, roll, pitch, yaw, angle_to_target = compute_rot(
torso_quat, velocity, ang_velocity, targets, torso_position
)
dof_pos_scaled = torch_utils.maths.unscale(dof_pos, dof_lower_limits, dof_upper_limits)
to_target = targets - torso_position
to_target[:, 2] = 0.0
prev_potentials[:] = potentials
potentials = -torch.norm(to_target, p=2, dim=-1) / dt
return (
up_proj,
heading_proj,
up_vec,
heading_vec,
vel_loc,
angvel_loc,
roll,
pitch,
yaw,
angle_to_target,
dof_pos_scaled,
prev_potentials,
potentials,
)
| 10,072 |
Python
| 35.103943 | 117 | 0.615469 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/locomotion/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
| 126 |
Python
| 24.399995 | 60 | 0.746032 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/anymal_c/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Ant locomotion environment.
"""
import gymnasium as gym
from . import agents
from .anymal_c_env import AnymalCEnv, AnymalCFlatEnvCfg, AnymalCRoughEnvCfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Velocity-Flat-Anymal-C-Direct-v0",
entry_point="omni.isaac.lab_tasks.direct.anymal_c:AnymalCEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": AnymalCFlatEnvCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_flat_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.AnymalCFlatPPORunnerCfg,
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml",
},
)
gym.register(
id="Isaac-Velocity-Rough-Anymal-C-Direct-v0",
entry_point="omni.isaac.lab_tasks.direct.anymal_c:AnymalCEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": AnymalCRoughEnvCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_rough_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.AnymalCRoughPPORunnerCfg,
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_rough_ppo_cfg.yaml",
},
)
| 1,279 |
Python
| 29.47619 | 85 | 0.679437 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/anymal_c/anymal_c_env.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
import omni.isaac.lab.sim as sim_utils
from omni.isaac.lab.assets import Articulation, ArticulationCfg
from omni.isaac.lab.envs import DirectRLEnv, DirectRLEnvCfg
from omni.isaac.lab.scene import InteractiveSceneCfg
from omni.isaac.lab.sensors import ContactSensor, ContactSensorCfg, RayCaster, RayCasterCfg, patterns
from omni.isaac.lab.sim import SimulationCfg
from omni.isaac.lab.terrains import TerrainImporterCfg
from omni.isaac.lab.utils import configclass
##
# Pre-defined configs
##
from omni.isaac.lab_assets.anymal import ANYMAL_C_CFG # isort: skip
from omni.isaac.lab.terrains.config.rough import ROUGH_TERRAINS_CFG # isort: skip
@configclass
class AnymalCFlatEnvCfg(DirectRLEnvCfg):
# simulation
sim: SimulationCfg = SimulationCfg(
dt=1 / 200,
disable_contact_processing=True,
physics_material=sim_utils.RigidBodyMaterialCfg(
friction_combine_mode="multiply",
restitution_combine_mode="multiply",
static_friction=1.0,
dynamic_friction=1.0,
restitution=0.0,
),
)
terrain = TerrainImporterCfg(
prim_path="/World/ground",
terrain_type="plane",
collision_group=-1,
physics_material=sim_utils.RigidBodyMaterialCfg(
friction_combine_mode="multiply",
restitution_combine_mode="multiply",
static_friction=1.0,
dynamic_friction=1.0,
restitution=0.0,
),
debug_vis=False,
)
# scene
scene: InteractiveSceneCfg = InteractiveSceneCfg(num_envs=4096, env_spacing=4.0, replicate_physics=True)
# robot
robot: ArticulationCfg = ANYMAL_C_CFG.replace(prim_path="/World/envs/env_.*/Robot")
contact_sensor: ContactSensorCfg = ContactSensorCfg(
prim_path="/World/envs/env_.*/Robot/.*", history_length=3, update_period=0.005, track_air_time=True
)
# env
episode_length_s = 20.0
decimation = 4
action_scale = 0.5
num_actions = 12
num_observations = 48
num_states = 0
# reward scales
lin_vel_reward_scale = 1.0
yaw_rate_reward_scale = 0.5
z_vel_reward_scale = -2.0
ang_vel_reward_scale = -0.05
joint_torque_reward_scale = -2.5e-5
joint_accel_reward_scale = -2.5e-7
action_rate_reward_scale = -0.01
feet_air_time_reward_scale = 0.5
undersired_contact_reward_scale = -1.0
flat_orientation_reward_scale = -5.0
@configclass
class AnymalCRoughEnvCfg(AnymalCFlatEnvCfg):
# env
num_observations = 235
terrain = TerrainImporterCfg(
prim_path="/World/ground",
terrain_type="generator",
terrain_generator=ROUGH_TERRAINS_CFG,
max_init_terrain_level=9,
collision_group=-1,
physics_material=sim_utils.RigidBodyMaterialCfg(
friction_combine_mode="multiply",
restitution_combine_mode="multiply",
static_friction=1.0,
dynamic_friction=1.0,
),
visual_material=sim_utils.MdlFileCfg(
mdl_path="{NVIDIA_NUCLEUS_DIR}/Materials/Base/Architecture/Shingles_01.mdl",
project_uvw=True,
),
debug_vis=False,
)
# we add a height scanner for perceptive locomotion
height_scanner = RayCasterCfg(
prim_path="/World/envs/env_.*/Robot/base",
offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 20.0)),
attach_yaw_only=True,
pattern_cfg=patterns.GridPatternCfg(resolution=0.1, size=[1.6, 1.0]),
debug_vis=False,
mesh_prim_paths=["/World/ground"],
)
# reward scales (override from flat config)
flat_orientation_reward_scale = 0.0
class AnymalCEnv(DirectRLEnv):
cfg: AnymalCFlatEnvCfg | AnymalCRoughEnvCfg
def __init__(self, cfg: AnymalCFlatEnvCfg | AnymalCRoughEnvCfg, render_mode: str | None = None, **kwargs):
super().__init__(cfg, render_mode, **kwargs)
# Joint position command (deviation from default joint positions)
self._actions = torch.zeros(self.num_envs, self.cfg.num_actions, device=self.device)
self._previous_actions = torch.zeros(self.num_envs, self.cfg.num_actions, device=self.device)
# X/Y linear velocity and yaw angular velocity commands
self._commands = torch.zeros(self.num_envs, 3, device=self.device)
# Logging
self._episode_sums = {
key: torch.zeros(self.num_envs, dtype=torch.float, device=self.device)
for key in [
"track_lin_vel_xy_exp",
"track_ang_vel_z_exp",
"lin_vel_z_l2",
"ang_vel_xy_l2",
"dof_torques_l2",
"dof_acc_l2",
"action_rate_l2",
"feet_air_time",
"undesired_contacts",
"flat_orientation_l2",
]
}
# Get specific body indices
self._base_id, _ = self._contact_sensor.find_bodies("base")
self._feet_ids, _ = self._contact_sensor.find_bodies(".*FOOT")
self._underisred_contact_body_ids, _ = self._contact_sensor.find_bodies(".*THIGH")
# Randomize robot friction
env_ids = self._robot._ALL_INDICES
mat_props = self._robot.root_physx_view.get_material_properties()
mat_props[:, :, :2].uniform_(0.6, 0.8)
self._robot.root_physx_view.set_material_properties(mat_props, env_ids.cpu())
# Randomize base mass
base_id, _ = self._robot.find_bodies("base")
masses = self._robot.root_physx_view.get_masses()
masses[:, base_id] += torch.zeros_like(masses[:, base_id]).uniform_(-5.0, 5.0)
self._robot.root_physx_view.set_masses(masses, env_ids.cpu())
def _setup_scene(self):
self._robot = Articulation(self.cfg.robot)
self.scene.articulations["robot"] = self._robot
self._contact_sensor = ContactSensor(self.cfg.contact_sensor)
self.scene.sensors["contact_sensor"] = self._contact_sensor
if isinstance(self.cfg, AnymalCRoughEnvCfg):
# we add a height scanner for perceptive locomotion
self._height_scanner = RayCaster(self.cfg.height_scanner)
self.scene.sensors["height_scanner"] = self._height_scanner
self.cfg.terrain.num_envs = self.scene.cfg.num_envs
self.cfg.terrain.env_spacing = self.scene.cfg.env_spacing
self._terrain = self.cfg.terrain.class_type(self.cfg.terrain)
# clone, filter, and replicate
self.scene.clone_environments(copy_from_source=False)
self.scene.filter_collisions(global_prim_paths=[self.cfg.terrain.prim_path])
# add lights
light_cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.75, 0.75, 0.75))
light_cfg.func("/World/Light", light_cfg)
def _pre_physics_step(self, actions: torch.Tensor):
self._actions = actions.clone()
self._processed_actions = self.cfg.action_scale * self._actions + self._robot.data.default_joint_pos
def _apply_action(self):
self._robot.set_joint_position_target(self._processed_actions)
def _get_observations(self) -> dict:
self._previous_actions = self._actions.clone()
height_data = None
if isinstance(self.cfg, AnymalCRoughEnvCfg):
height_data = (
self._height_scanner.data.pos_w[:, 2].unsqueeze(1) - self._height_scanner.data.ray_hits_w[..., 2] - 0.5
).clip(-1.0, 1.0)
obs = torch.cat(
[
tensor
for tensor in (
self._robot.data.root_lin_vel_b,
self._robot.data.root_ang_vel_b,
self._robot.data.projected_gravity_b,
self._commands,
self._robot.data.joint_pos - self._robot.data.default_joint_pos,
self._robot.data.joint_vel,
height_data,
self._actions,
)
if tensor is not None
],
dim=-1,
)
observations = {"policy": obs}
return observations
def _get_rewards(self) -> torch.Tensor:
# linear velocity tracking
lin_vel_error = torch.sum(torch.square(self._commands[:, :2] - self._robot.data.root_lin_vel_b[:, :2]), dim=1)
lin_vel_error_mapped = torch.exp(-lin_vel_error / 0.25)
# yaw rate tracking
yaw_rate_error = torch.square(self._commands[:, 2] - self._robot.data.root_ang_vel_b[:, 2])
yaw_rate_error_mapped = torch.exp(-yaw_rate_error / 0.25)
# z velocity tracking
z_vel_error = torch.square(self._robot.data.root_lin_vel_b[:, 2])
# angular velocity x/y
ang_vel_error = torch.sum(torch.square(self._robot.data.root_ang_vel_b[:, :2]), dim=1)
# joint torques
joint_torques = torch.sum(torch.square(self._robot.data.applied_torque), dim=1)
# joint acceleration
joint_accel = torch.sum(torch.square(self._robot.data.joint_acc), dim=1)
# action rate
action_rate = torch.sum(torch.square(self._actions - self._previous_actions), dim=1)
# feet air time
first_contact = self._contact_sensor.compute_first_contact(self.step_dt)[:, self._feet_ids]
last_air_time = self._contact_sensor.data.last_air_time[:, self._feet_ids]
air_time = torch.sum((last_air_time - 0.5) * first_contact, dim=1) * (
torch.norm(self._commands[:, :2], dim=1) > 0.1
)
# undersired contacts
net_contact_forces = self._contact_sensor.data.net_forces_w_history
is_contact = (
torch.max(torch.norm(net_contact_forces[:, :, self._underisred_contact_body_ids], dim=-1), dim=1)[0] > 1.0
)
contacts = torch.sum(is_contact, dim=1)
# flat orientation
flat_orientation = torch.sum(torch.square(self._robot.data.projected_gravity_b[:, :2]), dim=1)
rewards = {
"track_lin_vel_xy_exp": lin_vel_error_mapped * self.cfg.lin_vel_reward_scale * self.step_dt,
"track_ang_vel_z_exp": yaw_rate_error_mapped * self.cfg.yaw_rate_reward_scale * self.step_dt,
"lin_vel_z_l2": z_vel_error * self.cfg.z_vel_reward_scale * self.step_dt,
"ang_vel_xy_l2": ang_vel_error * self.cfg.ang_vel_reward_scale * self.step_dt,
"dof_torques_l2": joint_torques * self.cfg.joint_torque_reward_scale * self.step_dt,
"dof_acc_l2": joint_accel * self.cfg.joint_accel_reward_scale * self.step_dt,
"action_rate_l2": action_rate * self.cfg.action_rate_reward_scale * self.step_dt,
"feet_air_time": air_time * self.cfg.feet_air_time_reward_scale * self.step_dt,
"undesired_contacts": contacts * self.cfg.undersired_contact_reward_scale * self.step_dt,
"flat_orientation_l2": flat_orientation * self.cfg.flat_orientation_reward_scale * self.step_dt,
}
reward = torch.sum(torch.stack(list(rewards.values())), dim=0)
# Logging
for key, value in rewards.items():
self._episode_sums[key] += value
return reward
def _get_dones(self) -> tuple[torch.Tensor, torch.Tensor]:
time_out = self.episode_length_buf >= self.max_episode_length - 1
net_contact_forces = self._contact_sensor.data.net_forces_w_history
died = torch.any(torch.max(torch.norm(net_contact_forces[:, :, self._base_id], dim=-1), dim=1)[0] > 1.0, dim=1)
return died, time_out
def _reset_idx(self, env_ids: torch.Tensor | None):
if env_ids is None or len(env_ids) == self.num_envs:
env_ids = self._robot._ALL_INDICES
self._robot.reset(env_ids)
super()._reset_idx(env_ids)
if len(env_ids) == self.num_envs:
# Spread out the resets to avoid spikes in training when many environments reset at a similar time
self.episode_length_buf[:] = torch.randint_like(self.episode_length_buf, high=int(self.max_episode_length))
self._actions[env_ids] = 0.0
self._previous_actions[env_ids] = 0.0
# Sample new commands
self._commands[env_ids] = torch.zeros_like(self._commands[env_ids]).uniform_(-1.0, 1.0)
# Reset robot state
joint_pos = self._robot.data.default_joint_pos[env_ids]
joint_vel = self._robot.data.default_joint_vel[env_ids]
default_root_state = self._robot.data.default_root_state[env_ids]
default_root_state[:, :3] += self._terrain.env_origins[env_ids]
self._robot.write_root_pose_to_sim(default_root_state[:, :7], env_ids)
self._robot.write_root_velocity_to_sim(default_root_state[:, 7:], env_ids)
self._robot.write_joint_state_to_sim(joint_pos, joint_vel, None, env_ids)
# Logging
extras = dict()
for key in self._episode_sums.keys():
episodic_sum_avg = torch.mean(self._episode_sums[key][env_ids])
extras["Episode Reward/" + key] = episodic_sum_avg / self.max_episode_length_s
self._episode_sums[key][env_ids] = 0.0
self.extras["log"] = dict()
self.extras["log"].update(extras)
extras = dict()
extras["Episode Termination/base_contact"] = torch.count_nonzero(self.reset_terminated[env_ids]).item()
extras["Episode Termination/time_out"] = torch.count_nonzero(self.reset_time_outs[env_ids]).item()
self.extras["log"].update(extras)
| 13,576 |
Python
| 42.938511 | 119 | 0.617045 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/anymal_c/agents/rsl_rl_ppo_cfg.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.lab.utils import configclass
from omni.isaac.lab_tasks.utils.wrappers.rsl_rl import (
RslRlOnPolicyRunnerCfg,
RslRlPpoActorCriticCfg,
RslRlPpoAlgorithmCfg,
)
@configclass
class AnymalCFlatPPORunnerCfg(RslRlOnPolicyRunnerCfg):
num_steps_per_env = 24
max_iterations = 500
save_interval = 50
experiment_name = "anymal_c_flat_direct"
empirical_normalization = False
policy = RslRlPpoActorCriticCfg(
init_noise_std=1.0,
actor_hidden_dims=[128, 128, 128],
critic_hidden_dims=[128, 128, 128],
activation="elu",
)
algorithm = RslRlPpoAlgorithmCfg(
value_loss_coef=1.0,
use_clipped_value_loss=True,
clip_param=0.2,
entropy_coef=0.005,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=1.0e-3,
schedule="adaptive",
gamma=0.99,
lam=0.95,
desired_kl=0.01,
max_grad_norm=1.0,
)
@configclass
class AnymalCRoughPPORunnerCfg(RslRlOnPolicyRunnerCfg):
num_steps_per_env = 24
max_iterations = 1500
save_interval = 50
experiment_name = "anymal_c_rough_direct"
empirical_normalization = False
policy = RslRlPpoActorCriticCfg(
init_noise_std=1.0,
actor_hidden_dims=[512, 256, 128],
critic_hidden_dims=[512, 256, 128],
activation="elu",
)
algorithm = RslRlPpoAlgorithmCfg(
value_loss_coef=1.0,
use_clipped_value_loss=True,
clip_param=0.2,
entropy_coef=0.005,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=1.0e-3,
schedule="adaptive",
gamma=0.99,
lam=0.95,
desired_kl=0.01,
max_grad_norm=1.0,
)
| 1,877 |
Python
| 25.450704 | 60 | 0.626532 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/anymal_c/agents/rl_games_flat_ppo_cfg.yaml
|
params:
seed: 42
# environment wrapper clipping
env:
clip_actions: 1.0
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [128, 128, 128]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: False # flag which sets whether to load the checkpoint
load_path: '' # path to the checkpoint to load
config:
name: anymal_c_flat_direct
env_name: rlgpu
device: 'cuda:0'
device_name: 'cuda:0'
multi_gpu: False
ppo: True
mixed_precision: True
normalize_input: False
normalize_value: True
value_bootstrap: True
num_actors: -1 # configured from the script (based on num_envs)
reward_shaper:
scale_value: 0.6
normalize_advantage: True
gamma: 0.99
tau: 0.95
learning_rate: 1e-3
lr_schedule: adaptive
schedule_type: legacy
kl_threshold: 0.01
score_to_win: 20000
max_epochs: 1500
save_best_after: 100
save_frequency: 50
grad_norm: 1.0
entropy_coef: 0.005
truncate_grads: True
e_clip: 0.2
horizon_length: 24
minibatch_size: 24576
mini_epochs: 5
critic_coef: 2.0
clip_value: True
seq_length: 4
bounds_loss_coef: 0.0
| 1,572 |
YAML
| 19.428571 | 73 | 0.608142 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/anymal_c/agents/rl_games_rough_ppo_cfg.yaml
|
params:
seed: 42
# environment wrapper clipping
env:
clip_actions: 1.0
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [512, 256, 128]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: False # flag which sets whether to load the checkpoint
load_path: '' # path to the checkpoint to load
config:
name: anymal_c_rough_direct
env_name: rlgpu
device: 'cuda:0'
device_name: 'cuda:0'
multi_gpu: False
ppo: True
mixed_precision: True
normalize_input: False
normalize_value: True
value_bootstrap: True
num_actors: -1 # configured from the script (based on num_envs)
reward_shaper:
scale_value: 0.6
normalize_advantage: True
gamma: 0.99
tau: 0.95
learning_rate: 1e-3
lr_schedule: adaptive
schedule_type: legacy
kl_threshold: 0.01
score_to_win: 20000
max_epochs: 1500
save_best_after: 100
save_frequency: 50
grad_norm: 1.0
entropy_coef: 0.005
truncate_grads: True
e_clip: 0.2
horizon_length: 24
minibatch_size: 24576
mini_epochs: 5
critic_coef: 2.0
clip_value: True
seq_length: 4
bounds_loss_coef: 0.0
| 1,573 |
YAML
| 19.441558 | 73 | 0.608392 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/anymal_c/agents/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from . import rsl_rl_ppo_cfg
| 156 |
Python
| 21.428568 | 60 | 0.737179 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/anymal_c/agents/skrl_rough_ppo_cfg.yaml
|
seed: 42
# Models are instantiated using skrl's model instantiator utility
# https://skrl.readthedocs.io/en/latest/api/utils/model_instantiators.html
models:
separate: False
policy: # see skrl.utils.model_instantiators.torch.gaussian_model for parameter details
clip_actions: True
clip_log_std: True
initial_log_std: 0
min_log_std: -20.0
max_log_std: 2.0
input_shape: "Shape.STATES"
hiddens: [512, 256, 128]
hidden_activation: ["elu", "elu"]
output_shape: "Shape.ACTIONS"
output_activation: ""
output_scale: 1.0
value: # see skrl.utils.model_instantiators.torch.deterministic_model for parameter details
clip_actions: False
input_shape: "Shape.STATES"
hiddens: [512, 256, 128]
hidden_activation: ["elu", "elu"]
output_shape: "Shape.ONE"
output_activation: ""
output_scale: 1.0
# PPO agent configuration (field names are from PPO_DEFAULT_CONFIG)
# https://skrl.readthedocs.io/en/latest/api/agents/ppo.html
agent:
rollouts: 24
learning_epochs: 5
mini_batches: 4
discount_factor: 0.99
lambda: 0.95
learning_rate: 1.e-3
learning_rate_scheduler: "KLAdaptiveLR"
learning_rate_scheduler_kwargs:
kl_threshold: 0.01
state_preprocessor: "RunningStandardScaler"
state_preprocessor_kwargs: null
value_preprocessor: "RunningStandardScaler"
value_preprocessor_kwargs: null
random_timesteps: 0
learning_starts: 0
grad_norm_clip: 1.0
ratio_clip: 0.2
value_clip: 0.2
clip_predicted_values: True
entropy_loss_scale: 0.005
value_loss_scale: 1.0
kl_threshold: 0
rewards_shaper_scale: 0.6
# logging and checkpoint
experiment:
directory: "anymal_c_rough_direct"
experiment_name: ""
write_interval: 180
checkpoint_interval: 1800
# Sequential trainer
# https://skrl.readthedocs.io/en/latest/api/trainers/sequential.html
trainer:
timesteps: 36000
environment_info: "log"
| 1,903 |
YAML
| 27 | 94 | 0.712034 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/direct/anymal_c/agents/skrl_flat_ppo_cfg.yaml
|
seed: 42
# Models are instantiated using skrl's model instantiator utility
# https://skrl.readthedocs.io/en/latest/api/utils/model_instantiators.html
models:
separate: False
policy: # see skrl.utils.model_instantiators.torch.gaussian_model for parameter details
clip_actions: True
clip_log_std: True
initial_log_std: 0
min_log_std: -20.0
max_log_std: 2.0
input_shape: "Shape.STATES"
hiddens: [128, 128, 128]
hidden_activation: ["elu", "elu"]
output_shape: "Shape.ACTIONS"
output_activation: ""
output_scale: 1.0
value: # see skrl.utils.model_instantiators.torch.deterministic_model for parameter details
clip_actions: False
input_shape: "Shape.STATES"
hiddens: [128, 128, 128]
hidden_activation: ["elu", "elu"]
output_shape: "Shape.ONE"
output_activation: ""
output_scale: 1.0
# PPO agent configuration (field names are from PPO_DEFAULT_CONFIG)
# https://skrl.readthedocs.io/en/latest/api/agents/ppo.html
agent:
rollouts: 24
learning_epochs: 5
mini_batches: 4
discount_factor: 0.99
lambda: 0.95
learning_rate: 1.e-3
learning_rate_scheduler: "KLAdaptiveLR"
learning_rate_scheduler_kwargs:
kl_threshold: 0.01
state_preprocessor: "RunningStandardScaler"
state_preprocessor_kwargs: null
value_preprocessor: "RunningStandardScaler"
value_preprocessor_kwargs: null
random_timesteps: 0
learning_starts: 0
grad_norm_clip: 1.0
ratio_clip: 0.2
value_clip: 0.2
clip_predicted_values: True
entropy_loss_scale: 0.005
value_loss_scale: 1.0
kl_threshold: 0
rewards_shaper_scale: 0.6
# logging and checkpoint
experiment:
directory: "anymal_c_flat_direct"
experiment_name: ""
write_interval: 60
checkpoint_interval: 600
# Sequential trainer
# https://skrl.readthedocs.io/en/latest/api/trainers/sequential.html
trainer:
timesteps: 12000
environment_info: "log"
| 1,900 |
YAML
| 26.955882 | 94 | 0.711579 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Config-based workflow environments.
"""
import gymnasium as gym
| 196 |
Python
| 16.909089 | 60 | 0.739796 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Classic environments for control.
These environments are based on the MuJoCo environments provided by OpenAI.
Reference:
https://github.com/openai/gym/tree/master/gym/envs/mujoco
"""
| 319 |
Python
| 23.615383 | 75 | 0.758621 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/ant/ant_env_cfg.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import omni.isaac.lab.sim as sim_utils
from omni.isaac.lab.assets import AssetBaseCfg
from omni.isaac.lab.envs import ManagerBasedRLEnvCfg
from omni.isaac.lab.managers import EventTermCfg as EventTerm
from omni.isaac.lab.managers import ObservationGroupCfg as ObsGroup
from omni.isaac.lab.managers import ObservationTermCfg as ObsTerm
from omni.isaac.lab.managers import RewardTermCfg as RewTerm
from omni.isaac.lab.managers import SceneEntityCfg
from omni.isaac.lab.managers import TerminationTermCfg as DoneTerm
from omni.isaac.lab.scene import InteractiveSceneCfg
from omni.isaac.lab.terrains import TerrainImporterCfg
from omni.isaac.lab.utils import configclass
import omni.isaac.lab_tasks.manager_based.classic.humanoid.mdp as mdp
##
# Pre-defined configs
##
from omni.isaac.lab_assets.ant import ANT_CFG # isort: skip
@configclass
class MySceneCfg(InteractiveSceneCfg):
"""Configuration for the terrain scene with an ant robot."""
# terrain
terrain = TerrainImporterCfg(
prim_path="/World/ground",
terrain_type="plane",
collision_group=-1,
physics_material=sim_utils.RigidBodyMaterialCfg(
friction_combine_mode="average",
restitution_combine_mode="average",
static_friction=1.0,
dynamic_friction=1.0,
restitution=0.0,
),
debug_vis=False,
)
# robot
robot = ANT_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
# lights
light = AssetBaseCfg(
prim_path="/World/light",
spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0),
)
##
# MDP settings
##
@configclass
class CommandsCfg:
"""Command terms for the MDP."""
# no commands for this MDP
null = mdp.NullCommandCfg()
@configclass
class ActionsCfg:
"""Action specifications for the MDP."""
joint_effort = mdp.JointEffortActionCfg(asset_name="robot", joint_names=[".*"], scale=7.5)
@configclass
class ObservationsCfg:
"""Observation specifications for the MDP."""
@configclass
class PolicyCfg(ObsGroup):
"""Observations for the policy."""
base_height = ObsTerm(func=mdp.base_pos_z)
base_lin_vel = ObsTerm(func=mdp.base_lin_vel)
base_ang_vel = ObsTerm(func=mdp.base_ang_vel)
base_yaw_roll = ObsTerm(func=mdp.base_yaw_roll)
base_angle_to_target = ObsTerm(func=mdp.base_angle_to_target, params={"target_pos": (1000.0, 0.0, 0.0)})
base_up_proj = ObsTerm(func=mdp.base_up_proj)
base_heading_proj = ObsTerm(func=mdp.base_heading_proj, params={"target_pos": (1000.0, 0.0, 0.0)})
joint_pos_norm = ObsTerm(func=mdp.joint_pos_limit_normalized)
joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel, scale=0.2)
feet_body_forces = ObsTerm(
func=mdp.body_incoming_wrench,
scale=0.1,
params={
"asset_cfg": SceneEntityCfg(
"robot", body_names=["front_left_foot", "front_right_foot", "left_back_foot", "right_back_foot"]
)
},
)
actions = ObsTerm(func=mdp.last_action)
def __post_init__(self):
self.enable_corruption = False
self.concatenate_terms = True
# observation groups
policy: PolicyCfg = PolicyCfg()
@configclass
class EventCfg:
"""Configuration for events."""
reset_base = EventTerm(
func=mdp.reset_root_state_uniform,
mode="reset",
params={"pose_range": {}, "velocity_range": {}},
)
reset_robot_joints = EventTerm(
func=mdp.reset_joints_by_offset,
mode="reset",
params={
"position_range": (-0.2, 0.2),
"velocity_range": (-0.1, 0.1),
},
)
@configclass
class RewardsCfg:
"""Reward terms for the MDP."""
# (1) Reward for moving forward
progress = RewTerm(func=mdp.progress_reward, weight=1.0, params={"target_pos": (1000.0, 0.0, 0.0)})
# (2) Stay alive bonus
alive = RewTerm(func=mdp.is_alive, weight=0.5)
# (3) Reward for non-upright posture
upright = RewTerm(func=mdp.upright_posture_bonus, weight=0.1, params={"threshold": 0.93})
# (4) Reward for moving in the right direction
move_to_target = RewTerm(
func=mdp.move_to_target_bonus, weight=0.5, params={"threshold": 0.8, "target_pos": (1000.0, 0.0, 0.0)}
)
# (5) Penalty for large action commands
action_l2 = RewTerm(func=mdp.action_l2, weight=-0.005)
# (6) Penalty for energy consumption
energy = RewTerm(func=mdp.power_consumption, weight=-0.05, params={"gear_ratio": {".*": 15.0}})
# (7) Penalty for reaching close to joint limits
joint_limits = RewTerm(
func=mdp.joint_limits_penalty_ratio, weight=-0.1, params={"threshold": 0.99, "gear_ratio": {".*": 15.0}}
)
@configclass
class TerminationsCfg:
"""Termination terms for the MDP."""
# (1) Terminate if the episode length is exceeded
time_out = DoneTerm(func=mdp.time_out, time_out=True)
# (2) Terminate if the robot falls
torso_height = DoneTerm(func=mdp.root_height_below_minimum, params={"minimum_height": 0.31})
@configclass
class CurriculumCfg:
"""Curriculum terms for the MDP."""
pass
@configclass
class AntEnvCfg(ManagerBasedRLEnvCfg):
"""Configuration for the MuJoCo-style Ant walking environment."""
# Scene settings
scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=5.0)
# Basic settings
observations: ObservationsCfg = ObservationsCfg()
actions: ActionsCfg = ActionsCfg()
commands: CommandsCfg = CommandsCfg()
# MDP settings
rewards: RewardsCfg = RewardsCfg()
terminations: TerminationsCfg = TerminationsCfg()
events: EventCfg = EventCfg()
curriculum: CurriculumCfg = CurriculumCfg()
def __post_init__(self):
"""Post initialization."""
# general settings
self.decimation = 2
self.episode_length_s = 16.0
# simulation settings
self.sim.dt = 1 / 120.0
self.sim.physx.bounce_threshold_velocity = 0.2
# default friction material
self.sim.physics_material.static_friction = 1.0
self.sim.physics_material.dynamic_friction = 1.0
self.sim.physics_material.restitution = 0.0
| 6,402 |
Python
| 30.69802 | 116 | 0.652921 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/ant/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Ant locomotion environment (similar to OpenAI Gym Ant-v2).
"""
import gymnasium as gym
from . import agents, ant_env_cfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Ant-v0",
entry_point="omni.isaac.lab.envs:ManagerBasedRLEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": ant_env_cfg.AntEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.AntPPORunnerCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
"sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml",
},
)
| 786 |
Python
| 25.233332 | 79 | 0.656489 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/ant/agents/rsl_rl_ppo_cfg.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.lab.utils import configclass
from omni.isaac.lab_tasks.utils.wrappers.rsl_rl import (
RslRlOnPolicyRunnerCfg,
RslRlPpoActorCriticCfg,
RslRlPpoAlgorithmCfg,
)
@configclass
class AntPPORunnerCfg(RslRlOnPolicyRunnerCfg):
num_steps_per_env = 32
max_iterations = 1000
save_interval = 50
experiment_name = "ant"
empirical_normalization = False
policy = RslRlPpoActorCriticCfg(
init_noise_std=1.0,
actor_hidden_dims=[400, 200, 100],
critic_hidden_dims=[400, 200, 100],
activation="elu",
)
algorithm = RslRlPpoAlgorithmCfg(
value_loss_coef=1.0,
use_clipped_value_loss=True,
clip_param=0.2,
entropy_coef=0.0,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=5.0e-4,
schedule="adaptive",
gamma=0.99,
lam=0.95,
desired_kl=0.01,
max_grad_norm=1.0,
)
| 1,068 |
Python
| 24.45238 | 60 | 0.640449 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/ant/agents/skrl_ppo_cfg.yaml
|
seed: 42
# Models are instantiated using skrl's model instantiator utility
# https://skrl.readthedocs.io/en/latest/api/utils/model_instantiators.html
models:
separate: False
policy: # see skrl.utils.model_instantiators.torch.gaussian_model for parameter details
clip_actions: True
clip_log_std: True
initial_log_std: 0
min_log_std: -20.0
max_log_std: 2.0
input_shape: "Shape.STATES"
hiddens: [256, 128, 64]
hidden_activation: ["elu", "elu", "elu"]
output_shape: "Shape.ACTIONS"
output_activation: "tanh"
output_scale: 1.0
value: # see skrl.utils.model_instantiators.torch.deterministic_model for parameter details
clip_actions: False
input_shape: "Shape.STATES"
hiddens: [256, 128, 64]
hidden_activation: ["elu", "elu", "elu"]
output_shape: "Shape.ONE"
output_activation: ""
output_scale: 1.0
# PPO agent configuration (field names are from PPO_DEFAULT_CONFIG)
# https://skrl.readthedocs.io/en/latest/api/agents/ppo.html
agent:
rollouts: 16
learning_epochs: 8
mini_batches: 4
discount_factor: 0.99
lambda: 0.95
learning_rate: 3.e-4
learning_rate_scheduler: "KLAdaptiveLR"
learning_rate_scheduler_kwargs:
kl_threshold: 0.008
state_preprocessor: "RunningStandardScaler"
state_preprocessor_kwargs: null
value_preprocessor: "RunningStandardScaler"
value_preprocessor_kwargs: null
random_timesteps: 0
learning_starts: 0
grad_norm_clip: 1.0
ratio_clip: 0.2
value_clip: 0.2
clip_predicted_values: True
entropy_loss_scale: 0.0
value_loss_scale: 1.0
kl_threshold: 0
rewards_shaper_scale: 0.01
# logging and checkpoint
experiment:
directory: "ant"
experiment_name: ""
write_interval: 40
checkpoint_interval: 400
# Sequential trainer
# https://skrl.readthedocs.io/en/latest/api/trainers/sequential.html
trainer:
timesteps: 8000
environment_info: "log"
| 1,898 |
YAML
| 26.92647 | 94 | 0.708641 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/ant/agents/sb3_ppo_cfg.yaml
|
# Reference: https://github.com/DLR-RM/rl-baselines3-zoo/blob/master/hyperparams/ppo.yml#L161
seed: 42
n_timesteps: !!float 1e7
policy: 'MlpPolicy'
batch_size: 128
n_steps: 512
gamma: 0.99
gae_lambda: 0.9
n_epochs: 20
ent_coef: 0.0
sde_sample_freq: 4
max_grad_norm: 0.5
vf_coef: 0.5
learning_rate: !!float 3e-5
use_sde: True
clip_range: 0.4
device: "cuda:0"
policy_kwargs: "dict(
log_std_init=-1,
ortho_init=False,
activation_fn=nn.ReLU,
net_arch=dict(pi=[256, 256], vf=[256, 256])
)"
| 574 |
YAML
| 21.999999 | 93 | 0.599303 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/ant/agents/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from . import rsl_rl_ppo_cfg
| 156 |
Python
| 21.428568 | 60 | 0.737179 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/ant/agents/rl_games_ppo_cfg.yaml
|
params:
seed: 42
# environment wrapper clipping
env:
clip_actions: 1.0
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [256, 128, 64]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: False # flag which sets whether to load the checkpoint
load_path: '' # path to the checkpoint to load
config:
name: ant
env_name: rlgpu
device: 'cuda:0'
device_name: 'cuda:0'
multi_gpu: False
ppo: True
mixed_precision: True
normalize_input: True
normalize_value: True
value_bootstrap: True
num_actors: -1
reward_shaper:
scale_value: 0.6
normalize_advantage: True
gamma: 0.99
tau: 0.95
learning_rate: 3e-4
lr_schedule: adaptive
schedule_type: legacy
kl_threshold: 0.008
score_to_win: 20000
max_epochs: 500
save_best_after: 100
save_frequency: 50
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 16
minibatch_size: 32768
mini_epochs: 4
critic_coef: 2
clip_value: True
seq_length: 4
bounds_loss_coef: 0.0001
| 1,502 |
YAML
| 18.51948 | 73 | 0.601198 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/cartpole/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Cartpole balancing environment.
"""
import gymnasium as gym
from . import agents
from .cartpole_env_cfg import CartpoleEnvCfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Cartpole-v0",
entry_point="omni.isaac.lab.envs:ManagerBasedRLEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": CartpoleEnvCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.CartpolePPORunnerCfg,
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
"sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml",
},
)
| 794 |
Python
| 24.64516 | 79 | 0.670025 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/cartpole/cartpole_env_cfg.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import math
import omni.isaac.lab.sim as sim_utils
from omni.isaac.lab.assets import ArticulationCfg, AssetBaseCfg
from omni.isaac.lab.envs import ManagerBasedRLEnvCfg
from omni.isaac.lab.managers import EventTermCfg as EventTerm
from omni.isaac.lab.managers import ObservationGroupCfg as ObsGroup
from omni.isaac.lab.managers import ObservationTermCfg as ObsTerm
from omni.isaac.lab.managers import RewardTermCfg as RewTerm
from omni.isaac.lab.managers import SceneEntityCfg
from omni.isaac.lab.managers import TerminationTermCfg as DoneTerm
from omni.isaac.lab.scene import InteractiveSceneCfg
from omni.isaac.lab.utils import configclass
import omni.isaac.lab_tasks.manager_based.classic.cartpole.mdp as mdp
##
# Pre-defined configs
##
from omni.isaac.lab_assets.cartpole import CARTPOLE_CFG # isort:skip
##
# Scene definition
##
@configclass
class CartpoleSceneCfg(InteractiveSceneCfg):
"""Configuration for a cart-pole scene."""
# ground plane
ground = AssetBaseCfg(
prim_path="/World/ground",
spawn=sim_utils.GroundPlaneCfg(size=(100.0, 100.0)),
)
# cartpole
robot: ArticulationCfg = CARTPOLE_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
# lights
dome_light = AssetBaseCfg(
prim_path="/World/DomeLight",
spawn=sim_utils.DomeLightCfg(color=(0.9, 0.9, 0.9), intensity=500.0),
)
distant_light = AssetBaseCfg(
prim_path="/World/DistantLight",
spawn=sim_utils.DistantLightCfg(color=(0.9, 0.9, 0.9), intensity=2500.0),
init_state=AssetBaseCfg.InitialStateCfg(rot=(0.738, 0.477, 0.477, 0.0)),
)
##
# MDP settings
##
@configclass
class CommandsCfg:
"""Command terms for the MDP."""
# no commands for this MDP
null = mdp.NullCommandCfg()
@configclass
class ActionsCfg:
"""Action specifications for the MDP."""
joint_effort = mdp.JointEffortActionCfg(asset_name="robot", joint_names=["slider_to_cart"], scale=100.0)
@configclass
class ObservationsCfg:
"""Observation specifications for the MDP."""
@configclass
class PolicyCfg(ObsGroup):
"""Observations for policy group."""
# observation terms (order preserved)
joint_pos_rel = ObsTerm(func=mdp.joint_pos_rel)
joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel)
def __post_init__(self) -> None:
self.enable_corruption = False
self.concatenate_terms = True
# observation groups
policy: PolicyCfg = PolicyCfg()
@configclass
class EventCfg:
"""Configuration for events."""
# reset
reset_cart_position = EventTerm(
func=mdp.reset_joints_by_offset,
mode="reset",
params={
"asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"]),
"position_range": (-1.0, 1.0),
"velocity_range": (-0.5, 0.5),
},
)
reset_pole_position = EventTerm(
func=mdp.reset_joints_by_offset,
mode="reset",
params={
"asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"]),
"position_range": (-0.25 * math.pi, 0.25 * math.pi),
"velocity_range": (-0.25 * math.pi, 0.25 * math.pi),
},
)
@configclass
class RewardsCfg:
"""Reward terms for the MDP."""
# (1) Constant running reward
alive = RewTerm(func=mdp.is_alive, weight=1.0)
# (2) Failure penalty
terminating = RewTerm(func=mdp.is_terminated, weight=-2.0)
# (3) Primary task: keep pole upright
pole_pos = RewTerm(
func=mdp.joint_pos_target_l2,
weight=-1.0,
params={"asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"]), "target": 0.0},
)
# (4) Shaping tasks: lower cart velocity
cart_vel = RewTerm(
func=mdp.joint_vel_l1,
weight=-0.01,
params={"asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"])},
)
# (5) Shaping tasks: lower pole angular velocity
pole_vel = RewTerm(
func=mdp.joint_vel_l1,
weight=-0.005,
params={"asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"])},
)
@configclass
class TerminationsCfg:
"""Termination terms for the MDP."""
# (1) Time out
time_out = DoneTerm(func=mdp.time_out, time_out=True)
# (2) Cart out of bounds
cart_out_of_bounds = DoneTerm(
func=mdp.joint_pos_out_of_manual_limit,
params={"asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"]), "bounds": (-3.0, 3.0)},
)
@configclass
class CurriculumCfg:
"""Configuration for the curriculum."""
pass
##
# Environment configuration
##
@configclass
class CartpoleEnvCfg(ManagerBasedRLEnvCfg):
"""Configuration for the locomotion velocity-tracking environment."""
# Scene settings
scene: CartpoleSceneCfg = CartpoleSceneCfg(num_envs=4096, env_spacing=4.0)
# Basic settings
observations: ObservationsCfg = ObservationsCfg()
actions: ActionsCfg = ActionsCfg()
events: EventCfg = EventCfg()
# MDP settings
curriculum: CurriculumCfg = CurriculumCfg()
rewards: RewardsCfg = RewardsCfg()
terminations: TerminationsCfg = TerminationsCfg()
# No command generator
commands: CommandsCfg = CommandsCfg()
# Post initialization
def __post_init__(self) -> None:
"""Post initialization."""
# general settings
self.decimation = 2
self.episode_length_s = 5
# viewer settings
self.viewer.eye = (8.0, 0.0, 5.0)
# simulation settings
self.sim.dt = 1 / 120
| 5,686 |
Python
| 26.877451 | 109 | 0.653535 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/cartpole/agents/rsl_rl_ppo_cfg.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.lab.utils import configclass
from omni.isaac.lab_tasks.utils.wrappers.rsl_rl import (
RslRlOnPolicyRunnerCfg,
RslRlPpoActorCriticCfg,
RslRlPpoAlgorithmCfg,
)
@configclass
class CartpolePPORunnerCfg(RslRlOnPolicyRunnerCfg):
num_steps_per_env = 16
max_iterations = 150
save_interval = 50
experiment_name = "cartpole"
empirical_normalization = False
policy = RslRlPpoActorCriticCfg(
init_noise_std=1.0,
actor_hidden_dims=[32, 32],
critic_hidden_dims=[32, 32],
activation="elu",
)
algorithm = RslRlPpoAlgorithmCfg(
value_loss_coef=1.0,
use_clipped_value_loss=True,
clip_param=0.2,
entropy_coef=0.005,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=1.0e-3,
schedule="adaptive",
gamma=0.99,
lam=0.95,
desired_kl=0.01,
max_grad_norm=1.0,
)
| 1,065 |
Python
| 24.380952 | 60 | 0.643192 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/cartpole/agents/skrl_ppo_cfg.yaml
|
seed: 42
# Models are instantiated using skrl's model instantiator utility
# https://skrl.readthedocs.io/en/latest/api/utils/model_instantiators.html
models:
separate: False
policy: # see skrl.utils.model_instantiators.torch.gaussian_model for parameter details
clip_actions: True
clip_log_std: True
initial_log_std: 0
min_log_std: -20.0
max_log_std: 2.0
input_shape: "Shape.STATES"
hiddens: [32, 32]
hidden_activation: ["elu", "elu"]
output_shape: "Shape.ACTIONS"
output_activation: "tanh"
output_scale: 1.0
value: # see skrl.utils.model_instantiators.torch.deterministic_model for parameter details
clip_actions: False
input_shape: "Shape.STATES"
hiddens: [32, 32]
hidden_activation: ["elu", "elu"]
output_shape: "Shape.ONE"
output_activation: ""
output_scale: 1.0
# PPO agent configuration (field names are from PPO_DEFAULT_CONFIG)
# https://skrl.readthedocs.io/en/latest/api/agents/ppo.html
agent:
rollouts: 16
learning_epochs: 5
mini_batches: 4
discount_factor: 0.99
lambda: 0.95
learning_rate: 1.e-3
learning_rate_scheduler: "KLAdaptiveLR"
learning_rate_scheduler_kwargs:
kl_threshold: 0.01
state_preprocessor: "RunningStandardScaler"
state_preprocessor_kwargs: null
value_preprocessor: "RunningStandardScaler"
value_preprocessor_kwargs: null
random_timesteps: 0
learning_starts: 0
grad_norm_clip: 1.0
ratio_clip: 0.2
value_clip: 0.2
clip_predicted_values: True
entropy_loss_scale: 0.0
value_loss_scale: 2.0
kl_threshold: 0
rewards_shaper_scale: 1.0
# logging and checkpoint
experiment:
directory: "cartpole"
experiment_name: ""
write_interval: 12
checkpoint_interval: 120
# Sequential trainer
# https://skrl.readthedocs.io/en/latest/api/trainers/sequential.html
trainer:
timesteps: 2400
environment_info: "log"
| 1,875 |
YAML
| 26.588235 | 94 | 0.711467 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/cartpole/agents/sb3_ppo_cfg.yaml
|
# Reference: https://github.com/DLR-RM/rl-baselines3-zoo/blob/master/hyperparams/ppo.yml#L32
seed: 42
n_timesteps: !!float 1e6
policy: 'MlpPolicy'
n_steps: 16
batch_size: 4096
gae_lambda: 0.95
gamma: 0.99
n_epochs: 20
ent_coef: 0.01
learning_rate: !!float 3e-4
clip_range: !!float 0.2
policy_kwargs: "dict(
activation_fn=nn.ELU,
net_arch=[32, 32],
squash_output=False,
)"
vf_coef: 1.0
max_grad_norm: 1.0
device: "cuda:0"
| 492 |
YAML
| 21.40909 | 92 | 0.611789 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/cartpole/agents/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from . import rsl_rl_ppo_cfg # noqa: F401, F403
| 176 |
Python
| 24.285711 | 60 | 0.721591 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/cartpole/agents/rl_games_ppo_cfg.yaml
|
params:
seed: 42
# environment wrapper clipping
env:
# added to the wrapper
clip_observations: 5.0
# can make custom wrapper?
clip_actions: 1.0
algo:
name: a2c_continuous
model:
name: continuous_a2c_logstd
# doesn't have this fine grained control but made it close
network:
name: actor_critic
separate: False
space:
continuous:
mu_activation: None
sigma_activation: None
mu_init:
name: default
sigma_init:
name: const_initializer
val: 0
fixed_sigma: True
mlp:
units: [32, 32]
activation: elu
d2rl: False
initializer:
name: default
regularizer:
name: None
load_checkpoint: False # flag which sets whether to load the checkpoint
load_path: '' # path to the checkpoint to load
config:
name: cartpole
env_name: rlgpu
device: 'cuda:0'
device_name: 'cuda:0'
multi_gpu: False
ppo: True
mixed_precision: False
normalize_input: False
normalize_value: False
num_actors: -1 # configured from the script (based on num_envs)
reward_shaper:
scale_value: 1.0
normalize_advantage: False
gamma: 0.99
tau : 0.95
learning_rate: 3e-4
lr_schedule: adaptive
kl_threshold: 0.008
score_to_win: 20000
max_epochs: 150
save_best_after: 50
save_frequency: 25
grad_norm: 1.0
entropy_coef: 0.0
truncate_grads: True
e_clip: 0.2
horizon_length: 16
minibatch_size: 8192
mini_epochs: 8
critic_coef: 4
clip_value: True
seq_length: 4
bounds_loss_coef: 0.0001
| 1,648 |
YAML
| 19.873417 | 73 | 0.61165 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/cartpole/mdp/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""This sub-module contains the functions that are specific to the cartpole environments."""
from omni.isaac.lab.envs.mdp import * # noqa: F401, F403
from .rewards import * # noqa: F401, F403
| 323 |
Python
| 28.454543 | 92 | 0.733746 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/cartpole/mdp/rewards.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import torch
from typing import TYPE_CHECKING
from omni.isaac.lab.assets import Articulation
from omni.isaac.lab.managers import SceneEntityCfg
from omni.isaac.lab.utils.math import wrap_to_pi
if TYPE_CHECKING:
from omni.isaac.lab.envs import ManagerBasedRLEnv
def joint_pos_target_l2(env: ManagerBasedRLEnv, target: float, asset_cfg: SceneEntityCfg) -> torch.Tensor:
"""Penalize joint position deviation from a target value."""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
# wrap the joint positions to (-pi, pi)
joint_pos = wrap_to_pi(asset.data.joint_pos[:, asset_cfg.joint_ids])
# compute the reward
return torch.sum(torch.square(joint_pos - target), dim=1)
| 919 |
Python
| 33.074073 | 106 | 0.744287 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/humanoid/__init__.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Humanoid locomotion environment (similar to OpenAI Gym Humanoid-v2).
"""
import gymnasium as gym
from . import agents, humanoid_env_cfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Humanoid-v0",
entry_point="omni.isaac.lab.envs:ManagerBasedRLEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": humanoid_env_cfg.HumanoidEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_ppo_cfg.HumanoidPPORunnerCfg,
"rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml",
"skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml",
"sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml",
},
)
| 821 |
Python
| 26.399999 | 79 | 0.671133 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/humanoid/humanoid_env_cfg.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import omni.isaac.lab.sim as sim_utils
from omni.isaac.lab.actuators import ImplicitActuatorCfg
from omni.isaac.lab.assets import ArticulationCfg, AssetBaseCfg
from omni.isaac.lab.envs import ManagerBasedRLEnvCfg
from omni.isaac.lab.managers import EventTermCfg as EventTerm
from omni.isaac.lab.managers import ObservationGroupCfg as ObsGroup
from omni.isaac.lab.managers import ObservationTermCfg as ObsTerm
from omni.isaac.lab.managers import RewardTermCfg as RewTerm
from omni.isaac.lab.managers import SceneEntityCfg
from omni.isaac.lab.managers import TerminationTermCfg as DoneTerm
from omni.isaac.lab.scene import InteractiveSceneCfg
from omni.isaac.lab.terrains import TerrainImporterCfg
from omni.isaac.lab.utils import configclass
from omni.isaac.lab.utils.assets import ISAAC_NUCLEUS_DIR
import omni.isaac.lab_tasks.manager_based.classic.humanoid.mdp as mdp
##
# Scene definition
##
@configclass
class MySceneCfg(InteractiveSceneCfg):
"""Configuration for the terrain scene with a humanoid robot."""
# terrain
terrain = TerrainImporterCfg(
prim_path="/World/ground",
terrain_type="plane",
collision_group=-1,
physics_material=sim_utils.RigidBodyMaterialCfg(static_friction=1.0, dynamic_friction=1.0, restitution=0.0),
debug_vis=False,
)
# robot
robot = ArticulationCfg(
prim_path="{ENV_REGEX_NS}/Robot",
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Robots/Humanoid/humanoid_instanceable.usd",
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=None,
max_depenetration_velocity=10.0,
enable_gyroscopic_forces=True,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=True,
solver_position_iteration_count=4,
solver_velocity_iteration_count=0,
sleep_threshold=0.005,
stabilization_threshold=0.001,
),
copy_from_source=False,
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 1.34),
joint_pos={".*": 0.0},
),
actuators={
"body": ImplicitActuatorCfg(
joint_names_expr=[".*"],
stiffness={
".*_waist.*": 20.0,
".*_upper_arm.*": 10.0,
"pelvis": 10.0,
".*_lower_arm": 2.0,
".*_thigh:0": 10.0,
".*_thigh:1": 20.0,
".*_thigh:2": 10.0,
".*_shin": 5.0,
".*_foot.*": 2.0,
},
damping={
".*_waist.*": 5.0,
".*_upper_arm.*": 5.0,
"pelvis": 5.0,
".*_lower_arm": 1.0,
".*_thigh:0": 5.0,
".*_thigh:1": 5.0,
".*_thigh:2": 5.0,
".*_shin": 0.1,
".*_foot.*": 1.0,
},
),
},
)
# lights
light = AssetBaseCfg(
prim_path="/World/light",
spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0),
)
##
# MDP settings
##
@configclass
class CommandsCfg:
"""Command terms for the MDP."""
# no commands for this MDP
null = mdp.NullCommandCfg()
@configclass
class ActionsCfg:
"""Action specifications for the MDP."""
joint_effort = mdp.JointEffortActionCfg(
asset_name="robot",
joint_names=[".*"],
scale={
".*_waist.*": 67.5,
".*_upper_arm.*": 67.5,
"pelvis": 67.5,
".*_lower_arm": 45.0,
".*_thigh:0": 45.0,
".*_thigh:1": 135.0,
".*_thigh:2": 45.0,
".*_shin": 90.0,
".*_foot.*": 22.5,
},
)
@configclass
class ObservationsCfg:
"""Observation specifications for the MDP."""
@configclass
class PolicyCfg(ObsGroup):
"""Observations for the policy."""
base_height = ObsTerm(func=mdp.base_pos_z)
base_lin_vel = ObsTerm(func=mdp.base_lin_vel)
base_ang_vel = ObsTerm(func=mdp.base_ang_vel, scale=0.25)
base_yaw_roll = ObsTerm(func=mdp.base_yaw_roll)
base_angle_to_target = ObsTerm(func=mdp.base_angle_to_target, params={"target_pos": (1000.0, 0.0, 0.0)})
base_up_proj = ObsTerm(func=mdp.base_up_proj)
base_heading_proj = ObsTerm(func=mdp.base_heading_proj, params={"target_pos": (1000.0, 0.0, 0.0)})
joint_pos_norm = ObsTerm(func=mdp.joint_pos_limit_normalized)
joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel, scale=0.1)
feet_body_forces = ObsTerm(
func=mdp.body_incoming_wrench,
scale=0.01,
params={"asset_cfg": SceneEntityCfg("robot", body_names=["left_foot", "right_foot"])},
)
actions = ObsTerm(func=mdp.last_action)
def __post_init__(self):
self.enable_corruption = False
self.concatenate_terms = True
# observation groups
policy: PolicyCfg = PolicyCfg()
@configclass
class EventCfg:
"""Configuration for events."""
reset_base = EventTerm(
func=mdp.reset_root_state_uniform,
mode="reset",
params={"pose_range": {}, "velocity_range": {}},
)
reset_robot_joints = EventTerm(
func=mdp.reset_joints_by_offset,
mode="reset",
params={
"position_range": (-0.2, 0.2),
"velocity_range": (-0.1, 0.1),
},
)
@configclass
class RewardsCfg:
"""Reward terms for the MDP."""
# (1) Reward for moving forward
progress = RewTerm(func=mdp.progress_reward, weight=1.0, params={"target_pos": (1000.0, 0.0, 0.0)})
# (2) Stay alive bonus
alive = RewTerm(func=mdp.is_alive, weight=2.0)
# (3) Reward for non-upright posture
upright = RewTerm(func=mdp.upright_posture_bonus, weight=0.1, params={"threshold": 0.93})
# (4) Reward for moving in the right direction
move_to_target = RewTerm(
func=mdp.move_to_target_bonus, weight=0.5, params={"threshold": 0.8, "target_pos": (1000.0, 0.0, 0.0)}
)
# (5) Penalty for large action commands
action_l2 = RewTerm(func=mdp.action_l2, weight=-0.01)
# (6) Penalty for energy consumption
energy = RewTerm(
func=mdp.power_consumption,
weight=-0.005,
params={
"gear_ratio": {
".*_waist.*": 67.5,
".*_upper_arm.*": 67.5,
"pelvis": 67.5,
".*_lower_arm": 45.0,
".*_thigh:0": 45.0,
".*_thigh:1": 135.0,
".*_thigh:2": 45.0,
".*_shin": 90.0,
".*_foot.*": 22.5,
}
},
)
# (7) Penalty for reaching close to joint limits
joint_limits = RewTerm(
func=mdp.joint_limits_penalty_ratio,
weight=-0.25,
params={
"threshold": 0.98,
"gear_ratio": {
".*_waist.*": 67.5,
".*_upper_arm.*": 67.5,
"pelvis": 67.5,
".*_lower_arm": 45.0,
".*_thigh:0": 45.0,
".*_thigh:1": 135.0,
".*_thigh:2": 45.0,
".*_shin": 90.0,
".*_foot.*": 22.5,
},
},
)
@configclass
class TerminationsCfg:
"""Termination terms for the MDP."""
# (1) Terminate if the episode length is exceeded
time_out = DoneTerm(func=mdp.time_out, time_out=True)
# (2) Terminate if the robot falls
torso_height = DoneTerm(func=mdp.root_height_below_minimum, params={"minimum_height": 0.8})
@configclass
class CurriculumCfg:
"""Curriculum terms for the MDP."""
pass
@configclass
class HumanoidEnvCfg(ManagerBasedRLEnvCfg):
"""Configuration for the MuJoCo-style Humanoid walking environment."""
# Scene settings
scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=5.0)
# Basic settings
observations: ObservationsCfg = ObservationsCfg()
actions: ActionsCfg = ActionsCfg()
commands: CommandsCfg = CommandsCfg()
# MDP settings
rewards: RewardsCfg = RewardsCfg()
terminations: TerminationsCfg = TerminationsCfg()
events: EventCfg = EventCfg()
curriculum: CurriculumCfg = CurriculumCfg()
def __post_init__(self):
"""Post initialization."""
# general settings
self.decimation = 2
self.episode_length_s = 16.0
# simulation settings
self.sim.dt = 1 / 120.0
self.sim.physx.bounce_threshold_velocity = 0.2
# default friction material
self.sim.physics_material.static_friction = 1.0
self.sim.physics_material.dynamic_friction = 1.0
self.sim.physics_material.restitution = 0.0
| 9,092 |
Python
| 30.682927 | 116 | 0.558513 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/humanoid/agents/rsl_rl_ppo_cfg.py
|
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.lab.utils import configclass
from omni.isaac.lab_tasks.utils.wrappers.rsl_rl import (
RslRlOnPolicyRunnerCfg,
RslRlPpoActorCriticCfg,
RslRlPpoAlgorithmCfg,
)
@configclass
class HumanoidPPORunnerCfg(RslRlOnPolicyRunnerCfg):
num_steps_per_env = 32
max_iterations = 1000
save_interval = 50
experiment_name = "humanoid"
empirical_normalization = False
policy = RslRlPpoActorCriticCfg(
init_noise_std=1.0,
actor_hidden_dims=[400, 200, 100],
critic_hidden_dims=[400, 200, 100],
activation="elu",
)
algorithm = RslRlPpoAlgorithmCfg(
value_loss_coef=1.0,
use_clipped_value_loss=True,
clip_param=0.2,
entropy_coef=0.0,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=5.0e-4,
schedule="adaptive",
gamma=0.99,
lam=0.95,
desired_kl=0.01,
max_grad_norm=1.0,
)
| 1,078 |
Python
| 24.690476 | 60 | 0.643785 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/humanoid/agents/skrl_ppo_cfg.yaml
|
seed: 42
# Models are instantiated using skrl's model instantiator utility
# https://skrl.readthedocs.io/en/latest/api/utils/model_instantiators.html
models:
separate: False
policy: # see skrl.utils.model_instantiators.torch.gaussian_model for parameter details
clip_actions: True
clip_log_std: True
initial_log_std: 0
min_log_std: -20.0
max_log_std: 2.0
input_shape: "Shape.STATES"
hiddens: [400, 200, 100]
hidden_activation: ["elu", "elu", "elu"]
output_shape: "Shape.ACTIONS"
output_activation: "tanh"
output_scale: 1.0
value: # see skrl.utils.model_instantiators.torch.deterministic_model for parameter details
clip_actions: False
input_shape: "Shape.STATES"
hiddens: [400, 200, 100]
hidden_activation: ["elu", "elu", "elu"]
output_shape: "Shape.ONE"
output_activation: ""
output_scale: 1.0
# PPO agent configuration (field names are from PPO_DEFAULT_CONFIG)
# https://skrl.readthedocs.io/en/latest/api/agents/ppo.html
agent:
rollouts: 32
learning_epochs: 8
mini_batches: 8
discount_factor: 0.99
lambda: 0.95
learning_rate: 3.e-4
learning_rate_scheduler: "KLAdaptiveLR"
learning_rate_scheduler_kwargs:
kl_threshold: 0.008
state_preprocessor: "RunningStandardScaler"
state_preprocessor_kwargs: null
value_preprocessor: "RunningStandardScaler"
value_preprocessor_kwargs: null
random_timesteps: 0
learning_starts: 0
grad_norm_clip: 1.0
ratio_clip: 0.2
value_clip: 0.2
clip_predicted_values: True
entropy_loss_scale: 0.0
value_loss_scale: 1.0
kl_threshold: 0
rewards_shaper_scale: 0.01
# logging and checkpoint
experiment:
directory: "humanoid"
experiment_name: ""
write_interval: 80
checkpoint_interval: 800
# Sequential trainer
# https://skrl.readthedocs.io/en/latest/api/trainers/sequential.html
trainer:
timesteps: 16000
environment_info: "log"
| 1,906 |
YAML
| 27.044117 | 94 | 0.709864 |
isaac-sim/IsaacLab/source/extensions/omni.isaac.lab_tasks/omni/isaac/lab_tasks/manager_based/classic/humanoid/agents/sb3_ppo_cfg.yaml
|
# Reference: https://github.com/DLR-RM/rl-baselines3-zoo/blob/master/hyperparams/ppo.yml#L245
seed: 42
policy: 'MlpPolicy'
n_timesteps: !!float 5e7
batch_size: 256
n_steps: 512
gamma: 0.99
learning_rate: !!float 2.5e-4
ent_coef: 0.0
clip_range: 0.2
n_epochs: 10
gae_lambda: 0.95
max_grad_norm: 1.0
vf_coef: 0.5
device: "cuda:0"
policy_kwargs: "dict(
log_std_init=-1,
ortho_init=False,
activation_fn=nn.ReLU,
net_arch=dict(pi=[256, 256], vf=[256, 256])
)"
| 544 |
YAML
| 22.695651 | 93 | 0.591912 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.