Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
* Added the ``joint_ids_wp`` and ``body_ids_wp`` fields to :class:`~isaaclab.managers.SceneEntityCfg`: ``int32``
Warp arrays of the resolved joint and body indices, in the order of ``joint_ids`` and ``body_ids``, for Warp terms.
The new :meth:`~isaaclab.managers.SceneEntityCfg.resolve_warp_ids`, which the Warp managers call after
:meth:`~isaaclab.managers.SceneEntityCfg.resolve`, fills them; :meth:`~isaaclab.managers.SceneEntityCfg.resolve`,
``joint_ids`` and ``body_ids`` are unchanged. Copies of the configuration, :func:`copy.deepcopy` included, share
them; ``to_dict`` stores them as lists, and a pickled configuration leaves them out (``None``) until
:meth:`~isaaclab.managers.SceneEntityCfg.resolve_warp_ids` runs again.
* Added :attr:`~isaaclab.scene.InteractiveScene.env_origins_wp` and
:attr:`~isaaclab.terrains.TerrainImporter.env_origins_wp`, the ``wp.vec3f`` Warp array that holds the environment
origins, for Warp code. ``env_origins`` stays a :class:`torch.Tensor`, now a view of that array: assigning
``TerrainImporter.env_origins`` writes the new origins into it, so an earlier view of either stays current.
Empty file.
62 changes: 61 additions & 1 deletion source/isaaclab/isaaclab/managers/scene_entity_cfg.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@

from __future__ import annotations

from dataclasses import MISSING
import copy
from dataclasses import MISSING, field
from typing import TYPE_CHECKING

import numpy as np
import torch
import warp as wp

from ..utils import configclass

Expand Down Expand Up @@ -123,6 +126,22 @@ class for more details.

"""

joint_ids_wp: wp.array | None = field(default=None, metadata={"copy": False})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Api — Invalidate replaced Warp selections

replace() shares resolved Warp arrays while allowing joint_ids or body_ids to change. The replacement can report one selection and execute another. Clear derived IDs when selection fields change.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved by 0a297ba (#8856): the Warp managers fill joint_ids_wp and body_ids_wp right after every resolve(), so a replaced selection gets its own ids when it is resolved.

"""The selected joints as an ``int32`` Warp array of indices, in the order of :attr:`joint_ids`.
Defaults to None.

Filled by :meth:`resolve_warp_ids` for the Warp terms; torch terms read :attr:`joint_ids`.
:func:`~isaaclab.utils.clone`, :func:`~isaaclab.utils.replace` and :func:`copy.deepcopy` share it.
"""

body_ids_wp: wp.array | None = field(default=None, metadata={"copy": False})
"""The selected bodies as an ``int32`` Warp array of indices, in the order of :attr:`body_ids`.
Defaults to None.

Filled by :meth:`resolve_warp_ids` for the Warp terms; torch terms read :attr:`body_ids`.
:func:`~isaaclab.utils.clone`, :func:`~isaaclab.utils.replace` and :func:`copy.deepcopy` share it.
"""

def resolve(self, scene: InteractiveScene):
"""Resolves the scene entity and converts the joint and body names to indices.

Expand Down Expand Up @@ -156,6 +175,25 @@ def resolve(self, scene: InteractiveScene):
# convert object collection names to indices based on regex
self._resolve_object_collection_names(scene)

def resolve_warp_ids(self, scene: InteractiveScene):
"""Fill :attr:`joint_ids_wp` and :attr:`body_ids_wp` with the selected indices, in selection order.

The Warp managers call it after :meth:`resolve` for their terms; torch terms do not need it.
A slice expands over the entity's joints or bodies (the sensors of a contact sensor) and a negative index
wraps, as in torch indexing.

Args:
scene: The interactive scene instance.
"""
entity = scene[self.name]
if hasattr(entity, "num_joints"):
self.joint_ids_wp = wp.array(
np.arange(entity.num_joints, dtype=np.int32)[self.joint_ids], device=scene.device
)
num_bodies = entity.num_sensors if hasattr(entity, "num_sensors") else getattr(entity, "num_bodies", None)
if num_bodies is not None:
self.body_ids_wp = wp.array(np.arange(num_bodies, dtype=np.int32)[self.body_ids], device=scene.device)

def finalize(self, device: str) -> None:
"""Move resolved index selections to the device.

Expand All @@ -172,6 +210,28 @@ def finalize(self, device: str) -> None:
if not isinstance(indices, (slice, torch.Tensor)):
setattr(self, name, torch.tensor(indices, dtype=torch.long, device=device))

def __deepcopy__(self, memo: dict) -> SceneEntityCfg:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Style Consistency — Order deepcopy with dunder members

deepcopy follows public lifecycle methods, contrary to the prescribed class-member order. Move it before resolve and finalize.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left where it is: member order only, no behaviour change.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Style Consistency — Order the new dunder method

deepcopy follows ordinary public methods, contrary to the prescribed class-member order. Move it before resolve and finalize.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left where it is: member order only, no behaviour change.

"""Deep-copy every field, ``init=False`` ones included.

The Warp ids are shared: a Warp array cannot be deep-copied.
"""
memo[id(self)] = copied = copy.copy(self)
for name, value in vars(self).items():
if not isinstance(value, wp.array):
setattr(copied, name, copy.deepcopy(value, memo))
return copied

def __copy__(self) -> SceneEntityCfg:
"""Copy every field; the copy shares the Warp ids."""
copied = object.__new__(type(self))
copied.__dict__.update(vars(self))
return copied

def __getstate__(self) -> dict:
"""Pickle without the Warp ids, which a Warp array cannot be: they unpickle as None, and
:meth:`resolve_warp_ids` fills them again."""
return {**vars(self), "joint_ids_wp": None, "body_ids_wp": None}

def _resolve_joint_names(self, scene: InteractiveScene):
# convert joint names to indices based on regex
if self.joint_names is not None or self.joint_ids != slice(None):
Expand Down
33 changes: 29 additions & 4 deletions source/isaaclab/isaaclab/scene/interactive_scene.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,16 +315,41 @@ def num_envs(self) -> int:

@property
def env_origins(self) -> torch.Tensor:
"""Per-env world origins, shape ``(num_envs, 3)``."""
"""Per-env world origins, shape ``(num_envs, 3)``.

A torch view of :attr:`env_origins_wp`, which holds them, so a write of either shows in the other.
"""
if self._terrain is not None:
return self._terrain.env_origins
self._update_env_origins()
return self._env_origins_torch

@property
def env_origins_wp(self) -> wp.array:
"""Per-env world origins as a Warp array of ``wp.vec3f``, shape ``(num_envs,)``, for Warp code.

It holds the origins; :attr:`env_origins` is its torch view.
"""
if self._terrain is not None:
return self._terrain.env_origins_wp
self._update_env_origins()
return self._env_origins_wp

def _update_env_origins(self):
"""Write the origins of a new clone plan, or the first ones, into the held array, which keeps its address."""
plan = self.sim.get_clone_plan()
if plan is not None and plan is not self._env_origins_plan:
self._env_origins = plan.positions
self._env_origins_plan = plan
if not isinstance(self._env_origins, torch.Tensor):
self._env_origins = torch.as_tensor(self._env_origins, device=self._ALL_INDICES.device)
return self._env_origins
if self._env_origins is getattr(self, "_env_origins_written", None):
return
origins = torch.as_tensor(self._env_origins, dtype=torch.float32)
if getattr(self, "_env_origins_wp", None) is None or self._env_origins_wp.shape[0] != origins.shape[0]:
device = wp.device_from_torch(self._ALL_INDICES.device)
self._env_origins_wp = wp.zeros(origins.shape[0], dtype=wp.vec3f, device=device)
self._env_origins_torch = wp.to_torch(self._env_origins_wp)
self._env_origins_torch.copy_(origins)
self._env_origins_written = self._env_origins

@property
def terrain(self) -> TerrainImporter | None:
Expand Down
32 changes: 29 additions & 3 deletions source/isaaclab/isaaclab/terrains/terrain_importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import numpy as np
import torch
import trimesh
import warp as wp

from .. import sim as sim_utils
from ..markers import VisualizationMarkers
Expand Down Expand Up @@ -52,9 +53,6 @@ class TerrainImporter:
Otherwise, the environment origins are computed based on the grid spacing.
"""

env_origins: torch.Tensor
"""The origins of the environments. Shape is (num_envs, 3)."""

def __init__(self, cfg: TerrainImporterCfg):
"""Initialize the terrain importer.

Expand Down Expand Up @@ -142,6 +140,34 @@ def flat_patches(self) -> dict[str, torch.Tensor]:
"""
return self._terrain_flat_patches

@property
def env_origins(self) -> torch.Tensor | None:
"""The origins of the environments. Shape is (num_envs, 3).

A torch view of :attr:`env_origins_wp`, which holds them, so a write of either shows in the other. Assigning
origins writes them into the held array, so a view taken earlier stays valid.
"""
return getattr(self, "_env_origins", None)

@env_origins.setter
def env_origins(self, origins: torch.Tensor | np.ndarray | None):
if origins is None:
self._env_origins_wp = self._env_origins = None
return
origins = torch.as_tensor(origins, dtype=torch.float32)
if self.env_origins_wp is None or self.env_origins_wp.shape[0] != origins.shape[0]:
self._env_origins_wp = wp.zeros(origins.shape[0], dtype=wp.vec3f, device=self.device)
self._env_origins = wp.to_torch(self._env_origins_wp)
self._env_origins.copy_(origins)

@property
def env_origins_wp(self) -> wp.array | None:
"""The origins of the environments as a Warp array of ``wp.vec3f``, shape (num_envs,), for Warp code.

It holds the origins; :attr:`env_origins` is its torch view.
"""
return getattr(self, "_env_origins_wp", None)

@property
def terrain_names(self) -> list[str]:
"""A list of names of the imported terrains."""
Expand Down
5 changes: 5 additions & 0 deletions source/isaaclab/isaaclab/utils/configclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
from dataclasses import MISSING, Field, dataclass, field
from typing import Any, ClassVar, TypeVar

import warp as wp

from .dict import to_dict, update_from_dict
from .string import ResolvableString

Expand Down Expand Up @@ -366,6 +368,9 @@ def validate_config(self):
current_path = f"{prefix}[{index}]"
missing_fields.extend(_validate(item, prefix=current_path, _custom_validators=_custom_validators))
return missing_fields
elif isinstance(obj, wp.array):
# an array value, such as the Warp ids of a SceneEntityCfg, has no fields
return missing_fields
elif isinstance(obj, dict):
# Convert any non-string keys to strings to allow validation of dict with non-string keys
if any(not isinstance(key, str) for key in obj.keys()):
Expand Down
4 changes: 4 additions & 0 deletions source/isaaclab/isaaclab/utils/dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from typing import Any

import torch
import warp as wp

from .array import TENSOR_TYPE_CONVERSIONS, TENSOR_TYPES
from .string import ResolvableString, callable_to_string, string_to_slice
Expand Down Expand Up @@ -48,6 +49,9 @@ def class_to_dict(obj: object) -> dict[str, Any]:
# dict, which would mean that a torch.tensor would be stored as an empty dict. Instead we
# want to store it directly as the tensor.
return obj
elif isinstance(obj, wp.array):
# a Warp array (such as the Warp ids of a SceneEntityCfg) is stored as the list of its values
return obj.numpy().tolist()
elif hasattr(obj, "__dict__"):
obj_dict = obj.__dict__
else:
Expand Down
74 changes: 74 additions & 0 deletions source/isaaclab/test/managers/test_scene_entity_cfg.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,32 @@
"""Scene selections resolve on the host, then finalize to device indices used without synchronization."""

import copy
import pickle
from dataclasses import field
from functools import partial
from types import SimpleNamespace
from unittest.mock import Mock

import pytest
import torch
import warp as wp

from isaaclab.envs.mdp.events import apply_external_force_torque
from isaaclab.envs.mdp.observations import joint_pos
from isaaclab.managers import SceneEntityCfg
from isaaclab.test.utils import DeviceScope, test_devices
from isaaclab.utils import clone, configclass
from isaaclab.utils.string import resolve_matching_names

pytestmark = pytest.mark.unit


class _Scene(dict):
"""Entity lookup and device of :class:`~isaaclab.scene.InteractiveScene`."""

device = "cpu"


@pytest.fixture
def scene():
names = ["part_0", "part_1", "part_2", "part_3"]
Expand Down Expand Up @@ -108,3 +118,67 @@ def test_external_force_uses_selected_body_count(scene):
torch.testing.assert_close(kwargs["forces"], torch.full((2, 2, 3), 2.0))
torch.testing.assert_close(kwargs["torques"], torch.full((2, 2, 3), 3.0))
assert kwargs["body_ids"].tolist() == [3, 1]


def test_resolve_warp_ids_fills_the_selection_order(scene):
"""Warp ids keep the resolved order and repeats, expand slices, and count the bodies of a contact sensor.

:meth:`resolve` does no Warp work, so a scene without a device resolves the torch selections as on main.
"""
sensor_entity = SimpleNamespace(num_sensors=2, num_bodies=5)
subset = SceneEntityCfg("robot", joint_names=["part_2", "part_0"], preserve_order=True, body_ids=[3, 3, -1])
full = SceneEntityCfg("robot")
sensor = SceneEntityCfg("sensor")
for cfg in (subset, full, sensor):
cfg.resolve(dict(scene, sensor=sensor_entity))
assert cfg.joint_ids_wp is None and cfg.body_ids_wp is None
cfg.resolve_warp_ids(_Scene(scene, sensor=sensor_entity))

assert subset.joint_ids_wp.dtype == wp.int32
assert subset.joint_ids_wp.numpy().tolist() == [2, 0]
assert subset.body_ids_wp.numpy().tolist() == [3, 3, 3]
assert full.joint_ids_wp.numpy().tolist() == [0, 1, 2, 3]
assert full.body_ids_wp.numpy().tolist() == [0, 1, 2, 3]
assert sensor.joint_ids_wp is None
assert sensor.body_ids_wp.numpy().tolist() == [0, 1]


def test_a_cfg_with_warp_ids_serializes(scene):
"""With Warp ids, a configuration converts to a dictionary with the ids as lists and validates; it pickles
without them, and resolving the Warp ids again fills them."""
scene = _Scene(scene)
cfg = SceneEntityCfg("robot", joint_names=["part_2", "part_0"], preserve_order=True)
cfg.resolve(scene)
cfg.resolve_warp_ids(scene)

assert cfg.to_dict()["joint_ids_wp"] == [2, 0]
cfg.validate()
restored = pickle.loads(pickle.dumps(cfg))
assert restored.joint_ids == [2, 0] and restored.joint_ids_wp is None and restored.body_ids_wp is None
restored.resolve_warp_ids(scene)
assert restored.joint_ids_wp.numpy().tolist() == [2, 0]


@configclass
class _SelectionCfg(SceneEntityCfg):
"""Keeps resolved state in a field the constructor does not take, as the contrib selection configuration does."""

instance_ids: torch.Tensor = field(default_factory=lambda: torch.empty(0, dtype=torch.long), init=False)


def test_deepcopy_keeps_resolved_subclass_state(scene):
"""A deep copy keeps the fields the constructor does not take and, like any configuration copy, shares the Warp
ids instead of copying device memory."""
scene = _Scene(scene)
cfg = _SelectionCfg("robot", joint_names=["part_1"])
cfg.resolve(scene)
cfg.resolve_warp_ids(scene)
cfg.instance_ids = torch.tensor([3, -1, 0])

copied = copy.deepcopy(cfg)

torch.testing.assert_close(copied.instance_ids, cfg.instance_ids)
assert copied.instance_ids is not cfg.instance_ids
assert copied.joint_ids_wp is cfg.joint_ids_wp
assert copied.body_ids_wp is cfg.body_ids_wp
assert clone(cfg).joint_ids_wp is cfg.joint_ids_wp
3 changes: 3 additions & 0 deletions source/isaaclab/test/scene/test_interactive_scene.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@ def test_empty_scene_leaves_clone_lifecycle_to_caller():
env_template = scene.cfg.clone_cfg.clone_template
grid_positions = cloner.grid_transforms(4, 1.0)[0]
torch.testing.assert_close(scene.env_origins, torch.from_numpy(grid_positions))
first_origins_ptr = scene.env_origins_wp.ptr
env_0 = scene.stage.GetPrimAtPath(env_template.format(0))
assert env_0 and not env_0.GetAttribute("xformOpOrder").Get()
assert all(not scene.stage.GetPrimAtPath(env_template.format(i)).IsValid() for i in range(1, 4))
Expand All @@ -278,6 +279,8 @@ def test_empty_scene_leaves_clone_lifecycle_to_caller():
assert sim.get_clone_plan() is plan
assert all(scene.stage.GetPrimAtPath(f"{env_template.format(i)}/Cube").IsValid() for i in range(4))
torch.testing.assert_close(scene.env_origins, torch.from_numpy(positions))
# the Warp array holds the origins of the new clone plan at its address, and env_origins is its view
assert scene.env_origins_wp.ptr == scene.env_origins.data_ptr() == first_origins_ptr
for env_id, position in enumerate(positions):
np.testing.assert_allclose(
sim_utils.resolve_prim_pose(scene.stage.GetPrimAtPath(env_template.format(env_id)))[0], position
Expand Down
9 changes: 9 additions & 0 deletions source/isaaclab/test/terrains/test_terrain_importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ def test_plane(num_envs, env_spacing):
assert origins.device == torch.device("cuda:0")
torch.testing.assert_close(origins[0].cpu(), torch.tensor([half_span, -half_span, 0.0]))
torch.testing.assert_close(origins[-1].cpu(), torch.tensor([-half_span, half_span, 0.0]))
# the Warp array holds the origins and env_origins is its view
assert terrain_importer.env_origins_wp.ptr == origins.data_ptr()
assert terrain_importer.env_origins_wp.shape == (num_envs,)
origins_view = origins

# check if mesh prim path exists
mesh_prim_path = terrain_importer.cfg.prim_path + "/terrain"
Expand Down Expand Up @@ -128,6 +132,11 @@ def test_plane(num_envs, env_spacing):
mesh = _obtain_collision_mesh(mesh_prim_path, mesh_type="Plane")
assert mesh is None

# assigning the origins again writes them into the held array, so the earlier view shows them
terrain_importer.env_origins = torch.ones(num_envs, 3, device="cuda:0")
assert terrain_importer.env_origins.data_ptr() == origins_view.data_ptr()
torch.testing.assert_close(origins_view, torch.ones(num_envs, 3, device="cuda:0"))


def test_usd():
"""Imports terrain from a usd and tests that the resulting mesh has the correct size."""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
* Changed the Warp joint penalties ``joint_torques_l2``, ``joint_vel_l1``, ``joint_vel_l2``, ``joint_acc_l2``,
``joint_deviation_l1`` and ``joint_pos_limits``, and the termination ``joint_pos_out_of_manual_limit``, to loop over
the selected joints in the order of ``joint_ids``. A joint selected twice now counts twice, as in the torch terms.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
* **Breaking:** Removed the Warp subclass ``isaaclab_experimental.managers.SceneEntityCfg``; the name now resolves to
:class:`isaaclab.managers.SceneEntityCfg`, whose ``joint_ids_wp`` and ``body_ids_wp`` the Warp managers fill. Its
``joint_mask`` and ``from_stable`` are removed: Warp terms loop over ``joint_ids_wp``.
Loading
Loading