From fe830d2ce89b4644b3861a5c70e7502a421917e5 Mon Sep 17 00:00:00 2001 From: Neel Jawale Date: Mon, 16 Nov 2026 22:18:32 -0800 Subject: [PATCH 1/4] Extend cuRobo planning for multi-arm robots Add named planning groups, robot configuration and collision-sphere utilities, and embodiment-aware planning queries. Preserve single-arm SkillGen planning and update Rerun plan playback. Signed-off-by: Neel Jawale --- autodata_interfaces/datastream/datastream.py | 232 +- autodata_interfaces/embodiments/__init__.py | 6 +- .../bimanual_embodiment_adapter.py | 269 ++- .../embodiments/embodiment_adapter.py | 213 +- .../embodiments/embodiment_types.py | 42 +- autodata_interfaces/env/pink_ik_action.py | 307 ++- .../motion_planners/__init__.py | 14 +- .../motion_planners/curobo/__init__.py | 36 +- .../curobo/collision_spheres.py | 480 ++++ .../motion_planners/curobo/curobo_planner.py | 2023 ++++++++++++++--- .../curobo/curobo_planner_cfg.py | 42 +- .../motion_planners/curobo/plan_visualizer.py | 432 ++-- .../motion_planners/curobo/planner_factory.py | 596 +++++ .../motion_planners/curobo/robot_config.py | 728 ++++++ .../motion_planners/motion_planner_base.py | 8 + .../interfaces/datastream/test_datastream.py | 8 + .../test_bimanual_embodiment_adapter.py | 29 + .../embodiments/test_embodiment_adapter.py | 20 + .../embodiments/test_embodiment_types.py | 14 +- .../interfaces/env/test_pink_ik_action.py | 135 ++ .../motion_planners/test_collision_spheres.py | 63 + .../test_curobo_planner_cfg.py | 30 + .../motion_planners/test_plan_visualizer.py | 70 + autodata_utils/pose_math.py | 18 + 24 files changed, 5366 insertions(+), 449 deletions(-) create mode 100644 autodata_interfaces/motion_planners/curobo/collision_spheres.py create mode 100644 autodata_interfaces/motion_planners/curobo/planner_factory.py create mode 100644 autodata_interfaces/motion_planners/curobo/robot_config.py create mode 100644 autodata_tests/interfaces/env/test_pink_ik_action.py create mode 100644 autodata_tests/interfaces/motion_planners/test_collision_spheres.py create mode 100644 autodata_tests/interfaces/motion_planners/test_plan_visualizer.py diff --git a/autodata_interfaces/datastream/datastream.py b/autodata_interfaces/datastream/datastream.py index 667537c..3ad5afa 100644 --- a/autodata_interfaces/datastream/datastream.py +++ b/autodata_interfaces/datastream/datastream.py @@ -5,13 +5,15 @@ import asyncio import torch -from collections.abc import Sequence +from collections.abc import Callable, Sequence +from pathlib import Path from typing import Any from isaaclab.utils.datasets import EpisodeData from autodata_core.pool import DataGenInfoPool from autodata_interfaces.embodiments.embodiment_adapter import EmbodimentAdapter +from autodata_interfaces.embodiments.embodiment_types import ActionTargetFrame, NamedJointTrajectory from autodata_interfaces.tasks.generation_policy_spec import GenerationPolicy from autodata_interfaces.tasks.subtask_constraint_spec import SubtaskConstraint from autodata_interfaces.tasks.subtask_spec import Subtask, SubtaskAlgoParams @@ -228,21 +230,164 @@ def get_robot_eef_pose(self, env_ids: Sequence[int] | None, eef_name: str) -> to return self.embodiment_adapter.get_eef_poses(env_ids=env_ids)[eef_name] - def get_robot_joint_positions(self, env_ids: Sequence[int] | None = None) -> torch.Tensor: - """Read the robot's current joint positions [rad] via the embodiment adapter. + def get_robot_joint_positions( + self, + env_ids: Sequence[int] | None = None, + *, + joint_names: Sequence[str] | None = None, + ) -> torch.Tensor: + """Read joint positions [rad, m] through the embodiment adapter. + + Args: + env_ids: Environment indices; None selects all environments. + joint_names: Ordered subset of articulation joints. None preserves native order. + + Returns: + Positions shaped ``(num_selected_envs, num_selected_joints)``. + """ + + if joint_names is None: + return self.embodiment_adapter.get_joint_positions(env_ids=env_ids) + return self.embodiment_adapter.get_joint_positions(env_ids=env_ids, joint_names=joint_names) + + def get_robot_joint_position_limits(self, env_ids: Sequence[int] | None = None) -> torch.Tensor: + """Read live lower and upper joint position limits [rad, m] via the embodiment adapter. - Returns a tensor of shape ``(len(env_ids), num_dof)`` in the articulation's native joint - order (see :meth:`get_robot_joint_names`). Consumed by motion planners as a planning - start state. + Args: + env_ids: Environment indices; None selects all environments. + + Returns: + Limits shaped ``(num_selected_envs, num_joints, 2)`` in articulation order. """ - return self.embodiment_adapter.get_joint_positions(env_ids=env_ids) + return self.embodiment_adapter.get_joint_position_limits(env_ids=env_ids) + + def get_robot_joint_velocity_limits(self, env_ids: Sequence[int] | None = None) -> torch.Tensor: + """Read live maximum joint speeds [rad/s, m/s] through the embodiment adapter. + + Args: + env_ids: Environment indices; None selects all environments. + + Returns: + Maximum speeds shaped ``(num_selected_envs, num_joints)`` in articulation order. + """ + return self.embodiment_adapter.get_joint_velocity_limits(env_ids=env_ids) def get_robot_joint_names(self) -> list[str]: - """Return the robot articulation's joint names, ordered to match :meth:`get_robot_joint_positions`.""" + """Return articulation joint names in native order.""" return self.embodiment_adapter.get_joint_names() + def get_robot_eef_joint_names(self, eef_name: str) -> tuple[str, ...]: + """Return positional passthrough joints owned by one end effector. + + Args: + eef_name: End effector to query. + + Returns: + Joint names in passthrough-action order. + """ + + return self.embodiment_adapter.get_eef_joint_names(eef_name) + + def get_eef_passthrough_preset(self, eef_name: str, preset_name: str) -> tuple[float, ...]: + """Return an embodiment-owned passthrough preset. + + Args: + eef_name: End effector to query. + preset_name: Configured posture name. + + Returns: + Joint positions in the end effector's passthrough-action order [rad, m]. + """ + + return self.embodiment_adapter.get_eef_passthrough_preset(eef_name, preset_name) + + def get_passthrough_actions( + self, + env_ids: Sequence[int] | None = None, + ) -> dict[str, torch.Tensor] | None: + """Return current passthrough actions when the embodiment can recover them. + + Args: + env_ids: Environment indices, or None for all environments. + + Returns: + Batched tensors per action channel, or None if a required channel is unavailable. + """ + + return self.embodiment_adapter.get_passthrough_actions(env_ids) + + def get_robot_action_target_frames(self) -> tuple[ActionTargetFrame, ...]: + """Return exact controlled frames in pose-action block order, when available.""" + + return self.embodiment_adapter.get_action_target_frames() + + def get_robot_planning_model_path(self) -> Path | None: + """Return the exact local model used by the live embodiment controller, when exposed.""" + + return self.embodiment_adapter.get_planning_model_path() + + def solve_robot_joint_trajectory( + self, + target_eef_poses: dict[str, torch.Tensor], + joint_seed_trajectories: dict[str, NamedJointTrajectory], + initial_joint_positions: torch.Tensor, + position_tolerance_m: float, + rotation_tolerance_rad: float, + joint_state_is_valid: Callable[[tuple[str, ...], torch.Tensor, int], bool] | None = None, + env_id: int = 0, + ) -> NamedJointTrajectory | None: + """Solve shared-joint end-effector targets through the embodiment controller. + + Args: + target_eef_poses: Target poses per end effector with shape (T, 4, 4) [m]. + joint_seed_trajectories: Named planner joint proposals per end effector. + initial_joint_positions: Initial state in live articulation joint order [rad, m]. + position_tolerance_m: Required tool-position accuracy [m]. + rotation_tolerance_rad: Required tool-rotation accuracy [rad]. + joint_state_is_valid: Optional feasibility check for each joint sample. + env_id: Environment controller to use. + + Returns: + Named joint trajectory, or None when the embodiment does not support coupled solving. + """ + + return self.embodiment_adapter.solve_joint_trajectory( + target_eef_poses, + joint_seed_trajectories, + initial_joint_positions, + position_tolerance_m, + rotation_tolerance_rad, + joint_state_is_valid, + env_id, + ) + + def set_robot_joint_posture_target( + self, + joint_names: tuple[str, ...], + joint_positions: torch.Tensor, + env_id: int = 0, + ) -> None: + """Set the embodiment controller's posture reference for the next step. + + Args: + joint_names: Names aligned with the position values. + joint_positions: Posture target with shape (J,) [rad, m]. + env_id: Environment controller to update. + """ + + self.embodiment_adapter.set_joint_posture_target(joint_names, joint_positions, env_id) + + def reset_robot_joint_posture_target(self, env_id: int = 0) -> None: + """Restore the embodiment controller's default posture reference. + + Args: + env_id: Environment controller to update. + """ + + self.embodiment_adapter.reset_joint_posture_target(env_id) + def target_eef_pose_to_action( self, target_eef_pose_dict: dict[str, torch.Tensor], @@ -269,6 +414,25 @@ def actions_to_passthrough_actions(self, actions: torch.Tensor) -> dict[str, tor return self.embodiment_adapter.actions_to_passthrough_actions(actions) + def passthrough_actions_to_joint_positions( + self, passthrough_action_dict: dict[str, torch.Tensor] + ) -> dict[str, torch.Tensor]: + """Apply passthrough commands as externally controlled articulation positions.""" + + return self.embodiment_adapter.passthrough_actions_to_joint_positions(passthrough_action_dict) + + def joint_positions_to_passthrough_actions( + self, + joint_position_dict: dict[str, torch.Tensor], + passthrough_action_dict: dict[str, torch.Tensor], + ) -> dict[str, torch.Tensor]: + """Project named planned joints into positional passthrough channels.""" + + return self.embodiment_adapter.joint_positions_to_passthrough_actions( + joint_position_dict, + passthrough_action_dict, + ) + # ------------------------------------------------------------------ # Other runtime queries # ------------------------------------------------------------------ @@ -373,6 +537,7 @@ def get_robot_root_pose(self, env_ids: Sequence[int] | None = None) -> torch.Ten :meth:`get_object_poses`. Without a configured controller frame, both queries return environment-relative poses. Motion planners use this pose to transform between the embodiment frame and the robot base frame their solver plans in. + Planning-root queries use :meth:`get_robot_planning_root_pose` for named links. """ index: slice | Sequence[int] = slice(None) if env_ids is None else env_ids @@ -385,6 +550,32 @@ def get_robot_root_pose(self, env_ids: Sequence[int] | None = None) -> torch.Ten reference_inverse = self._reference_frame_inverse(env_ids) return reference_inverse @ pose if reference_inverse is not None else pose + def get_robot_planning_root_pose( + self, + root_pose_source_frame_name: str, + env_ids: Sequence[int] | None = None, + ) -> torch.Tensor: + """Get the named kinematic planning-root pose in the env-relative frame. + + This is the frame-safe query for motion planning and ScheduleGen. It delegates to the + embodiment adapter so a controller-specific adapter can return the exact transform used + by its live controller. :meth:`get_robot_root_pose` remains the articulation-root query + used by legacy callers and is not assumed to equal this frame. + + Args: + root_pose_source_frame_name: Exact live controller/articulation lookup key declared by + the robot planning description. + env_ids: Environments to read; ``None`` reads all. + + Returns: + Planning-root transforms with shape ``(N, 4, 4)`` [m]. + """ + + poses = self.embodiment_adapter.get_planning_root_pose(root_pose_source_frame_name, env_ids) + assert isinstance(poses, torch.Tensor), "planning-root poses must be a torch.Tensor" + assert poses.ndim == 3 and poses.shape[1:] == (4, 4), "planning-root poses must have shape (N, 4, 4)" + return poses + def get_scene_state(self, is_relative: bool = True) -> dict: """Return the raw scene-state snapshot from the underlying env. @@ -407,8 +598,8 @@ def get_usd_stage(self) -> Any: """Return the live USD stage backing the scene. Sanctioned collision-geometry source for motion planners that extract obstacles via a USD - parser. Planners scope extraction with :meth:`get_env_prim_path` and - :meth:`get_robot_prim_path`. + parser. Planners scope extraction with :meth:`get_env_prim_path`; frame-sensitive poses + are reconciled with the live planning root rather than authored robot-prim transforms. """ return self.env.scene.stage @@ -418,6 +609,27 @@ def get_env_prim_path(self, env_id: int) -> str: return f"/World/envs/env_{env_id}" + def get_object_prim_path(self, object_ref: str, env_id: int) -> str: + """Return the exact environment-specific root prim for one rigid scene object. + + Args: + object_ref: Exact key in the live scene's rigid-object mapping. + env_id: Environment index. + """ + + scene = self.env.scene + assert type(env_id) is int and 0 <= env_id < len(scene.env_prim_paths), "env_id is out of range" + if object_ref not in scene.rigid_objects: + raise KeyError(f"unknown rigid scene object {object_ref!r}") + prim_pattern = scene.rigid_objects[object_ref].cfg.prim_path + assert isinstance(prim_pattern, str) and prim_pattern, "rigid-object prim path must be non-empty" + if prim_pattern == scene.env_regex_ns or prim_pattern.startswith(f"{scene.env_regex_ns}/"): + prim_path = scene.env_prim_paths[env_id] + prim_pattern[len(scene.env_regex_ns) :] + else: + prim_path = prim_pattern + assert scene.stage.GetPrimAtPath(prim_path).IsValid(), f"rigid-object prim does not exist: {prim_path}" + return prim_path + def get_robot_prim_path(self, env_id: int) -> str: """Return the USD prim path of the robot articulation root for the given environment. diff --git a/autodata_interfaces/embodiments/__init__.py b/autodata_interfaces/embodiments/__init__.py index 39cddd4..b8ffd2c 100644 --- a/autodata_interfaces/embodiments/__init__.py +++ b/autodata_interfaces/embodiments/__init__.py @@ -3,7 +3,7 @@ """Concrete :class:`EmbodimentAdapter` implementations, organized by morphology. -Two morphology trees ship this phase: :class:`SingleArmEmbodimentAdapter` +Single-arm and bimanual adapters share the same interface: :class:`SingleArmEmbodimentAdapter` (with :class:`DeltaPoseIKSingleArmAdapter` for delta-pose IK control) and :class:`BimanualEmbodimentAdapter` (with :class:`AbsolutePoseWholeBodyBimanualAdapter` for absolute-pose whole-body @@ -16,7 +16,7 @@ BimanualEefConfig, BimanualEmbodimentAdapter, ) -from autodata_interfaces.embodiments.embodiment_types import PoseObsKeys +from autodata_interfaces.embodiments.embodiment_types import ActionTargetFrame, NamedJointTrajectory, PoseObsKeys from autodata_interfaces.embodiments.factory import ( EMBODIMENT_TYPE_REGISTRY, embodiment_adapter_from_dict, @@ -30,10 +30,12 @@ __all__ = [ "AbsolutePoseEmbodimentAdapter", "AbsolutePoseWholeBodyBimanualAdapter", + "ActionTargetFrame", "BimanualEefConfig", "BimanualEmbodimentAdapter", "DeltaPoseIKSingleArmAdapter", "EMBODIMENT_TYPE_REGISTRY", + "NamedJointTrajectory", "PoseObsKeys", "SingleArmEmbodimentAdapter", "embodiment_adapter_from_dict", diff --git a/autodata_interfaces/embodiments/bimanual_embodiment_adapter.py b/autodata_interfaces/embodiments/bimanual_embodiment_adapter.py index 8cce101..e92a1b5 100644 --- a/autodata_interfaces/embodiments/bimanual_embodiment_adapter.py +++ b/autodata_interfaces/embodiments/bimanual_embodiment_adapter.py @@ -14,14 +14,17 @@ from __future__ import annotations +import math import torch from abc import abstractmethod -from collections.abc import Sequence +from collections.abc import Callable, Mapping, Sequence from dataclasses import dataclass, field +from pathlib import Path +from types import MappingProxyType from typing import Any from autodata_interfaces.embodiments.embodiment_adapter import EmbodimentAdapter -from autodata_interfaces.embodiments.embodiment_types import PoseObsKeys +from autodata_interfaces.embodiments.embodiment_types import ActionTargetFrame, NamedJointTrajectory, PoseObsKeys from autodata_utils import pose_math @@ -35,11 +38,40 @@ class BimanualEefConfig: gripper_action_indices: Indices into the interleaved hand-joints slice of the env action vector. Length equals this EEF's gripper action dim. + joint_names: Positional passthrough joint names in local channel order. + passthrough_presets: Named positional passthrough values in the same local joint order. """ name: str pose_obs_keys: PoseObsKeys gripper_action_indices: tuple[int, ...] + joint_names: tuple[str, ...] = () + passthrough_presets: Mapping[str, tuple[float, ...]] = field(default_factory=dict) + + def __post_init__(self) -> None: + """Check local hand-joint ordering and freeze the named passthrough presets.""" + assert not self.joint_names or len(self.joint_names) == len( + self.gripper_action_indices + ), "joint_names must align with gripper_action_indices" + assert len(set(self.joint_names)) == len(self.joint_names), "joint_names must be unique" + if self.passthrough_presets: + assert len(self.joint_names) == len( + self.gripper_action_indices + ), "passthrough presets require joint_names aligned with gripper_action_indices" + + presets: dict[str, tuple[float, ...]] = {} + for preset_name, preset_values in self.passthrough_presets.items(): + assert isinstance(preset_name, str) and preset_name, "passthrough preset names must be non-empty strings" + values = tuple(float(value) for value in preset_values) + assert len(values) == len(self.gripper_action_indices), ( + f"passthrough preset {preset_name!r} must contain {len(self.gripper_action_indices)} values " + f"in joint_names order, got {len(values)}" + ) + assert all( + math.isfinite(value) for value in values + ), f"passthrough preset {preset_name!r} values must be finite" + presets[preset_name] = values + object.__setattr__(self, "passthrough_presets", MappingProxyType(presets)) @dataclass(kw_only=True) @@ -82,6 +114,27 @@ def __post_init__(self) -> None: def get_eef_names(self) -> tuple[str, ...]: return (self.left.name, self.right.name) + def get_eef_joint_names(self, eef_name: str) -> tuple[str, ...]: + """Return the named hand joints commanded by one EEF passthrough channel.""" + + by_name = {eef.name: eef.joint_names for eef in (self.left, self.right)} + assert eef_name in by_name, f"unknown end-effector {eef_name!r}" + return by_name[eef_name] + + def get_eef_passthrough_preset(self, eef_name: str, preset_name: str) -> tuple[float, ...]: + """Return a named hand preset in the EEF's configured joint order.""" + + by_name = {eef.name: eef for eef in (self.left, self.right)} + assert eef_name in by_name, f"unknown end-effector {eef_name!r}" + assert isinstance(preset_name, str) and preset_name, "preset_name must be a non-empty string" + presets = by_name[eef_name].passthrough_presets + if preset_name not in presets: + raise KeyError( + f"unknown passthrough preset {preset_name!r} for end-effector {eef_name!r}; " + f"available presets: {sorted(presets)}" + ) + return presets[preset_name] + def get_eef_poses(self, env_ids: Sequence[int] | None = None) -> dict[str, torch.Tensor]: assert self.env is not None, "Call bind_env(env) before reading state." index: slice | Sequence[int] = slice(None) if env_ids is None else env_ids @@ -147,6 +200,7 @@ class AbsolutePoseWholeBodyBimanualAdapter(BimanualEmbodimentAdapter): hand_joints_slice: tuple[int, int] canonicalize_quat: bool = True passthrough_channels: dict[str, tuple[int, int]] = field(default_factory=dict) + planning_model_action_term: str | None = None def __post_init__(self) -> None: super().__post_init__() @@ -185,6 +239,207 @@ def __post_init__(self) -> None: ) occupied_ranges.append(tuple(channel_slice)) + def get_passthrough_actions( + self, + env_ids: Sequence[int] | None = None, + ) -> dict[str, torch.Tensor] | None: + """Recover positional hand commands from the live articulation state. + + Args: + env_ids: Environment indices, or None for all environments. + + Returns: + Hand-action tensors per end effector, or None if a required channel is unavailable. + """ + + eefs = (self.left, self.right) + if self.passthrough_channels or any(not eef.joint_names for eef in eefs): + return None + joint_names = tuple(self.get_joint_names()) + missing = {name for eef in eefs for name in eef.joint_names} - set(joint_names) + assert not missing, f"passthrough joints are absent from the live articulation: {sorted(missing)}" + joint_index = {name: index for index, name in enumerate(joint_names)} + positions = self.get_joint_positions(env_ids) + return {eef.name: positions[:, [joint_index[name] for name in eef.joint_names]].clone() for eef in eefs} + + def _planning_action_term(self) -> Any: + """Resolve the configured planning action from the bound environment.""" + assert self.env is not None, "Call bind_env(env) before resolving the planning model." + terms = getattr(self.env.action_manager, "_terms", {}) + assert ( + self.planning_model_action_term in terms + ), f"unknown planning action term {self.planning_model_action_term!r}" + return terms[self.planning_model_action_term] + + def get_action_target_frames(self) -> tuple[ActionTargetFrame, ...]: + """Match end effectors to the action's controlled frames. + + Returns: + Ordered end-effector/frame pairs, or an empty tuple without a planning action. + """ + if self.planning_model_action_term is None: + return () + eef_names = self.get_eef_names() + frame_names = self._planning_action_term().get_action_target_frame_names() + assert len(frame_names) == len(eef_names), "planning action frame count must match the embodiment EEF count" + return tuple(ActionTargetFrame(eef, frame) for eef, frame in zip(eef_names, frame_names, strict=True)) + + def get_planning_model_path(self) -> Path | None: + """Locate the URDF exported for the live Pink controller. + + Returns: + Existing URDF path, or None without a planning action. + """ + + if self.planning_model_action_term is None: + return None + controller = self._planning_action_term().cfg.controller + if controller.urdf_path: + path = Path(controller.urdf_path).expanduser() + else: + assert controller.usd_path and controller.urdf_output_dir + path = Path(controller.urdf_output_dir).expanduser() / "urdf" / f"{Path(controller.usd_path).stem}.urdf" + path = path.resolve() + assert path.is_file(), f"controller URDF file does not exist: {path}" + return path + + def solve_joint_trajectory( + self, + target_eef_poses: Mapping[str, torch.Tensor], + joint_seed_trajectories: Mapping[str, NamedJointTrajectory], + initial_joint_positions: torch.Tensor, + position_tolerance_m: float, + rotation_tolerance_rad: float, + joint_state_is_valid: Callable[[tuple[str, ...], torch.Tensor, int], bool] | None = None, + env_id: int = 0, + ) -> NamedJointTrajectory | None: + """Solve synchronized targets through the configured planning action. + + Args: + target_eef_poses: Target poses per end effector with shape (T, 4, 4) [m]. + joint_seed_trajectories: Named planner joint proposals per end effector. + initial_joint_positions: Initial state in live articulation joint order [rad, m]. + position_tolerance_m: Required tool-position accuracy [m]. + rotation_tolerance_rad: Required tool-rotation accuracy [rad]. + joint_state_is_valid: Optional feasibility check for each joint sample. + env_id: Environment controller to use. + + Returns: + Named joint trajectory, or None without a planning action. + """ + if self.planning_model_action_term is None: + return None + frames = self.get_action_target_frames() + assert set(target_eef_poses) == set(joint_seed_trajectories) == {frame.eef_name for frame in frames} + return self._planning_action_term().solve_joint_trajectory( + {frame.frame_name: target_eef_poses[frame.eef_name] for frame in frames}, + {frame.frame_name: joint_seed_trajectories[frame.eef_name] for frame in frames}, + NamedJointTrajectory(tuple(self.get_joint_names()), initial_joint_positions.unsqueeze(0)), + position_tolerance_m, + rotation_tolerance_rad, + joint_state_is_valid, + env_id, + ) + + def set_joint_posture_target( + self, + joint_names: tuple[str, ...], + joint_positions: torch.Tensor, + env_id: int = 0, + ) -> None: + """Set the planning action's posture reference. + + Args: + joint_names: Names aligned with the position values. + joint_positions: Posture target with shape (J,) [rad, m]. + env_id: Environment controller to update. + """ + self._planning_action_term().set_joint_posture_target(joint_names, joint_positions, env_id) + + def reset_joint_posture_target(self, env_id: int = 0) -> None: + """Restore the planning action's default posture reference. + + Args: + env_id: Environment controller to update. + """ + self._planning_action_term().reset_joint_posture_target(env_id) + + def get_planning_root_pose( + self, + root_pose_source_frame_name: str, + env_ids: Sequence[int] | None = None, + ) -> torch.Tensor: + """Return the planning-root pose, using the live controller frame when available. + + Args: + root_pose_source_frame_name: Robot frame used as the planning root. + env_ids: Environment indices, or None for all environments. + + Returns: + Environment-relative root transforms with shape (N, 4, 4) [m]. + """ + + if self.planning_model_action_term is None: + return super().get_planning_root_pose(root_pose_source_frame_name, env_ids) + action_term = self._planning_action_term() + assert action_term.cfg.controller.base_link_name == root_pose_source_frame_name + return action_term.get_base_link_pose(env_ids) + + def passthrough_actions_to_joint_positions( + self, + passthrough_action_dict: dict[str, torch.Tensor], + ) -> dict[str, torch.Tensor]: + """Map hand-action channels to named articulation joint positions. + + Args: + passthrough_action_dict: Unbatched hand-action tensors keyed by end effector. + + Returns: + Scalar joint-position tensors keyed by articulation joint name [rad, m]. + """ + + result: dict[str, torch.Tensor] = {} + for eef in (self.left, self.right): + if not eef.joint_names or eef.name not in passthrough_action_dict: + continue + values = passthrough_action_dict[eef.name] + assert values.shape == (len(eef.joint_names),) + result.update(zip(eef.joint_names, values, strict=True)) + return result + + def joint_positions_to_passthrough_actions( + self, + joint_position_dict: dict[str, torch.Tensor], + passthrough_action_dict: dict[str, torch.Tensor], + ) -> dict[str, torch.Tensor]: + """Update hand-action channels from named joint positions. + + Args: + joint_position_dict: Scalar joint positions keyed by name [rad, m]. + passthrough_action_dict: Action tensors providing the channel shapes and defaults. + + Returns: + Copied action channels with the supplied hand-joint positions applied. + """ + + result = {name: value.clone() for name, value in passthrough_action_dict.items()} + for eef in (self.left, self.right): + selected = tuple(name in joint_position_dict for name in eef.joint_names) + if not any(selected): + continue + assert all(selected), f"planned joint state only partially covers the {eef.name!r} hand" + assert eef.name in result, f"passthrough actions are missing the {eef.name!r} hand channel" + template = result[eef.name] + assert template.shape == (len(eef.joint_names),) + values = tuple(joint_position_dict[name] for name in eef.joint_names) + assert all( + isinstance(value, torch.Tensor) and value.numel() == 1 for value in values + ), "planned hand joint positions must be scalar tensors" + result[eef.name] = torch.stack( + [value.reshape(()).to(device=template.device, dtype=template.dtype) for value in values] + ) + return result + @property def action_dim(self) -> int: """Total width of the env action vector (pose + hands + any extra passthrough channels).""" @@ -348,9 +603,15 @@ def from_dict(cls, data: dict[str, Any]) -> AbsolutePoseWholeBodyBimanualAdapter left: pose_obs_keys: {pos: , quat: } gripper_action_indices: [, ...] + joint_names: [, ...] # optional + passthrough_presets: # optional + : [, ...] right: pose_obs_keys: {pos: , quat: } gripper_action_indices: [, ...] + joint_names: [, ...] # optional + passthrough_presets: # optional + : [, ...] action_layout: left_pose_slice: [, ] right_pose_slice: [, ] @@ -376,13 +637,17 @@ def from_dict(cls, data: dict[str, Any]) -> AbsolutePoseWholeBodyBimanualAdapter hand_joints_slice=tuple(layout["hand_joints_slice"]), canonicalize_quat=bool(layout.get("canonicalize_quat", True)), passthrough_channels=passthrough_channels, + planning_model_action_term=data.get("planning_model_action_term"), ) @staticmethod def _eef_from_dict(name: str, data: dict[str, Any]) -> BimanualEefConfig: + """Build one end-effector configuration from its YAML fields.""" pose_keys = data["pose_obs_keys"] return BimanualEefConfig( name=name, pose_obs_keys=PoseObsKeys(pos=pose_keys["pos"], quat=pose_keys["quat"]), gripper_action_indices=tuple(int(i) for i in data["gripper_action_indices"]), + joint_names=tuple(data.get("joint_names", ())), + passthrough_presets=data.get("passthrough_presets", {}), ) diff --git a/autodata_interfaces/embodiments/embodiment_adapter.py b/autodata_interfaces/embodiments/embodiment_adapter.py index 2b416c0..18cf506 100644 --- a/autodata_interfaces/embodiments/embodiment_adapter.py +++ b/autodata_interfaces/embodiments/embodiment_adapter.py @@ -16,9 +16,12 @@ import torch from abc import ABC, abstractmethod -from collections.abc import Sequence +from collections.abc import Callable, Mapping, Sequence +from pathlib import Path from typing import Any +from autodata_interfaces.embodiments.embodiment_types import ActionTargetFrame, NamedJointTrajectory +from autodata_utils import pose_math from autodata_utils.tensor_utils import as_torch @@ -91,24 +94,93 @@ def bind_env(self, env: Any) -> None: # so consumers that need the raw joint configuration (e.g. a motion planner's start state) # read it here rather than reaching into the env's articulation directly. - def get_joint_positions(self, env_ids: Sequence[int] | None = None) -> torch.Tensor: - """Read the robot's current joint positions [rad] from the live env. + def get_joint_positions( + self, + env_ids: Sequence[int] | None = None, + *, + joint_names: Sequence[str] | None = None, + ) -> torch.Tensor: + """Read joint positions [rad, m], optionally in an explicit name order. + + Args: + env_ids: Environment indices; None selects all environments. + joint_names: Ordered subset of articulation joints. None preserves native order. - Returns a tensor of shape ``(len(env_ids), num_dof)`` in the articulation's native joint - order (see :meth:`get_joint_names`). + Returns: + Positions shaped ``(num_selected_envs, num_selected_joints)``. """ assert self.env is not None, "Call bind_env(env) before reading state." index: slice | Sequence[int] = slice(None) if env_ids is None else env_ids robot = self.env.scene[self.robot_asset_name] - return as_torch(robot.data.joint_pos)[index] + positions = as_torch(robot.data.joint_pos)[index] + if joint_names is None: + return positions + by_name = {name: index for index, name in enumerate(self.get_joint_names())} + missing = set(joint_names) - set(by_name) + assert not missing, f"joints are absent from the articulation: {sorted(missing)}" + assert len(joint_names) == len(set(joint_names)), "requested joint names must be unique" + return positions[:, [by_name[name] for name in joint_names]] + + def get_joint_position_limits(self, env_ids: Sequence[int] | None = None) -> torch.Tensor: + """Read the robot's live lower and upper joint position limits [rad]. + + Returns a tensor of shape ``(len(env_ids), num_dof, 2)`` in the articulation's native + joint order (see :meth:`get_joint_names`). + """ + + assert self.env is not None, "Call bind_env(env) before reading state." + index: slice | Sequence[int] = slice(None) if env_ids is None else env_ids + robot = self.env.scene[self.robot_asset_name] + return as_torch(robot.data.joint_pos_limits)[index] + + def get_joint_velocity_limits(self, env_ids: Sequence[int] | None = None) -> torch.Tensor: + """Read live maximum joint speeds [rad/s, m/s] in articulation order. + + Args: + env_ids: Environment indices; None selects all environments. + + Returns: + Maximum speeds shaped ``(num_selected_envs, num_joints)``. + """ + assert self.env is not None, "Call bind_env(env) before reading state." + index: slice | Sequence[int] = slice(None) if env_ids is None else env_ids + return as_torch(self.env.scene[self.robot_asset_name].data.joint_vel_limits)[index] def get_joint_names(self) -> list[str]: - """Return the robot articulation's joint names, ordered to match :meth:`get_joint_positions`.""" + """Return articulation joint names in native order.""" assert self.env is not None, "Call bind_env(env) before reading state." return list(self.env.scene[self.robot_asset_name].data.joint_names) + def get_planning_model_path(self) -> Path | None: + """Return the live controller's local robot model, when it exposes one.""" + + def get_planning_root_pose( + self, + root_pose_source_frame_name: str, + env_ids: Sequence[int] | None = None, + ) -> torch.Tensor: + """Read a named articulation-link pose in each environment frame. + + Args: + root_pose_source_frame_name: Robot frame used as the planning root. + env_ids: Environment indices, or None for all environments. + + Returns: + Environment-relative root transforms with shape (N, 4, 4) [m]. + """ + + assert self.env is not None, "Call bind_env(env) before reading state." + robot = self.env.scene[self.robot_asset_name] + body_names = tuple(robot.data.body_names) + assert root_pose_source_frame_name in body_names, f"unknown planning-root frame {root_pose_source_frame_name!r}" + index: slice | Sequence[int] = slice(None) if env_ids is None else env_ids + body_index = body_names.index(root_pose_source_frame_name) + body_state = as_torch(robot.data.body_link_state_w)[index, body_index, :7] + position = body_state[:, :3] - self.env.scene.env_origins[index] + return pose_math.make_pose(position, pose_math.matrix_from_quat(body_state[:, 3:7])) + @abstractmethod def get_eef_names(self) -> tuple[str, ...]: """Return the ordered names of all end-effectors this embodiment exposes. @@ -117,6 +189,115 @@ def get_eef_names(self) -> tuple[str, ...]: Tuple of EEF names. Stable across calls; never empty. """ + def get_eef_joint_names(self, eef_name: str) -> tuple[str, ...]: + """Return positional passthrough joints owned by an end effector. + + Args: + eef_name: End effector to query. + + Returns: + Joint names in action order, or an empty tuple when unavailable. + """ + + assert eef_name in self.get_eef_names(), f"unknown end-effector {eef_name!r}" + return () + + def get_eef_passthrough_preset(self, eef_name: str, preset_name: str) -> tuple[float, ...]: + """Return a positional passthrough preset for an end effector. + + Args: + eef_name: End effector to query. + preset_name: Configured posture name. + + Returns: + Joint positions in the end effector's passthrough-action order [rad, m]. + + Raises: + KeyError: The embodiment does not define the requested preset. + """ + + assert eef_name in self.get_eef_names(), f"unknown end-effector {eef_name!r}" + assert isinstance(preset_name, str) and preset_name, "preset_name must be a non-empty string" + raise KeyError(f"end-effector {eef_name!r} has no passthrough preset {preset_name!r}") + + def get_action_target_frames(self) -> tuple[ActionTargetFrame, ...]: + """Return exact controlled frames in pose-action block order, when available.""" + + return () + + def solve_joint_trajectory( + self, + target_eef_poses: Mapping[str, torch.Tensor], + joint_seed_trajectories: Mapping[str, NamedJointTrajectory], + initial_joint_positions: torch.Tensor, + position_tolerance_m: float, + rotation_tolerance_rad: float, + joint_state_is_valid: Callable[[tuple[str, ...], torch.Tensor, int], bool] | None = None, + env_id: int = 0, + ) -> NamedJointTrajectory | None: + """Solve joint positions for synchronized end-effector targets using the controller's kinematics. + + This optional capability is used when independently accumulated planning groups share + joints. Returning ``None`` declares that the embodiment has no shared-joint solver. + + Args: + target_eef_poses: Per-EEF target poses with shape ``(T, 4, 4)`` [m]. + joint_seed_trajectories: Per-EEF named planner proposals with ``T`` samples. + initial_joint_positions: Initial articulation state in :meth:`get_joint_names` order + [rad, m]. + position_tolerance_m: Required EEF position convergence [m]. + rotation_tolerance_rad: Required EEF rotation convergence [rad]. + joint_state_is_valid: Optional collision or feasibility predicate for one computed joint sample. + env_id: Environment whose controller solves the target poses. + + Returns: + Controller-owned named joint trajectory, or ``None`` when unsupported. + """ + + del target_eef_poses, joint_seed_trajectories, initial_joint_positions + del position_tolerance_m, rotation_tolerance_rad, joint_state_is_valid, env_id + + def set_joint_posture_target( + self, + joint_names: tuple[str, ...], + joint_positions: torch.Tensor, + env_id: int = 0, + ) -> None: + """Set an optional controller posture reference for the next action step. + + Args: + joint_names: Names aligned with ``joint_positions``. + joint_positions: One named posture target [rad, m]. + env_id: Environment controller to update. + """ + + del joint_names, joint_positions, env_id + + def reset_joint_posture_target(self, env_id: int = 0) -> None: + """Restore the controller's default posture reference after guided replay. + + Args: + env_id: Environment controller to update. + """ + + del env_id + + def get_passthrough_actions( + self, + env_ids: Sequence[int] | None = None, + ) -> dict[str, torch.Tensor] | None: + """Return current command-compatible passthrough actions when recoverable from live state. + + Args: + env_ids: Environment indices, or None for all environments. + + Returns: + Batched tensors with shape (N, channel_width) keyed by action channel. + None means that at least one required channel cannot be recovered. + """ + + del env_ids + @abstractmethod def get_eef_poses(self, env_ids: Sequence[int] | None = None) -> dict[str, torch.Tensor]: """Read current end-effector poses [m, m, m] from the live env. @@ -183,3 +364,21 @@ def actions_to_passthrough_actions(self, actions: torch.Tensor) -> dict[str, tor Returns: Map ``channel_name → passthrough action tensor``. """ + + def passthrough_actions_to_joint_positions( + self, + passthrough_action_dict: dict[str, torch.Tensor], + ) -> dict[str, torch.Tensor]: + """Map positional passthrough channels to named joints when supported.""" + + return {} + + def joint_positions_to_passthrough_actions( + self, + joint_position_dict: dict[str, torch.Tensor], + passthrough_action_dict: dict[str, torch.Tensor], + ) -> dict[str, torch.Tensor]: + """Project named planned joints into positional passthrough channels when supported.""" + + del joint_position_dict + return {name: value.clone() for name, value in passthrough_action_dict.items()} diff --git a/autodata_interfaces/embodiments/embodiment_types.py b/autodata_interfaces/embodiments/embodiment_types.py index 23b5279..be018cf 100644 --- a/autodata_interfaces/embodiments/embodiment_types.py +++ b/autodata_interfaces/embodiments/embodiment_types.py @@ -5,15 +5,55 @@ from __future__ import annotations +import torch from dataclasses import dataclass +@dataclass(frozen=True) +class ActionTargetFrame: + """Exact robot frame commanded by one ordered pose-action block. + + Args: + eef_name: End-effector name exposed by the embodiment adapter. + frame_name: Exact controlled frame name in the live robot model. + """ + + eef_name: str + frame_name: str + + def __post_init__(self) -> None: + """Require named end-effector and controller frames.""" + assert self.eef_name, "eef_name must be a non-empty string" + assert self.frame_name, "frame_name must be a non-empty string" + + +@dataclass(frozen=True) +class NamedJointTrajectory: + """Joint positions with an explicit, stable name order. + + Args: + joint_names: Unique articulation joint names. + positions: Joint positions with shape ``(T, J)`` [rad, m]. + """ + + joint_names: tuple[str, ...] + positions: torch.Tensor + + def __post_init__(self) -> None: + """Require unique joint names and finite, nonempty position samples.""" + assert self.joint_names and len(self.joint_names) == len(set(self.joint_names)) + assert all(isinstance(name, str) and name for name in self.joint_names) + assert isinstance(self.positions, torch.Tensor) and self.positions.ndim == 2 + assert self.positions.shape[1] == len(self.joint_names) + assert len(self.positions) > 0 and bool(torch.isfinite(self.positions).all()) + + @dataclass(frozen=True) class PoseObsKeys: """Observation-buffer keys for a single end-effector's pose. Both keys index into ``env.obs_buf[obs_group]``. ``pos`` returns a position - tensor; ``quat`` returns a (w, x, y, z) orientation quaternion. + tensor; ``quat`` returns a (x, y, z, w) orientation quaternion. Args: pos: Observation key for end-effector position. diff --git a/autodata_interfaces/env/pink_ik_action.py b/autodata_interfaces/env/pink_ik_action.py index ab352bf..1b958e6 100644 --- a/autodata_interfaces/env/pink_ik_action.py +++ b/autodata_interfaces/env/pink_ik_action.py @@ -5,15 +5,21 @@ from __future__ import annotations +import math +import numpy as np import tempfile +import torch import xml.etree.ElementTree as ET +from collections.abc import Callable, Mapping, Sequence from pathlib import Path -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any from isaaclab.controllers import utils as controller_utils from isaaclab.envs.mdp.actions.pink_actions_cfg import PinkInverseKinematicsActionCfg from isaaclab.envs.mdp.actions.pink_task_space_actions import PinkInverseKinematicsAction +from autodata_interfaces.embodiments.embodiment_types import NamedJointTrajectory + if TYPE_CHECKING: from isaaclab.envs import ManagerBasedEnv @@ -42,8 +48,307 @@ def __init__(self, cfg: PinkInverseKinematicsActionCfg, env: ManagerBasedEnv): # in the generated URDF so Pinocchio needs no additional package directory. urdf_path = Path(controller.urdf_path) tree = ET.parse(urdf_path) + _urdf_mimic_joints_sync(tree.getroot(), controller.usd_path) for mesh in tree.iter("mesh"): mesh.set("filename", str((urdf_path.parent / mesh.attrib["filename"]).resolve())) tree.write(urdf_path, encoding="unicode") controller.mesh_path = None super().__init__(cfg, env) + + def _initialize_joint_info(self) -> None: + """Keep passthrough action order independent of the physics backend's joint order.""" + super()._initialize_joint_info() + self._hand_joint_ids, self._hand_joint_names = self._asset.find_joints( + self.cfg.hand_joint_names, preserve_order=True + ) + self._controlled_joint_ids = self._isaaclab_controlled_joint_ids + self._hand_joint_ids + self._controlled_joint_names = self._isaaclab_controlled_joint_names + self._hand_joint_names + + def get_action_target_frame_names(self) -> tuple[str, ...]: + """Return the controlled frame names in action order. + + Returns: + Frame names shared by the per-environment Pink controllers. + """ + + controllers = tuple(getattr(self, "_ik_controllers", ())) + assert controllers, "planning action term exposes no live IK controllers" + + frame_count = self._num_frame_tasks + assert frame_count > 0, "planning action term must expose at least one frame task" + frame_orders: list[tuple[str, ...]] = [] + for controller in controllers: + tasks = tuple(controller.cfg.variable_input_tasks) + assert len(tasks) >= frame_count, "planning controller has too few variable-input tasks" + frame_names = tuple(getattr(task, "frame", None) for task in tasks[:frame_count]) + assert all( + isinstance(name, str) and name for name in frame_names + ), "planning controller frame tasks must lead variable_input_tasks in action order" + assert not any( + getattr(task, "frame", None) for task in tasks[frame_count:] + ), "planning controller contains an unexpected extra frame task" + frame_orders.append(frame_names) + + assert all( + order == frame_orders[0] for order in frame_orders[1:] + ), "planning controllers disagree on action-target frame order" + return frame_orders[0] + + def get_base_link_pose(self, env_ids: Sequence[int] | None = None) -> torch.Tensor: + """Return controller-base poses for the selected environments. + + Args: + env_ids: Environment indices, or None for all environments. + + Returns: + Controller-base transforms with shape (N, 4, 4); translation is in [m]. + """ + poses = self._get_base_link_frame_transform().detach().clone() + index: slice | Sequence[int] = slice(None) if env_ids is None else env_ids + return poses[index] + + def solve_joint_trajectory( + self, + target_frame_poses: Mapping[str, torch.Tensor], + joint_seed_trajectories: Mapping[str, NamedJointTrajectory], + initial_state: NamedJointTrajectory, + position_tolerance_m: float, + rotation_tolerance_rad: float, + joint_state_is_valid: Callable[[tuple[str, ...], torch.Tensor, int], bool] | None = None, + env_id: int = 0, + ) -> NamedJointTrajectory: + """Solve joint positions for synchronized frame targets using the controller's kinematics. + + Named planner proposals provide the posture reference and a fallback kinematic seed. + Values proposed by more than one group (the waist on a humanoid) are averaged. The prior + coupled state remains the preferred seed for continuity. After the live controller horizon, + Pink solves only the original frame tasks so execution smoothing cannot mask feasibility. + + Args: + target_frame_poses: Ordered frame targets with shape (T, 4, 4) [m]. + joint_seed_trajectories: Named posture proposals per frame, with T samples. + initial_state: One named initial articulation state [rad, m]. + position_tolerance_m: Required frame-position convergence [m]. + rotation_tolerance_rad: Required frame-rotation convergence [rad]. + joint_state_is_valid: Optional feasibility predicate for each named joint sample. + env_id: Controller to use. + + Returns: + Named controlled-joint trajectory. + """ + + frame_names = tuple(target_frame_poses) + assert len(frame_names) == self._num_frame_tasks, "targets must match the action's frame count" + assert set(joint_seed_trajectories) == set(frame_names) + sample_counts = {len(poses) for poses in target_frame_poses.values()} + sample_counts.update(len(trajectory.positions) for trajectory in joint_seed_trajectories.values()) + assert len(sample_counts) == 1, "EEF targets and joint seeds must have one common length" + sample_count = sample_counts.pop() + assert all(poses.shape == (sample_count, 4, 4) for poses in target_frame_poses.values()) + + live_names = tuple(self._asset.joint_names) + assert initial_state.joint_names == live_names, "initial state must match the action's asset joint order" + assert len(initial_state.positions) == 1, "initial state must contain exactly one sample" + initial_joint_positions = initial_state.positions[0] + assert bool(torch.isfinite(initial_joint_positions).all()) + assert math.isfinite(position_tolerance_m) and position_tolerance_m > 0.0 + assert math.isfinite(rotation_tolerance_rad) and rotation_tolerance_rad > 0.0 + live_index = {name: index for index, name in enumerate(live_names)} + posture = initial_joint_positions.repeat(sample_count, 1) + proposals: dict[str, list[torch.Tensor]] = {} + for trajectory in joint_seed_trajectories.values(): + missing = set(trajectory.joint_names) - set(live_names) + assert not missing, f"joint-seed trajectory contains unknown joints: {sorted(missing)}" + for index, joint_name in enumerate(trajectory.joint_names): + proposals.setdefault(joint_name, []).append( + trajectory.positions[:, index].to(device=posture.device, dtype=posture.dtype) + ) + for joint_name, values in proposals.items(): + posture[:, live_index[joint_name]] = torch.stack(values).mean(dim=0) + controller = self._planning_controller(env_id) + controlled_names = tuple(self._isaaclab_controlled_joint_names) + controlled_ids = tuple(self._isaaclab_controlled_joint_ids) + controller_substeps = int(self._env.cfg.decimation) + assert tuple(controller.cfg.joint_names) == controlled_names + assert len(controlled_ids) == len(controlled_names) + assert controller_substeps >= 1 + + frame_tasks = tuple(task for task in controller.cfg.variable_input_tasks if hasattr(task, "frame")) + assert frame_names == tuple(task.frame for task in frame_tasks) + saved_frame_targets = tuple(self._pink_frame_target(task).copy() for task in frame_tasks) + posture_tasks = tuple(task for task in controller.cfg.variable_input_tasks if hasattr(task, "target_q")) + saved_posture_targets = tuple( + task.target_q.copy() if task.target_q is not None else None for task in posture_tasks + ) + + assert self.cfg.controller.base_link_name == controller.cfg.base_link_name, "controller base-frame mismatch" + root_pose = self.get_base_link_pose(env_ids=[env_id])[0] + root_from_env = torch.linalg.inv(root_pose) + targets_in_root = { + eef_name: root_from_env.to(device=poses.device, dtype=poses.dtype) @ poses + for eef_name, poses in target_frame_poses.items() + } + current = initial_joint_positions.detach().cpu().numpy().copy() + solutions: list[torch.Tensor] = [] + from pink import solve_ik + + try: + for sample in range(sample_count): + for eef_name, task in zip(frame_names, frame_tasks, strict=True): + pose = targets_in_root[eef_name][sample].detach().cpu().numpy() + target = self._pink_frame_target(task).copy() + target.translation = pose[:3, 3] + target.rotation = pose[:3, :3] + task.set_target(target) + proposal = posture[sample].detach().cpu().numpy() + posture_target = proposal[controller.isaac_lab_to_pink_ordering] + converged = False + valid = False + for seed in (current.copy(), proposal): + current = seed.copy() + controller.update_null_space_joint_targets(posture_target) + for iteration in range(100): + if iteration < controller_substeps: + solution = controller.compute(current, self._sim_dt) + assert solution.shape == (len(controlled_names),) and bool(torch.isfinite(solution).all()) + current[np.asarray(controlled_ids)] = solution.detach().cpu().numpy() + else: + controller.pink_configuration.update(current[controller.isaac_lab_to_pink_ordering]) + velocity = solve_ik( + controller.pink_configuration, + frame_tasks, + self._sim_dt, + solver="daqp", + safety_break=controller.cfg.fail_on_joint_limit_violation, + ) + joint_delta = velocity * self._sim_dt + current[np.asarray(controlled_ids)] += joint_delta[ + controller.pink_to_isaac_lab_controlled_ordering + ] + solution = torch.as_tensor( + current[np.asarray(controlled_ids)], + device=posture.device, + dtype=posture.dtype, + ) + controller.pink_configuration.update(current[controller.isaac_lab_to_pink_ordering]) + frame_errors = tuple(task.compute_error(controller.pink_configuration) for task in frame_tasks) + converged = all( + np.linalg.norm(error[:3]) <= position_tolerance_m + and np.linalg.norm(error[3:]) <= rotation_tolerance_rad + for error in frame_errors + ) + if converged and iteration + 1 >= controller_substeps: + break + if converged: + valid = joint_state_is_valid is None or joint_state_is_valid(controlled_names, solution, sample) + if valid: + break + residuals = ", ".join( + f"{eef_name}=({np.linalg.norm(error[:3]):.6f} m, {np.linalg.norm(error[3:]):.6f} rad)" + for eef_name, error in zip(frame_names, frame_errors, strict=True) + ) + configuration = controller.pink_configuration + limit_margins = np.minimum( + configuration.q - configuration.model.lowerPositionLimit, + configuration.model.upperPositionLimit - configuration.q, + ) + nearest_limits = ", ".join( + f"{configuration.controlled_joint_names_pinocchio_order[index]}={limit_margins[index]:.6f} rad" + for index in np.argsort(limit_margins)[:3] + ) + assert converged and valid, ( + f"Pink could not solve a valid synchronized end-effector target at sample {sample}: {residuals}; " + f"collision_free={valid}; nearest joint-limit margins: {nearest_limits}" + ) + solutions.append(solution.to(device=posture.device, dtype=posture.dtype)) + finally: + for task, target in zip(frame_tasks, saved_frame_targets, strict=True): + task.set_target(target) + for task, target in zip(posture_tasks, saved_posture_targets, strict=True): + if target is not None: + task.set_target(target) + return NamedJointTrajectory(controlled_names, torch.stack(solutions)) + + def set_joint_posture_target( + self, + joint_names: tuple[str, ...], + joint_positions: torch.Tensor, + env_id: int = 0, + ) -> None: + """Set a named posture reference for one controller. + + Args: + joint_names: Names aligned with the position values. + joint_positions: Posture target with shape (J,) [rad, m]. + env_id: Environment controller to update. + """ + + controller = self._planning_controller(env_id) + assert joint_positions.shape == (len(joint_names),) + by_name = dict(zip(joint_names, joint_positions, strict=True)) + pin_names = tuple(controller.pink_configuration.controlled_joint_names_pinocchio_order) + posture = controller.init_joint_positions.copy() + for index, name in enumerate(pin_names): + if name in by_name: + posture[index] = float(by_name[name].item()) + controller.update_null_space_joint_targets(posture) + + def reset_joint_posture_target(self, env_id: int = 0) -> None: + """Restore the controller's initial posture target. + + Args: + env_id: Environment controller to update. + """ + + controller = self._planning_controller(env_id) + controller.update_null_space_joint_targets(controller.init_joint_positions) + + def _planning_controller(self, env_id: int) -> Any: + """Return the live IK controller for the selected environment.""" + controllers = tuple(getattr(self, "_ik_controllers", ())) + assert 0 <= env_id < len(controllers), "env_id has no live Pink controller" + return controllers[env_id] + + @staticmethod + def _pink_frame_target(task: Any) -> Any: + """Return the pose target stored by the Pink frame task.""" + if hasattr(task, "transform_target_to_base"): + return task.transform_target_to_base + assert hasattr(task, "transform_target_to_world"), "Pink pose tasks must expose a target transform" + return task.transform_target_to_world + + +def _urdf_mimic_joints_sync(root: ET.Element, usd_path: str) -> None: + """Match exported PhysX mimic coefficients to the source joint equation.""" + from pxr import Usd, UsdGeom + + joints = {joint.get("name"): joint for joint in root.findall("joint")} + mimics = {name: joint for name, joint in joints.items() if joint.find("mimic") is not None} + if not mimics: + return + stage = Usd.Stage.Open(usd_path) + assert stage is not None, f"Cannot open controller model {usd_path!r}." + units = { + "revolute": math.pi / 180.0, + "continuous": math.pi / 180.0, + "prismatic": UsdGeom.GetStageMetersPerUnit(stage), + } + for prim in stage.Traverse(): + joint = mimics.get(prim.GetName()) + metadata = prim.GetMetadata("apiSchemas") + schemas = metadata.GetAppliedItems() if metadata is not None else () + if joint is None or "NewtonMimicAPI" in schemas: + continue + instances = [name.split(":", 1)[1] for name in schemas if name.startswith("PhysxMimicJointAPI:")] + if not instances: + continue + assert len(instances) == 1, "URDF joints support exactly one mimic degree of freedom." + prefix = f"physxMimicJoint:{instances[0]}" + gearing = prim.GetAttribute(f"{prefix}:gearing").Get() + offset = prim.GetAttribute(f"{prefix}:offset").Get() + # PhysX: q + gearing*q_ref + offset = 0. URDF: q = multiplier*q_ref + offset. + mimic = joint.find("mimic") + joint_unit = units[joint.get("type")] + reference_unit = units[joints[mimic.get("joint")].get("type")] + mimic.set("multiplier", str(-float(gearing if gearing is not None else 1.0) * joint_unit / reference_unit)) + mimic.set("offset", str(-float(offset if offset is not None else 0.0) * joint_unit)) diff --git a/autodata_interfaces/motion_planners/__init__.py b/autodata_interfaces/motion_planners/__init__.py index 837cbfb..3d2e4e3 100644 --- a/autodata_interfaces/motion_planners/__init__.py +++ b/autodata_interfaces/motion_planners/__init__.py @@ -1,9 +1,9 @@ # Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Motion-planner backends for SkillGen. +"""Motion-planner backends for SkillGen and ScheduleGen. -This branch ships the cuRobo v1 backend only. The package exposes the abstract +The package provides the cuRobo v1 backend and exposes the abstract :class:`MotionPlannerBase` and the v1 :class:`CuroboPlanner` / :class:`CuroboPlannerCfg`. The planner class is imported lazily so the configuration dataclass and the abstract base can be @@ -15,11 +15,10 @@ from typing import TYPE_CHECKING -from autodata_interfaces.motion_planners.curobo import CuroboPlannerCfg from autodata_interfaces.motion_planners.motion_planner_base import MotionPlannerBase if TYPE_CHECKING: - from autodata_interfaces.motion_planners.curobo import CuroboPlanner + from autodata_interfaces.motion_planners.curobo import CuroboPlanner, CuroboPlannerCfg __all__ = [ "MotionPlannerBase", @@ -29,8 +28,9 @@ def __getattr__(name: str): - if name == "CuroboPlanner": - from autodata_interfaces.motion_planners.curobo import CuroboPlanner as _CuroboPlanner + """Load planner symbols lazily so ordinary imports do not require cuRobo.""" + if name in {"CuroboPlanner", "CuroboPlannerCfg"}: + from autodata_interfaces.motion_planners import curobo - return _CuroboPlanner + return getattr(curobo, name) raise AttributeError(f"module 'motion_planners' has no attribute {name!r}") diff --git a/autodata_interfaces/motion_planners/curobo/__init__.py b/autodata_interfaces/motion_planners/curobo/__init__.py index 8ff85dc..83ae373 100644 --- a/autodata_interfaces/motion_planners/curobo/__init__.py +++ b/autodata_interfaces/motion_planners/curobo/__init__.py @@ -1,7 +1,7 @@ # Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""cuRobo v1 backend for the SkillGen motion planner. +"""cuRobo v1 planning, collision geometry and robot-model utilities. Imports the planner lazily so the configuration dataclass can be loaded in sim-free contexts (e.g. unit tests or factory selection) without bringing in Isaac Lab. @@ -12,19 +12,49 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: + from autodata_interfaces.motion_planners.curobo.collision_spheres import ObjectCollisionSpheres from autodata_interfaces.motion_planners.curobo.curobo_planner import CuroboPlanner - -from autodata_interfaces.motion_planners.curobo.curobo_planner_cfg import CuroboPlannerCfg + from autodata_interfaces.motion_planners.curobo.curobo_planner_cfg import CuroboPlannerCfg + from autodata_interfaces.motion_planners.curobo.planner_factory import ( + CuroboPlanningContext, + curobo_group_planners_create, + curobo_planning_context_create, + ) __all__ = [ "CuroboPlanner", "CuroboPlannerCfg", + "CuroboPlanningContext", + "ObjectCollisionSpheres", + "curobo_group_planners_create", + "curobo_planning_context_create", ] def __getattr__(name: str): + """Load the requested cuRobo planner or robot-model symbol on demand.""" + if name == "ObjectCollisionSpheres": + from autodata_interfaces.motion_planners.curobo.collision_spheres import ( + ObjectCollisionSpheres as _ObjectCollisionSpheres, + ) + + return _ObjectCollisionSpheres if name == "CuroboPlanner": from autodata_interfaces.motion_planners.curobo.curobo_planner import CuroboPlanner as _CuroboPlanner return _CuroboPlanner + if name == "CuroboPlannerCfg": + from autodata_interfaces.motion_planners.curobo.curobo_planner_cfg import CuroboPlannerCfg as _CuroboPlannerCfg + + return _CuroboPlannerCfg + if name == "curobo_group_planners_create": + from autodata_interfaces.motion_planners.curobo.planner_factory import ( + curobo_group_planners_create as _curobo_group_planners_create, + ) + + return _curobo_group_planners_create + if name in {"CuroboPlanningContext", "curobo_planning_context_create"}: + from autodata_interfaces.motion_planners.curobo import planner_factory + + return getattr(planner_factory, name) raise AttributeError(f"module 'curobo' has no attribute {name!r}") diff --git a/autodata_interfaces/motion_planners/curobo/collision_spheres.py b/autodata_interfaces/motion_planners/curobo/collision_spheres.py new file mode 100644 index 0000000..af093ab --- /dev/null +++ b/autodata_interfaces/motion_planners/curobo/collision_spheres.py @@ -0,0 +1,480 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Deterministic collision-sphere fitting for URDF link geometry.""" + +from __future__ import annotations + +import hashlib +import json +import math +import numpy as np +import os +import tempfile +import trimesh +import xml.etree.ElementTree as ET +from collections import defaultdict +from collections.abc import Mapping, Sequence +from contextlib import suppress +from dataclasses import asdict, dataclass, field +from pathlib import Path +from types import MappingProxyType + + +@dataclass(frozen=True) +class CollisionSphere: + """One collision sphere expressed in its owning link frame. + + Args: + center: Link-relative XYZ center [m]. + radius: Positive sphere radius [m]. + """ + + center: tuple[float, float, float] + radius: float + + def __post_init__(self) -> None: + """Require a finite three-dimensional center and positive finite radius.""" + + assert len(self.center) == 3 and all(math.isfinite(value) for value in self.center) + assert math.isfinite(self.radius) and self.radius > 0.0 + + def to_dict(self) -> dict[str, object]: + """Return the mapping accepted by cuRobo robot configuration files.""" + + return {"center": list(self.center), "radius": self.radius} + + +@dataclass(frozen=True, kw_only=True) +class ObjectCollisionSpheres: + """Immutable object-frame spheres captured from one native attachment fit. + + These spheres preserve the exact approximation used by cuRobo for carried-object planning. The fit + does not claim conservative coverage of the source geometry. + + Args: + object_name: Exact logical scene-object name. + obstacle_path: Exact obstacle path resolved in cuRobo's world. + spheres: Active spheres expressed in the object frame. + fit_type: Native sphere-fit algorithm name. + surface_sphere_radius_m: Surface-sample radius [m]. + slot_capacity: Number of reserved native attachment slots. + tool_frame: Physical tool frame used for capture. + attachment_link: Identity-fixed virtual link owning native attachment slots. + captured_tool_from_object: Capture-time rigid transform from object to tool. + """ + + object_name: str + obstacle_path: str + spheres: tuple[CollisionSphere, ...] + fit_type: str + surface_sphere_radius_m: float + slot_capacity: int + tool_frame: str + attachment_link: str + captured_tool_from_object: tuple[tuple[float, float, float, float], ...] + geometry_digest: str = field(init=False) + + def __post_init__(self) -> None: + """Validate the captured fit and rigid transform, then hash its object-frame geometry.""" + + for value_name in ("object_name", "obstacle_path", "fit_type", "tool_frame", "attachment_link"): + value = getattr(self, value_name) + assert ( + isinstance(value, str) and value and value == value.strip() + ), f"{value_name} must be non-empty and trimmed" + spheres = tuple(self.spheres) + assert spheres and all(isinstance(sphere, CollisionSphere) for sphere in spheres) + assert math.isfinite(self.surface_sphere_radius_m) and self.surface_sphere_radius_m > 0.0 + assert type(self.slot_capacity) is int and self.slot_capacity >= len(spheres) + + transform = tuple(tuple(float(value) for value in row) for row in self.captured_tool_from_object) + transform_array = np.asarray(transform) + assert transform_array.shape == (4, 4) and np.isfinite(transform_array).all() + assert np.allclose(transform_array[3], (0.0, 0.0, 0.0, 1.0), atol=1.0e-5, rtol=0.0) + rotation = transform_array[:3, :3] + assert np.allclose(rotation.T @ rotation, np.eye(3), atol=1.0e-4, rtol=0.0) + assert math.isclose(float(np.linalg.det(rotation)), 1.0, abs_tol=1.0e-4) + + digest_payload = { + "schema": "isaac-autodata.object-collision-spheres.v1", + "obstacle_path": self.obstacle_path, + "fit_type": self.fit_type, + "surface_sphere_radius_m": self.surface_sphere_radius_m, + "slot_capacity": self.slot_capacity, + "spheres": [sphere.to_dict() for sphere in spheres], + } + digest = hashlib.sha256(json.dumps(digest_payload, sort_keys=True, separators=(",", ":")).encode()).hexdigest() + object.__setattr__(self, "spheres", spheres) + object.__setattr__(self, "captured_tool_from_object", transform) + object.__setattr__(self, "geometry_digest", digest) + + +@dataclass(frozen=True, kw_only=True) +class CollisionSphereFitConfig: + """Sampling limits and acceptance thresholds for deterministic per-link fitting. + + Args: + max_spheres_per_link: Maximum selected spheres for one link. + surface_samples_per_geometry: Surface samples drawn from each source mesh. + candidates_per_geometry: Sampled points used to construct tangent-sphere candidates. + inflation_m: Radius added to each candidate sphere [m]. + min_coverage_ratio: Required fraction of sampled surface points covered by selected spheres. + max_uncovered_distance_m: Maximum sampled point-to-sphere gap [m]. + convexify_non_watertight: Whether non-watertight meshes use a convex hull for tangent fitting. + """ + + max_spheres_per_link: int = 64 + surface_samples_per_geometry: int = 1_000 + candidates_per_geometry: int = 200 + inflation_m: float = 0.01 + min_coverage_ratio: float = 0.95 + max_uncovered_distance_m: float = 0.01 + convexify_non_watertight: bool = True + + def __post_init__(self) -> None: + """Check sampling budgets and nonnegative fit tolerances.""" + + assert self.max_spheres_per_link > 0 + assert self.surface_samples_per_geometry >= self.max_spheres_per_link + assert self.candidates_per_geometry >= self.max_spheres_per_link + assert self.surface_samples_per_geometry >= self.candidates_per_geometry + assert self.inflation_m >= 0.0 + assert 0.0 < self.min_coverage_ratio <= 1.0 + assert self.max_uncovered_distance_m >= 0.0 + + +@dataclass(frozen=True) +class CollisionSphereSet: + """Content-addressed collision spheres grouped by URDF link name. + + Args: + cache_key: SHA-256 identity of selected geometry and fitting settings. + spheres_by_link: Nonempty sphere sets expressed in their owning link frames [m]. + """ + + cache_key: str + spheres_by_link: Mapping[str, tuple[CollisionSphere, ...]] + + def __post_init__(self) -> None: + """Validate sphere sets and freeze a link-name-sorted copy of their mapping.""" + + assert len(self.cache_key) == 64 + normalized = {name: tuple(spheres) for name, spheres in sorted(self.spheres_by_link.items())} + assert normalized and all(name and spheres for name, spheres in normalized.items()) + assert all(isinstance(sphere, CollisionSphere) for spheres in normalized.values() for sphere in spheres) + object.__setattr__(self, "spheres_by_link", MappingProxyType(normalized)) + + def to_dict(self) -> dict[str, object]: + """Return a stable JSON-compatible cache representation.""" + + return { + "schema": "isaac-autodata.collision-spheres.v1", + "cache_key": self.cache_key, + "spheres": { + name: [sphere.to_dict() for sphere in spheres] for name, spheres in self.spheres_by_link.items() + }, + } + + @classmethod + def from_dict(cls, value: Mapping[str, object]) -> CollisionSphereSet: + """Load and validate a cache representation.""" + + assert value.get("schema") == "isaac-autodata.collision-spheres.v1" + raw_spheres = value.get("spheres") + assert isinstance(raw_spheres, Mapping) + spheres_by_link: dict[str, tuple[CollisionSphere, ...]] = {} + for link_name, entries in raw_spheres.items(): + assert isinstance(link_name, str) and isinstance(entries, Sequence) + spheres_by_link[link_name] = tuple( + CollisionSphere( + center=tuple(float(item) for item in entry["center"]), + radius=float(entry["radius"]), + ) + for entry in entries + ) + return cls(cache_key=str(value["cache_key"]), spheres_by_link=spheres_by_link) + + +def collision_spheres_fit_urdf( + urdf_path: str | Path, + *, + link_names: Sequence[str] | None = None, + config: CollisionSphereFitConfig | None = None, + package_roots: Mapping[str, str | Path] | None = None, + cache_dir: str | Path | None = None, + force_rebuild: bool = False, +) -> CollisionSphereSet: + """Fit or load deterministic spheres for selected URDF links. + + Visual geometry is preferred because USD-to-URDF collision primitives are often deliberately + coarse; collision geometry is the fallback when a link has no visual. Every geometry is + transformed into its link frame before fitting. Cache identity includes the complete geometry, + selected links, and fit configuration. + + Args: + urdf_path: Local URDF file used to resolve link geometry. + link_names: Links to fit; ``None`` selects every geometry-bearing link. + config: Sampling and acceptance settings; ``None`` uses default settings. + package_roots: Local roots for resolving ``package://`` mesh references. + cache_dir: Cache directory; ``None`` uses the AutoData user cache. + force_rebuild: Whether to fit again even when a matching cached result exists. + + Returns: + Link-frame spheres and their geometry/settings checksum. Coverage checks apply to + sampled points, not a proof of conservative coverage of the complete mesh. + + Raises: + AssertionError: Selected geometry is missing or sampled fitting thresholds are not met. + FileNotFoundError: The URDF or a referenced mesh cannot be resolved. + """ + + source_path = Path(urdf_path).expanduser().resolve() + if not source_path.is_file(): + raise FileNotFoundError(f"URDF must be a local file: {source_path}") + fit_config = config or CollisionSphereFitConfig() + link_meshes = _urdf_link_meshes(source_path, package_roots or {}) + selected = tuple(sorted(link_meshes)) if link_names is None else tuple(dict.fromkeys(link_names)) + assert selected, "at least one geometry-bearing link is required" + unknown = sorted(set(selected) - set(link_meshes)) + assert not unknown, f"selected links have no URDF geometry: {unknown}" + + cache_key = _cache_key(selected, fit_config, link_meshes) + root = ( + Path(cache_dir).expanduser().resolve() + if cache_dir is not None + else Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "autodata" / "collision_spheres" + ) + cache_path = root / f"{cache_key}.json" + if cache_path.is_file() and not force_rebuild: + cached = CollisionSphereSet.from_dict(json.loads(cache_path.read_text(encoding="utf-8"))) + assert cached.cache_key == cache_key, "collision-sphere cache key mismatch" + return cached + + spheres_by_link = {link_name: _fit_link(link_meshes[link_name], fit_config, link_name) for link_name in selected} + result = CollisionSphereSet(cache_key=cache_key, spheres_by_link=spheres_by_link) + root.mkdir(parents=True, exist_ok=True) + _json_write_atomic(cache_path, result.to_dict()) + return result + + +def _fit_link( + source_meshes: tuple[trimesh.Trimesh, ...], + config: CollisionSphereFitConfig, + link_name: str, +) -> tuple[CollisionSphere, ...]: + """Fit inflated tangent-sphere candidates and require the sampled link-coverage thresholds.""" + + surface_parts: list[np.ndarray] = [] + center_parts: list[np.ndarray] = [] + radius_parts: list[np.ndarray] = [] + for geometry_index, source_mesh in enumerate(source_meshes): + mesh = trimesh.Trimesh( + vertices=np.asarray(source_mesh.vertices, dtype=np.float64).copy(), + faces=np.asarray(source_mesh.faces).copy(), + process=True, + ) + assert len(mesh.vertices) and len(mesh.faces), f"geometry for {link_name!r} is empty" + points = trimesh.sample.sample_surface( + mesh, + config.surface_samples_per_geometry, + seed=geometry_index, + )[0] + tangent_mesh = mesh + if not tangent_mesh.is_watertight: + assert config.convexify_non_watertight, f"geometry for {link_name!r} is not watertight" + tangent_mesh = tangent_mesh.convex_hull + candidates = points[: config.candidates_per_geometry] + centers, radii = trimesh.proximity.max_tangent_sphere(tangent_mesh, candidates) + radii = np.asarray(radii, dtype=np.float64) + config.inflation_m + keep = np.isfinite(radii) & (radii > 0.0) & (radii <= 0.5 * np.linalg.norm(mesh.extents)) + surface_parts.append(points) + center_parts.append(np.asarray(centers, dtype=np.float64)[keep]) + radius_parts.append(radii[keep]) + + points = np.concatenate(surface_parts) + centers = np.concatenate(center_parts) + radii = np.concatenate(radius_parts) + assert len(centers), f"sphere fitting produced no candidates for {link_name!r}" + spheres, coverage, max_gap = _greedy_cover(points, centers, radii, config) + assert ( + coverage + 1.0e-12 >= config.min_coverage_ratio + ), f"sphere fit for {link_name!r} covers {coverage:.3f}, required {config.min_coverage_ratio:.3f}" + assert ( + max_gap <= config.max_uncovered_distance_m + 1.0e-12 + ), f"sphere fit for {link_name!r} leaves {max_gap:.4f} m, required <= {config.max_uncovered_distance_m:.4f} m" + return tuple(spheres) + + +def _greedy_cover( + points: np.ndarray, + centers: np.ndarray, + radii: np.ndarray, + config: CollisionSphereFitConfig, +) -> tuple[list[CollisionSphere], float, float]: + """Select candidates greedily by newly covered surface samples. + + Args: + points: Link-frame surface samples with shape ``(N, 3)`` [m]. + centers: Candidate sphere centers with shape ``(S, 3)`` [m]. + radii: Candidate sphere radii with shape ``(S,)`` [m]. + config: Sphere budget and sampled coverage/gap thresholds. + + Returns: + Selected spheres, covered sample fraction and maximum uncovered surface gap [m]. + Reaching the sphere budget can return a result below the configured thresholds. + """ + + gaps = np.linalg.norm(points[:, None, :] - centers[None, :, :], axis=-1) - radii[None, :] + uncovered = np.ones(len(points), dtype=bool) + available = np.ones(len(centers), dtype=bool) + min_gaps = np.full(len(points), math.inf) + selected: list[CollisionSphere] = [] + for _ in range(config.max_spheres_per_link): + gains = np.count_nonzero(gaps[uncovered] <= 0.0, axis=0) + gains[~available] = -1 + index = int(np.argmax(gains)) + if gains[index] <= 0: + break + sphere = CollisionSphere(center=tuple(float(value) for value in centers[index]), radius=float(radii[index])) + selected.append(sphere) + available[index] = False + min_gaps = np.minimum(min_gaps, gaps[:, index]) + uncovered = min_gaps > 0.0 + coverage = float(np.count_nonzero(~uncovered) / len(points)) + max_gap = float(np.max(np.maximum(min_gaps, 0.0))) + if coverage >= config.min_coverage_ratio and max_gap <= config.max_uncovered_distance_m: + return selected, coverage, max_gap + if not np.any(uncovered): + break + coverage = float(np.count_nonzero(~uncovered) / len(points)) + return selected, coverage, float(np.max(np.maximum(min_gaps, 0.0))) + + +def _urdf_link_meshes( + urdf_path: Path, + package_roots: Mapping[str, str | Path], +) -> dict[str, tuple[trimesh.Trimesh, ...]]: + """Load link-frame meshes, preferring each link's visual geometry over collision geometry.""" + + root = ET.fromstring(urdf_path.read_bytes()) + resolved_roots = {name: Path(path).expanduser().resolve() for name, path in package_roots.items()} + by_link: dict[str, list[trimesh.Trimesh]] = defaultdict(list) + for link in root.findall("link"): + link_name = link.get("name") + assert link_name, "URDF link is missing a name" + elements = link.findall("visual") or link.findall("collision") + for element in elements: + geometry = element.find("geometry") + assert geometry is not None, f"geometry on {link_name!r} is incomplete" + mesh = _geometry_mesh(geometry, urdf_path.parent, resolved_roots) + mesh.apply_transform(_origin_matrix(element.find("origin"))) + by_link[link_name].append(mesh) + assert by_link, f"URDF has no visual or collision geometry: {urdf_path}" + return {link_name: tuple(meshes) for link_name, meshes in sorted(by_link.items())} + + +def _geometry_mesh( + geometry: ET.Element, + urdf_root: Path, + package_roots: Mapping[str, Path], +) -> trimesh.Trimesh: + """Load scaled mesh geometry or build a supported URDF primitive in local metres.""" + + if (element := geometry.find("mesh")) is not None: + reference = element.get("filename") or element.get("url") + assert reference, "URDF mesh geometry has no filename" + path = _mesh_path(reference, urdf_root, package_roots) + loaded = trimesh.load(path, process=False) + mesh = loaded.to_mesh() if isinstance(loaded, trimesh.Scene) else loaded + assert isinstance(mesh, trimesh.Trimesh) and len(mesh.faces), f"mesh has no faces: {path}" + scale = _vector(element.get("scale"), (1.0, 1.0, 1.0)) + mesh = mesh.copy() + mesh.apply_scale(scale) + return mesh + if (element := geometry.find("box")) is not None: + return trimesh.creation.box(extents=_vector(element.get("size"))) + if (element := geometry.find("cylinder")) is not None: + return trimesh.creation.cylinder(radius=float(element.get("radius")), height=float(element.get("length"))) + if (element := geometry.find("sphere")) is not None: + return trimesh.creation.icosphere(subdivisions=2, radius=float(element.get("radius"))) + raise ValueError("unsupported URDF collision geometry") + + +def _mesh_path(reference: str, urdf_root: Path, package_roots: Mapping[str, Path]) -> Path: + """Resolve package, file or relative mesh references, including adjacent export meshes.""" + + if reference.startswith("package://"): + package_name, separator, relative = reference[len("package://") :].partition("/") + assert separator and package_name in package_roots, f"no package root for {reference!r}" + path = package_roots[package_name] / relative + elif reference.startswith("file://"): + path = Path(reference[len("file://") :]) + else: + path = Path(reference) + if not path.is_absolute(): + path = urdf_root / path + path = path.expanduser().resolve() + if not path.is_file(): + adjacent_export = urdf_root.parent / "meshes" / path.name + if adjacent_export.is_file(): + path = adjacent_export + if not path.is_file(): + raise FileNotFoundError(f"URDF mesh does not exist: {path}") + return path + + +def _origin_matrix(origin: ET.Element | None) -> np.ndarray: + """Convert optional URDF XYZ [m] and roll/pitch/yaw [rad] into a rigid transform.""" + + xyz = (0.0, 0.0, 0.0) if origin is None else _vector(origin.get("xyz"), (0.0, 0.0, 0.0)) + rpy = (0.0, 0.0, 0.0) if origin is None else _vector(origin.get("rpy"), (0.0, 0.0, 0.0)) + transform = trimesh.transformations.euler_matrix(*rpy, axes="sxyz") + transform[:3, 3] = xyz + return transform + + +def _vector(value: str | None, default: tuple[float, float, float] | None = None) -> tuple[float, float, float]: + """Parse three finite URDF values, or use the supplied default when absent.""" + + if value is None: + assert default is not None, "required URDF vector is missing" + return default + result = tuple(float(item) for item in value.split()) + assert len(result) == 3 and all(math.isfinite(item) for item in result) + return result + + +def _cache_key( + links: tuple[str, ...], + config: CollisionSphereFitConfig, + meshes: Mapping[str, tuple[trimesh.Trimesh, ...]], +) -> str: + """Hash selected link geometry and fit settings, excluding export paths and joint metadata.""" + + # Export directories and joint metadata do not affect link-local sphere fitting. + digest = hashlib.sha256(b"autodata.collision-sphere-fit.v2") + digest.update(json.dumps(asdict(config), sort_keys=True, separators=(",", ":")).encode()) + for link_name in links: + digest.update(json.dumps((link_name, len(meshes[link_name]))).encode()) + for mesh in meshes[link_name]: + digest.update(json.dumps((mesh.vertices.shape, mesh.faces.shape)).encode()) + digest.update(np.asarray(mesh.vertices, dtype=np.float64).tobytes()) + digest.update(np.asarray(mesh.faces, dtype=np.int64).tobytes()) + return digest.hexdigest() + + +def _json_write_atomic(path: Path, value: Mapping[str, object]) -> None: + """Flush a JSON cache entry to a temporary sibling before atomically replacing its target.""" + + descriptor, temporary_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) + try: + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + json.dump(value, stream, sort_keys=True, separators=(",", ":")) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary_name, path) + except BaseException: + with suppress(FileNotFoundError): + os.unlink(temporary_name) + raise diff --git a/autodata_interfaces/motion_planners/curobo/curobo_planner.py b/autodata_interfaces/motion_planners/curobo/curobo_planner.py index 1a43077..40e7a3d 100644 --- a/autodata_interfaces/motion_planners/curobo/curobo_planner.py +++ b/autodata_interfaces/motion_planners/curobo/curobo_planner.py @@ -4,33 +4,96 @@ from __future__ import annotations import logging +import math import numpy as np import torch +from collections.abc import Iterator, Mapping +from contextlib import contextmanager, nullcontext from dataclasses import dataclass -from types import SimpleNamespace +from types import MappingProxyType, SimpleNamespace from typing import TYPE_CHECKING, Any import warp as wp -from curobo.cuda_robot_model.cuda_robot_model import CudaRobotModelState -from curobo.geom.sdf.world import CollisionCheckerType +from curobo.cuda_robot_model.cuda_robot_model import CudaRobotModel +from curobo.cuda_robot_model.types import JointLimits +from curobo.geom.sdf.world import CollisionCheckerType, CollisionQueryBuffer from curobo.geom.sphere_fit import SphereFitType from curobo.geom.types import WorldConfig from curobo.types.base import TensorDeviceType from curobo.types.math import Pose +from curobo.types.robot import RobotConfig from curobo.types.state import JointState from curobo.util.logger import setup_curobo_logger from curobo.util.usd_helper import UsdHelper from curobo.util_file import load_yaml -from curobo.wrap.reacher.motion_gen import MotionGen, MotionGenConfig, MotionGenPlanConfig +from curobo.wrap.reacher.motion_gen import MotionGen, MotionGenConfig, MotionGenPlanConfig, MotionGenStatus from isaaclab.sim.spawners.materials import PreviewSurfaceCfg from isaaclab.sim.spawners.meshes import MeshSphereCfg, spawn_mesh_sphere +from autodata_interfaces.embodiments.embodiment_types import NamedJointTrajectory +from autodata_interfaces.motion_planners.curobo.collision_spheres import CollisionSphere, ObjectCollisionSpheres from autodata_interfaces.motion_planners.curobo.curobo_planner_cfg import CuroboPlannerCfg from autodata_interfaces.motion_planners.motion_planner_base import MotionPlannerBase from autodata_utils import pose_math as PoseUtils if TYPE_CHECKING: from autodata_interfaces.datastream.datastream import Datastream + from autodata_interfaces.motion_planners.curobo.plan_visualizer import PlanVisualizer + + +def _usd_mesh_missing_scales_fill(stage: Any) -> None: + """Supply identity scale where cuRobo's USD reader requires an authored mesh value.""" + + from pxr import Gf, Sdf, UsdGeom + + for prim in stage.Traverse(): + if not prim.IsA(UsdGeom.Mesh): + continue + scale = prim.GetAttribute("xformOp:scale") + if scale and scale.Get() is not None: + continue + if not scale: + scale = prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Float3) + scale.Set(Gf.Vec3f(1.0)) + + +def _self_collision_fallback_buffers_reset_install(motion_gen: MotionGen) -> None: + """Clear pinned cuRobo fallback outputs before every self-collision evaluation.""" + + visited: set[int] = set() + for rollout in motion_gen.get_all_rollout_instances(): + for attribute in ("robot_self_collision_cost", "robot_self_collision_constraint"): + cost = getattr(rollout, attribute, None) + if cost is None or id(cost) in visited: + continue + visited.add(id(cost)) + config = getattr(cost, "self_collision_kin_config", None) + if config is None or config.experimental_kernel: + continue + if getattr(cost, "_autodata_buffer_reset_installed", False): + continue + original_forward = cost.forward + + def forward(robot_spheres: torch.Tensor, *, _cost=cost, _original=original_forward): + """Clear reused self-collision buffers before evaluating the sphere batch.""" + _cost.update_batch_size(robot_spheres) + batch, horizon, sphere_count, width = robot_spheres.shape + expected_shapes = { + "_out_distance": (batch, horizon), + "_out_vec": (batch, horizon, sphere_count, width), + "_sparse_sphere_idx": (batch, horizon, sphere_count), + } + for name, shape in expected_shapes.items(): + buffer = getattr(_cost, name, None) + assert ( + isinstance(buffer, torch.Tensor) and buffer.shape == shape + ), f"cuRobo self-collision buffer {name!r} changed contract" + buffer.zero_() + return _original(robot_spheres) + + cost.forward = forward + cost._autodata_buffer_reset_installed = True + # cuRobo ebb71702 still uses this namespace in WorldMeshCollision. Warp 1.16 # exposes the same bridge at the top level and no longer provides warp.torch. @@ -128,6 +191,14 @@ class Attachment: parent: str # Parent link name +@dataclass(frozen=True) +class _CollisionOnlyBackend: + """cuRobo kinematics paired with an already initialized collision world.""" + + kinematics: CudaRobotModel + world_coll_checker: Any + + class CuroboPlanner(MotionPlannerBase): """Motion planner for robot manipulation using cuRobo. @@ -143,6 +214,8 @@ class CuroboPlanner(MotionPlannerBase): multi-phase planning for contact scenarios like grasping and placing objects. """ + plan_visualizer: PlanVisualizer | None + def __init__( self, datastream: Datastream, @@ -153,6 +226,7 @@ def __init__( num_trajopt_seeds: int = 12, num_graph_seeds: int = 12, interpolation_dt: float = 0.05, + collision_world_source: CuroboPlanner | None = None, ) -> None: """Initialize the motion planner for a specific environment. @@ -164,12 +238,14 @@ def __init__( datastream: Read interface over the env, task, and embodiment. World state (collision geometry source, object poses, joint configuration) is read through it. config: Configuration object containing planner parameters and settings - task_name: Task name for auto-configuration + task_name: Legacy argument retained for compatibility; configure the planner through ``config``. env_id: Environment ID for multi-environment setups (0 to num_envs-1) - collision_checker: Type of collision checker - num_trajopt_seeds: Number of seeds for trajectory optimization - num_graph_seeds: Number of seeds for graph search - interpolation_dt: Time step for interpolating waypoints + collision_checker: Legacy argument; use ``config.collision_checker_type``. + num_trajopt_seeds: Legacy argument; use ``config.num_trajopt_seeds``. + num_graph_seeds: Legacy argument; use ``config.num_graph_seeds``. + interpolation_dt: Legacy argument; use ``config.interpolation_dt`` [s]. + collision_world_source: Initialized planner whose synchronized world is reused by a + collision-only context. Raises: ValueError: If ``robot_config_file`` is not provided @@ -188,28 +264,14 @@ def __init__( self.step_size: float | None = self.config.motion_step_size self.visualize_plan: bool = self.config.visualize_plan self.visualize_spheres: bool = self.config.visualize_spheres + self.plan_visualizer: PlanVisualizer | None = None # Log the config parameter values self.logger.info(f"Config parameter values: {self.config}") - # Initialize plan visualizer if enabled - if self.visualize_plan: - from autodata_interfaces.motion_planners.curobo.plan_visualizer import PlanVisualizer - - # Debug-visualization only (gated by ``visualize_plan``, off by default). Reads the - # raw env/robot handles directly to compute an env-local render offset; not part of - # the planning pipeline, which reads exclusively through ``self.datastream``. - env_origin = self.env.scene.env_origins[env_id, :3] - base_translation = (wp.to_torch(self.robot.data.root_pos_w)[env_id, :3] - env_origin).detach().cpu().numpy() - self.plan_visualizer = PlanVisualizer( - robot_name=self.config.robot_name, - recording_id=f"curobo_plan_{env_id}", - debug=config.debug_planner, - base_translation=base_translation, - ) - # Store attached objects as Attachment objects self.attached_objects: dict[str, Attachment] = {} # object_name -> Attachment + self._object_collision_spheres: dict[str, ObjectCollisionSpheres] = {} # Initialize cuRobo components - FORCE CUDA DEVICE FOR ISOLATION setup_curobo_logger("warn") @@ -241,37 +303,92 @@ def __init__( if self.config.extra_collision_spheres: robot_cfg["kinematics"]["extra_collision_spheres"] = self.config.extra_collision_spheres + configured_self_collision_ignore = { + str(name): tuple(str(ignored_name) for ignored_name in ignored_names) + for name, ignored_names in robot_cfg["kinematics"]["self_collision_ignore"].items() + } + self._self_collision_ignore = MappingProxyType(configured_self_collision_ignore) + if not self.config.use_native_self_collision: + collision_links = tuple(str(name) for name in robot_cfg["kinematics"]["collision_link_names"]) + robot_cfg["kinematics"]["self_collision_ignore"] = {name: list(collision_links) for name in collision_links} + self.robot_cfg: dict[str, Any] = robot_cfg + self._locked_joint_positions = MappingProxyType( + {str(name): float(value) for name, value in robot_cfg["kinematics"].get("lock_joints", {}).items()} + ) + self.planning_root_frame_name = str(robot_cfg["kinematics"]["base_link"]) + self.root_pose_source_frame_name = config.root_pose_source_frame_name # Load world configuration using the config's method world_cfg: WorldConfig = self.config.get_world_config() - - # Create motion generator config with parameters from configuration - motion_gen_config: MotionGenConfig = MotionGenConfig.load_from_robot_config( - robot_cfg, - world_cfg, - tensor_args=self.tensor_args, - collision_checker_type=self.config.collision_checker_type, - num_trajopt_seeds=self.config.num_trajopt_seeds, - num_graph_seeds=self.config.num_graph_seeds, - interpolation_dt=self.config.interpolation_dt, - collision_cache=self.config.collision_cache_size, - trajopt_tsteps=self.config.trajopt_tsteps, - collision_activation_distance=self.config.collision_activation_distance, - position_threshold=self.config.position_threshold, - rotation_threshold=self.config.rotation_threshold, - ) - - # Create motion generator - self.motion_gen: MotionGen = MotionGen(motion_gen_config) - - # Set motion generator reference for plan visualizer if enabled - if self.visualize_plan: - self.plan_visualizer.set_motion_generator_reference(self.motion_gen) + self._configured_world_config = world_cfg.get_collision_check_world() + + # Synchronize before rollout construction: exported zero velocities are not valid bounds. + robot_configuration = RobotConfig.from_dict(robot_cfg, self.tensor_args) + self._joint_limits_sync(robot_configuration.kinematics.get_joint_limits()) + + if collision_world_source is None: + assert self.config.planning_enabled, "collision-only contexts require an initialized world source" + motion_gen_config = MotionGenConfig.load_from_robot_config( + robot_configuration, + world_cfg, + tensor_args=self.tensor_args, + collision_checker_type=self.config.collision_checker_type, + num_trajopt_seeds=self.config.num_trajopt_seeds, + num_graph_seeds=self.config.num_graph_seeds, + interpolation_dt=self.config.interpolation_dt, + collision_cache=self.config.collision_cache_size, + trajopt_tsteps=self.config.trajopt_tsteps, + collision_activation_distance=self.config.collision_activation_distance, + position_threshold=self.config.position_threshold, + rotation_threshold=self.config.rotation_threshold, + store_debug_in_result=self.config.debug_planner, + self_collision_check=self.config.use_native_self_collision, + self_collision_opt=self.config.use_native_self_collision, + ) + self.motion_gen: MotionGen | _CollisionOnlyBackend = MotionGen(motion_gen_config) + _self_collision_fallback_buffers_reset_install(self.motion_gen) + else: + assert not self.config.planning_enabled, "planning backends cannot reuse another planner's world" + assert isinstance(collision_world_source.motion_gen, MotionGen) + assert collision_world_source.env_id == self.env_id + assert collision_world_source.datastream is self.datastream + robot_model = CudaRobotModel(robot_configuration.kinematics) + self.motion_gen = _CollisionOnlyBackend( + kinematics=robot_model, + world_coll_checker=collision_world_source.motion_gen.world_coll_checker, + ) + self._collision_world_owner: CuroboPlanner = collision_world_source or self + self._collision_world_active_context: CuroboPlanner | None = None + self._kinematics = self.motion_gen.kinematics + self._kinematic_robot_cfg = robot_cfg + if config.kinematic_robot_config_file is not None: + self._kinematic_robot_cfg = load_yaml(config.kinematic_robot_config_file)["robot_cfg"] + for field in ("base_link", "ee_link", "collision_link_names"): + assert self._kinematic_robot_cfg["kinematics"][field] == robot_cfg["kinematics"][field], field + query_config = RobotConfig.from_dict(self._kinematic_robot_cfg, self.tensor_args) + self._joint_limits_sync(query_config.kinematics.get_joint_limits()) + self._kinematics = CudaRobotModel(query_config.kinematics) + self._self_collision_ignore = MappingProxyType({ + str(name): tuple(str(ignored) for ignored in ignored_names) + for name, ignored_names in self._kinematic_robot_cfg["kinematics"]["self_collision_ignore"].items() + }) + self._active_joint_names = tuple(str(name) for name in self._kinematics.joint_names) + planning_names = set(self.motion_gen.kinematics.joint_names) + assert planning_names <= set(self._active_joint_names), "planning joints must belong to the state-query model" + self._auxiliary_joint_indices = { + name: index for index, name in enumerate(self._active_joint_names) if name not in planning_names + } + assert set(self._auxiliary_joint_indices) <= set(self._locked_joint_positions) + self._locked_joint_positions = MappingProxyType({ + name: value for name, value in self._locked_joint_positions.items() if name not in self._active_joint_names + }) + self._self_collision_pair_cache: tuple[torch.Tensor, torch.Tensor, tuple[str, ...]] | None = None # Create plan config with parameters from configuration self.plan_config: MotionGenPlanConfig = MotionGenPlanConfig( enable_graph=self.config.enable_graph, + enable_opt=self.config.enable_opt, enable_graph_attempt=self.config.enable_graph_attempt, max_attempts=self.config.max_planning_attempts, enable_finetune_trajopt=self.config.enable_finetune_trajopt, @@ -285,6 +402,7 @@ def __init__( # Initialize planning state self._current_plan: JointState | None = None + self._failed_joint_state: JointState | None = None self._plan_index: int = 0 # Initialize visualization state @@ -292,12 +410,32 @@ def __init__( self.spheres: list[tuple[str, float]] | None = None self.sphere_update_freq: int = self.config.sphere_update_freq - # Warm up planner - self.logger.info("Warming up motion planner...") - self.motion_gen.warmup(enable_graph=True, warmup_js_trajopt=False) + # cuRobo plans in its kinematic root frame, while the rest of AutoData exchanges + # env-relative poses. Establish that transform before loading either static or dynamic + # collision geometry so every pose follows the same frame path. + identity_pose = torch.eye(4, dtype=torch.float32, device=self.datastream.device) + self._base_pose_in_env: torch.Tensor = identity_pose + self._env_to_base_transform: torch.Tensor = identity_pose.clone() + self._base_frame_is_identity: bool = True + self._refresh_base_frame_transform() + + if self.visualize_plan: + from autodata_interfaces.motion_planners.curobo.plan_visualizer import PlanVisualizer as _PlanVisualizer + + self.plan_visualizer = _PlanVisualizer( + robot_name=self.config.robot_name, + recording_id=f"curobo_plan_{env_id}", + debug=config.debug_planner, + base_pose_in_env=self._base_pose_in_env, + ) + self.plan_visualizer.set_motion_generator_reference(self.motion_gen) + + if self.config.planning_enabled: + assert isinstance(self.motion_gen, MotionGen) + self.logger.info("Warming up motion planner...") + self.motion_gen.warmup(enable_graph=self.config.enable_graph, warmup_js_trajopt=False) - # Read static world geometry once - self._initialize_static_world() + self._initialize_static_world(activate=collision_world_source is None) # Defer object validation baseline until first update_world() call when scene is fully loaded self._expected_objects: set[str] | None = None @@ -309,15 +447,6 @@ def __init__( # Only recompute when objects are added/removed, not when poses change self._cached_object_mappings: dict[str, str] | None = None - # Robot base frame (cuRobo's planning frame) expressed in the env-relative frame the - # planner exchanges with callers. Refreshed from the live articulation in - # update_world(); object, goal, and planned poses are reconciled between the two frames. - # Initialized to identity so the transform is a no-op until the first world update. - identity_pose = torch.eye(4, dtype=torch.float32, device=self.datastream.device) - self._base_pose_in_env: torch.Tensor = identity_pose - self._env_to_base_transform: torch.Tensor = identity_pose.clone() - self._base_frame_is_identity: bool = True - # ===================================================================================== # DEVICE CONVERSION UTILITIES # ===================================================================================== @@ -333,9 +462,9 @@ def _to_curobo_device(self, tensor: torch.Tensor) -> torch.Tensor: tensor: Input tensor (may be on any device) Returns: - Tensor converted to cuRobo's CUDA device with appropriate dtype + Contiguous tensor on cuRobo's CUDA device with the appropriate dtype. """ - return tensor.to(device=self.tensor_args.device, dtype=self.tensor_args.dtype) + return tensor.to(device=self.tensor_args.device, dtype=self.tensor_args.dtype).contiguous() def _to_env_device(self, tensor: torch.Tensor) -> torch.Tensor: """Convert tensor back to environment device for Isaac Lab compatibility. @@ -355,6 +484,11 @@ def _to_env_device(self, tensor: torch.Tensor) -> torch.Tensor: # FRAME RECONCILIATION # ===================================================================================== + def planning_root_pose_refresh(self) -> None: + """Refresh the live planning-root transform used by FK, planning, and visualization.""" + + self._refresh_base_frame_transform() + def _refresh_base_frame_transform(self) -> None: """Refresh the cached transform between the env-relative and robot base frames. @@ -363,10 +497,18 @@ def _refresh_base_frame_transform(self) -> None: base pose (env-relative) and caches the forward and inverse transforms used to map object, goal, and planned poses between the two frames. """ - self._base_pose_in_env = self.datastream.get_robot_root_pose(env_ids=[self.env_id])[0] + if self.root_pose_source_frame_name is None: + self._base_pose_in_env = self.datastream.get_robot_root_pose(env_ids=[self.env_id])[0] + else: + self._base_pose_in_env = self.datastream.get_robot_planning_root_pose( + self.root_pose_source_frame_name, + env_ids=[self.env_id], + )[0] self._env_to_base_transform = torch.linalg.inv(self._base_pose_in_env) identity = torch.eye(4, dtype=self._base_pose_in_env.dtype, device=self._base_pose_in_env.device) self._base_frame_is_identity = bool(torch.allclose(self._base_pose_in_env, identity, atol=1e-6)) + if self.plan_visualizer is not None: + self.plan_visualizer.set_base_pose_in_env(self._base_pose_in_env) def _pose_env_to_base(self, pose_env: torch.Tensor) -> torch.Tensor: """Express an env-relative pose in the robot base frame. @@ -408,7 +550,38 @@ def _pose_base_to_env(self, pose_base: torch.Tensor) -> torch.Tensor: # INITIALIZATION AND CONFIGURATION # ===================================================================================== - def _initialize_static_world(self) -> None: + def _joint_limits_sync(self, curobo_limits: JointLimits) -> None: + """Synchronize positions and fill missing speed bounds from the live articulation.""" + curobo_joint_names = tuple(curobo_limits.joint_names) + live_joint_names = tuple(self.datastream.get_robot_joint_names()) + missing = set(curobo_joint_names) - set(live_joint_names) + assert not missing, f"cuRobo joints are absent from the live articulation: {sorted(missing)}" + live_index = {name: index for index, name in enumerate(live_joint_names)} + selected = [live_index[name] for name in curobo_joint_names] + live_limits = self.datastream.get_robot_joint_position_limits(env_ids=[self.env_id])[0, selected] + synchronized = self._to_curobo_device(live_limits).T.contiguous() + assert synchronized.shape == curobo_limits.position.shape + mismatch_count = int(torch.sum(torch.abs(curobo_limits.position - synchronized) > 0.01).item()) + curobo_limits.position.copy_(synchronized) + live_speed = self._to_curobo_device( + self.datastream.get_robot_joint_velocity_limits(env_ids=[self.env_id])[0, selected] + ) + assert bool((live_speed > 0.0).all()), "Live joint speed limits must be positive." + exported_speed = curobo_limits.velocity.abs().amax(dim=0) + speed = torch.where(exported_speed > 0.0, torch.minimum(exported_speed, live_speed), live_speed) + if self.config.max_joint_velocity is not None: + cap = self.config.max_joint_velocity + assert math.isfinite(cap) and cap > 0.0, "max_joint_velocity must be finite and positive." + speed = speed.clamp(max=cap) + assert bool(torch.isfinite(speed).all()), "Unbounded joint speeds require an explicit max_joint_velocity." + curobo_limits.velocity.copy_(torch.stack((-speed, speed))) + self.logger.debug( + "Synchronized %d cuRobo joint limits from the live articulation (%d bound differences)", + len(curobo_joint_names), + mismatch_count, + ) + + def _initialize_static_world(self, *, activate: bool = True) -> None: """Initialize static world geometry from USD stage. Reads static environment geometry once during planner initialization to establish @@ -416,29 +589,62 @@ def _initialize_static_world(self) -> None: that don't change during the simulation. Dynamic objects are synchronized separately in update_world() to maintain performance. """ + _usd_mesh_missing_scales_fill(self.usd_helper.stage) # Prim scoping for obstacle extraction comes from the Datastream (collision-world source), # not from direct env access. env_prim_path = self.datastream.get_env_prim_path(self.env_id) robot_prim_path = self.config.robot_prim_path or self.datastream.get_robot_prim_path(self.env_id) - ignore_list = self.config.world_ignore_substrings or [ - f"{env_prim_path}/Robot", - f"{env_prim_path}/target", - "/World/defaultGroundPlane", - "/curobo", - ] + ignore_list = list( + self.config.world_ignore_substrings + or [ + f"{env_prim_path}/target", + "/World/defaultGroundPlane", + "/curobo", + ] + ) + if robot_prim_path not in ignore_list: + ignore_list.append(robot_prim_path) - # Static obstacles are expressed relative to the robot prim, which is assumed to - # coincide with the kinematic root link that defines cuRobo's planning frame. + # USD articulation-link transforms need not equal the live controller root. Extract in + # the env frame, then use the same live root transform as goals and dynamic objects. self._static_world_config = self.usd_helper.get_obstacles_from_stage( only_paths=[env_prim_path], - reference_prim_path=robot_prim_path, + reference_prim_path=env_prim_path, ignore_substring=ignore_list, ) + self._transform_world_config_to_base_frame(self._static_world_config) self._static_world_config = self._static_world_config.get_collision_check_world() + if self.config.include_configured_world: + combined_world = self._configured_world_config.clone() + for obstacle in self._static_world_config: + combined_world.add_obstacle(obstacle) + self._static_world_config = combined_world + + if activate: + self._static_world_activate() - # Initialize cuRobo world with static geometry - self.motion_gen.update_world(self._static_world_config) + def _static_world_activate(self) -> None: + """Install this context's world in its shared fixed-capacity collision checker.""" + + owner = self._collision_world_owner + if owner._collision_world_active_context is self: + return + # Rebuild the cache so pinned cuRobo cannot retain an unlisted bootstrap cuboid. + owner.motion_gen.clear_world_cache() + owner.motion_gen.update_world(self._static_world_config) + owner._collision_world_active_context = self + + def _transform_world_config_to_base_frame(self, world_config: WorldConfig) -> None: + """Express env-relative cuRobo obstacles in the live planning-root frame.""" + + for obstacle in world_config: + if obstacle.pose is None: + continue + pose = torch.as_tensor(obstacle.pose, dtype=torch.float32, device=self.datastream.device) + quat_xyzw = torch.cat((pose[4:], pose[3:4])) + pose_env = PoseUtils.make_pose(pose[:3], PoseUtils.matrix_from_quat(quat_xyzw)) + obstacle.pose = self._object_pose_to_curobo_list(self._pose_env_to_base(pose_env)) # ===================================================================================== # PROPERTIES AND BASIC GETTERS @@ -459,6 +665,667 @@ def current_plan(self) -> JointState | None: """Current plan from cuRobo motion generator.""" return self._current_plan + @property + def active_joint_names(self) -> tuple[str, ...]: + """Joint names in state-query order, including separately commanded auxiliary joints.""" + return self._active_joint_names + + @property + def locked_joint_positions(self) -> Mapping[str, float]: + """Exact named joint positions compiled as fixed in this cuRobo model [rad, m].""" + + return self._locked_joint_positions + + @property + def current_joint_position_path(self) -> torch.Tensor | None: + """Current arm-local joint-position path in :attr:`active_joint_names` order.""" + if self._current_plan is None: + return None + plan = self._current_plan.get_ordered_joint_state(self.active_joint_names) + return self._to_env_device(plan.position).detach().clone() + + def get_planned_joint_trajectory(self) -> NamedJointTrajectory | None: + """Return the complete planned joint trajectory. + + Returns: + Joint names and sampled positions with shape (T, J) [rad, m], + or None when no plan is available. + """ + positions = self.current_joint_position_path + return None if positions is None else NamedJointTrajectory(self.active_joint_names, positions) + + def joint_positions_to_ee_poses(self, joint_positions: torch.Tensor) -> torch.Tensor: + """Compute env-relative end-effector poses for arm-local joint positions. + + Args: + joint_positions: Joint positions with shape ``(T, J)`` in + :attr:`active_joint_names` order [rad, m]. + + Returns: + End-effector poses with shape ``(T, 4, 4)`` in the env-relative frame. + """ + + ee_link = self.config.ee_link_name or self.robot_cfg["kinematics"]["ee_link"] + return self.joint_positions_to_link_poses(joint_positions, (ee_link,))[ee_link] + + def joint_positions_to_link_poses( + self, + joint_positions: torch.Tensor, + link_names: tuple[str, ...], + ) -> dict[str, torch.Tensor]: + """Compute env-relative poses for configured robot links. + + Args: + joint_positions: Joint positions with shape ``(T, J)`` in + :attr:`active_joint_names` order [rad, m]. + link_names: Configured links whose poses are requested. + + Returns: + Link-name mapping to poses with shape ``(T, 4, 4)`` in the env-relative frame. + """ + + query = self._joint_positions_query(joint_positions) + assert link_names and len(link_names) == len(set(link_names)), "link_names must be non-empty and unique" + state = self._kinematics.get_state(query, calculate_jacobian=False) + available = {str(name): index for index, name in enumerate(state.link_names)} + missing = set(link_names) - set(available) + assert not missing, f"cuRobo state does not expose links: {sorted(missing)}" + result: dict[str, torch.Tensor] = {} + for link_name in link_names: + link_index = available[link_name] + position = self._to_env_device(state.links_position[..., link_index, :]) + quaternion_wxyz = self._to_env_device(state.links_quaternion[..., link_index, :]) + quaternion_xyzw = torch.cat((quaternion_wxyz[..., 1:], quaternion_wxyz[..., :1]), dim=-1) + pose_base = PoseUtils.make_pose(position, PoseUtils.matrix_from_quat(quaternion_xyzw)) + result[link_name] = self._pose_base_to_env(pose_base).detach().clone() + return result + + def joint_positions_to_collision_spheres(self, joint_positions: torch.Tensor) -> torch.Tensor: + """Return configured collision spheres in the planning-root frame. + + Args: + joint_positions: Joint positions with shape ``(T, J)`` in + :attr:`active_joint_names` order [rad, m]. + + Returns: + Sphere tensor with shape ``(T, S, 4)``; the final coordinate is radius [m]. + """ + + query = self._joint_positions_query(joint_positions) + state = self._kinematics.get_state(query, calculate_jacobian=False) + spheres = state.link_spheres_tensor + assert isinstance(spheres, torch.Tensor), "cuRobo kinematics returned no collision spheres" + return spheres.reshape(query.shape[0], -1, 4).detach().clone() + + def joint_positions_self_collision_free( + self, + joint_positions: torch.Tensor, + collision_margin_m: float = 0.0, + ) -> torch.Tensor: + """Check configured full-robot self collision for batched states. + + Args: + joint_positions: Joint positions with shape ``(T, J)`` in + :attr:`active_joint_names` order [rad, m]. + collision_margin_m: Required sphere-surface separation [m]. + + Returns: + Boolean collision freedom with shape ``(T,)`` on the environment device. + """ + + assert math.isfinite(collision_margin_m) and collision_margin_m >= 0.0 + spheres = self.joint_positions_to_collision_spheres(joint_positions) + if not self.config.use_native_self_collision or self._auxiliary_joint_indices: + collisions = self._collision_spheres_self_collisions(spheres, collision_margin_m) + return self._to_env_device(~collisions).detach().clone() + if collision_margin_m: + spheres[..., 3] += torch.where( + spheres[..., 3] > 0.0, + 0.5 * collision_margin_m, + 0.0, + ) + spheres = spheres.unsqueeze(1) + constraint = self.motion_gen.rollout_fn.robot_self_collision_constraint + assert constraint.enabled, "cuRobo self-collision constraint is disabled" + cost = constraint.forward(spheres) + assert cost.shape == (len(joint_positions), 1), "cuRobo returned unexpected self-collision shape" + return self._to_env_device(cost[:, 0] <= 0.0).detach().clone() + + def _collision_spheres_self_collisions( + self, + spheres: torch.Tensor, + collision_margin_m: float, + ) -> torch.Tensor: + """Check configured robot-sphere pairs in bounded sample batches.""" + + pair_indices, sphere_offsets, _ = self._self_collision_pair_data(spheres.shape[1]) + collisions = torch.zeros(len(spheres), dtype=torch.bool, device=spheres.device) + if not len(pair_indices): + return collisions + pair_count = len(pair_indices) + sample_batch_size = max(1, 2_000_000 // pair_count) + first_indices, second_indices = pair_indices.T + for start in range(0, len(spheres), sample_batch_size): + stop = min(start + sample_batch_size, len(spheres)) + batch = spheres[start:stop] + first = batch[:, first_indices] + second = batch[:, second_indices] + clearance = ( + torch.linalg.vector_norm(first[..., :3] - second[..., :3], dim=-1) + - first[..., 3] + - second[..., 3] + - sphere_offsets[first_indices] + - sphere_offsets[second_indices] + ) + active = (first[..., 3] > 0.0) & (second[..., 3] > 0.0) + collisions[start:stop] = torch.any(active & (clearance <= collision_margin_m), dim=1) + return collisions + + def _self_collision_pair_data( + self, + sphere_count: int, + ) -> tuple[torch.Tensor, torch.Tensor, tuple[str, ...]]: + """Build direct collision pairs without cuRobo's fallback scan kernel.""" + + if self._self_collision_pair_cache is not None: + pairs, offsets, link_names = self._self_collision_pair_cache + assert len(link_names) == sphere_count + return pairs, offsets, link_names + + link_names = self.collision_sphere_link_names(sphere_count) + unknown = set(link_names) - set(self._self_collision_ignore) + assert not unknown, f"collision links have no self-collision policy: {sorted(unknown)}" + first_indices, second_indices = np.triu_indices(sphere_count, k=1) + enabled = np.fromiter( + ( + link_names[first] != link_names[second] + and link_names[second] not in self._self_collision_ignore[link_names[first]] + for first, second in zip(first_indices, second_indices, strict=True) + ), + dtype=np.bool_, + count=len(first_indices), + ) + pair_indices = torch.as_tensor( + np.stack((first_indices[enabled], second_indices[enabled]), axis=1), + dtype=torch.long, + device=self.tensor_args.device, + ) + buffers = self._kinematic_robot_cfg["kinematics"]["self_collision_buffer"] + sphere_offsets = torch.tensor( + [float(buffers[name]) for name in link_names], + dtype=self.tensor_args.dtype, + device=self.tensor_args.device, + ) + self._self_collision_pair_cache = pair_indices, sphere_offsets, link_names + return self._self_collision_pair_cache + + def joint_positions_world_collision_free( + self, + joint_positions: torch.Tensor, + collision_margin_m: float = 0.0, + *, + excluded_obstacle_paths: tuple[str, ...] = (), + ) -> torch.Tensor: + """Check robot states against the synchronized cuRobo world. + + Args: + joint_positions: Joint positions with shape ``(T, J)`` in + :attr:`active_joint_names` order [rad, m]. + collision_margin_m: Required sphere-to-world separation [m]. + excluded_obstacle_paths: Exact cuRobo obstacle paths omitted only for this query. + + Returns: + Boolean collision freedom with shape ``(T,)`` on the environment device. + """ + + spheres = self.joint_positions_to_collision_spheres(joint_positions) + return self._planning_spheres_world_collision_free( + spheres, + collision_margin_m, + excluded_obstacle_paths=excluded_obstacle_paths, + ) + + def joint_positions_environment_spheres_collision_free( + self, + joint_positions: torch.Tensor, + environment_spheres: torch.Tensor, + collision_margin_m: float = 0.0, + *, + allowed_robot_link_names: tuple[str, ...] = (), + ) -> torch.Tensor: + """Check robot states against matched environment-frame object spheres. + + Args: + joint_positions: Joint positions with shape ``(T, J)`` in + :attr:`active_joint_names` order [rad, m]. + environment_spheres: Object spheres with shape ``(T, O, 4)`` in the + environment frame, with radius last [m]. + collision_margin_m: Required robot-to-object sphere separation [m]. + allowed_robot_link_names: Exact robot links whose overlap with these + object spheres is authorized. + + Returns: + Boolean collision freedom with shape ``(T,)`` on the environment device. + """ + + collisions, _ = self._joint_positions_environment_spheres_collisions( + joint_positions, + environment_spheres, + collision_margin_m, + allowed_robot_link_names=allowed_robot_link_names, + ) + return ~collisions + + def joint_positions_environment_spheres_collision_witness( + self, + joint_positions: torch.Tensor, + environment_spheres: torch.Tensor, + collision_margin_m: float = 0.0, + *, + allowed_robot_link_names: tuple[str, ...] = (), + ) -> tuple[str, int, int] | None: + """Return the first forbidden robot-to-object sphere overlap. + + Args: + joint_positions: One joint state shaped ``(1, J)`` in + :attr:`active_joint_names` order [rad, m]. + environment_spheres: One object sphere state shaped ``(1, O, 4)`` in + the environment frame, with radius last [m]. + collision_margin_m: Required robot-to-object sphere separation [m]. + allowed_robot_link_names: Exact robot links whose overlap with these + object spheres is authorized. + + Returns: + Robot link name, robot sphere index, and object sphere index, or ``None``. + """ + + assert joint_positions.shape == (1, len(self.active_joint_names)) + assert environment_spheres.shape[0] == 1 + _, witness = self._joint_positions_environment_spheres_collisions( + joint_positions, + environment_spheres, + collision_margin_m, + allowed_robot_link_names=allowed_robot_link_names, + ) + return witness + + def _joint_positions_environment_spheres_collisions( + self, + joint_positions: torch.Tensor, + environment_spheres: torch.Tensor, + collision_margin_m: float, + *, + allowed_robot_link_names: tuple[str, ...], + ) -> tuple[torch.Tensor, tuple[str, int, int] | None]: + """Check exact robot/object sphere pairs in bounded sample batches.""" + + assert math.isfinite(collision_margin_m) and collision_margin_m >= 0.0 + robot_spheres = self.joint_positions_to_collision_spheres(joint_positions) + object_spheres = self._collision_spheres_validate(environment_spheres).to( + device=robot_spheres.device, + dtype=robot_spheres.dtype, + ) + assert robot_spheres.shape[0] == object_spheres.shape[0], "robot and object batches must match" + + transform = self._env_to_base_transform.to(device=object_spheres.device, dtype=object_spheres.dtype) + object_spheres[..., :3] = object_spheres[..., :3] @ transform[:3, :3].T + transform[:3, 3] + + robot_link_names = self.collision_sphere_link_names(robot_spheres.shape[1]) + assert isinstance(allowed_robot_link_names, tuple) and len(allowed_robot_link_names) == len( + set(allowed_robot_link_names) + ) + assert all( + isinstance(name, str) and name and name == name.strip() for name in allowed_robot_link_names + ), "allowed_robot_link_names must contain unique, non-empty, trimmed strings" + missing = set(allowed_robot_link_names) - set(robot_link_names) + assert not missing, f"allowed robot links have no cuRobo collision spheres: {sorted(missing)}" + allowed = torch.tensor( + [name in allowed_robot_link_names for name in robot_link_names], + dtype=torch.bool, + device=robot_spheres.device, + ) + + collisions = torch.zeros(len(robot_spheres), dtype=torch.bool, device=robot_spheres.device) + witness: tuple[str, int, int] | None = None + for start in range(0, len(robot_spheres), 128): + stop = min(start + 128, len(robot_spheres)) + robot_batch = robot_spheres[start:stop] + object_batch = object_spheres[start:stop] + clearance = ( + torch.cdist(robot_batch[..., :3], object_batch[..., :3]) + - robot_batch[..., 3].unsqueeze(-1) + - object_batch[..., 3].unsqueeze(-2) + ) + active = (robot_batch[..., 3].unsqueeze(-1) > 0.0) & (object_batch[..., 3].unsqueeze(-2) > 0.0) + forbidden = active & ~allowed.view(1, -1, 1) & (clearance <= collision_margin_m) + collisions[start:stop] = torch.any(forbidden.flatten(start_dim=1), dim=1) + if len(robot_spheres) == 1 and witness is None: + indices = torch.nonzero(forbidden[0], as_tuple=False) + if len(indices): + robot_index, object_index = (int(index.item()) for index in indices[0]) + witness = robot_link_names[robot_index], robot_index, object_index + return self._to_env_device(collisions).detach().clone(), witness + + def collision_sphere_link_names(self, sphere_count: int) -> tuple[str, ...]: + """Map every configured cuRobo collision sphere to its exact robot link. + + Args: + sphere_count: Number of spheres returned by cuRobo kinematics. + + Returns: + Link name for each sphere in cuRobo tensor order. + """ + + kinematics = self._kinematics.kinematics_config + sphere_links = kinematics.link_sphere_idx_map + assert sphere_links.shape == (sphere_count,) + names_by_index = {int(index): str(name) for name, index in kinematics.link_name_to_idx_map.items()} + missing = {int(index.item()) for index in sphere_links} - set(names_by_index) + assert not missing, f"cuRobo sphere links have no names: {sorted(missing)}" + return tuple(names_by_index[int(index.item())] for index in sphere_links) + + def world_object_obstacle_paths(self, object_ref: str) -> tuple[str, ...]: + """Resolve one logical scene object to its exact cuRobo obstacle inventory. + + Args: + object_ref: Exact key exposed by :meth:`Datastream.get_object_poses`. + + Returns: + Canonically ordered cuRobo obstacle paths comprising that scene object. + """ + + assert object_ref and object_ref == object_ref.strip(), "object_ref must be non-empty and trimmed" + root_path = self.datastream.get_object_prim_path(object_ref, self.env_id) + matches = tuple( + path + for path in sorted(set(self._get_world_object_names())) + if path == root_path or path.startswith(f"{root_path}/") + ) + if not matches: + raise KeyError(f"scene object {object_ref!r} has no cuRobo obstacle inventory") + return matches + + def environment_spheres_world_collision_free( + self, + spheres: torch.Tensor, + collision_margin_m: float = 0.0, + *, + excluded_obstacle_paths: tuple[str, ...] = (), + ) -> torch.Tensor: + """Check arbitrary environment-frame spheres against the synchronized cuRobo world. + + Args: + spheres: Sphere states shaped ``(T, S, 4)`` with environment-relative centers and + radius last [m]. + collision_margin_m: Required sphere-to-world separation [m]. + excluded_obstacle_paths: Exact cuRobo obstacle paths omitted only for this query. + + Returns: + Boolean collision freedom with shape ``(T,)`` on the environment device. + """ + + query = self._collision_spheres_validate(spheres) + transform = self._env_to_base_transform.to(device=query.device, dtype=query.dtype) + query[..., :3] = query[..., :3] @ transform[:3, :3].T + transform[:3, 3] + return self._planning_spheres_world_collision_free( + query, + collision_margin_m, + excluded_obstacle_paths=excluded_obstacle_paths, + ) + + def environment_spheres_world_collision_witness( + self, + spheres: torch.Tensor, + collision_margin_m: float = 0.0, + *, + excluded_obstacle_paths: tuple[str, ...] = (), + ) -> tuple[int, str] | None: + """Return the first environment-sphere and configured-obstacle collision. + + Args: + spheres: One environment-frame sphere state shaped ``(1, S, 4)`` with radius last [m]. + collision_margin_m: Required sphere-to-world separation [m]. + excluded_obstacle_paths: Exact cuRobo obstacle paths omitted from attribution. + + Returns: + Sphere index and exact obstacle path, or ``None``. + """ + + assert spheres.shape[0] == 1 + query = self._collision_spheres_validate(spheres) + transform = self._env_to_base_transform.to(device=query.device, dtype=query.dtype) + query[..., :3] = query[..., :3] @ transform[:3, :3].T + transform[:3, 3] + return self._planning_spheres_world_collision_witness( + query, + collision_margin_m, + excluded_obstacle_paths=excluded_obstacle_paths, + ) + + def _planning_spheres_world_collision_free( + self, + spheres: torch.Tensor, + collision_margin_m: float, + *, + excluded_obstacle_paths: tuple[str, ...], + ) -> torch.Tensor: + """Return collision freedom for each sphere batch in the planner's root frame. + + Args: + spheres: Sphere states with shape (T, S, 4), storing XYZ and radius [m]. + collision_margin_m: Required sphere-to-world separation [m]. + excluded_obstacle_paths: Exact obstacle paths omitted from this query. + + Returns: + One collision-free flag per batch sample. + """ + collisions = self._planning_spheres_world_collisions( + spheres, + collision_margin_m, + excluded_obstacle_paths=excluded_obstacle_paths, + ) + return ~torch.any(collisions, dim=1) + + def _planning_spheres_world_collisions( + self, + spheres: torch.Tensor, + collision_margin_m: float, + *, + excluded_obstacle_paths: tuple[str, ...], + ) -> torch.Tensor: + """Return the native binary collision result for every query sphere.""" + + assert math.isfinite(collision_margin_m) and collision_margin_m >= 0.0 + assert isinstance(excluded_obstacle_paths, tuple) and len(excluded_obstacle_paths) == len( + set(excluded_obstacle_paths) + ) + assert all(path and path == path.strip() for path in excluded_obstacle_paths) + query = self._collision_spheres_validate(spheres) + if collision_margin_m: + query[..., 3] += torch.where(query[..., 3] > 0.0, collision_margin_m, 0.0) + + query = query.unsqueeze(1) + checker = self.motion_gen.world_coll_checker + buffer = CollisionQueryBuffer() + buffer.update_buffer_shape(query.shape, self.tensor_args, checker.collision_types) + with self._world_obstacles_disabled(excluded_obstacle_paths): + collisions = checker.get_sphere_collision( + query, + buffer, + weight=self.tensor_args.to_device([1.0]), + activation_distance=self.tensor_args.to_device([0.0]), + ) + assert collisions.shape == query.shape[:-1], "cuRobo returned unexpected world-collision shape" + return self._to_env_device(torch.any(collisions > 0.0, dim=1)).detach().clone() + + @contextmanager + def _world_obstacles_disabled(self, obstacle_paths: tuple[str, ...]) -> Iterator[None]: + """Temporarily disable an exact, validated cuRobo obstacle set.""" + + assert isinstance(obstacle_paths, tuple) and len(obstacle_paths) == len(set(obstacle_paths)) + assert all( + isinstance(path, str) and path and path == path.strip() for path in obstacle_paths + ), "obstacle_paths must contain unique, non-empty, trimmed strings" + disabled_paths: list[str] = [] + try: + for path in obstacle_paths: + self.motion_gen.world_coll_checker.enable_obstacle(path, enable=False) + disabled_paths.append(path) + yield + finally: + for path in reversed(disabled_paths): + self.motion_gen.world_coll_checker.enable_obstacle(path, enable=True) + + def joint_positions_world_collision_witness( + self, + joint_positions: torch.Tensor, + collision_margin_m: float = 0.0, + *, + excluded_obstacle_paths: tuple[str, ...] = (), + ) -> tuple[str, int, str] | None: + """Return the first exact robot-link sphere and configured obstacle collision. + + Args: + joint_positions: One joint state shaped ``(1, J)`` in + :attr:`active_joint_names` order [rad, m]. + collision_margin_m: Required sphere-to-world separation [m]. + excluded_obstacle_paths: Exact cuRobo obstacle paths omitted from attribution. + + Returns: + Robot link name, global sphere index, and exact obstacle path, or ``None``. + """ + + assert joint_positions.shape == (1, len(self.active_joint_names)) + spheres = self.joint_positions_to_collision_spheres(joint_positions) + witness = self._planning_spheres_world_collision_witness( + spheres, + collision_margin_m, + excluded_obstacle_paths=excluded_obstacle_paths, + ) + if witness is None: + return None + sphere_index, obstacle_path = witness + return self.collision_sphere_link_names(spheres.shape[1])[sphere_index], sphere_index, obstacle_path + + def _planning_spheres_world_collision_witness( + self, + spheres: torch.Tensor, + collision_margin_m: float, + *, + excluded_obstacle_paths: tuple[str, ...], + ) -> tuple[int, str] | None: + """Isolate the first collision against the synchronized obstacle inventory.""" + + assert spheres.shape[0] == 1 + object_mappings = self._get_object_mappings() + attached_paths = { + object_mappings[object_name] for object_name in self.attached_objects if object_name in object_mappings + } + candidate_paths = tuple( + sorted(set(self._get_world_object_names()) - set(excluded_obstacle_paths) - attached_paths) + ) + inventory_exclusions = tuple(sorted(set(excluded_obstacle_paths) | set(candidate_paths))) + residual = self._planning_spheres_world_collisions( + spheres, + collision_margin_m, + excluded_obstacle_paths=inventory_exclusions, + ) + if bool(residual.any()): + raise RuntimeError("world collision remains after disabling the synchronized obstacle inventory") + for obstacle_path in candidate_paths: + isolated_exclusions = tuple(sorted(set(excluded_obstacle_paths) | (set(candidate_paths) - {obstacle_path}))) + collisions = self._planning_spheres_world_collisions( + spheres, + collision_margin_m, + excluded_obstacle_paths=isolated_exclusions, + ) + colliding = torch.nonzero(collisions[0], as_tuple=False) + if not len(colliding): + continue + sphere_index = int(colliding[0, 0].item()) + return sphere_index, obstacle_path + return None + + def _collision_spheres_validate(self, spheres: torch.Tensor) -> torch.Tensor: + """Check sphere batches and copy them to the planner's device. + + Args: + spheres: Sphere states with shape (T, S, 4), storing XYZ and radius [m]. + + Returns: + A detached copy on the cuRobo device, safe for query-specific changes. + """ + assert isinstance(spheres, torch.Tensor), "spheres must be a torch.Tensor" + assert spheres.ndim == 3 and spheres.shape[0] > 0 and spheres.shape[1] > 0 and spheres.shape[2] == 4 + assert bool(torch.isfinite(spheres).all()), "spheres must be finite" + assert bool((spheres[..., 3] > 0.0).any(dim=1).all()), "every sample must contain an active sphere" + return self._to_curobo_device(spheres).detach().clone() + + def joint_positions_self_collision_witness( + self, + joint_positions: torch.Tensor, + collision_margin_m: float = 0.0, + ) -> tuple[str, int, str, int, float] | None: + """Return the deepest enabled sphere overlap for one robot state. + + Args: + joint_positions: One joint state shaped ``(1, J)`` in :attr:`active_joint_names` order [rad, m]. + collision_margin_m: Required sphere-surface separation [m]. + + Returns: + First link, first sphere index, second link, second sphere index, and clearance [m], + or ``None`` when the state satisfies the requested margin. + """ + + assert joint_positions.shape == (1, len(self.active_joint_names)) + assert math.isfinite(collision_margin_m) and collision_margin_m >= 0.0 + spheres = self.joint_positions_to_collision_spheres(joint_positions)[0] + sphere_count = len(spheres) + pair_indices, sphere_offsets, link_names = self._self_collision_pair_data(sphere_count) + if not len(pair_indices): + return None + first_indices, second_indices = pair_indices.T + radii = spheres[:, 3] + clearance = ( + torch.linalg.vector_norm(spheres[first_indices, :3] - spheres[second_indices, :3], dim=-1) + - radii[first_indices] + - radii[second_indices] + - sphere_offsets[first_indices] + - sphere_offsets[second_indices] + ) + active = (radii[first_indices] > 0.0) & (radii[second_indices] > 0.0) + minimum, pair_index = torch.where(active, clearance, torch.inf).min(dim=0) + if not bool(torch.isfinite(minimum)) or float(minimum.item()) > collision_margin_m: + return None + + first_sphere = int(first_indices[pair_index].item()) + second_sphere = int(second_indices[pair_index].item()) + return ( + link_names[first_sphere], + first_sphere, + link_names[second_sphere], + second_sphere, + float(minimum.item()), + ) + + def _joint_positions_query(self, joint_positions: torch.Tensor) -> torch.Tensor: + """Check joint samples and place them on the planner's device. + + Args: + joint_positions: Samples with shape (T, J) in active-joint order [rad, m]. + + Returns: + Finite joint samples on the cuRobo device. + """ + assert isinstance(joint_positions, torch.Tensor), "joint_positions must be a torch.Tensor" + assert ( + joint_positions.ndim == 2 and joint_positions.shape[0] > 0 + ), "joint_positions must have non-empty shape (T, J)" + assert joint_positions.shape[1] == len( + self.active_joint_names + ), "joint_positions width must match active_joint_names" + assert bool(torch.isfinite(joint_positions).all()), "joint_positions must be finite" + return self._to_curobo_device(joint_positions) + # ===================================================================================== # WORLD AND OBJECT MANAGEMENT, ATTACHMENT, AND DETACHMENT # ===================================================================================== @@ -494,7 +1361,7 @@ def get_object_pose(self, object_name: str) -> Pose | None: continue for obj in obj_list: - if obj.name and object_path in str(obj.name): + if obj.name and object_path == str(obj.name): if obj.pose is not None: return Pose.from_list(obj.pose, tensor_args=self.tensor_args) @@ -588,7 +1455,7 @@ def create_attachment( return Attachment(attach_pose, link_name) - def update_world(self) -> None: + def update_world(self, object_pose_overrides: Mapping[str, torch.Tensor] | None = None) -> None: """Synchronize collision world with current Isaac Lab scene state. Updates all dynamic object poses in cuRobo's collision world to match their current @@ -599,13 +1466,18 @@ def update_world(self) -> None: The method validates that the set of objects hasn't changed at runtime, as cuRobo requires world model reinitialization when objects are added or removed. + Args: + object_pose_overrides: Optional environment-relative dynamic-object poses [m] used by + offline path accumulation instead of their live simulator poses. + Raises: - RuntimeError: If the set of objects has changed at runtime + RuntimeError: If the set of objects has changed at runtime. """ # Refresh the env-relative -> robot base frame transform before syncing geometry, so # object, goal, and planned poses are reconciled against the current base pose. self._refresh_base_frame_transform() + self._static_world_activate() # Establish validation baseline on first call, validate on subsequent calls if self._expected_objects is None: @@ -631,7 +1503,7 @@ def update_world(self) -> None: raise RuntimeError(error_msg) # Sync object poses with Isaac Lab - self._sync_object_poses_with_isaaclab() + self._sync_object_poses_with_isaaclab(object_pose_overrides) if self.visualize_spheres: self._update_sphere_visualization(force_update=True) @@ -639,6 +1511,19 @@ def update_world(self) -> None: if torch.cuda.is_available(): torch.cuda.synchronize() + def world_visualization_refresh(self) -> None: + """Refresh the Rerun world scene from this planner's current synchronized world.""" + + if self.plan_visualizer is None: + return + world_scene = None + try: + self.update_world() + world_scene = WorldConfig.get_scene_graph(self.motion_gen.world_coll_checker.world_model) + except Exception as error: + self.logger.warning(f"Failed to refresh the Rerun world scene: {error}") + self.plan_visualizer.world_scene_set(world_scene) + def _get_world_object_names(self) -> list[str]: """Extract all object names from cuRobo's collision world model. @@ -674,7 +1559,10 @@ def _get_world_object_names(self) -> list[str]: self.logger.debug(f"ERROR getting world object names: {e}") return [] - def _sync_object_poses_with_isaaclab(self) -> None: + def _sync_object_poses_with_isaaclab( + self, + object_pose_overrides: Mapping[str, torch.Tensor] | None = None, + ) -> None: """Synchronize cuRobo collision world with Isaac Lab object positions. Updates all dynamic object poses in cuRobo's world model to match their current @@ -685,24 +1573,34 @@ def _sync_object_poses_with_isaaclab(self) -> None: The method updates both the world model and the collision checker to ensure consistency across all cuRobo components. """ - # Get cached object mappings and world model. Object poses are read through the - # Datastream in env-relative frame (env origin already subtracted) — the same - # robot-relative frame cuRobo's collision world is built in. + # Object poses enter in the Datastream's env-relative frame and are converted to the + # planning-root frame before updating cuRobo's collision world. object_mappings = self._get_object_mappings() world_model = self.motion_gen.world_coll_checker.world_model object_poses = self.datastream.get_object_poses(env_ids=[self.env_id]) + pose_overrides = dict(object_pose_overrides or {}) + unknown_overrides = set(pose_overrides) - set(object_mappings) + assert not unknown_overrides, f"object-pose overrides reference unknown obstacles: {sorted(unknown_overrides)}" static_objects = getattr(self.config, "static_objects", []) def _is_static(name: str) -> bool: return any(static_name in name.lower() for static_name in static_objects) - updated_count = 0 - + updates: list[tuple[str, str, list[float]]] = [] for object_name, object_path in object_mappings.items(): - if object_name not in object_poses or _is_static(object_name): + if _is_static(object_name): continue - pose_base = self._pose_env_to_base(object_poses[object_name][0]) - pose_list = self._object_pose_to_curobo_list(pose_base) + if object_name in pose_overrides: + pose_env = pose_overrides[object_name] + elif object_name in object_poses: + pose_env = object_poses[object_name][0] + else: + continue + pose_list = self._object_pose_to_curobo_list(self._pose_env_to_base(pose_env)) + updates.append((object_name, object_path, pose_list)) + + updated_count = 0 + for object_name, object_path, pose_list in updates: if self._update_object_in_world_model(world_model, object_name, object_path, pose_list): updated_count += 1 @@ -711,11 +1609,7 @@ def _is_static(name: str) -> bool: # Sync object poses with collision checker. This preserves static mesh objects unlike # load_collision_model which rebuilds everything. if updated_count > 0: - for object_name, object_path in object_mappings.items(): - if object_name not in object_poses or _is_static(object_name): - continue - pose_base = self._pose_env_to_base(object_poses[object_name][0]) - pose_list = self._object_pose_to_curobo_list(pose_base) + for _, object_path, pose_list in updates: # pose_list quaternion is already cuRobo (w, x, y, z) order. curobo_pose = self._make_pose(position=pose_list[:3], quaternion=pose_list[3:], quat_is_xyzw=False) self.motion_gen.world_coll_checker.update_obstacle_pose( # type: ignore @@ -775,24 +1669,29 @@ def _discover_object_mappings(self, world_model, object_names: list[str]) -> dic Dictionary mapping scene object names to their corresponding USD paths """ mappings = {} - env_prefix = f"{self.datastream.get_env_prim_path(self.env_id)}/" world_object_paths = [] # Collect all primitive objects from cuRobo world model for primitive_type in self.primitive_types: primitive_list = getattr(world_model, primitive_type) for primitive in primitive_list: - if primitive.name and env_prefix in str(primitive.name): + if primitive.name: world_object_paths.append(str(primitive.name)) + world_object_paths = sorted(set(world_object_paths)) - # Match scene object names to world paths for object_name in object_names: - # Direct name matching - for path in world_object_paths: - if object_name.lower().replace("_", "") in path.lower().replace("_", ""): - mappings[object_name] = path - self.logger.debug(f"MAPPING: {object_name} -> {path}") - break + root_path = self.datastream.get_object_prim_path(object_name, self.env_id) + matches = tuple( + path for path in world_object_paths if path == root_path or path.startswith(f"{root_path}/") + ) + if len(matches) == 1: + mappings[object_name] = matches[0] + self.logger.debug(f"MAPPING: {object_name} -> {matches[0]}") + elif matches: + self.logger.debug( + f"WARNING: Object {object_name} has {len(matches)} cuRobo obstacles; " + "single-obstacle attachment mapping is unavailable" + ) else: self.logger.debug(f"WARNING: Could not find world path for {object_name}") @@ -803,9 +1702,8 @@ def _update_object_in_world_model( ) -> bool: """Update a single object's pose in cuRobo's collision world model. - Searches through all primitive types in the world model to find the specified object - and updates its pose. Uses flexible matching to handle variations in path naming - between Isaac Lab and cuRobo representations. + Searches every primitive type for the exact resolved cuRobo obstacle path and updates + its pose. Args: world_model: cuRobo's collision world model @@ -829,8 +1727,7 @@ def _update_object_in_world_model( for primitive in primitive_list: if primitive.name: primitive_name = str(primitive.name) - # Use bidirectional matching for robust path matching - if object_path == primitive_name or object_path in primitive_name or primitive_name in object_path: + if object_path == primitive_name: primitive.pose = pose_list self.logger.debug(f"Updated {primitive_type} {object_name} pose") return True @@ -838,7 +1735,145 @@ def _update_object_in_world_model( self.logger.debug(f"WARNING: Object {object_name} not found in world model") return False - def _attach_object(self, object_name: str, object_path: str, env_id: int) -> bool: + def object_collision_spheres_fit( + self, + object_name: str, + env_id: int, + start_joint_positions: torch.Tensor, + expected_tool_from_object: torch.Tensor, + object_collision_spheres: ObjectCollisionSpheres | None = None, + ) -> ObjectCollisionSpheres: + """Fit or bind the exact object spheres used by carried-object planning. + + The query applies the virtual grasp pose in the planner world, attaches at the supplied + robot state, captures or reuses object-frame geometry, and detaches before returning. + Cleanup failures propagate. + + Args: + object_name: Exact logical scene-object name. + env_id: Environment index used by the planner. + start_joint_positions: Arm-local attachment state in planner joint order [rad, m]. + expected_tool_from_object: Expected rigid object pose in the physical tool frame. + object_collision_spheres: Optional sphere geometry captured by another planner in this episode. + + Returns: + Immutable object-frame spheres and their fit details. + """ + + assert self.config.planning_enabled, "object sphere fitting requires an ordinary planning context" + assert env_id == self.env_id, "object sphere fitting must use the planner's environment" + assert isinstance(expected_tool_from_object, torch.Tensor) and expected_tool_from_object.shape == (4, 4) + tool_pose = self.joint_positions_to_ee_poses(start_joint_positions.unsqueeze(0))[0] + object_pose = tool_pose @ expected_tool_from_object.to(device=tool_pose.device, dtype=tool_pose.dtype) + self.update_world({object_name: object_pose}) + object_path = self._get_object_mappings().get(object_name) + if object_path is None: + raise KeyError(f"object {object_name!r} has no exact cuRobo obstacle mapping") + if object_collision_spheres is not None: + assert object_collision_spheres.object_name == object_name + assert object_collision_spheres.obstacle_path == object_path + cached = self._object_collision_spheres.setdefault(object_name, object_collision_spheres) + assert cached is object_collision_spheres, "planner already owns different geometry for this object" + try: + if not self._attach_object(object_name, object_path, start_joint_positions): + raise RuntimeError(f"cuRobo failed to fit attachment spheres for {object_name!r}") + attachment = self.attached_objects[object_name] + captured_transform = torch.as_tensor( + attachment.pose.get_matrix(), + device=expected_tool_from_object.device, + dtype=expected_tool_from_object.dtype, + ).reshape(4, 4) + assert torch.allclose( + captured_transform, expected_tool_from_object, atol=1.0e-4, rtol=0.0 + ), f"attachment transform for {object_name!r} does not match its planned attachment event" + return self._object_collision_spheres[object_name] + finally: + self._detach_objects() + + def object_collision_spheres_reset(self) -> None: + """Clear fitted object geometry at an episode boundary.""" + + assert not self.attached_objects, "cannot clear object geometry while an object is attached" + self._object_collision_spheres.clear() + + def _object_collision_spheres_capture( + self, + object_name: str, + object_path: str, + attachment: Attachment, + ) -> ObjectCollisionSpheres: + """Capture active native attachment slots as immutable object-frame spheres.""" + + link_name = self.config.attached_object_link_name + slots = self.motion_gen.kinematics.kinematics_config.get_link_spheres(link_name).detach().clone() + assert slots.ndim == 2 and slots.shape[1] == 4, "native attachment slots must have shape (S, 4)" + active = slots[:, 3] > 0.0 + assert bool(active.any()), f"native attachment fit for {object_name!r} produced no active spheres" + active_slots = slots[active] + object_centers = attachment.pose.inverse().transform_points(active_slots[:, :3]) + spheres = tuple( + CollisionSphere( + center=tuple(float(value) for value in center), + radius=float(radius), + ) + for center, radius in zip( + object_centers.detach().cpu().tolist(), + active_slots[:, 3].detach().cpu().tolist(), + strict=True, + ) + ) + transform = attachment.pose.get_matrix().detach().cpu().reshape(4, 4).tolist() + result = ObjectCollisionSpheres( + object_name=object_name, + obstacle_path=object_path, + spheres=spheres, + fit_type=SphereFitType.SAMPLE_SURFACE.value, + surface_sphere_radius_m=self.config.surface_sphere_radius, + slot_capacity=len(slots), + tool_frame=self.config.ee_link_name or self.robot_cfg["kinematics"]["ee_link"], + attachment_link=link_name, + captured_tool_from_object=tuple(tuple(float(value) for value in row) for row in transform), + ) + self._object_collision_spheres[object_name] = result + return result + + def _object_collision_spheres_attach( + self, + geometry: ObjectCollisionSpheres, + attachment: Attachment, + ) -> None: + """Reload cached object-frame spheres into the native virtual attachment slots.""" + + link_name = self.config.attached_object_link_name + assert geometry.obstacle_path == self._get_object_mappings().get(geometry.object_name) + assert geometry.attachment_link == link_name + assert geometry.fit_type == SphereFitType.SAMPLE_SURFACE.value + assert math.isclose(geometry.surface_sphere_radius_m, self.config.surface_sphere_radius) + current_slots = self.motion_gen.kinematics.kinematics_config.get_link_spheres(link_name) + assert current_slots.shape == (geometry.slot_capacity, 4), "native attachment-slot capacity changed" + object_centers = torch.as_tensor( + [sphere.center for sphere in geometry.spheres], + device=current_slots.device, + dtype=current_slots.dtype, + ) + tool_centers = attachment.pose.transform_points(object_centers) + sphere_tensor = torch.zeros_like(current_slots) + sphere_tensor[:, 3] = -10.0 + sphere_tensor[: len(geometry.spheres), :3] = tool_centers + sphere_tensor[: len(geometry.spheres), 3] = torch.as_tensor( + [sphere.radius for sphere in geometry.spheres], + device=current_slots.device, + dtype=current_slots.dtype, + ) + self.motion_gen.attach_spheres_to_robot(sphere_tensor=sphere_tensor, link_name=link_name) + self.motion_gen.world_coll_checker.enable_obstacle(geometry.obstacle_path, enable=False) + + def _attach_object( + self, + object_name: str, + object_path: str, + start_joint_positions: torch.Tensor | None = None, + ) -> bool: """Attach an object to the robot for manipulation planning. Establishes an attachment between the specified object and the robot's end-effector @@ -849,51 +1884,68 @@ def _attach_object(self, object_name: str, object_path: str, env_id: int) -> boo Args: object_name: Short name of the object to attach (e.g., "cube_2") object_path: Full USD path for the object in cuRobo world model - env_id: Environment ID for multi-environment support + start_joint_positions: Optional arm-local attachment state for offline planning. Returns: True if attachment succeeded, False if attachment failed """ - current_joint_state = self._get_current_joint_state_for_curobo() - self.logger.debug(f"Attaching {object_name} at path {object_path}") - - # Create attachment record (relative pose object-frame to parent link) - attachment = self.create_attachment( - object_name, - self.config.attached_object_link_name, - current_joint_state, - ) - self.attached_objects[object_name] = attachment - success = self.motion_gen.attach_objects_to_robot( - joint_state=current_joint_state, - object_names=[object_path], - link_name=self.config.attached_object_link_name, - surface_sphere_radius=self.config.surface_sphere_radius, - sphere_fit_type=SphereFitType.SAMPLE_SURFACE, - world_objects_pose_offset=None, - ) + try: + current_joint_state = self._get_current_joint_state_for_curobo(start_joint_positions) + attachment = self.create_attachment( + object_name, + self.config.attached_object_link_name, + current_joint_state, + ) + cached_geometry = self._object_collision_spheres.get(object_name) + if cached_geometry is None: + success = self.motion_gen.attach_objects_to_robot( + joint_state=current_joint_state, + object_names=[object_path], + link_name=self.config.attached_object_link_name, + surface_sphere_radius=self.config.surface_sphere_radius, + sphere_fit_type=SphereFitType.SAMPLE_SURFACE, + world_objects_pose_offset=None, + ) + if success: + self._object_collision_spheres_capture(object_name, object_path, attachment) + else: + assert cached_geometry.obstacle_path == object_path, "cached object obstacle path changed" + self._object_collision_spheres_attach(cached_geometry, attachment) + success = True + except Exception as error: + self.logger.error(f"Failed to attach {object_name}: {error}") + success = False if success: + self.attached_objects[object_name] = attachment self.logger.debug(f"Successfully attached {object_name}") self.logger.debug(f"Current attached objects: {list(self.attached_objects.keys())}") # Force sphere visualization update if self.visualize_spheres: - self._update_sphere_visualization(force_update=True) - - self.logger.info(f"Sphere count after attach is successful: {self._count_active_spheres()}") - - # Deactivate the original obstacle as it's now carried by the robot - self.motion_gen.world_coll_checker.enable_obstacle(object_path, enable=False) + try: + self._update_sphere_visualization(force_update=True) + except Exception as error: + self.logger.warning(f"Failed to visualize attachment for {object_name}: {error}") return True - else: - self.logger.error(f"cuRobo attach_objects_to_robot failed for {object_name}") - # Clean up on failure - if object_name in self.attached_objects: - del self.attached_objects[object_name] - return False + + self.logger.error(f"cuRobo attach_objects_to_robot failed for {object_name}") + self.attached_objects.pop(object_name, None) + try: + self.motion_gen.detach_object_from_robot(link_name=self.config.attached_object_link_name) + except Exception as error: + self.logger.error(f"Failed to clear attachment slots for {object_name}: {error}") + try: + self._set_active_links([self.config.attached_object_link_name], active=True) + except Exception as error: + self.logger.error(f"Failed to restore attachment spheres for {object_name}: {error}") + try: + self.motion_gen.world_coll_checker.enable_obstacle(object_path, enable=True) + except Exception as error: + self.logger.error(f"Failed to restore world obstacle for {object_name}: {error}") + return False def _detach_objects(self, link_names: set[str] | None = None) -> bool: """Detach objects from robot and restore collision checking. @@ -977,22 +2029,34 @@ def has_attached_objects(self) -> bool: # JOINT STATE AND KINEMATICS # ===================================================================================== - def _get_current_joint_state_for_curobo(self) -> JointState: - """ - Construct the current joint state for cuRobo with zero velocity and acceleration. + def _get_current_joint_state_for_curobo( + self, + start_joint_positions: torch.Tensor | None = None, + ) -> JointState: + """Read one state and select the optimizer's joint order. - This helper reads the robot's joint positions from Isaac Lab for the current environment - and pairs them with zero velocities and accelerations as required by cuRobo planning. - All tensors are moved to the cuRobo device and reordered to match the kinematic chain - used by the cuRobo motion generator. + Args: + start_joint_positions: Optional state shaped ``(J,)`` or ``(1, J)`` in + :attr:`active_joint_names` order [rad, m]. ``None`` reads the live articulation. Returns: - JointState on the cuRobo device, ordered according to - `self.motion_gen.kinematics.joint_names`, with position from the robot - and zero velocity/acceleration. + CuRobo planning state with zero velocity and acceleration. Separately commanded + auxiliary joints remain outside the optimizer's state vector. """ - # Fetch joint position (shape: [1, num_joints]) and names through the Datastream. - joint_pos_raw: torch.Tensor = self.datastream.get_robot_joint_positions(env_ids=[self.env_id]) + if start_joint_positions is None: + joint_names = list(self.active_joint_names) + joint_pos_raw = self.datastream.get_robot_joint_positions(env_ids=[self.env_id], joint_names=joint_names) + else: + # Offline accumulation passes one arm-local state in this planner's native order. + joint_pos_raw = start_joint_positions + if joint_pos_raw.ndim == 1: + joint_pos_raw = joint_pos_raw.unsqueeze(0) + joint_names = list(self.active_joint_names) + assert joint_pos_raw.ndim == 2 and joint_pos_raw.shape[0] == 1 + assert joint_pos_raw.shape[1] == len(joint_names), ( + f"planning group {self.config.planning_group_name!r} expects {len(joint_names)} " + f"joint positions, got {joint_pos_raw.shape[1]}" + ) joint_vel_raw: torch.Tensor = torch.zeros_like(joint_pos_raw) joint_acc_raw: torch.Tensor = torch.zeros_like(joint_pos_raw) @@ -1005,10 +2069,74 @@ def _get_current_joint_state_for_curobo(self) -> JointState: position=joint_pos, velocity=joint_vel, acceleration=joint_acc, - joint_names=self.datastream.get_robot_joint_names(), + joint_names=joint_names, + tensor_args=self.tensor_args, + ).get_ordered_joint_state(self.motion_gen.kinematics.joint_names) + + position_limits = self.motion_gen.kinematics.get_joint_limits().position + lower, upper = position_limits[0], position_limits[1] + margin = 1e-4 + assert bool(torch.all(upper - lower > 2.0 * margin)), "joint limits are narrower than the safety margin" + position = torch.clamp(cu_js.position, lower + margin, upper - margin) + return JointState( + position=position, + velocity=torch.zeros_like(position), + acceleration=torch.zeros_like(position), + joint_names=cu_js.joint_names, tensor_args=self.tensor_args, ) - return cu_js.get_ordered_joint_state(self.motion_gen.kinematics.joint_names) + + def _auxiliary_joint_positions_update(self, joint_positions: torch.Tensor | None) -> None: + """Hold separately commanded joints fixed while the optimizer moves the arm. + + Args: + joint_positions: One state in :attr:`active_joint_names` order [rad, m]. + ``None`` reads the live articulation. + """ + if not self._auxiliary_joint_indices: + return + positions = ( + self.datastream.get_robot_joint_positions(env_ids=[self.env_id], joint_names=self.active_joint_names) + if joint_positions is None + else joint_positions.reshape(1, -1) + ) + assert positions.shape == (1, len(self.active_joint_names)) and bool(torch.isfinite(positions).all()) + auxiliary = {name: float(positions[0, index].item()) for name, index in self._auxiliary_joint_indices.items()} + locked = self.robot_cfg["kinematics"]["lock_joints"] + if any(locked[name] != value for name, value in auxiliary.items()): + spheres = { + link: self.motion_gen.kinematics.kinematics_config.get_link_spheres(link).clone() + for link in self.attachment_links + } + self.motion_gen.update_locked_joints({**locked, **auxiliary}, self.robot_cfg) + self._joint_limits_sync(self.motion_gen.kinematics.get_joint_limits()) + for link, geometry in spheres.items(): + self.motion_gen.kinematics.kinematics_config.update_link_spheres(link, geometry) + + def _planning_joint_state_expand( + self, state: JointState, auxiliary_joint_positions: torch.Tensor | None = None + ) -> JointState: + """Expand a plan using the current auxiliary-joint targets. + + Args: + state: Joint state in the optimizer's joint order [rad, m]. + auxiliary_joint_positions: Reference state in :attr:`active_joint_names` order [rad, m]. + ``None`` uses the auxiliary positions held by the planning model. + + Returns: + Full joint state with the auxiliary positions used for this planning call. + """ + result = self.motion_gen.get_full_js(state).clone() + reference = ( + self._to_curobo_device(auxiliary_joint_positions).reshape(-1) + if auxiliary_joint_positions is not None + else None + ) + for name, index in self._auxiliary_joint_indices.items(): + result.position[..., result.joint_names.index(name)] = ( + self.robot_cfg["kinematics"]["lock_joints"][name] if reference is None else reference[index] + ) + return result def get_ee_pose(self, joint_state: JointState) -> Pose: """Compute end-effector pose from joint configuration. @@ -1049,6 +2177,250 @@ def get_ee_pose(self, joint_state: JointState) -> Pose: kin_state: Any = self.motion_gen.rollout_fn.compute_kinematics(cuda_joint_state) return kin_state.ee_pose + def solve_ik( + self, + target_pose: torch.Tensor, + seed_joint_positions: torch.Tensor | None = None, + ) -> torch.Tensor | None: + """Solve one collision-feasible arm-local IK problem. + + Args: + target_pose: End-effector pose as a 4x4 matrix in the env-relative frame. + seed_joint_positions: Arm-local seed in :attr:`active_joint_names` order. ``None`` + uses the live articulation state. + + Returns: + Solved arm-local joint positions on the environment device, or ``None`` when IK fails. + """ + return self._solve_ik(target_pose, seed_joint_positions, require_feasible=True) + + def solve_ik_kinematic( + self, + target_pose: torch.Tensor, + seed_joint_positions: torch.Tensor | None = None, + ) -> torch.Tensor | None: + """Return the nearest-seed pose-validated arm-local IK candidate for offline scheduling. + + Demonstrated skill poses are replayed as Cartesian controller targets. Their cuRobo joint + candidates are used to approximate robot geometry during inter-arm scheduling, so world + contact may make a solver-unsuccessful candidate useful. Robot self collision remains + forbidden, and explicit forward kinematics must match the target within configured tolerances. + + Args: + target_pose: End-effector pose as a 4x4 matrix in the env-relative frame. + seed_joint_positions: Arm-local seed in :attr:`active_joint_names` order. ``None`` + uses the live articulation state. + + Returns: + Pose-validated arm-local joint positions, or ``None`` when no candidate passes FK. + """ + return self._solve_ik(target_pose, seed_joint_positions, require_feasible=False) + + @contextmanager + def _ik_collision_costs_disabled(self) -> Iterator[None]: + """Disable warmed IK collision rollouts and restore their exact prior states.""" + + attributes = ( + "primitive_collision_cost", + "primitive_collision_constraint", + "robot_self_collision_cost", + "robot_self_collision_constraint", + ) + costs = { + id(cost): (cost, bool(cost.enabled)) + for rollout in self.motion_gen.ik_solver.get_all_rollout_instances() + for attribute in attributes + if (cost := getattr(rollout, attribute, None)) is not None + } + try: + for cost, _ in costs.values(): + cost.disable_cost() + yield + finally: + for cost, was_enabled in costs.values(): + (cost.enable_cost if was_enabled else cost.disable_cost)() + + def joint_positions_to_named_positions(self, joint_positions: torch.Tensor) -> dict[str, torch.Tensor]: + """Expand one active joint configuration, including its dependent mimic joints. + + Args: + joint_positions: Active joint positions in planner order [rad, m]. + + Returns: + Named scalar positions on the environment device. + """ + assert joint_positions.shape == (len(self.active_joint_names),) + state = JointState.from_position( + position=self._to_curobo_device(joint_positions), joint_names=list(self.active_joint_names) + ) + expanded = self._kinematics.get_mimic_js(state) + if expanded is not None: + state = expanded + positions = self._to_env_device(state.position) + return dict(zip(state.joint_names, positions, strict=True)) + + def _solve_ik( + self, + target_pose: torch.Tensor, + seed_joint_positions: torch.Tensor | None, + *, + require_feasible: bool, + ) -> torch.Tensor | None: + """Solve a tool pose and validate candidates with the state-query model. + + Args: + target_pose: Environment-relative tool transform [m]. + seed_joint_positions: Reference state in :attr:`active_joint_names` order [rad, m]. + ``None`` reads the live articulation. + require_feasible: Keep native collision constraints enabled during IK. + + Returns: + Accepted joint state, or ``None`` when no candidate passes the configured checks. + """ + assert self.config.planning_enabled, "IK is disabled for this collision-only backend" + assert target_pose.shape == (4, 4), f"target pose must have shape (4, 4), got {target_pose.shape}" + if seed_joint_positions is None: + seed_joint_positions = self.datastream.get_robot_joint_positions( + env_ids=[self.env_id], joint_names=self.active_joint_names + )[0] + # Kinematic sampling checks auxiliary geometry in the query model, not the native IK costs. + if require_feasible: + self._auxiliary_joint_positions_update(seed_joint_positions) + seed_state = self._get_current_joint_state_for_curobo(seed_joint_positions) + target_pose_base = self._to_curobo_device(self._pose_env_to_base(target_pose)) + target_position, target_rotation = PoseUtils.unmake_pose(target_pose_base) + goal_pose = self._make_pose( + position=target_position, + quaternion=PoseUtils.quat_from_matrix(target_rotation), + ) + candidate_count = self.config.ik_candidate_count + assert type(candidate_count) is int and candidate_count >= 1, "ik_candidate_count must be positive" + solver_candidate_count = self.motion_gen.ik_solver.num_seeds + assert ( + candidate_count <= solver_candidate_count + ), "ik_candidate_count cannot exceed the warmed-up cuRobo IK seed count" + returned_candidate_count = solver_candidate_count if self.config.debug_planner else candidate_count + + try: + collision_scope = nullcontext() if require_feasible else self._ik_collision_costs_disabled() + with collision_scope: + result = self.motion_gen.ik_solver.solve_single( + goal_pose, + retract_config=seed_state.position, + seed_config=seed_state.position.unsqueeze(0), + return_seeds=returned_candidate_count, + ) + except Exception as error: + self.logger.debug(f"IK solve failed: {error}") + return None + + solution_state = JointState( + position=result.solution.reshape(-1, len(self.motion_gen.kinematics.joint_names)), + joint_names=list(self.motion_gen.kinematics.joint_names), + tensor_args=self.tensor_args, + ) + solutions = ( + self._planning_joint_state_expand(solution_state, seed_joint_positions) + .get_ordered_joint_state(self.active_joint_names) + .position + ) + successes = result.success.reshape(-1) + assert ( + len(solutions) == len(successes) == returned_candidate_count + ), "cuRobo returned an unexpected IK candidate shape" + solutions = self._to_env_device(solutions).detach() + successes = successes.to(device=solutions.device) + try: + actual_poses = self.joint_positions_to_ee_poses(solutions) + except Exception as error: + self.logger.debug(f"IK candidate FK failed: {error}") + return None + target_poses = target_pose.to(device=actual_poses.device, dtype=actual_poses.dtype).expand_as(actual_poses) + position_error = torch.linalg.vector_norm(actual_poses[:, :3, 3] - target_poses[:, :3, 3], dim=-1) + relative_rotation = actual_poses[:, :3, :3].transpose(-1, -2) @ target_poses[:, :3, :3] + cosine = torch.clamp((relative_rotation.diagonal(dim1=-2, dim2=-1).sum(-1) - 1.0) * 0.5, -1.0, 1.0) + rotation_error = torch.acos(cosine) + accepted = ( + torch.isfinite(solutions).all(dim=-1) + & torch.isfinite(actual_poses).all(dim=(-2, -1)) + & (position_error <= self.config.position_threshold) + & (rotation_error <= self.config.rotation_threshold) + ) + if require_feasible: + accepted &= successes + else: + candidate_indices = torch.nonzero(accepted[:candidate_count], as_tuple=False).reshape(-1) + if len(candidate_indices): + collision_free = self.joint_positions_self_collision_free( + solutions.index_select(0, candidate_indices), + 0.0, + ) + accepted[candidate_indices] &= collision_free + seed_positions = self._to_env_device( + self._planning_joint_state_expand(seed_state, seed_joint_positions) + .get_ordered_joint_state(self.active_joint_names) + .position + ).reshape(1, -1) + auxiliary_names = set(self.config.initial_auxiliary_joint_positions) + pose_joint_indices = [ + index for index, name in enumerate(self.active_joint_names) if name not in auxiliary_names + ] + assert pose_joint_indices, "IK planner must contain at least one non-auxiliary joint" + seed_distance = torch.sum( + torch.square(solutions[:, pose_joint_indices] - seed_positions[:, pose_joint_indices]), + dim=-1, + ) + accepted_indices = torch.nonzero(accepted[:candidate_count], as_tuple=False).reshape(-1) + if len(accepted_indices) == 0: + if returned_candidate_count > candidate_count: + position_limits = self._to_env_device(self._kinematics.get_joint_limits().position) + joint_slack, limiting_joint = torch.min( + torch.minimum( + solutions[:, pose_joint_indices] - position_limits[0, pose_joint_indices], + position_limits[1, pose_joint_indices] - solutions[:, pose_joint_indices], + ), + dim=-1, + ) + audit_lines = [ + f"[{index:02d}] eligible={index < candidate_count} " + f"solver_success={bool(successes[index].item())} " + f"position_error={float(position_error[index].item()):.6f}m " + f"rotation_error={float(rotation_error[index].item()):.6f}rad " + f"pose_seed_distance={float(torch.sqrt(seed_distance[index]).item()):.6f} " + f"pose_joint_slack={float(joint_slack[index].item()):.6f} " + f"limiting_joint={self.active_joint_names[pose_joint_indices[int(limiting_joint[index].item())]]}" + for index in range(returned_candidate_count) + ] + self.logger.debug( + "IK candidate audit for group %r after configured prefix %d failed:\n%s", + self.config.planning_group_name, + candidate_count, + "\n".join(audit_lines), + ) + best = int( + torch.argmin( + torch.nan_to_num(position_error[:candidate_count] + rotation_error[:candidate_count], nan=torch.inf) + ).item() + ) + self.logger.debug( + "IK candidates for group %r failed FK validation: position_error=%.6f m, " + "rotation_error=%.6f rad, solver_success=%s", + self.config.planning_group_name, + float(position_error[best].item()), + float(rotation_error[best].item()), + bool(successes[best].item()), + ) + return None + + selected = int(accepted_indices[torch.argmin(seed_distance[accepted_indices])].item()) + if not bool(successes[selected].item()): + self.logger.debug( + "IK candidate %d for group %r passes explicit FK but is solver-unsuccessful", + selected, + self.config.planning_group_name, + ) + return solutions[selected].clone() + # ===================================================================================== # PLANNING CORE METHODS # ===================================================================================== @@ -1089,7 +2461,7 @@ def _make_pose( if not isinstance(quaternion, torch.Tensor): quaternion = torch.tensor(quaternion, dtype=self.tensor_args.dtype, device=self.tensor_args.device) else: - quaternion = self._to_curobo_device(quaternion) + quaternion = self._to_curobo_device(quaternion).clone() if quat_is_xyzw: quaternion_wxyz = torch.roll(quaternion, shifts=1, dims=-1) @@ -1099,7 +2471,7 @@ def _make_pose( if not isinstance(position, torch.Tensor): position = torch.tensor(position, dtype=self.tensor_args.dtype, device=self.tensor_args.device) else: - position = self._to_curobo_device(position) + position = self._to_curobo_device(position).clone() return Pose(position=position, quaternion=quaternion_wxyz, name=name, normalize_rotation=normalize_rotation) @@ -1126,6 +2498,9 @@ def plan_motion( target_pose: torch.Tensor, step_size: float | None = None, enable_retiming: bool | None = None, + start_joint_positions: torch.Tensor | None = None, + retreat_distance: float | None = None, + object_pose_overrides: Mapping[str, torch.Tensor] | None = None, ) -> bool: """Plan collision-free motion to target pose. @@ -1137,10 +2512,18 @@ def plan_motion( target_pose: Target end-effector pose as 4x4 transformation matrix step_size: Step size for linear retiming, enables retiming if provided enable_retiming: Whether to enable linear retiming, auto-detected from step_size if None + start_joint_positions: Optional arm-local planning state in the configured cuRobo + joint order. ``None`` reads the live articulation state. + retreat_distance: Optional per-call start-retreat override [m]. + object_pose_overrides: Optional environment-relative dynamic-object poses [m] retained + for plan visualization during offline accumulation. Returns: True if planning succeeded and a valid trajectory was found, False otherwise """ + assert self.config.planning_enabled, "motion planning is disabled for this collision-only backend" + self._failed_joint_state = None + self._auxiliary_joint_positions_update(start_joint_positions) if enable_retiming is None: enable_retiming = step_size is not None @@ -1159,25 +2542,28 @@ def plan_motion( quaternion=PoseUtils.quat_from_matrix(target_rot), ) - start_state: JointState = self._get_current_joint_state_for_curobo() + start_state = self._get_current_joint_state_for_curobo(start_joint_positions) self.logger.debug(f"Retiming enabled: {enable_retiming}, Step size: {step_size}") success: bool = self._plan_to_contact( start_state=start_state, goal_pose=target_curobo_pose, - retreat_distance=self.config.retreat_distance, + retreat_distance=self.config.retreat_distance if retreat_distance is None else retreat_distance, approach_distance=self.config.approach_distance, retime_plan=enable_retiming, step_size=step_size, contact=False, ) - # Visualize plan if enabled - if success and self.visualize_plan and self._current_plan is not None: + # Visualize the successful trajectory, or at least retain the failed target and start state. + if self.visualize_plan: + self.plan_visualizer.robot_name = self.config.robot_name + self.plan_visualizer.set_motion_generator_reference(self.motion_gen) # Get current spheres for visualization - self._sync_object_poses_with_isaaclab() - cu_js = self._get_current_joint_state_for_curobo() + self._sync_object_poses_with_isaaclab(object_pose_overrides) + cu_js = self._failed_joint_state if not success and self._failed_joint_state is not None else start_state + cu_js = cu_js.get_ordered_joint_state(self.motion_gen.kinematics.joint_names) sphere_list = self.motion_gen.kinematics.get_robot_as_spheres(cu_js.position)[0] # Split spheres into robot and attached object spheres @@ -1203,11 +2589,27 @@ def plan_motion( else: attached_spheres.append(sphere) + try: + world_scene = WorldConfig.get_scene_graph(self.motion_gen.world_coll_checker.world_model) + except Exception: + world_scene = None + + if not success or self._current_plan is None: + self.plan_visualizer.visualize_failure( + target_pose=target_pose, + robot_spheres=robot_spheres, + attached_spheres=attached_spheres, + world_scene=world_scene, + ) + return success + + viz_plan = self._current_plan.get_ordered_joint_state(self.motion_gen.kinematics.joint_names) + # Compute end-effector positions for visualization ee_positions_list = [] try: - for i in range(len(self._current_plan.position)): - js: JointState = self._current_plan[i] + for i in range(len(viz_plan.position)): + js: JointState = viz_plan[i] kin = self.motion_gen.compute_kinematics(js) ee_pos = kin.ee_position if hasattr(kin, "ee_position") else kin.ee_pose.position ee_positions_list.append(ee_pos.cpu().numpy().squeeze()) @@ -1220,32 +2622,29 @@ def plan_motion( self.logger.debug(f"Failed to compute EE positions for visualization: {e}") ee_positions_list = None - try: - world_scene = WorldConfig.get_scene_graph(self.motion_gen.world_coll_checker.world_model) - except Exception: - world_scene = None - # Visualize plan self.plan_visualizer.visualize_plan( - plan=self._current_plan, + plan=viz_plan, target_pose=target_pose, robot_spheres=robot_spheres, attached_spheres=attached_spheres, ee_positions=np.array(ee_positions_list) if ee_positions_list else None, world_scene=world_scene, ) - # Animate EE positions over the timeline for playback if ee_positions_list: - self.plan_visualizer.animate_plan(np.array(ee_positions_list)) + self.plan_visualizer.animate_plan( + np.array(ee_positions_list), + timeline="planning", + ) # Animate spheres along the path for collision visualization self.plan_visualizer.animate_spheres_along_path( - plan=self._current_plan, + plan=viz_plan, robot_spheres_at_start=robot_spheres, attached_spheres_at_start=attached_spheres, - timeline="sphere_animation", - interpolation_steps=15, # More steps for smoother animation + timeline="planning", + interpolation_steps=1, ) return success @@ -1308,17 +2707,19 @@ def _plan_to_contact_pose( planning_success = False try: - result: Any = self.motion_gen.plan_single(start_state, goal_pose, self.plan_config) + try: + result: Any = self.motion_gen.plan_single(start_state, goal_pose, self.plan_config) + finally: + # cuRobo can return early from a world-colliding start without restoring this flag. + self.motion_gen.rollout_fn.primitive_collision_constraint.enable_cost() + self.motion_gen.rollout_fn.robot_self_collision_constraint.enable_cost() if result.success.item(): - if result.optimized_plan is not None and len(result.optimized_plan.position) != 0: - self._current_plan = result.optimized_plan - self.logger.debug(f"Using optimized plan with {len(self._current_plan.position)} waypoints") - else: - self._current_plan = result.get_interpolated_plan() - self.logger.debug(f"Using interpolated plan with {len(self._current_plan.position)} waypoints") + # The optimizer's sample period can differ from the controller's fixed period. + self._current_plan = result.get_interpolated_plan() + self.logger.debug(f"Using interpolated plan with {len(self._current_plan.position)} waypoints") - self._current_plan = self.motion_gen.get_full_js(self._current_plan) + self._current_plan = self._planning_joint_state_expand(self._current_plan) common_js_names: list[str] = [ x for x in self.datastream.get_robot_joint_names() if x in self._current_plan.joint_names ] @@ -1328,10 +2729,20 @@ def _plan_to_contact_pose( planning_success = True self.logger.debug(f"Contact planning succeeded with {len(self._current_plan.position)} waypoints") else: - self.logger.debug(f"Contact planning failed: {result.status}") + self.logger.warning(f"Planning failed for group {self.config.planning_group_name!r}: {result.status}") + if self.config.debug_planner: + self._log_closest_ik_candidate(result) + if result.status in { + MotionGenStatus.INVALID_START_STATE_SELF_COLLISION, + MotionGenStatus.INVALID_START_STATE_WORLD_COLLISION, + }: + self._log_start_collision( + start_state, + self_collision=result.status == MotionGenStatus.INVALID_START_STATE_SELF_COLLISION, + ) except Exception as e: - self.logger.debug(f"Error during planning: {e}") + self.logger.warning(f"Planning errored for group {self.config.planning_group_name!r}: {e}") # Always restore sphere state after planning, regardless of success if contact: @@ -1340,6 +2751,72 @@ def _plan_to_contact_pose( self.motion_gen.kinematics.kinematics_config.update_link_spheres(attached_link, spheres) return planning_success + def _log_closest_ik_candidate(self, result: Any) -> None: + """Retain and report the closest IK candidate returned by a failed plan stage.""" + + if not isinstance(result.debug_info, dict) or "ik_result" not in result.debug_info: + return + ik_result = result.debug_info["ik_result"] + solver = self.motion_gen.ik_solver + positions = ik_result.solution.reshape(-1, solver.dof) + position_error = ik_result.position_error.reshape(-1) + rotation_error = ik_result.rotation_error.reshape(-1) + best = int(torch.argmin(position_error + rotation_error).item()) + self._failed_joint_state = JointState.from_position( + positions[best].unsqueeze(0).clone(), + joint_names=solver.joint_names, + ) + self.logger.debug( + "Closest IK candidate for group %r: position_error=%.6f m, rotation_error=%.6f rad", + self.config.planning_group_name, + float(position_error[best].item()), + float(rotation_error[best].item()), + ) + candidate = self._to_env_device( + self._planning_joint_state_expand(self._failed_joint_state) + .get_ordered_joint_state(self.active_joint_names) + .position + ) + for margin in dict.fromkeys((0.0, self.config.collision_activation_distance)): + try: + self_witness = self.joint_positions_self_collision_witness(candidate, margin) + world_witness = self.joint_positions_world_collision_witness(candidate, margin) + self.logger.debug( + "Closest IK candidate collision at %.6f m margin: self=%s, world=%s", + margin, + self_witness or "clear", + world_witness or "clear", + ) + except Exception as error: + self.logger.debug( + "Closest IK candidate collision attribution failed at %.6f m margin: %s: %s", + margin, + type(error).__name__, + error, + ) + + def _log_start_collision(self, start_state: JointState, *, self_collision: bool) -> None: + """Report the exact collision behind a rejected start state.""" + + try: + ordered = self._planning_joint_state_expand(start_state).get_ordered_joint_state(self.active_joint_names) + margin = self.config.collision_activation_distance + positions = self._to_env_device(ordered.position) + witness = ( + self.joint_positions_self_collision_witness(positions, margin) + if self_collision + else self.joint_positions_world_collision_witness(positions, margin) + ) + kind = "self" if self_collision else "world" + self.logger.debug( + "Start-state %s-collision witness at %.6f m activation: %s", + kind, + margin, + witness or "unattributed", + ) + except Exception as error: + self.logger.debug("Start-state collision attribution failed: %s: %s", type(error).__name__, error) + def _plan_to_contact( self, start_state: JointState, @@ -1371,23 +2848,48 @@ def _plan_to_contact( target_poses: list[Pose] = [] contacts: list[bool] = [] + direction = self.config.approach_direction + in_world_frame = self.config.approach_retreat_frame == "world" + world_sign = -1.0 if in_world_frame else 1.0 if retreat_distance is not None and retreat_distance > 0: ee_pose: Pose = self.get_ee_pose(start_state) - retreat_pose: Pose = ee_pose.multiply( - self._make_pose( - position=[0.0, 0.0, -retreat_distance], + if in_world_frame: + position = ee_pose.position.squeeze() + offset = torch.tensor( + [world_sign * component * retreat_distance for component in direction], + device=position.device, + dtype=position.dtype, + ) + retreat_pose = self._make_pose( + position=position + offset, + quaternion=ee_pose.quaternion, + quat_is_xyzw=False, + ) + else: + retreat_pose = ee_pose.multiply( + self._make_pose(position=[component * retreat_distance for component in direction]) ) - ) target_poses.append(retreat_pose) contacts.append(True) contacts.append(contact) if approach_distance is not None and approach_distance > 0: - approach_pose: Pose = goal_pose.multiply( - self._make_pose( - position=[0.0, 0.0, -approach_distance], + if in_world_frame: + position = goal_pose.position.squeeze() + offset = torch.tensor( + [world_sign * component * approach_distance for component in direction], + device=position.device, + dtype=position.dtype, + ) + approach_pose = self._make_pose( + position=position + offset, + quaternion=goal_pose.quaternion, + quat_is_xyzw=False, + ) + else: + approach_pose = goal_pose.multiply( + self._make_pose(position=[component * approach_distance for component in direction]) ) - ) target_poses.append(approach_pose) contacts.append(True) @@ -1467,20 +2969,15 @@ def _linearly_retime_plan( if len(path) <= 1: return plan + assert path.ndim == 2, f"joint path must have shape (T, J), got {tuple(path.shape)}" deltas = path[1:] - path[:-1] distances = torch.linalg.norm(deltas, dim=-1) - - waypoints = [path[0]] - for distance, waypoint in zip(distances, path[1:]): - if distance > 1e-6: - waypoints.append(waypoint) - + keep = torch.cat((torch.ones(1, dtype=torch.bool, device=path.device), distances > 1e-6)) + waypoints = path[keep] if len(waypoints) <= 1: return plan - waypoints = torch.stack(waypoints) - if len(waypoints) > 1: deltas = waypoints[1:] - waypoints[:-1] distances = torch.linalg.norm(deltas, dim=-1) @@ -1542,7 +3039,9 @@ def get_next_waypoint_ee_pose(self) -> Pose: """Get end-effector pose for the next waypoint in the trajectory. Advances the trajectory execution index and computes the end-effector pose - for the next waypoint using forward kinematics. + for the next waypoint using forward kinematics. The optimized trajectory is + first projected into :attr:`active_joint_names` order because its storage order + is not a kinematics API contract for projected humanoid chains. Returns: End-effector pose for the next waypoint in world coordinates @@ -1552,15 +3051,13 @@ def get_next_waypoint_ee_pose(self) -> Pose: """ if not self.has_next_waypoint(): raise IndexError("No more waypoints in the plan.") - next_joint_state: JointState = self._current_plan[self._plan_index] + + joint_positions = self.current_joint_position_path + assert joint_positions is not None + next_joint_positions = joint_positions[self._plan_index : self._plan_index + 1] self._plan_index += 1 - eef_state: CudaRobotModelState = self.motion_gen.compute_kinematics(next_joint_state) - if self._base_frame_is_identity: - return eef_state.ee_pose - # Express the base-frame EE pose in the env-relative frame callers expect. - ee_pos = self._to_env_device(eef_state.ee_pose.position) - ee_rot = self._to_env_device(eef_state.ee_pose.get_rotation()) - ee_pose_env = self._pose_base_to_env(PoseUtils.make_pose(ee_pos, ee_rot)) + + ee_pose_env = self.joint_positions_to_ee_poses(next_joint_positions)[0] env_pos, env_rot = PoseUtils.unmake_pose(ee_pose_env) return self._make_pose(position=env_pos, quaternion=PoseUtils.quat_from_matrix(env_rot)) @@ -1573,58 +3070,28 @@ def reset_plan(self) -> None: self._plan_index = 0 self._current_plan = None if self.visualize_plan and hasattr(self, "plan_visualizer"): - self.plan_visualizer.clear_visualization() self.plan_visualizer.mark_idle() def get_planned_poses(self) -> list[torch.Tensor]: """Extract all end-effector poses from current trajectory. - Computes end-effector poses for all waypoints in the current trajectory without - affecting the execution state. Optionally repeats the final pose multiple times - if configured for stable goal reaching. + Computes end-effector poses for all waypoints without affecting the execution state. + The plan is first ordered by :attr:`active_joint_names`; cuRobo's optimized trajectory + storage order is not a kinematics API contract and can differ for projected humanoid + chains. Optionally repeats the final pose when configured for stable goal reaching. Returns: List of end-effector poses as 4x4 transformation matrices, with optional repetition """ - if self._current_plan is None: + joint_positions = self.current_joint_position_path + if joint_positions is None: return [] - # Save current execution state - original_plan_index = self._plan_index + planned_poses = list(self.joint_positions_to_ee_poses(joint_positions).unbind(0)) - # Iterate through the plan to get all poses - planned_poses: list[torch.Tensor] = [] - self._plan_index = 0 - while self.has_next_waypoint(): - # Directly use the joint state from the plan to compute pose - # without advancing the main plan index in get_next_waypoint_ee_pose - next_joint_state: JointState = self._current_plan[self._plan_index] - self._plan_index += 1 # Manually advance index for this loop - eef_state: Any = self.motion_gen.compute_kinematics(next_joint_state) - planned_pose: Pose | None = eef_state.ee_pose - - if planned_pose is not None: - # Convert pose to environment device for compatibility - position = ( - self._to_env_device(planned_pose.position) - if isinstance(planned_pose.position, torch.Tensor) - else planned_pose.position - ) - rotation = ( - self._to_env_device(planned_pose.get_rotation()) - if isinstance(planned_pose.get_rotation(), torch.Tensor) - else planned_pose.get_rotation() - ) - ee_pose_base = PoseUtils.make_pose(position, rotation)[0] - planned_poses.append(self._pose_base_to_env(ee_pose_base)) - - # Restore the original execution state - self._plan_index = original_plan_index - - if self.n_repeat is not None and self.n_repeat > 0 and len(planned_poses) > 0: + if self.n_repeat is not None and self.n_repeat > 0 and planned_poses: self.logger.info(f"Repeating final pose {self.n_repeat} times") - final_pose: torch.Tensor = planned_poses[-1] - planned_poses.extend([final_pose] * self.n_repeat) + planned_poses.extend(planned_poses[-1].clone() for _ in range(self.n_repeat)) return planned_poses @@ -1838,6 +3305,10 @@ def update_world_and_plan_motion( env_id: int = 0, step_size: float | None = None, enable_retiming: bool | None = None, + start_joint_positions: torch.Tensor | None = None, + force_object_attachment: bool = False, + retreat_distance: float | None = None, + object_pose_overrides: Mapping[str, torch.Tensor] | None = None, ) -> bool: """Complete planning pipeline with world updates and object attachment handling. @@ -1851,17 +3322,25 @@ def update_world_and_plan_motion( env_id: Environment ID for multi-environment setups step_size: Step size for linear retiming if retiming is enabled enable_retiming: Whether to enable linear retiming of trajectory + start_joint_positions: Optional arm-local state for offline path accumulation. + force_object_attachment: Attach the expected object at ``start_joint_positions`` + without consulting the live hand state. Supply its virtual grasp pose through + ``object_pose_overrides``. + retreat_distance: Optional per-call start-retreat override [m]. + object_pose_overrides: Optional environment-relative dynamic-object poses [m] used + instead of live poses during offline path accumulation. Returns: True if complete planning pipeline succeeded, False if any step failed """ + assert self.config.planning_enabled, "motion planning is disabled for this collision-only backend" # Always reset the plan before starting a new one to ensure a clean state self.reset_plan() self.logger.debug("=== MOTION PLANNING DEBUG ===") self.logger.debug(f"Expected attached object: {expected_attached_object}") - self.update_world() + self.update_world(object_pose_overrides) gripper_closed = expected_attached_object is not None self._set_gripper_state(gripper_closed) current_attached = self.get_attached_objects() @@ -1891,12 +3370,22 @@ def update_world_and_plan_motion( f"Gripper positions: {gripper_pos}; open val: {self.config.grasp_gripper_open_val}" ) - is_grasped = self._check_object_grasped(gripper_pos, expected_attached_object) + is_grasped = force_object_attachment or self._check_object_grasped( + gripper_pos, expected_attached_object + ) self.logger.debug(f"Is grasped check result: {is_grasped}") if is_grasped: - self._attach_object(expected_attached_object, expected_path, env_id) + attached = self._attach_object( + expected_attached_object, + expected_path, + start_joint_positions=start_joint_positions, + ) + if force_object_attachment and not attached: + if self.has_attached_objects(): + self._detach_objects() + return False self.logger.debug(f"Attached {expected_attached_object}") else: self.logger.debug( @@ -1904,6 +3393,10 @@ def update_world_and_plan_motion( ) # This will cause collision with ghost object! else: self.logger.debug(f"Object {expected_attached_object} not found in world mappings") + if force_object_attachment: + if self.has_attached_objects(): + self._detach_objects() + return False # Detach objects if no object should be attached (i.e., placing/releasing) if expected_attached_object is None and current_attached: @@ -1912,14 +3405,20 @@ def update_world_and_plan_motion( self.logger.debug(f"Planning motion with attached objects: {self.get_attached_objects()}") - plan_success = self.plan_motion(target_pose, step_size, enable_retiming) - - self.logger.debug(f"Planning result: {plan_success}") - self.logger.debug("=== END POST-GRASP DEBUG ===") - - self._detach_objects() - - return plan_success + try: + plan_success = self.plan_motion( + target_pose, + step_size, + enable_retiming, + start_joint_positions=start_joint_positions, + retreat_distance=retreat_distance, + object_pose_overrides=object_pose_overrides, + ) + self.logger.debug(f"Planning result: {plan_success}") + self.logger.debug("=== END POST-GRASP DEBUG ===") + return plan_success + finally: + self._detach_objects() # ===================================================================================== # UTILITY METHODS @@ -1965,6 +3464,8 @@ def _set_gripper_state(self, has_attached_objects: bool) -> None: # Open gripper for manipulation locked_joints = self.config.gripper_open_positions + if not locked_joints: + return self.motion_gen.update_locked_joints(locked_joints, self.robot_cfg) def _count_active_spheres(self) -> dict[str, int]: diff --git a/autodata_interfaces/motion_planners/curobo/curobo_planner_cfg.py b/autodata_interfaces/motion_planners/curobo/curobo_planner_cfg.py index ff905f2..229e81b 100644 --- a/autodata_interfaces/motion_planners/curobo/curobo_planner_cfg.py +++ b/autodata_interfaces/motion_planners/curobo/curobo_planner_cfg.py @@ -5,6 +5,7 @@ import tempfile import yaml from collections.abc import Callable +from typing import Literal from curobo.geom.sdf.world import CollisionCheckerType from curobo.geom.types import WorldConfig @@ -38,12 +39,27 @@ class CuroboPlannerCfg: robot_config_file: str | None = None """cuRobo robot configuration file (path defined by curobo api).""" + kinematic_robot_config_file: str | None = None + """Optional state-query model with auxiliary joints held fixed during motion planning.""" + robot_name: str = "" """Robot name for visualization and identification.""" + planning_group_name: str = "" + """Named joint group served by this planner, such as ``left`` or ``right``.""" + ee_link_name: str | None = None """End-effector link name (auto-detected from robot config if None).""" + root_pose_source_frame_name: str | None = None + """Live articulation link corresponding to the cuRobo kinematic root. + + ``None`` preserves the legacy behavior of using the articulation root. + """ + + initial_auxiliary_joint_positions: dict[str, float] = {} + """Configured auxiliary-joint state used to begin a complete-path episode.""" + # Gripper configuration gripper_joint_names: list[str] = [] """Names of gripper joints.""" @@ -66,13 +82,16 @@ class CuroboPlannerCfg: world_config_file: str = "collision_table.yml" """CuRobo world configuration file (without path).""" + include_configured_world: bool = True + """Whether to combine the configured world with obstacles extracted from the live stage.""" + # Static objects to not update in the world model static_objects: list[str] = [] """Names of static objects to not update in the world model.""" # Optional prim path configuration robot_prim_path: str | None = None - """Absolute USD prim path to the robot root for world extraction; None derives it from environment root.""" + """Absolute robot USD prim to exclude from world extraction; ``None`` derives it from the environment.""" world_ignore_substrings: list[str] | None = None """List of substring patterns to ignore when extracting world obstacles @@ -83,6 +102,9 @@ class CuroboPlannerCfg: collision_checker_type: CollisionCheckerType = CollisionCheckerType.MESH """Type of collision checker to use.""" + use_native_self_collision: bool = True + """Whether cuRobo rollouts construct their native self-collision cost.""" + num_trajopt_seeds: int = 12 """Number of seeds for trajectory optimization.""" @@ -92,6 +114,9 @@ class CuroboPlannerCfg: interpolation_dt: float = 0.05 """Time step for interpolating waypoints.""" + max_joint_velocity: float | None = None + """Optional planning speed cap [rad/s, m/s], also bounded by the live actuator limits.""" + collision_cache_size: dict[str, int] = {"obb": 150, "mesh": 150} """Cache sizes for different collision types.""" @@ -107,13 +132,25 @@ class CuroboPlannerCfg: retreat_distance: float = 0.05 """Distance to retreat at the start of the plan.""" + approach_retreat_frame: Literal["world", "eef"] = "eef" + """Frame in which :attr:`approach_direction` is expressed.""" + + approach_direction: tuple[float, float, float] = (0.0, 0.0, -1.0) + """Direction used to construct approach and retreat poses.""" + grasp_gripper_open_val: float = 0.04 """Gripper joint value when considered open for grasp detection.""" # Planning configuration + planning_enabled: bool = True + """Whether this backend performs motion planning and planning warmup.""" + enable_graph: bool = True """Whether to enable graph-based planning.""" + enable_opt: bool = True + """Whether to optimize graph paths before returning them.""" + enable_graph_attempt: int = 5 """Number of graph planning attempts.""" @@ -164,6 +201,9 @@ class CuroboPlannerCfg: rotation_threshold: float = 0.05 """Rotation threshold for motion planning.""" + ik_candidate_count: int = 1 + """Number of ordered cuRobo IK candidates to validate explicitly with FK.""" + cuda_device: int | None = 0 """Preferred CUDA device index; None uses torch.cuda.current_device() (respects CUDA_VISIBLE_DEVICES).""" diff --git a/autodata_interfaces/motion_planners/curobo/plan_visualizer.py b/autodata_interfaces/motion_planners/curobo/plan_visualizer.py index 756ba72..62b9df2 100644 --- a/autodata_interfaces/motion_planners/curobo/plan_visualizer.py +++ b/autodata_interfaces/motion_planners/curobo/plan_visualizer.py @@ -1,11 +1,9 @@ # Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Utility for visualizing motion plans using Rerun. +"""Rerun views of planned paths, collision spheres and scene geometry.""" -This module provides tools to visualize motion plans, robot poses, and collision spheres -using Rerun's visualization capabilities. It helps in debugging and validating collision-free paths. -""" +from __future__ import annotations import atexit import numpy as np @@ -15,11 +13,13 @@ import time import torch import weakref -from typing import TYPE_CHECKING, Any, Optional +from pathlib import Path +from typing import TYPE_CHECKING, Any # Check if rerun is installed try: import rerun as rr + import rerun.blueprint as rrb except ImportError: raise ImportError("Rerun is not installed!") @@ -42,7 +42,7 @@ # Global registry to track all PlanVisualizer instances for cleanup -_GLOBAL_PLAN_VISUALIZERS: list["PlanVisualizer"] = [] +_GLOBAL_PLAN_VISUALIZERS: list[PlanVisualizer] = [] def _kill_owned_rerun_processes(owner_pid: int) -> int: @@ -108,7 +108,7 @@ def __init__( recording_id: str | None = None, debug: bool = False, save_path: str | None = None, - base_translation: np.ndarray | None = None, + base_pose_in_env: np.ndarray | None = None, ): """Initialize the plan visualizer. @@ -117,17 +117,14 @@ def __init__( recording_id: Optional ID for the Rerun recording debug: Whether to print debug information save_path: Optional path to save the recording - base_translation: Optional base translation to apply to all visualized entities + base_pose_in_env: Planner-base pose in the environment frame. """ self.robot_name = robot_name self.debug = debug self.recording_id = recording_id or f"motion_plan_{robot_name}" self.save_path = save_path self._closed = False - # Translation offset applied to all visualized entities (for multi-env setups) - self._base_translation = ( - np.array(base_translation, dtype=float) if base_translation is not None else np.zeros(3) - ) + self.set_base_pose_in_env(np.eye(4) if base_pose_in_env is None else base_pose_in_env) # Enhanced process management self._parent_pid = os.getpid() @@ -143,38 +140,42 @@ def __init__( # Initialize Rerun rr.init(self.recording_id, spawn=False) - # Spawn the viewer. Recent Rerun SDK versions return ``None`` while older versions may - # return a process handle, so cleanup supports either result. self._rerun_process = None - try: - self._rerun_process = rr.spawn() - except Exception as exc: - raise RuntimeError( - "Failed to spawn the Rerun viewer. Ensure the `rerun` executable from the rerun-sdk " - "package is on PATH, for example in the Python environment's bin directory." - ) from exc + if self.save_path is not None: + output_path = Path(self.save_path).expanduser().resolve() + output_path.parent.mkdir(parents=True, exist_ok=True) + self.save_path = str(output_path) + rr.save(self.save_path) + self._rerun_process = None + else: + # Spawn viewer and keep handle if provided so we can terminate it later. + try: + self._rerun_process = rr.spawn() + except Exception as exc: + raise RuntimeError("Failed to spawn Rerun; check that its executable is on PATH.") from exc # Set up coordinate system - rr.log("world", rr.ViewCoordinates.RIGHT_HAND_Y_UP) + rr.log("world", rr.ViewCoordinates.RIGHT_HAND_Z_UP) + self._send_blueprint("planning") # Store visualization state self._current_frame = 0 + self._plan_frame = 0 + self._active_plan_root = "world/plans" + self._world_scene = None self._sphere_entities: dict[str, list[str]] = {"robot": [], "attached": [], "target": []} - # Start enhanced parent process monitoring + # Close orphaned viewers when their parent process exits. self._start_parent_process_monitoring() # Use weakref.finalize for cleanup when object is garbage collected - self._finalizer = weakref.finalize( - self, self._cleanup_class_resources, self.recording_id, self.save_path, debug - ) + self._finalizer = weakref.finalize(self, self._cleanup_class_resources, self.recording_id, debug) # Also register atexit handler as backup for normal script termination # Store values locally to avoid capturing self in the closure recording_id = self.recording_id - save_path = self.save_path debug_flag = debug - atexit.register(self._cleanup_class_resources, recording_id, save_path, debug_flag) + atexit.register(self._cleanup_class_resources, recording_id, debug_flag) # Store original signal handlers so we can restore them after cleanup self._original_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_DFL) @@ -198,11 +199,73 @@ def signal_handler(signum, frame): if self.debug: print(f"Initialized Rerun visualization with recording ID: {self.recording_id}") - if np.linalg.norm(self._base_translation) > 0: - print(f"Applying translation offset: {self._base_translation}") + if not np.allclose(self._base_pose_in_env, np.eye(4)): + print(f"Applying planner-base pose:\n{self._base_pose_in_env}") if PSUTIL_AVAILABLE: print("Enhanced process monitoring enabled") + def set_base_pose_in_env(self, base_pose_in_env: np.ndarray | torch.Tensor) -> None: + """Set the planner-base pose in the environment frame. + + Args: + base_pose_in_env: Homogeneous 4x4 transform from planner base to environment. + """ + + if torch.is_tensor(base_pose_in_env): + base_pose_in_env = base_pose_in_env.detach().cpu().numpy() + pose = np.asarray(base_pose_in_env, dtype=float) + assert pose.shape == (4, 4), f"base_pose_in_env must have shape (4, 4), got {pose.shape}" + assert np.isfinite(pose).all(), "base_pose_in_env must contain finite values" + assert np.allclose(pose[3], [0.0, 0.0, 0.0, 1.0]), "base_pose_in_env must be homogeneous" + rotation = pose[:3, :3] + assert np.allclose(rotation @ rotation.T, np.eye(3), atol=1e-5), "base rotation must be orthonormal" + assert np.isclose(np.linalg.det(rotation), 1.0, atol=1e-5), "base rotation must be right-handed" + self._base_pose_in_env = pose.copy() + + def world_scene_set(self, world_scene: trimesh.Scene | None) -> None: + """Replace the world scene used by subsequent plan and schedule timelines.""" + + self._world_scene = world_scene + + def _points_base_to_env(self, points: np.ndarray) -> np.ndarray: + """Transform planner-base points into the environment frame.""" + + points = np.asarray(points, dtype=float) + assert points.shape[-1] == 3, f"points must end in dimension 3, got {points.shape}" + return points @ self._base_pose_in_env[:3, :3].T + self._base_pose_in_env[:3, 3] + + def _send_blueprint(self, timeline: str | None = None) -> None: + """Separate arm plans from complete-robot checks using the same scene camera.""" + + base_position = self._base_pose_in_env[:3, 3] + look_target = base_position + np.array([0.0, 0.35, 0.2]) + camera_position = look_target + np.array([1.0, 0.85, 0.6]) + views = [ + rrb.Spatial3DView( + name=name, + origin="world", + contents=["world/scene/**", f"world/{root}/**"], + eye_controls=rrb.EyeControls3D( + position=camera_position, + look_target=look_target, + ), + ) + for name, root in (("Arm plans", "plans"), ("Scheduled robot", "schedules")) + ] + rr.send_blueprint( + rrb.Blueprint( + rrb.Tabs(*views, active_tab=0), + rrb.TimePanel( + state="expanded", + timeline=timeline, + fps=20.0, + playback_speed=1.0, + play_state="playing", + loop_mode="all", + ), + ) + ) + def _start_parent_process_monitoring(self) -> None: """Start monitoring the parent process and cleanup when it dies.""" if not PSUTIL_AVAILABLE: @@ -253,10 +316,12 @@ def _kill_rerun_processes(self) -> None: print(f"Killed {killed_count} Rerun viewer processes owned by PID {self._parent_pid}") @staticmethod - def _cleanup_class_resources(recording_id: str, save_path: str | None, debug: bool) -> None: - """Static method for cleanup that doesn't hold references to the instance. + def _cleanup_class_resources(recording_id: str, debug: bool) -> None: + """Disconnect Rerun and stop viewers owned by this process. - This is called by weakref.finalize when the object is garbage collected. + Args: + recording_id: Recording identifier included in debug messages. + debug: Whether to print cleanup progress. """ if debug: print(f"Cleaning up Rerun visualization for {recording_id}") @@ -264,12 +329,6 @@ def _cleanup_class_resources(recording_id: str, save_path: str | None, debug: bo # Disconnect from Rerun rr.disconnect() - # Save to file if requested - if save_path is not None: - rr.save(save_path) - if debug: - print(f"Saved Rerun recording to {save_path}") - # Kill only viewers spawned by this process; other Rerun sessions are left alone. killed_count = _kill_owned_rerun_processes(os.getpid()) if debug and killed_count: @@ -288,7 +347,7 @@ def _cleanup_on_exit(self) -> None: self._kill_rerun_processes() def close(self) -> None: - """Close the Rerun visualization with enhanced cleanup.""" + """Disconnect the recording and release its owned viewer resources.""" if self._closed: return @@ -301,12 +360,6 @@ def close(self) -> None: # Disconnect from Rerun (closes connections, servers, and files) rr.disconnect() - # Save to file if requested - if self.save_path is not None: - rr.save(self.save_path) - if self.debug: - print(f"Saved Rerun recording to {self.save_path}") - self._closed = True # Terminate viewer process if we have a handle @@ -340,8 +393,8 @@ def visualize_plan( robot_spheres: list[Any] | None = None, attached_spheres: list[Any] | None = None, ee_positions: np.ndarray | None = None, - world_scene: Optional["trimesh.Scene"] = None, - ) -> None: + world_scene: trimesh.Scene | None = None, + ) -> int: """Visualize a complete motion plan with all components. Args: @@ -351,34 +404,35 @@ def visualize_plan( attached_spheres: Optional list of attached object spheres ee_positions: Optional end-effector positions world_scene: Optional world scene to visualize + + Returns: + Monotonic plan index used to name the plan's entities. """ if self.debug: robot_count = len(robot_spheres) if robot_spheres else 0 attached_count = len(attached_spheres) if attached_spheres else 0 - offset_info = ( - f"offset={self._base_translation}" if np.linalg.norm(self._base_translation) > 0 else "no offset" - ) print( - f"Visualizing plan: {len(plan.position)} waypoints, {robot_count} robot spheres (with offset)," - f" {attached_count} attached spheres (no offset), {offset_info}" + f"Visualizing plan: {len(plan.position)} waypoints, {robot_count} robot spheres," + f" {attached_count} attached spheres" ) - # Set timeline for static visualization (separate from animation) - rr.set_time("static_plan", sequence=self._current_frame) - self._current_frame += 1 - - # Clear previous visualization of dynamic entities (keep static meshes) + plan_index = self._current_frame self._clear_visualization() + self._active_plan_root = f"world/plans/{plan_index:04d}_{self.robot_name}" + rr.reset_time() + rr.set_time("planning", sequence=self._plan_frame) + self._current_frame += 1 # If a scene is supplied and not yet logged, draw it once if world_scene is not None: + self._world_scene = world_scene self._visualize_world_scene(world_scene) # Visualize target pose self._visualize_target_pose(target_pose) # Visualize trajectory (end-effector positions if provided) - self._visualize_trajectory(plan, ee_positions) + self._visualize_trajectory(ee_positions) # Visualize spheres if provided if robot_spheres: @@ -388,27 +442,52 @@ def visualize_plan( else: # Clear any existing attached sphere visualization when no objects are attached self._clear_attached_spheres() + rr.reset_time() + return plan_index - def _clear_visualization(self) -> None: - """Clear all visualization entities.""" - # Clear dynamic trajectory, target, and finger logs to avoid artifacts between visualizations - dynamic_paths = [ - "trajectory", - "target", - "anim", - ] + def visualize_failure( + self, + target_pose: torch.Tensor, + robot_spheres: list[Any], + attached_spheres: list[Any], + world_scene: trimesh.Scene | None = None, + ) -> None: + """Retain the target and start-state spheres for a failed planning attempt. - for path in dynamic_paths: - rr.log(f"world/{path}", rr.Clear(recursive=True)) + Args: + target_pose: Failed end-effector target pose. + robot_spheres: Robot collision spheres at the planning start state. + attached_spheres: Attached-object spheres at the planning start state. + world_scene: Optional cuRobo collision scene. + """ - for entity_type, entities in self._sphere_entities.items(): - for entity in entities: - rr.log(f"world/{entity_type}/{entity}", rr.Clear(recursive=True)) - self._sphere_entities[entity_type] = [] - self._current_frame = 0 + plan_index = self._current_frame + self._clear_visualization() + self._active_plan_root = f"world/plans/{plan_index:04d}_{self.robot_name}_failed" + self._current_frame += 1 + rr.reset_time() + rr.set_time("planning", sequence=self._plan_frame) + if world_scene is not None: + self._world_scene = world_scene + self._visualize_world_scene(world_scene) + self._visualize_target_pose(target_pose) + self._visualize_robot_spheres(robot_spheres) + if attached_spheres: + self._visualize_attached_spheres(attached_spheres) + self._plan_frame += 1 + rr.reset_time() + + def _clear_visualization(self) -> None: + """End the current plan's visibility without deleting earlier playback frames.""" + rr.reset_time() + rr.set_time("planning", sequence=self._plan_frame) + rr.log(self._active_plan_root, rr.Clear(recursive=True)) + self._sphere_entities = {"robot": [], "attached": [], "target": []} + rr.reset_time() def clear_visualization(self) -> None: """Public method to clear the visualization.""" + self._clear_visualization() def _visualize_target_pose(self, target_pose: torch.Tensor) -> None: @@ -427,12 +506,9 @@ def _visualize_target_pose(self, target_pose: torch.Tensor) -> None: pos_np = pos_np.reshape(-1) rot_np = rot_np.reshape(3, 3) - # Apply translation offset - pos_np += self._base_translation - # Log target position rr.log( - "world/target/position", + f"{self._active_plan_root}/target/position", rr.Points3D( positions=np.array([pos_np]), colors=[[255, 0, 0]], # Red @@ -442,7 +518,7 @@ def _visualize_target_pose(self, target_pose: torch.Tensor) -> None: # Log target orientation as coordinate frame rr.log( - "world/target/frame", + f"{self._active_plan_root}/target/frame", rr.Transform3D( translation=pos_np, mat3x3=rot_np, @@ -451,48 +527,36 @@ def _visualize_target_pose(self, target_pose: torch.Tensor) -> None: def _visualize_trajectory( self, - plan: JointState, ee_positions: np.ndarray | None = None, ) -> None: """Visualize the robot trajectory. Args: - plan: Joint state trajectory - ee_positions: Optional end-effector positions + ee_positions: End-effector positions in the planner base frame [m]. """ if ee_positions is None: - raw = plan.position.detach().cpu().numpy() if torch.is_tensor(plan.position) else np.array(plan.position) - if raw.shape[1] >= 3: - positions = raw[:, :3] - else: - raise ValueError("ee_positions not provided and joint positions are not 3-D") - else: - positions = ee_positions - - # Apply translation offset - positions = positions + self._base_translation + return + positions = self._points_base_to_env(ee_positions) # Log trajectory points rr.log( - "world/trajectory", + f"{self._active_plan_root}/trajectory", rr.LineStrips3D( [positions], # single strip consisting of all waypoints colors=[[0, 100, 255]], # Blue radii=[0.005], ), - static=True, ) # Log keyframes for i, pos in enumerate(positions): rr.log( - f"world/trajectory/keyframe_{i}", + f"{self._active_plan_root}/trajectory/keyframe_{i}", rr.Points3D( positions=np.array([pos]), colors=[[0, 100, 255]], # Blue radii=[0.01], ), - static=True, ) def _visualize_robot_spheres(self, spheres: list[Any]) -> None: @@ -505,7 +569,6 @@ def _visualize_robot_spheres(self, spheres: list[Any]) -> None: spheres=spheres, entity_type="robot", color=[0, 255, 100, 128], # Semi-transparent green - apply_offset=True, ) def _visualize_attached_spheres(self, spheres: list[Any]) -> None: @@ -518,13 +581,12 @@ def _visualize_attached_spheres(self, spheres: list[Any]) -> None: spheres=spheres, entity_type="attached", color=[255, 0, 0, 128], # Semi-transparent red - apply_offset=False, ) def _clear_attached_spheres(self) -> None: """Clear all attached object spheres.""" for entity_id in self._sphere_entities.get("attached", []): - rr.log(f"world/attached/{entity_id}", rr.Clear(recursive=True)) + rr.log(f"{self._active_plan_root}/attached/{entity_id}", rr.Clear(recursive=True)) self._sphere_entities["attached"] = [] # --------------------------------------------------------------------- @@ -536,7 +598,6 @@ def _log_spheres( spheres: list[Any], entity_type: str, color: list[int], - apply_offset: bool = False, ) -> None: """Generic helper for sphere visualization. @@ -544,30 +605,27 @@ def _log_spheres( spheres: List of CuRobo ``Sphere`` objects. entity_type: Log path prefix (``robot`` or ``attached``). color: RGBA color for the spheres. - apply_offset: Whether to add ``self._base_translation`` to sphere positions. """ for i, sphere in enumerate(spheres): entity_id = f"sphere_{i}" # Track entities so we can clear them later self._sphere_entities.setdefault(entity_type, []).append(entity_id) - # Convert position to numpy and optionally apply offset + # cuRobo sphere positions are expressed in the planner base frame. pos = ( sphere.position.detach().cpu().numpy() if torch.is_tensor(sphere.position) else np.array(sphere.position) ) - if apply_offset: - pos = pos + self._base_translation - pos = pos.reshape(-1) # Ensure 1-D + pos = self._points_base_to_env(pos.reshape(1, 3))[0] # Log sphere via Rerun rr.log( - f"world/{entity_type}/{entity_id}", + f"{self._active_plan_root}/{entity_type}/{entity_id}", rr.Points3D(positions=np.array([pos]), colors=[color], radii=[float(sphere.radius)]), ) - def _visualize_world_scene(self, scene: "trimesh.Scene") -> None: + def _visualize_world_scene(self, scene: trimesh.Scene) -> None: """Log world geometry and dynamic transforms each call. Geometry is sent once (cached), but transforms are updated every invocation @@ -576,8 +634,8 @@ def _visualize_world_scene(self, scene: "trimesh.Scene") -> None: """ import trimesh # local import to avoid hard dependency at top - def _to_rerun_mesh(mesh: "trimesh.Trimesh") -> "rr.Mesh3D": - # Basic conversion without materials + def _to_rerun_mesh(mesh: trimesh.Trimesh) -> rr.Mesh3D: + """Convert triangle geometry to a Rerun mesh without material properties.""" return rr.Mesh3D( vertex_positions=mesh.vertices, triangle_indices=mesh.faces, @@ -594,17 +652,25 @@ def _to_rerun_mesh(mesh: "trimesh.Trimesh") -> "rr.Mesh3D": continue rr_path = f"world/scene/{node.replace('/', '_')}" - # Always update transform (objects may move between calls) - # NOTE: World scene objects are already in correct world coordinates, no offset needed + # cuRobo's collision scene is expressed in the planner base frame. + tform_env = self._base_pose_in_env @ tform if _RR_HAS_TRANSFORM_AXES: # rerun >= 0.28: axis_length moved to TransformAxes3D - rr.log(rr_path, rr.Transform3D(translation=tform[:3, 3], mat3x3=tform[:3, :3]), static=False) + rr.log( + rr_path, + rr.Transform3D(translation=tform_env[:3, 3], mat3x3=tform_env[:3, :3]), + static=False, + ) rr.log(rr_path, rr.TransformAxes3D(axis_length=0.25), static=False) else: # rerun <= 0.27: axis_length on Transform3D directly rr.log( rr_path, - rr.Transform3D(translation=tform[:3, 3], mat3x3=tform[:3, :3], axis_length=0.25), + rr.Transform3D( + translation=tform_env[:3, 3], + mat3x3=tform_env[:3, :3], + axis_length=0.25, + ), static=False, ) @@ -627,7 +693,7 @@ def animate_plan( self, ee_positions: np.ndarray, object_positions: dict[str, np.ndarray] | None = None, - timeline: str = "plan", + timeline: str = "planning", point_radius: float = 0.01, ) -> None: """Animate robot end-effector and (optionally) attached object positions over time using Rerun. @@ -638,9 +704,9 @@ def animate_plan( transfer to the viewer minimal. Args: - ee_positions: Array of shape (T, 3) with end-effector world positions. + ee_positions: Array of shape (T, 3) with planner-base end-effector positions. object_positions: Mapping from object name to an array (T, 3) with that - object's world positions. Each trajectory must be at least as long as + object's environment-frame positions. Each trajectory must be at least as long as ``ee_positions``; extra entries are ignored. timeline: Name of the Rerun timeline used for the animation frames. point_radius: Visual radius (in metres) of the rendered points. @@ -648,16 +714,20 @@ def animate_plan( if ee_positions is None or len(ee_positions) == 0: return + rr.reset_time() + rr.set_time(timeline, sequence=self._plan_frame) + if self._world_scene is not None: + self._visualize_world_scene(self._world_scene) # Iterate over timesteps and log a frame on the chosen timeline for idx, pos in enumerate(ee_positions): # Set time on the chosen timeline (creates it if needed) - rr.set_time(timeline, sequence=idx) + rr.set_time(timeline, sequence=self._plan_frame + idx) - # Log end-effector marker (needs offset for multi-env) + # End-effector positions from cuRobo FK use the planner base frame. rr.log( - "world/anim/ee", + f"{self._active_plan_root}/anim/ee", rr.Points3D( - positions=np.array([pos + self._base_translation]), + positions=self._points_base_to_env(np.asarray(pos).reshape(1, 3)), colors=[[0, 100, 255]], # Blue radii=[point_radius], ), @@ -670,20 +740,88 @@ def animate_plan( if idx >= len(traj): continue rr.log( - f"world/anim/{name}", + f"{self._active_plan_root}/anim/{name}", rr.Points3D( positions=np.array([traj[idx]]), colors=[[255, 128, 0]], # Orange radii=[point_radius], ), ) + rr.reset_time() + + def animate_collision_spheres( + self, + spheres: torch.Tensor, + *, + timeline_prefix: str = "full_state_schedule", + ) -> int: + """Animate a complete scheduled robot sphere tensor. + + Args: + spheres: Planner-root sphere states shaped ``(T, S, 4)`` with radius last [m]. + timeline_prefix: Prefix for the isolated Rerun sequence timeline. + + Returns: + Monotonic visualization index used in the timeline and entity path. + """ + + assert spheres.ndim == 3 and spheres.shape[-1] == 4 and len(spheres) > 0 + values = spheres.detach().cpu().numpy() + index = self._current_frame + self._current_frame += 1 + timeline = f"{timeline_prefix}_{index}" + entity_path = f"world/schedules/{index:04d}/robot_spheres" + + rr.reset_time() + rr.set_time(timeline, sequence=0) + if self._world_scene is not None: + self._visualize_world_scene(self._world_scene) + for tick, frame in enumerate(values): + valid = np.isfinite(frame).all(axis=1) & (frame[:, 3] > 0.0) + rr.set_time(timeline, sequence=tick) + rr.log( + entity_path, + rr.Points3D( + positions=self._points_base_to_env(frame[valid, :3]), + radii=frame[valid, 3], + colors=[0, 255, 100, 180], + ), + ) + rr.reset_time() + return index + + def animate_object_collision_spheres(self, spheres: torch.Tensor, *, schedule_index: int) -> None: + """Overlay environment-frame object spheres on a full-state schedule timeline. + + Args: + spheres: Environment-frame sphere states shaped ``(T, S, 4)`` with radius last [m]. + schedule_index: Index returned by :meth:`animate_collision_spheres`. + """ + + assert spheres.ndim == 3 and spheres.shape[-1] == 4 and len(spheres) > 0 + assert type(schedule_index) is int and schedule_index >= 0 + values = spheres.detach().cpu().numpy() + timeline = f"full_state_schedule_{schedule_index}" + entity_path = f"world/schedules/{schedule_index:04d}/object_spheres" + for tick, frame in enumerate(values): + valid = np.isfinite(frame).all(axis=1) & (frame[:, 3] > 0.0) + rr.set_time(timeline, sequence=tick) + rr.log( + entity_path, + rr.Points3D( + positions=frame[valid, :3], + radii=frame[valid, 3], + colors=[255, 160, 0, 180], + ), + ) + rr.reset_time() def animate_spheres_along_path( self, plan: JointState, robot_spheres_at_start: list[Any] | None = None, attached_spheres_at_start: list[Any] | None = None, - timeline: str = "sphere_animation", + timeline: str = "planning", interpolation_steps: int = 10, ) -> None: """Animate robot and attached object spheres along the planned trajectory with smooth interpolation. @@ -726,9 +864,6 @@ def animate_spheres_along_path( print("Motion generator kinematics not available for sphere animation") return - # Clear static spheres to avoid visual clutter during animation - self._hide_static_spheres_for_animation() - # Count robot link spheres (excluding attached objects) for consistent splitting robot_link_count = 0 if robot_spheres_at_start: @@ -740,10 +875,15 @@ def animate_spheres_along_path( if self.debug: print(f"Created interpolated trajectory with {len(interpolated_positions)} total frames") + rr.reset_time() + rr.set_time(timeline, sequence=self._plan_frame) + self._hide_static_spheres_for_animation() + if self._world_scene is not None: + self._visualize_world_scene(self._world_scene) # Animate spheres along the interpolated trajectory for frame_idx, joint_positions in enumerate(interpolated_positions): # Set time on the animation timeline with consistent timing - rr.set_time(timeline, sequence=frame_idx) + rr.set_time(timeline, sequence=self._plan_frame + frame_idx) # Create joint state for this interpolated position if isinstance(joint_positions, torch.Tensor): @@ -786,18 +926,16 @@ def animate_spheres_along_path( radius = float(sphere.radius) if i < robot_link_count: - # Robot sphere - needs base translation offset - robot_sphere_positions.append(pos + self._base_translation) + robot_sphere_positions.append(self._points_base_to_env(pos.reshape(1, 3))[0]) robot_sphere_radii.append(radius) else: - # Attached object sphere - already in world coordinates - attached_sphere_positions.append(pos) + attached_sphere_positions.append(self._points_base_to_env(pos.reshape(1, 3))[0]) attached_sphere_radii.append(radius) # Log robot spheres with green color if robot_sphere_positions: rr.log( - "world/robot_animation", + f"{self._active_plan_root}/robot_animation", rr.Points3D( positions=np.array(robot_sphere_positions), colors=[[0, 255, 100, 220]] * len(robot_sphere_positions), # Bright green @@ -808,7 +946,7 @@ def animate_spheres_along_path( # Log attached object spheres with orange color (or clear if no attached objects) if attached_sphere_positions: rr.log( - "world/attached_animation", + f"{self._active_plan_root}/attached_animation", rr.Points3D( positions=np.array(attached_sphere_positions), colors=[[255, 150, 0, 220]] * len(attached_sphere_positions), # Bright orange @@ -817,7 +955,10 @@ def animate_spheres_along_path( ) else: # Clear attached object spheres when no objects are attached - rr.log("world/attached_animation", rr.Clear(recursive=True)) + rr.log(f"{self._active_plan_root}/attached_animation", rr.Clear(recursive=True)) + + self._plan_frame += len(interpolated_positions) + rr.reset_time() if self.debug: print( @@ -828,11 +969,11 @@ def _hide_static_spheres_for_animation(self) -> None: """Hide static sphere visualization during animation to reduce visual clutter.""" # Clear static robot spheres for entity_id in self._sphere_entities.get("robot", []): - rr.log(f"world/robot/{entity_id}", rr.Clear(recursive=True)) + rr.log(f"{self._active_plan_root}/robot/{entity_id}", rr.Clear(recursive=True)) # Clear static attached spheres for entity_id in self._sphere_entities.get("attached", []): - rr.log(f"world/attached/{entity_id}", rr.Clear(recursive=True)) + rr.log(f"{self._active_plan_root}/attached/{entity_id}", rr.Clear(recursive=True)) if self.debug: print("Hidden static spheres for cleaner animation view") @@ -887,21 +1028,6 @@ def set_motion_generator_reference(self, motion_gen: Any) -> None: self._motion_gen_ref = motion_gen def mark_idle(self) -> None: - """Signal that the planner is idle, clearing animations. - - This method advances the animation timelines and logs empty data to ensure that - no leftover visualizations from the previous plan are shown. It's useful for - creating a clean state between planning episodes. - """ - # Advance plan timeline and emit empty anim so latest frame is blank - rr.set_time("plan", sequence=self._current_frame) - self._current_frame += 1 - empty = np.empty((0, 3), dtype=float) - rr.log("world/anim/ee", rr.Points3D(positions=empty)) - rr.log("world/robot_animation", rr.Points3D(positions=empty)) - rr.log("world/attached_animation", rr.Points3D(positions=empty)) - - # Also advance sphere animation timeline - rr.set_time("sphere_animation", sequence=self._current_frame) - rr.log("world/robot_animation", rr.Points3D(positions=empty)) - rr.log("world/attached_animation", rr.Points3D(positions=empty)) + """Clear the active arm preview between episodes, retaining its recorded history.""" + self._clear_visualization() + self._plan_frame += 1 diff --git a/autodata_interfaces/motion_planners/curobo/planner_factory.py b/autodata_interfaces/motion_planners/curobo/planner_factory.py new file mode 100644 index 0000000..441f546 --- /dev/null +++ b/autodata_interfaces/motion_planners/curobo/planner_factory.py @@ -0,0 +1,596 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Create ordinary arm-local cuRobo planners from a named-group description.""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import yaml +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path +from types import MappingProxyType +from typing import TYPE_CHECKING, Any + +from autodata_interfaces.motion_planners.curobo.collision_spheres import ( + CollisionSphereFitConfig, + collision_spheres_fit_urdf, +) +from autodata_interfaces.motion_planners.curobo.robot_config import ( + ATTACHED_OBJECT_LINK_NAME, + curobo_arm_chain, + curobo_full_robot_config_create, + curobo_robot_config_create, + curobo_robot_config_write, + curobo_robot_model_prepare, +) + +if TYPE_CHECKING: + from autodata_interfaces.datastream.datastream import Datastream + from autodata_interfaces.motion_planners.curobo.curobo_planner import CuroboPlanner + + +_SCHEMA = "isaac-autodata.curobo-planning-groups.v1" +_CUROBO_SELF_COLLISION_SPHERE_LIMIT = 1024 +_OVERLAY_REQUIRED_KEYS = {"schema", "extends", "name"} +_OVERLAY_KEYS = _OVERLAY_REQUIRED_KEYS | { + "full_state_collision_scope", + "inactive_joint_names", + "planner", + "robot_config", + "sphere_fit", +} +_ROOT_KEYS = { + "schema", + "name", + "root_link", + "root_pose_source_frame", + "full_state_collision_scope", + "inactive_joint_names", + "planning_groups", + "sphere_fit", + "robot_config", + "planner", +} +_ROBOT_CONFIG_KEYS = { + "attachment_sphere_count", + "self_collision_ignore_depth", + "max_acceleration", + "max_jerk", +} +_SPHERE_FIT_KEYS = set(CollisionSphereFitConfig.__dataclass_fields__) +_PLANNER_KEYS = { + "world_config_file", + "static_objects", + "world_ignore_substrings", + "num_trajopt_seeds", + "num_graph_seeds", + "interpolation_dt", + "max_joint_velocity", + "collision_cache_size", + "trajopt_tsteps", + "collision_activation_distance", + "approach_distance", + "retreat_distance", + "approach_retreat_frame", + "approach_direction", + "enable_graph", + "enable_opt", + "enable_graph_attempt", + "max_planning_attempts", + "enable_finetune_trajopt", + "time_dilation_factor", + "surface_sphere_radius", + "n_repeat", + "motion_step_size", + "debug_planner", + "sphere_update_freq", + "motion_noise_scale", + "position_threshold", + "rotation_threshold", + "ik_candidate_count", + "cuda_device", +} + + +@dataclass(frozen=True) +class CuroboPlanningContext: + """Arm-local planning handles plus one designated full-state collision context. + + Args: + group_planners: Arm planners keyed by end-effector name. + full_state: Combined model used to check scheduled robot states. + """ + + group_planners: Mapping[str, CuroboPlanner] + full_state: CuroboPlanner + + def __post_init__(self) -> None: + """Require arm planners and freeze a copy of the end-effector mapping.""" + + assert self.group_planners, "group_planners must not be empty" + object.__setattr__(self, "group_planners", MappingProxyType(dict(self.group_planners))) + + +def curobo_planning_context_create( + datastream: Datastream, + description_path: str | Path, + *, + env_id: int = 0, + visualize_plan: bool = False, + rerun_output: str | Path | None = None, + cache_dir: str | Path | None = None, +) -> CuroboPlanningContext: + """Build arm-local planners and one collision-only full-state context. + + Args: + datastream: Bound environment, embodiment and task interface. + description_path: Planning-groups YAML file. + env_id: Environment providing the named initial robot state. + visualize_plan: Whether environment zero logs paths and spheres to Rerun. + rerun_output: Optional recording file; ``None`` uses a live viewer when visualization is enabled. + cache_dir: Optional directory for reusable robot configurations and fitted spheres. + + Returns: + Per-arm planners and the combined collision model sharing one prepared robot description. + """ + + group_planners, full_state = _curobo_planners_create( + datastream, + description_path, + env_id=env_id, + visualize_plan=visualize_plan, + rerun_output=rerun_output, + cache_dir=cache_dir, + include_full_state=True, + ) + assert full_state is not None + return CuroboPlanningContext(group_planners, full_state) + + +def curobo_group_planners_create( + datastream: Datastream, + description_path: str | Path, + *, + env_id: int = 0, + visualize_plan: bool = False, + rerun_output: str | Path | None = None, + cache_dir: str | Path | None = None, +) -> dict[str, CuroboPlanner]: + """Build arm-local planners without allocating a combined collision model. + + Args: + datastream: Bound environment, embodiment and task interface. + description_path: Planning-groups YAML file. + env_id: Environment providing the named initial robot state. + visualize_plan: Whether environment zero logs paths and spheres to Rerun. + rerun_output: Optional recording file; ``None`` uses a live viewer when visualization is enabled. + cache_dir: Optional directory for reusable robot configurations and fitted spheres. + + Returns: + Planners keyed by end-effector name. + """ + + group_planners, full_state = _curobo_planners_create( + datastream, + description_path, + env_id=env_id, + visualize_plan=visualize_plan, + rerun_output=rerun_output, + cache_dir=cache_dir, + include_full_state=False, + ) + assert full_state is None + return group_planners + + +def _curobo_planners_create( + datastream: Datastream, + description_path: str | Path, + *, + env_id: int, + visualize_plan: bool, + rerun_output: str | Path | None, + cache_dir: str | Path | None, + include_full_state: bool, +) -> tuple[dict[str, CuroboPlanner], CuroboPlanner | None]: + """Build planners from one prepared model and one shared sphere set. + + Collision spheres are fitted once over the union of collision-bearing links. Each generated + robot configuration then selects spheres for its root-to-tool chain plus any + explicitly commanded auxiliary joints. Other owned joints are locked to the exact named + live state; unrelated branches are omitted from arm-local configurations. + + Args: + datastream: Bound AutoData environment, embodiment, and task interface. + description_path: Planning-groups YAML path. + env_id: Environment whose named start state initializes the planners. + visualize_plan: Whether environment zero logs paths and arm-local spheres to Rerun. + rerun_output: Optional Rerun recording path. When set, no live viewer is spawned. + cache_dir: Optional cache directory for robot configurations and fitted spheres. + include_full_state: Whether to allocate a combined collision-only robot model. + + Returns: + Group planners and the optional designated full-state context. + """ + + assert type(env_id) is int and env_id >= 0, "env_id must be non-negative" + description = _description_load(description_path) + _action_target_frames_validate(datastream, description["planning_groups"]) + controller_model_path = datastream.get_robot_planning_model_path() + assert ( + controller_model_path is not None and controller_model_path.is_file() + ), "the embodiment must expose its live controller URDF" + + root_link = description["root_link"] + inactive_joint_names = tuple(description["inactive_joint_names"]) + groups = description["planning_groups"] + auxiliary_by_group = { + group_name: tuple(group.get("auxiliary_joint_names", datastream.get_robot_eef_joint_names(group["eef_name"]))) + for group_name, group in groups.items() + } + auxiliary_joint_names = tuple( + dict.fromkeys(name for group_name in groups for name in auxiliary_by_group[group_name]) + ) + model_path = curobo_robot_model_prepare( + controller_model_path, + auxiliary_joint_names=auxiliary_joint_names, + ) + chains = { + group_name: curobo_arm_chain( + model_path, + group["tool_link"], + root_link=root_link, + inactive_joint_names=inactive_joint_names, + auxiliary_joint_names=auxiliary_by_group[group_name], + ) + for group_name, group in groups.items() + } + shared_collision_link_names = ( + set.intersection(*(set(chain.collision_link_names) for chain in chains.values())) if len(chains) > 1 else set() + ) + collision_links_by_group = { + group_name: tuple( + link_name + for link_name in chain.collision_link_names + if link_name not in shared_collision_link_names or link_name in chain.moving_link_names + ) + for group_name, chain in chains.items() + } + assert all(collision_links_by_group.values()), "each planning group must own links outside shared ancestry" + group_collision_link_names = tuple( + dict.fromkeys(link_name for names in collision_links_by_group.values() for link_name in names) + ) + assert group_collision_link_names, "planning groups contain no collision-bearing moving links" + full_state_link_names = ( + group_collision_link_names if description["full_state_collision_scope"] == "planning_groups" else None + ) + + cache_root = ( + Path(cache_dir).expanduser().resolve() + if cache_dir is not None + else Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "autodata" / "curobo" + ) + spheres = collision_spheres_fit_urdf( + model_path, + link_names=full_state_link_names if include_full_state else group_collision_link_names, + config=CollisionSphereFitConfig(**description["sphere_fit"]), + cache_dir=cache_root / "collision_spheres", + ) + if include_full_state: + _full_state_sphere_count_validate(spheres.spheres_by_link) + start_joint_positions = _named_start_state(datastream, env_id) + + from autodata_interfaces.motion_planners.curobo.curobo_planner import CuroboPlanner + from autodata_interfaces.motion_planners.curobo.curobo_planner_cfg import CuroboPlannerCfg + + planners: dict[str, CuroboPlanner] = {} + for group_name, group in groups.items(): + tool_link = group["tool_link"] + initial_auxiliary_positions = _initial_auxiliary_positions( + group.get("initial_auxiliary_joint_positions", {}), auxiliary_by_group[group_name] + ) + robot_config = curobo_robot_config_create( + model_path, + tool_link, + start_joint_positions, + spheres, + root_link=root_link, + inactive_joint_names=inactive_joint_names, + auxiliary_joint_names=auxiliary_by_group[group_name], + collision_link_names=collision_links_by_group[group_name], + self_collision_ignore_pairs=group.get("self_collision_ignore_pairs", ()), + **description["robot_config"], + ) + robot_config_path = _robot_config_cache_write(robot_config, cache_root / "robot_configs") + planning_config_path = robot_config_path + if auxiliary_by_group[group_name]: + # Auxiliary joints follow their own action channel, not the transit optimizer. + planning_config = curobo_robot_config_create( + model_path, + tool_link, + {**start_joint_positions, **initial_auxiliary_positions}, + spheres, + root_link=root_link, + inactive_joint_names=inactive_joint_names, + auxiliary_joint_names=auxiliary_by_group[group_name], + lock_auxiliary_joints=True, + collision_link_names=collision_links_by_group[group_name], + self_collision_ignore_pairs=group.get("self_collision_ignore_pairs", ()), + **description["robot_config"], + ) + planning_config_path = _robot_config_cache_write(planning_config, cache_root / "robot_configs") + planner_config = CuroboPlannerCfg( + robot_config_file=str(planning_config_path), + kinematic_robot_config_file=str(robot_config_path) if planning_config_path != robot_config_path else None, + robot_name=f"{description['name']}_{group_name}", + planning_group_name=group_name, + ee_link_name=tool_link, + root_pose_source_frame_name=description["root_pose_source_frame"], + include_configured_world=True, + initial_auxiliary_joint_positions=initial_auxiliary_positions, + hand_link_names=list(chains[group_name].contact_link_names), + attached_object_link_name=ATTACHED_OBJECT_LINK_NAME, + extra_collision_spheres={}, + visualize_plan=False, + visualize_spheres=False, + **description["planner"], + ) + eef_name = group["eef_name"] + planners[eef_name] = CuroboPlanner(datastream=datastream, config=planner_config, env_id=env_id) + + full_state: CuroboPlanner | None = None + if include_full_state: + full_robot_options = dict(description["robot_config"]) + full_robot_options.pop("attachment_sphere_count", None) + tool_links = tuple(group["tool_link"] for group in groups.values()) + active_joint_names = tuple( + dict.fromkeys(joint_name for chain in chains.values() for joint_name in chain.active_joint_names) + ) + ignore_pairs = tuple( + dict.fromkeys( + tuple(sorted(pair)) + for group in groups.values() + for pair in group.get("self_collision_ignore_pairs", ()) + ) + ) + full_robot_config = curobo_full_robot_config_create( + model_path, + tool_links, + active_joint_names, + start_joint_positions, + spheres, + root_link=root_link, + self_collision_ignore_pairs=ignore_pairs, + **full_robot_options, + ) + full_config_path = _robot_config_cache_write(full_robot_config, cache_root / "robot_configs") + full_planner_config = CuroboPlannerCfg( + robot_config_file=str(full_config_path), + robot_name=f"{description['name']}_full_state", + planning_group_name=f"{description['name']}_full_state", + ee_link_name=tool_links[0], + root_pose_source_frame_name=description["root_pose_source_frame"], + include_configured_world=False, + extra_collision_spheres={}, + visualize_plan=False, + visualize_spheres=False, + planning_enabled=False, + use_native_self_collision=False, + **description["planner"], + ) + full_state = CuroboPlanner( + datastream=datastream, + config=full_planner_config, + env_id=env_id, + collision_world_source=next(iter(planners.values())), + ) + + if visualize_plan and env_id == 0: + from autodata_interfaces.motion_planners.curobo.plan_visualizer import PlanVisualizer + + root_pose = datastream.get_robot_planning_root_pose( + description["root_pose_source_frame"], + env_ids=[env_id], + )[0] + visualizer = PlanVisualizer( + robot_name=description["name"], + recording_id=f"curobo_plan_{env_id}", + debug=any(planner.config.debug_planner for planner in planners.values()), + save_path=str(Path(rerun_output).expanduser().resolve()) if rerun_output is not None else None, + base_pose_in_env=root_pose, + ) + for planner in planners.values(): + planner.visualize_plan = True + planner.plan_visualizer = visualizer + if full_state is not None: + full_state.plan_visualizer = visualizer + return planners, full_state + + +def _full_state_sphere_count_validate(spheres_by_link: Mapping[str, tuple[Any, ...]]) -> None: + """Fail before cuRobo can abort on an oversized self-collision model.""" + + sphere_count = sum(len(spheres) for spheres in spheres_by_link.values()) + assert sphere_count < _CUROBO_SELF_COLLISION_SPHERE_LIMIT, ( + f"full-state model has {sphere_count} spheres; pinned cuRobo requires fewer than " + f"{_CUROBO_SELF_COLLISION_SPHERE_LIMIT}" + ) + + +def _action_target_frames_validate(datastream: Datastream, groups: Mapping[str, Mapping[str, Any]]) -> None: + """Require task, controller action, and planner tool frames to agree exactly.""" + + target_frames = datastream.get_robot_action_target_frames() + task_eef_names = tuple(datastream.get_eef_names()) + assert target_frames, "group planning requires explicit live action-target frames" + assert ( + tuple(frame.eef_name for frame in target_frames) == task_eef_names + ), "action-target frames must cover task EEFs in action order" + + group_by_eef = {group["eef_name"]: group for group in groups.values()} + assert len(group_by_eef) == len(groups), "planning-group end-effectors must be unique" + assert set(group_by_eef) == set(task_eef_names), "planning groups must cover every task end-effector" + for target_frame in target_frames: + tool_link = group_by_eef[target_frame.eef_name]["tool_link"] + assert tool_link == target_frame.frame_name, ( + f"planning tool {tool_link!r} does not match {target_frame.eef_name!r} " + f"action target {target_frame.frame_name!r}" + ) + + +def _description_load(path: str | Path, _parents: tuple[Path, ...] = ()) -> dict[str, Any]: + """Resolve planning-description overlays and validate supported fields. + + Args: + path: Base or overlay YAML file; relative overlay parents resolve beside this file. + _parents: Already visited files used to reject cyclic inheritance. + + Returns: + Fully merged description with validated planning groups and settings. + + Raises: + AssertionError: A file is absent, inheritance is cyclic, or fields are unsupported or invalid. + """ + + description_path = Path(path).expanduser().resolve() + assert description_path.is_file(), f"planning-groups description does not exist: {description_path}" + assert description_path not in _parents, f"cyclic planning-groups overlay: {description_path}" + with description_path.open(encoding="utf-8") as stream: + description = yaml.safe_load(stream) + assert isinstance(description, dict), "planning-groups description must be a mapping" + + if "extends" in description: + assert _OVERLAY_REQUIRED_KEYS <= set(description) <= _OVERLAY_KEYS, ( + f"planning-groups overlay fields must include {sorted(_OVERLAY_REQUIRED_KEYS)} " + f"and may include {sorted(_OVERLAY_KEYS - _OVERLAY_REQUIRED_KEYS)}" + ) + assert description["schema"] == _SCHEMA, f"unsupported planning-groups schema: {description['schema']!r}" + assert isinstance(description["extends"], str) and description["extends"], "extends must name a base file" + assert isinstance(description["name"], str) and description["name"], "name must be a non-empty string" + _keys_validate(description.get("planner", {}), _PLANNER_KEYS, "planner overlay") + _keys_validate(description.get("robot_config", {}), _ROBOT_CONFIG_KEYS, "robot config overlay") + _keys_validate(description.get("sphere_fit", {}), _SPHERE_FIT_KEYS, "sphere-fit overlay") + base = _description_load(description_path.parent / description["extends"], (*_parents, description_path)) + description = { + **base, + "name": description["name"], + "full_state_collision_scope": description.get( + "full_state_collision_scope", base["full_state_collision_scope"] + ), + "inactive_joint_names": description.get("inactive_joint_names", base["inactive_joint_names"]), + "planner": {**base["planner"], **description.get("planner", {})}, + "robot_config": {**base["robot_config"], **description.get("robot_config", {})}, + "sphere_fit": {**base["sphere_fit"], **description.get("sphere_fit", {})}, + } + + assert set(description) == _ROOT_KEYS, f"planning-groups fields must be {sorted(_ROOT_KEYS)}" + assert description["schema"] == _SCHEMA, f"unsupported planning-groups schema: {description['schema']!r}" + for key in ("name", "root_link", "root_pose_source_frame"): + assert isinstance(description[key], str) and description[key], f"{key} must be a non-empty string" + assert description["full_state_collision_scope"] in { + "complete", + "planning_groups", + }, "full_state_collision_scope must be 'complete' or 'planning_groups'" + inactive = description["inactive_joint_names"] + assert ( + isinstance(inactive, list) + and all(isinstance(name, str) and name for name in inactive) + and len(inactive) == len(set(inactive)) + ), "inactive_joint_names must contain unique non-empty strings" + groups = description["planning_groups"] + assert isinstance(groups, dict) and groups, "planning_groups must be a non-empty mapping" + eef_names: list[str] = [] + for group_name, group in groups.items(): + assert isinstance(group_name, str) and group_name and isinstance(group, dict) + required = {"eef_name", "tool_link"} + allowed = required | { + "auxiliary_joint_names", + "initial_auxiliary_joint_positions", + "self_collision_ignore_pairs", + } + assert required <= set(group) <= allowed, "planning groups contain unsupported fields" + assert all(isinstance(group[key], str) and group[key] for key in required) + auxiliary = group.get("auxiliary_joint_names", []) + assert ( + isinstance(auxiliary, list) + and all(isinstance(name, str) and name for name in auxiliary) + and len(auxiliary) == len(set(auxiliary)) + ), "auxiliary_joint_names must contain unique non-empty strings" + initial_auxiliary_positions = group.get("initial_auxiliary_joint_positions", {}) + assert isinstance( + initial_auxiliary_positions, dict | int | float + ), "initial_auxiliary_joint_positions must be a finite scalar or mapping" + if isinstance(initial_auxiliary_positions, dict): + assert not auxiliary or set(initial_auxiliary_positions) <= set( + auxiliary + ), "initial_auxiliary_joint_positions must only name explicit auxiliary joints" + initial_values = initial_auxiliary_positions.values() + else: + initial_values = (initial_auxiliary_positions,) + assert all( + isinstance(value, int | float) and math.isfinite(value) for value in initial_values + ), "initial_auxiliary_joint_positions must contain finite numeric values" + ignore_pairs = group.get("self_collision_ignore_pairs", []) + assert isinstance(ignore_pairs, list), "self_collision_ignore_pairs must be a list" + assert all( + isinstance(pair, list) + and len(pair) == 2 + and all(isinstance(name, str) and name for name in pair) + and pair[0] != pair[1] + for pair in ignore_pairs + ), "self_collision_ignore_pairs must contain two distinct non-empty link names" + eef_names.append(group["eef_name"]) + assert len(eef_names) == len(set(eef_names)), "planning-group end-effectors must be unique" + _keys_validate(description["sphere_fit"], _SPHERE_FIT_KEYS, "sphere_fit") + _keys_validate(description["robot_config"], _ROBOT_CONFIG_KEYS, "robot_config") + _keys_validate(description["planner"], _PLANNER_KEYS, "planner") + return description + + +def _keys_validate(value: object, allowed: set[str], owner: str) -> None: + """Require a settings mapping with only the supported keys for its owner.""" + + assert isinstance(value, Mapping), f"{owner} must be a mapping" + unknown = set(value) - allowed + assert not unknown, f"{owner} contains unknown fields: {sorted(unknown)}" + + +def _initial_auxiliary_positions( + configured: Mapping[str, float] | int | float, + joint_names: tuple[str, ...], +) -> dict[str, float]: + """Expand a scalar auxiliary-joint target or validate an explicitly named subset [rad, m].""" + + if isinstance(configured, Mapping): + unknown = set(configured) - set(joint_names) + assert not unknown, f"initial auxiliary joints are not owned by the embodiment EEF: {sorted(unknown)}" + return {name: float(value) for name, value in configured.items()} + return {name: float(configured) for name in joint_names} + + +def _named_start_state(datastream: Datastream, env_id: int) -> dict[str, float]: + """Pair measured joint values [rad, m] with unique names in live articulation order.""" + + joint_names = tuple(datastream.get_robot_joint_names()) + assert joint_names and len(joint_names) == len(set(joint_names)), "live joint names must be non-empty and unique" + positions = datastream.get_robot_joint_positions(env_ids=[env_id]) + assert positions.ndim == 2 and positions.shape == (1, len(joint_names)), "live joint state shape is inconsistent" + return dict(zip(joint_names, (float(value) for value in positions[0].detach().cpu().tolist()), strict=True)) + + +def _robot_config_cache_write(config: Mapping[str, object], cache_dir: Path) -> Path: + """Write a finite, content-addressed robot configuration unless already cached.""" + + payload = json.dumps(config, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + output_path = cache_dir / f"{hashlib.sha256(payload).hexdigest()}.yml" + if not output_path.is_file(): + curobo_robot_config_write(config, output_path) + return output_path + + +__all__ = ["CuroboPlanningContext", "curobo_group_planners_create", "curobo_planning_context_create"] diff --git a/autodata_interfaces/motion_planners/curobo/robot_config.py b/autodata_interfaces/motion_planners/curobo/robot_config.py new file mode 100644 index 0000000..907acd6 --- /dev/null +++ b/autodata_interfaces/motion_planners/curobo/robot_config.py @@ -0,0 +1,728 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Build arm-local and full-state cuRobo configurations from a named URDF state.""" + +from __future__ import annotations + +import copy +import hashlib +import math +import os +import tempfile +import xml.etree.ElementTree as ET +import yaml +from collections import defaultdict, deque +from collections.abc import Mapping, Sequence +from contextlib import suppress +from dataclasses import dataclass +from pathlib import Path + +from .collision_spheres import CollisionSphere, CollisionSphereSet + +ATTACHED_OBJECT_LINK_NAME = "attached_object" + + +@dataclass(frozen=True) +class CuroboArmChain: + """URDF-derived kinematic ownership for one independently planned tool. + + Args: + root_link: Planning reference link. + tool_link: Controlled end-effector link. + root_to_tool_link_names: Ordered links along the serial chain. + auxiliary_joint_names: Additional independent joints explicitly assigned to the group. + active_joint_names: Serial and auxiliary joints in planner order. + moving_link_names: Descendants of active joints, including other branches when shared. + collision_link_names: Geometry-bearing links owned by this tool's chain and contact subtree. + contact_link_names: Tool link and descendants used to resolve hand contact ownership. + """ + + root_link: str + tool_link: str + root_to_tool_link_names: tuple[str, ...] + auxiliary_joint_names: tuple[str, ...] + active_joint_names: tuple[str, ...] + moving_link_names: tuple[str, ...] + collision_link_names: tuple[str, ...] + contact_link_names: tuple[str, ...] + + +@dataclass(frozen=True) +class _Joint: + """Named URDF connection with its type, endpoints and optional mimic leader.""" + + name: str + joint_type: str + parent_link: str + child_link: str + mimic_joint: str | None + + +@dataclass(frozen=True) +class _UrdfModel: + """Parsed single-root topology and the names of links containing geometry.""" + + links: tuple[str, ...] + geometry_link_names: tuple[str, ...] + joints: Mapping[str, _Joint] + root_link: str + + +def curobo_robot_model_prepare( + urdf_path: str | Path, + *, + auxiliary_joint_names: Sequence[str] = (), +) -> Path: + """Materialize the planning view of a controller-owned URDF. + + Some task-space controllers reduce their own URDF by marking joints handled by a separate + positional action channel as fixed. A planning group may explicitly restore those joints as + movable. The derived file stays beside the source URDF so relative mesh paths remain valid. + + Args: + urdf_path: Controller-owned local URDF. + auxiliary_joint_names: Independently commanded joints to restore when fixed. + + Returns: + Source path when no restoration is needed, otherwise an atomically cached derived URDF. + """ + + source_path = Path(urdf_path).expanduser().resolve() + assert source_path.is_file(), f"URDF must be a local file: {source_path}" + requested = tuple(auxiliary_joint_names) + assert all(isinstance(name, str) and name for name in requested) + assert len(requested) == len(set(requested)), "auxiliary_joint_names must be unique" + + root = ET.fromstring(source_path.read_bytes()) + joint_elements = {element.get("name", ""): element for element in root.findall("joint")} + unknown = sorted(set(requested) - set(joint_elements)) + assert not unknown, f"unknown auxiliary joints: {unknown}" + restored: list[str] = [] + for name in requested: + element = joint_elements[name] + assert element.find("mimic") is None, f"auxiliary joint {name!r} is mimic-controlled" + joint_type = element.get("type", "") + if joint_type == "fixed": + assert ( + element.find("axis") is not None and element.find("limit") is not None + ), f"fixed auxiliary joint {name!r} lacks the axis/limit metadata needed for restoration" + element.set("type", "revolute") + restored.append(name) + else: + assert joint_type in { + "continuous", + "prismatic", + "revolute", + }, f"unsupported auxiliary joint type {joint_type!r} for {name!r}" + if not restored: + return source_path + + digest = hashlib.sha256() + digest.update(source_path.read_bytes()) + digest.update("\0".join(sorted(requested)).encode()) + output_path = source_path.with_name(f"{source_path.stem}.planning-{digest.hexdigest()[:16]}.urdf") + if output_path.is_file(): + return output_path + descriptor, temporary_name = tempfile.mkstemp(prefix=f".{output_path.name}.", dir=output_path.parent) + try: + with os.fdopen(descriptor, "wb") as stream: + ET.ElementTree(root).write(stream, encoding="utf-8", xml_declaration=True) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary_name, output_path) + except BaseException: + with suppress(FileNotFoundError): + os.unlink(temporary_name) + raise + return output_path + + +def curobo_arm_chain( + urdf_path: str | Path, + tool_link: str, + *, + root_link: str | None = None, + inactive_joint_names: Sequence[str] = (), + auxiliary_joint_names: Sequence[str] = (), +) -> CuroboArmChain: + """Derive active joints and moving links for one root-to-tool chain. + + Joints on the chain are active unless fixed, mimic-controlled, or explicitly inactive. + Independently commanded joints below that chain, such as dexterous-hand joints, may be added + explicitly. Moving links are the child and descendants of every active joint. Collision + ownership is narrower: geometry on the root-to-tool branch plus the selected tool's contact + descendants. This prevents a shared humanoid joint from making one group own its sibling arm. + + Args: + urdf_path: Local URDF describing the complete robot. + tool_link: End-effector link whose chain is extracted. + root_link: Planning reference link; ``None`` uses the URDF root. + inactive_joint_names: Joints to exclude from the active serial chain. + auxiliary_joint_names: Independent joints outside the serial chain to activate explicitly. + + Returns: + Named joint, motion, collision and contact ownership for the planning group. + """ + + model = _urdf_model_load(Path(urdf_path)) + root_name = model.root_link if root_link is None else root_link + assert root_name in model.links, f"unknown root link {root_name!r}" + assert tool_link in model.links, f"unknown tool link {tool_link!r}" + inactive = set(inactive_joint_names) + unknown_inactive = sorted(inactive - set(model.joints)) + assert not unknown_inactive, f"unknown inactive joints: {unknown_inactive}" + auxiliary = tuple(auxiliary_joint_names) + assert all( + isinstance(name, str) and name for name in auxiliary + ), "auxiliary_joint_names must contain non-empty strings" + assert len(auxiliary) == len(set(auxiliary)), "auxiliary_joint_names must be unique" + unknown_auxiliary = sorted(set(auxiliary) - set(model.joints)) + assert not unknown_auxiliary, f"unknown auxiliary joints: {unknown_auxiliary}" + + joint_by_child = {joint.child_link: joint for joint in model.joints.values()} + reverse_chain: list[_Joint] = [] + cursor = tool_link + while cursor != root_name: + assert cursor in joint_by_child, f"tool link {tool_link!r} is not below root {root_name!r}" + joint = joint_by_child[cursor] + reverse_chain.append(joint) + cursor = joint.parent_link + chain = tuple(reversed(reverse_chain)) + serial_active_joints = tuple( + joint.name + for joint in chain + if joint.joint_type != "fixed" and joint.mimic_joint is None and joint.name not in inactive + ) + assert serial_active_joints, f"root-to-tool chain for {tool_link!r} has no active joints" + + redundant_auxiliary = sorted(set(auxiliary) & {joint.name for joint in chain}) + assert not redundant_auxiliary, f"auxiliary joints already belong to the root-to-tool chain: {redundant_auxiliary}" + inactive_auxiliary = sorted(set(auxiliary) & inactive) + assert not inactive_auxiliary, f"auxiliary joints are explicitly inactive: {inactive_auxiliary}" + unsupported_auxiliary = sorted( + name + for name in auxiliary + if model.joints[name].joint_type == "fixed" or model.joints[name].mimic_joint is not None + ) + assert not unsupported_auxiliary, f"auxiliary joints must be independent and non-fixed: {unsupported_auxiliary}" + + children = _children_by_link(model) + serial_moving: set[str] = set() + for joint_name in serial_active_joints: + queue = deque([model.joints[joint_name].child_link]) + while queue: + link_name = queue.popleft() + if link_name in serial_moving: + continue + serial_moving.add(link_name) + queue.extend(children[link_name]) + outside_branch = sorted(name for name in auxiliary if model.joints[name].child_link not in serial_moving) + assert not outside_branch, f"auxiliary joints do not belong to the selected tool branch: {outside_branch}" + + active_joints = (*serial_active_joints, *auxiliary) + moving: set[str] = set() + for joint_name in active_joints: + queue = deque([model.joints[joint_name].child_link]) + while queue: + link_name = queue.popleft() + if link_name in moving: + continue + moving.add(link_name) + queue.extend(children[link_name]) + moving_link_names = tuple(link_name for link_name in model.links if link_name in moving) + collision_links = set(model.geometry_link_names) + contact_joints = set(auxiliary) + while ( + followers := {joint.name for joint in model.joints.values() if joint.mimic_joint in contact_joints} + - contact_joints + ): + contact_joints.update(followers) + contact_links = {tool_link} + for joint_name in contact_joints: + queue = deque([model.joints[joint_name].child_link]) + while queue: + link_name = queue.popleft() + if link_name in contact_links: + continue + contact_links.add(link_name) + queue.extend(children[link_name]) + owned_collision_links = ({root_name, *(joint.child_link for joint in chain)} | contact_links) & collision_links + return CuroboArmChain( + root_link=root_name, + tool_link=tool_link, + root_to_tool_link_names=(root_name, *(joint.child_link for joint in chain)), + auxiliary_joint_names=auxiliary, + active_joint_names=active_joints, + moving_link_names=moving_link_names, + collision_link_names=tuple(link_name for link_name in model.links if link_name in owned_collision_links), + contact_link_names=tuple(link_name for link_name in moving_link_names if link_name in contact_links), + ) + + +def curobo_robot_config_create( + urdf_path: str | Path, + tool_link: str, + start_joint_positions: Mapping[str, float], + collision_spheres: CollisionSphereSet | Mapping[str, Sequence[CollisionSphere | Mapping[str, object]]], + *, + root_link: str | None = None, + inactive_joint_names: Sequence[str] = (), + auxiliary_joint_names: Sequence[str] = (), + lock_auxiliary_joints: bool = False, + collision_link_names: Sequence[str] | None = None, + attachment_sphere_count: int = 50, + self_collision_ignore_depth: int = 2, + self_collision_ignore_pairs: Sequence[Sequence[str]] = (), + max_acceleration: float = 15.0, + max_jerk: float = 500.0, +) -> dict[str, object]: + """Create an ordinary arm-local cuRobo ``robot_cfg`` mapping. + + Inactive joints inside the selected root-to-tool chain and contact subtree are locked to the + supplied named start state. Unowned branches are omitted entirely. Only requested collision + spheres owned by this tool are emitted. Carried-object capacity lives on an + identity-fixed virtual child of the tool so cuRobo never replaces the tool's fitted geometry. + + Args: + urdf_path: Local URDF describing the complete robot. + tool_link: End-effector link whose planning configuration is built. + start_joint_positions: Named initial state covering independent owned joints [rad, m]. + collision_spheres: Shared link-frame geometry to project onto this group [m]. + root_link: Planning reference link; ``None`` uses the URDF root. + inactive_joint_names: Serial-chain joints locked to the supplied initial state. + auxiliary_joint_names: Independent joints outside the serial chain to model explicitly. + lock_auxiliary_joints: Hold auxiliary joints at their named start positions during planning. + collision_link_names: Optional subset of this tool's geometry-bearing links. + attachment_sphere_count: Reserved carried-object sphere slots; zero disables attachment slots. + self_collision_ignore_depth: Active-joint topology distance excluded from self-collision checks. + self_collision_ignore_pairs: Additional explicit link-pair exclusions. + max_acceleration: Planner acceleration limit [rad/s^2, m/s^2]. + max_jerk: Planner jerk limit [rad/s^3, m/s^3]. + + Returns: + A mapping accepted by cuRobo's robot configuration loader. + """ + + source_path = Path(urdf_path).expanduser().resolve() + model = _urdf_model_load(source_path) + chain = curobo_arm_chain( + source_path, + tool_link, + root_link=root_link, + inactive_joint_names=inactive_joint_names, + auxiliary_joint_names=auxiliary_joint_names, + ) + owned_links = set(chain.root_to_tool_link_names) | set(chain.contact_link_names) + independent = tuple( + joint.name + for joint in model.joints.values() + if joint.joint_type != "fixed" and joint.mimic_joint is None and joint.child_link in owned_links + ) + source_spheres = ( + collision_spheres.spheres_by_link if isinstance(collision_spheres, CollisionSphereSet) else collision_spheres + ) + requested_collision_links = ( + chain.collision_link_names if collision_link_names is None else tuple(collision_link_names) + ) + unknown_collision_links = set(requested_collision_links) - set(chain.collision_link_names) + assert ( + not unknown_collision_links + ), f"collision links are not owned by tool {tool_link!r}: {sorted(unknown_collision_links)}" + selected_collision_links = tuple(name for name in requested_collision_links if name in source_spheres) + assert selected_collision_links, f"no fitted collision links belong to tool {tool_link!r}" + if tool_link not in selected_collision_links: + selected_collision_links = (*selected_collision_links, tool_link) + return _robot_config_create( + source_path, + model, + root_link=chain.root_link, + link_names=(tool_link,), + independent_joint_names=independent, + active_joint_names=tuple( + name for name in chain.active_joint_names if not lock_auxiliary_joints or name not in auxiliary_joint_names + ), + collision_link_names=selected_collision_links, + start_joint_positions=start_joint_positions, + source_spheres=source_spheres, + attachment_parent_link=tool_link if attachment_sphere_count else None, + attachment_sphere_count=attachment_sphere_count, + self_collision_ignore_depth=self_collision_ignore_depth, + self_collision_ignore_pairs=self_collision_ignore_pairs, + max_acceleration=max_acceleration, + max_jerk=max_jerk, + ) + + +def curobo_full_robot_config_create( + urdf_path: str | Path, + tool_links: Sequence[str], + active_joint_names: Sequence[str], + start_joint_positions: Mapping[str, float], + collision_spheres: CollisionSphereSet | Mapping[str, Sequence[CollisionSphere | Mapping[str, object]]], + *, + root_link: str | None = None, + self_collision_ignore_depth: int = 2, + self_collision_ignore_pairs: Sequence[Sequence[str]] = (), + max_acceleration: float = 15.0, + max_jerk: float = 500.0, +) -> dict[str, object]: + """Create a cuRobo configuration for composed robot-state checks. + + Every independent joint not owned by a planning group is locked to the exact named start + state. Supplied fitted links form the collision model, while motion planning and IK stay on the + ordinary arm-local configurations. + + Args: + urdf_path: Controller-owned local URDF. + tool_links: Tool links exposed by the full-state FK model. + active_joint_names: Union of dynamically composed planning-group joints. + start_joint_positions: Complete named live articulation state [rad, m]. + collision_spheres: Shared collision spheres for the links to check. + root_link: Optional planning root; the URDF root is used by default. + self_collision_ignore_depth: Active-joint topology depth ignored for self collision. + self_collision_ignore_pairs: Additional reviewed link pairs to ignore. + max_acceleration: cuRobo configuration acceleration limit [rad/s^2, m/s^2]. + max_jerk: cuRobo configuration jerk limit [rad/s^3, m/s^3]. + + Returns: + A mapping accepted by cuRobo's robot configuration loader. + """ + + source_path = Path(urdf_path).expanduser().resolve() + model = _urdf_model_load(source_path) + root_name = model.root_link if root_link is None else root_link + assert root_name in model.links, f"unknown root link {root_name!r}" + tools = tuple(tool_links) + assert tools and all(name in model.links for name in tools), "tool_links must name URDF links" + assert len(tools) == len(set(tools)), "tool_links must be unique" + + requested_active = set(active_joint_names) + assert requested_active, "active_joint_names must not be empty" + unknown_active = sorted(requested_active - set(model.joints)) + assert not unknown_active, f"unknown active joints: {unknown_active}" + unsupported_active = sorted( + name + for name in requested_active + if model.joints[name].joint_type == "fixed" or model.joints[name].mimic_joint is not None + ) + assert not unsupported_active, f"active joints must be independent and non-fixed: {unsupported_active}" + active = tuple(joint.name for joint in model.joints.values() if joint.name in requested_active) + source_spheres = ( + collision_spheres.spheres_by_link if isinstance(collision_spheres, CollisionSphereSet) else collision_spheres + ) + collision_link_names = tuple(name for name in model.geometry_link_names if name in source_spheres) + assert collision_link_names, "full-state collision model must contain at least one robot link" + scoped_links = set(model.links) + if set(collision_link_names) != set(model.geometry_link_names): + scoped_links = {root_name} + joint_by_child = {joint.child_link: joint for joint in model.joints.values()} + for target_link in (*tools, *collision_link_names): + cursor = target_link + while cursor != root_name: + assert cursor in joint_by_child, f"link {target_link!r} is not below root {root_name!r}" + scoped_links.add(cursor) + cursor = joint_by_child[cursor].parent_link + independent = tuple( + joint.name + for joint in model.joints.values() + if joint.joint_type != "fixed" and joint.mimic_joint is None and joint.child_link in scoped_links + ) + assert requested_active <= set(independent), "active joints must belong to the scoped collision/tool model" + return _robot_config_create( + source_path, + model, + root_link=root_name, + link_names=tools, + independent_joint_names=independent, + active_joint_names=active, + collision_link_names=collision_link_names, + start_joint_positions=start_joint_positions, + source_spheres=source_spheres, + attachment_parent_link=None, + attachment_sphere_count=0, + self_collision_ignore_depth=self_collision_ignore_depth, + self_collision_ignore_pairs=self_collision_ignore_pairs, + max_acceleration=max_acceleration, + max_jerk=max_jerk, + ) + + +def _robot_config_create( + source_path: Path, + model: _UrdfModel, + *, + root_link: str, + link_names: tuple[str, ...], + independent_joint_names: tuple[str, ...], + active_joint_names: tuple[str, ...], + collision_link_names: tuple[str, ...], + start_joint_positions: Mapping[str, float], + source_spheres: Mapping[str, Sequence[CollisionSphere | Mapping[str, object]]], + attachment_parent_link: str | None, + attachment_sphere_count: int, + self_collision_ignore_depth: int, + self_collision_ignore_pairs: Sequence[Sequence[str]], + max_acceleration: float, + max_jerk: float, +) -> dict[str, object]: + """Assemble the shared cuRobo kinematics mapping.""" + + assert attachment_sphere_count >= 0 + assert self_collision_ignore_depth >= 0 + assert math.isfinite(max_acceleration) and max_acceleration > 0.0 + assert math.isfinite(max_jerk) and max_jerk > 0.0 + assert set(active_joint_names) <= set(independent_joint_names) + missing_positions = sorted(set(independent_joint_names) - set(start_joint_positions)) + assert not missing_positions, f"start state is missing independent joints: {missing_positions}" + positions = {name: float(start_joint_positions[name]) for name in independent_joint_names} + assert all(math.isfinite(value) for value in positions.values()), "start joint positions must be finite" + active = set(active_joint_names) + lock_joints = {name: positions[name] for name in independent_joint_names if name not in active} + projected_spheres = { + link_name: [_sphere_dict(sphere) for sphere in source_spheres.get(link_name, ())] + for link_name in collision_link_names + } + self_collision_ignore = _self_collision_ignore( + model, + active_joint_names, + collision_link_names, + self_collision_ignore_depth, + ) + _self_collision_ignore_pairs_add( + self_collision_ignore, + collision_link_names, + self_collision_ignore_pairs, + ) + extra_links: dict[str, object] = {} + if attachment_parent_link is not None: + attachment_joint_name = f"{ATTACHED_OBJECT_LINK_NAME}_joint" + assert ( + ATTACHED_OBJECT_LINK_NAME not in model.links + ), f"reserved attachment link {ATTACHED_OBJECT_LINK_NAME!r} already exists in the URDF" + assert ( + attachment_joint_name not in model.joints + ), f"reserved attachment joint {attachment_joint_name!r} already exists in the URDF" + attachment_ignores = [attachment_parent_link, *self_collision_ignore[attachment_parent_link]] + self_collision_ignore[ATTACHED_OBJECT_LINK_NAME] = attachment_ignores + for link_name in attachment_ignores: + self_collision_ignore[link_name].append(ATTACHED_OBJECT_LINK_NAME) + collision_link_names = (*collision_link_names, ATTACHED_OBJECT_LINK_NAME) + projected_spheres[ATTACHED_OBJECT_LINK_NAME] = [ + {"center": [0.0, 0.0, 0.0], "radius": -10.0} for _ in range(attachment_sphere_count) + ] + extra_links[ATTACHED_OBJECT_LINK_NAME] = { + "parent_link_name": attachment_parent_link, + "link_name": ATTACHED_OBJECT_LINK_NAME, + "fixed_transform": [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], + "joint_type": "FIXED", + "joint_name": attachment_joint_name, + } + kinematics: dict[str, object] = { + "use_usd_kinematics": False, + "urdf_path": str(source_path), + "asset_root_path": str(source_path.parent), + "base_link": root_link, + "ee_link": link_names[0], + "link_names": list(link_names), + "collision_link_names": list(collision_link_names), + "collision_spheres": projected_spheres, + "collision_sphere_buffer": 0.0, + "self_collision_ignore": self_collision_ignore, + "self_collision_buffer": {link_name: 0.0 for link_name in collision_link_names}, + "lock_joints": lock_joints, + "extra_links": extra_links, + "extra_collision_spheres": {}, + "cspace": { + "joint_names": list(active_joint_names), + "retract_config": [positions[name] for name in active_joint_names], + "null_space_weight": [1.0] * len(active_joint_names), + "cspace_distance_weight": [1.0] * len(active_joint_names), + "max_acceleration": max_acceleration, + "max_jerk": max_jerk, + }, + } + return {"robot_cfg": {"kinematics": kinematics}} + + +def curobo_robot_config_write(config: Mapping[str, object], path: str | Path) -> Path: + """Atomically write a cuRobo robot configuration YAML file. + + Args: + config: Robot configuration mapping containing ``robot_cfg``. + path: Destination YAML file; parent directories are created if needed. + + Returns: + Resolved destination path. + """ + + assert "robot_cfg" in config, "config must contain robot_cfg" + output_path = Path(path).expanduser().resolve() + output_path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp(prefix=f".{output_path.name}.", dir=output_path.parent) + try: + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + yaml.safe_dump(copy.deepcopy(dict(config)), stream, sort_keys=False) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary_name, output_path) + except BaseException: + with suppress(FileNotFoundError): + os.unlink(temporary_name) + raise + return output_path + + +def _urdf_model_load(path: Path) -> _UrdfModel: + """Read named links, geometry presence and joint topology from a single-root URDF.""" + + source_path = path.expanduser().resolve() + if not source_path.is_file(): + raise FileNotFoundError(f"URDF must be a local file: {source_path}") + root = ET.fromstring(source_path.read_bytes()) + link_elements = root.findall("link") + links = tuple(element.get("name", "") for element in link_elements) + assert links and all(links) and len(set(links)) == len(links), "URDF links must be named and unique" + geometry_link_names = tuple( + element.get("name", "") + for element in link_elements + if element.find("visual") is not None or element.find("collision") is not None + ) + joints: dict[str, _Joint] = {} + for element in root.findall("joint"): + parent, child = element.find("parent"), element.find("child") + name = element.get("name", "") + assert name and name not in joints and parent is not None and child is not None + mimic = element.find("mimic") + joints[name] = _Joint( + name=name, + joint_type=element.get("type", ""), + parent_link=parent.get("link", ""), + child_link=child.get("link", ""), + mimic_joint=None if mimic is None else mimic.get("joint"), + ) + child_links = {joint.child_link for joint in joints.values()} + roots = tuple(link_name for link_name in links if link_name not in child_links) + assert len(roots) == 1, f"URDF must have one root link, found {roots}" + return _UrdfModel( + links=links, + geometry_link_names=geometry_link_names, + joints=joints, + root_link=roots[0], + ) + + +def _children_by_link(model: _UrdfModel) -> dict[str, list[str]]: + """Index child links by their parent link in URDF joint order.""" + + children: dict[str, list[str]] = defaultdict(list) + for joint in model.joints.values(): + children[joint.parent_link].append(joint.child_link) + return children + + +def _self_collision_ignore( + model: _UrdfModel, + active_joint_names: tuple[str, ...], + collision_link_names: tuple[str, ...], + depth: int, +) -> dict[str, list[str]]: + """Derive symmetric collision exclusions from the active-joint topology. + + Args: + model: Full URDF link and joint topology. + active_joint_names: Joints that remain movable in this planning configuration. + collision_link_names: Links whose sphere pairs participate in collision checking. + depth: Maximum active-joint graph distance to exclude after merging inactive joints. + + Returns: + Ignored partners for each collision link. Links in the same rigid cluster are always + excluded; these are topology-based exclusions, not sampled collision observations. + """ + + parent = {link_name: link_name for link_name in model.links} + + def find(link_name: str) -> str: + """Return the rigid-cluster representative, compressing traversed parent links.""" + + while parent[link_name] != link_name: + parent[link_name] = parent[parent[link_name]] + link_name = parent[link_name] + return link_name + + def union(first: str, second: str) -> None: + """Merge two link clusters connected by an inactive joint.""" + + first_root, second_root = find(first), find(second) + if first_root != second_root: + parent[second_root] = first_root + + active = set(active_joint_names) + for joint in model.joints.values(): + if joint.name not in active: + union(joint.parent_link, joint.child_link) + adjacency: dict[str, set[str]] = defaultdict(set) + for joint_name in active_joint_names: + joint = model.joints[joint_name] + first, second = find(joint.parent_link), find(joint.child_link) + adjacency[first].add(second) + adjacency[second].add(first) + + result: dict[str, list[str]] = {link_name: [] for link_name in collision_link_names} + for index, first_link in enumerate(collision_link_names): + distances = {find(first_link): 0} + queue = deque(distances) + while queue: + cluster = queue.popleft() + if distances[cluster] == depth: + continue + for neighbor in adjacency[cluster]: + if neighbor not in distances: + distances[neighbor] = distances[cluster] + 1 + queue.append(neighbor) + for second_link in collision_link_names[index + 1 :]: + if distances.get(find(second_link), depth + 1) <= depth: + result[first_link].append(second_link) + result[second_link].append(first_link) + return result + + +def _self_collision_ignore_pairs_add( + ignore_by_link: dict[str, list[str]], + collision_link_names: tuple[str, ...], + pairs: Sequence[Sequence[str]], +) -> None: + """Validate explicit link pairs and add symmetric, canonically ordered exclusions.""" + + link_order = {name: index for index, name in enumerate(collision_link_names)} + link_names = set(link_order) + normalized: set[tuple[str, str]] = set() + for pair in pairs: + assert not isinstance(pair, str) and len(pair) == 2, "self-collision ignore pairs must contain two links" + first, second = pair + assert isinstance(first, str) and isinstance(second, str) and first and second + assert first != second, f"self-collision ignore pair repeats link {first!r}" + unknown = sorted({first, second} - link_names) + assert not unknown, f"self-collision ignore pair contains links outside the planning group: {unknown}" + if link_order[first] > link_order[second]: + first, second = second, first + assert (first, second) not in normalized, f"duplicate self-collision ignore pair: {(first, second)}" + normalized.add((first, second)) + + for first, second in sorted(normalized, key=lambda pair: (link_order[pair[0]], link_order[pair[1]])): + if second not in ignore_by_link[first]: + ignore_by_link[first].append(second) + if first not in ignore_by_link[second]: + ignore_by_link[second].append(first) + for ignored_links in ignore_by_link.values(): + ignored_links.sort(key=link_order.__getitem__) + + +def _sphere_dict(sphere: CollisionSphere | Mapping[str, object]) -> dict[str, object]: + """Validate and serialize one sphere as a cuRobo-compatible center/radius mapping.""" + + if isinstance(sphere, CollisionSphere): + return sphere.to_dict() + center = tuple(float(value) for value in sphere["center"]) + radius = float(sphere["radius"]) + return CollisionSphere(center=center, radius=radius).to_dict() diff --git a/autodata_interfaces/motion_planners/motion_planner_base.py b/autodata_interfaces/motion_planners/motion_planner_base.py index 8c8565d..d843092 100644 --- a/autodata_interfaces/motion_planners/motion_planner_base.py +++ b/autodata_interfaces/motion_planners/motion_planner_base.py @@ -11,6 +11,7 @@ # Defer Isaac Lab imports to type-checking time so this module can be imported in # sim-free contexts (e.g. unit tests that exercise only config or version detection). from autodata_interfaces.datastream.datastream import Datastream + from autodata_interfaces.embodiments.embodiment_types import NamedJointTrajectory class MotionPlannerBase(ABC): @@ -128,6 +129,13 @@ def get_planned_poses(self) -> list[Any]: planned_poses.append(pose) return planned_poses + def get_planned_joint_trajectory(self) -> NamedJointTrajectory | None: + """Return the complete joint path when the backend provides it. + + Returns: + Joint names and sampled positions [rad, m], or None when unavailable. + """ + @abstractmethod def reset_plan(self) -> None: """Reset the current plan and execution state. diff --git a/autodata_tests/interfaces/datastream/test_datastream.py b/autodata_tests/interfaces/datastream/test_datastream.py index 12d8fa1..d1c539f 100644 --- a/autodata_tests/interfaces/datastream/test_datastream.py +++ b/autodata_tests/interfaces/datastream/test_datastream.py @@ -343,3 +343,11 @@ def test_get_robot_root_pose(): def test_get_scene_state_passthrough(): datastream, _, _, _ = _datastream() assert datastream.get_scene_state(is_relative=True) is _SCENE_STATE_SENTINEL + + +def test_robot_joint_positions_preserve_requested_order(): + datastream, _, _, _ = _datastream() + assert torch.equal( + datastream.get_robot_joint_positions(env_ids=[0], joint_names=("j6", "j1")), + torch.tensor([[0.6, 0.1]]), + ) diff --git a/autodata_tests/interfaces/embodiments/test_bimanual_embodiment_adapter.py b/autodata_tests/interfaces/embodiments/test_bimanual_embodiment_adapter.py index 9e63324..cb53e30 100644 --- a/autodata_tests/interfaces/embodiments/test_bimanual_embodiment_adapter.py +++ b/autodata_tests/interfaces/embodiments/test_bimanual_embodiment_adapter.py @@ -5,10 +5,12 @@ import dataclasses import torch +from types import SimpleNamespace import pytest from autodata_interfaces.embodiments import AbsolutePoseWholeBodyBimanualAdapter, BimanualEefConfig, PoseObsKeys +from autodata_interfaces.embodiments.embodiment_types import NamedJointTrajectory from autodata_tests.interfaces.mocks import MockEnv from autodata_utils import pose_math @@ -52,6 +54,33 @@ def _bound(embodiment_adapter: AbsolutePoseWholeBodyBimanualAdapter, left_pos, r return embodiment_adapter +def test_coupled_joint_solving_delegates_named_targets_to_action(monkeypatch): + adapter = _embodiment_adapter() + adapter.planning_model_action_term = "arms" + captured = [] + expected = NamedJointTrajectory(("joint",), torch.zeros(2, 1)) + action = SimpleNamespace( + get_action_target_frame_names=lambda: ("left_frame", "right_frame"), + solve_joint_trajectory=lambda *args: captured.append(args) or expected, + ) + monkeypatch.setattr(adapter, "_planning_action_term", lambda: action) + monkeypatch.setattr(adapter, "get_joint_names", lambda: ["joint"]) + poses = {name: torch.eye(4).repeat(2, 1, 1) for name in ("left", "right")} + seeds = dict.fromkeys(poses, expected) + + def predicate(names, positions, sample): + return True + + result = adapter.solve_joint_trajectory(poses, seeds, torch.zeros(1), 0.01, 0.02, predicate, 3) + + assert result is expected + targets, proposals, initial, *options = captured[0] + assert tuple(targets) == tuple(proposals) == ("left_frame", "right_frame") + assert targets["left_frame"] is poses["left"] and proposals["right_frame"] is expected + assert initial.joint_names == ("joint",) and torch.equal(initial.positions, torch.zeros(1, 1)) + assert options == [0.01, 0.02, predicate, 3] + + # --------------------------------------------------------------------------------------------------- # action_dim # --------------------------------------------------------------------------------------------------- diff --git a/autodata_tests/interfaces/embodiments/test_embodiment_adapter.py b/autodata_tests/interfaces/embodiments/test_embodiment_adapter.py index f904ade..aa14d61 100644 --- a/autodata_tests/interfaces/embodiments/test_embodiment_adapter.py +++ b/autodata_tests/interfaces/embodiments/test_embodiment_adapter.py @@ -52,12 +52,32 @@ def test_get_joint_positions_all_and_indexed(): assert torch.equal(embodiment_adapter.get_joint_positions(env_ids=[1]), joint_pos[[1]]) +def test_get_joint_velocity_limits_all_and_indexed(): + speeds = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + env = _robot_env(torch.zeros(2, 2), ["j0", "j1"]) + env.scene["robot"].data.joint_vel_limits = speeds + adapter = _embodiment_adapter() + adapter.bind_env(env) + assert torch.equal(adapter.get_joint_velocity_limits(), speeds) + assert torch.equal(adapter.get_joint_velocity_limits(env_ids=[1]), speeds[[1]]) + + def test_get_joint_names(): embodiment_adapter = _embodiment_adapter() embodiment_adapter.bind_env(_robot_env(torch.zeros(1, 3), ["j0", "j1", "j2"])) assert embodiment_adapter.get_joint_names() == ["j0", "j1", "j2"] +def test_get_joint_positions_in_requested_order(): + adapter = _embodiment_adapter() + adapter.bind_env(_robot_env(torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), ["j0", "j1", "j2"])) + assert torch.equal(adapter.get_joint_positions([1], joint_names=("j2", "j0")), torch.tensor([[6.0, 4.0]])) + with pytest.raises(AssertionError, match="absent"): + adapter.get_joint_positions(joint_names=("missing",)) + with pytest.raises(AssertionError, match="unique"): + adapter.get_joint_positions(joint_names=("j0", "j0")) + + def test_joint_queries_require_bound_env(): with pytest.raises(AssertionError, match="bind_env"): _embodiment_adapter().get_joint_positions() diff --git a/autodata_tests/interfaces/embodiments/test_embodiment_types.py b/autodata_tests/interfaces/embodiments/test_embodiment_types.py index 60c8ad1..3cbd1fb 100644 --- a/autodata_tests/interfaces/embodiments/test_embodiment_types.py +++ b/autodata_tests/interfaces/embodiments/test_embodiment_types.py @@ -4,10 +4,22 @@ """Unit tests for :mod:`autodata_interfaces.embodiments.embodiment_types`.""" import dataclasses +import torch import pytest -from autodata_interfaces.embodiments.embodiment_types import PoseObsKeys +from autodata_interfaces.embodiments.embodiment_types import NamedJointTrajectory, PoseObsKeys + + +@pytest.mark.parametrize( + "positions", + [torch.empty(0, 1), torch.zeros(1, 2), torch.full((1, 1), float("nan"))], + ids=["empty", "wrong_joint_count", "nonfinite"], +) +def test_named_joint_trajectory_rejects_invalid_positions(positions): + """Reject invalid position arrays at construction, before planning uses them.""" + with pytest.raises(AssertionError): + NamedJointTrajectory(("joint",), positions) def test_pose_obs_keys_fields(): diff --git a/autodata_tests/interfaces/env/test_pink_ik_action.py b/autodata_tests/interfaces/env/test_pink_ik_action.py new file mode 100644 index 0000000..2c569a3 --- /dev/null +++ b/autodata_tests/interfaces/env/test_pink_ik_action.py @@ -0,0 +1,135 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""PhysX-to-URDF mimic conversion without constructing a simulator.""" + +import math +import numpy as np +import torch +import xml.etree.ElementTree as ET +from types import SimpleNamespace + +import pytest + +pytest.importorskip("isaaclab") +from pxr import Sdf, Usd, UsdGeom # noqa: E402 + +from autodata_interfaces.embodiments.embodiment_types import NamedJointTrajectory # noqa: E402 +from autodata_interfaces.env.pink_ik_action import ( # noqa: E402 + PinkInverseKinematicsAction, + PinkInverseKinematicsActionSharedUrdf, + _urdf_mimic_joints_sync, +) + + +def test_hand_action_order_does_not_follow_backend_joint_order(monkeypatch): + monkeypatch.setattr(PinkInverseKinematicsAction, "_initialize_joint_info", lambda self: None) + names = ["right_finger", "left_finger"] + + def find_joints(requested, *, preserve_order): + assert requested == names and preserve_order + return [4, 2], names + + action = object.__new__(PinkInverseKinematicsActionSharedUrdf) + action.cfg = SimpleNamespace(hand_joint_names=names) + action._asset = SimpleNamespace(find_joints=find_joints) + action._isaaclab_controlled_joint_ids = [0, 1] + action._isaaclab_controlled_joint_names = ["arm_a", "arm_b"] + + action._initialize_joint_info() + + assert action._controlled_joint_ids == [0, 1, 4, 2] + assert action._controlled_joint_names == ["arm_a", "arm_b", *names] + + +@pytest.mark.parametrize("valid", [True, False]) +def test_coupled_action_restores_targets_after_success_or_rejection(valid): + pin = pytest.importorskip("pinocchio") + frame = SimpleNamespace(frame="tool", transform_target_to_base=pin.SE3(np.eye(3), np.ones(3))) + + def set_frame_target(target): + frame.transform_target_to_base = target.copy() + + def frame_error(configuration): + return np.zeros(6) + + frame.set_target = set_frame_target + frame.compute_error = frame_error + posture = SimpleNamespace(target_q=np.array([0.3])) + + def set_posture_target(target): + posture.target_q = target.copy() + + posture.set_target = set_posture_target + configuration = SimpleNamespace( + q=np.zeros(1), + model=SimpleNamespace(lowerPositionLimit=np.array([-1.0]), upperPositionLimit=np.array([1.0])), + controlled_joint_names_pinocchio_order=("joint",), + ) + + def update_configuration(q): + configuration.q = q.copy() + + configuration.update = update_configuration + controller = SimpleNamespace( + cfg=SimpleNamespace(variable_input_tasks=(frame, posture), joint_names=("joint",), base_link_name="base"), + pink_configuration=configuration, + isaac_lab_to_pink_ordering=np.array([0]), + compute=lambda q, dt: torch.tensor(q.copy()), + update_null_space_joint_targets=posture.set_target, + init_joint_positions=np.zeros(1), + ) + action = object.__new__(PinkInverseKinematicsActionSharedUrdf) + action.cfg = SimpleNamespace(controller=SimpleNamespace(base_link_name="base")) + action._asset = SimpleNamespace(joint_names=["joint"]) + action._ik_controllers = [controller] + action._isaaclab_controlled_joint_names = ["joint"] + action._isaaclab_controlled_joint_ids = [0] + action._num_frame_tasks = 1 + action._sim_dt = 0.01 + action._env = SimpleNamespace(cfg=SimpleNamespace(decimation=1)) + + def base_link_pose(): + return torch.eye(4).unsqueeze(0) + + action._get_base_link_frame_transform = base_link_pose + initial = NamedJointTrajectory(("joint",), torch.zeros(1, 1)) + seeds = NamedJointTrajectory(("joint",), torch.zeros(2, 1)) + args = ({"tool": torch.eye(4).repeat(2, 1, 1)}, {"tool": seeds}, initial, 0.01, 0.02) + + assert action.get_action_target_frame_names() == ("tool",) + if valid: + result = action.solve_joint_trajectory(*args, lambda names, positions, sample: True) + assert result.joint_names == ("joint",) and torch.equal(result.positions, seeds.positions) + else: + with pytest.raises(AssertionError, match="Pink could not solve"): + action.solve_joint_trajectory(*args, lambda names, positions, sample: False) + assert np.array_equal(frame.transform_target_to_base.translation, np.ones(3)) + assert np.array_equal(posture.target_q, np.array([0.3])) + + +@pytest.mark.parametrize( + ("joint_type", "axis", "offset", "expected_offset"), + [("revolute", "rotZ", 30.0, -math.pi / 6.0), ("prismatic", "transX", 25.0, -0.25)], +) +def test_mimic_coefficients_match_physx_equation(tmp_path, joint_type, axis, offset, expected_offset): + path = tmp_path / "robot.usda" + stage = Usd.Stage.CreateNew(str(path)) + UsdGeom.SetStageMetersPerUnit(stage, 0.01) + prim = stage.DefinePrim("/robot/follower") + prim.SetMetadata("apiSchemas", Sdf.TokenListOp.CreateExplicit([f"PhysxMimicJointAPI:{axis}"])) + prim.CreateAttribute(f"physxMimicJoint:{axis}:gearing", Sdf.ValueTypeNames.Float).Set(-1.128) + prim.CreateAttribute(f"physxMimicJoint:{axis}:offset", Sdf.ValueTypeNames.Float).Set(offset) + stage.GetRootLayer().Save() + root = ET.fromstring( + f'' + '' + ) + + _urdf_mimic_joints_sync(root, str(path)) + mimic = root.find("joint[@name='follower']/mimic") + assert float(mimic.get("multiplier")) == pytest.approx(1.128) + assert float(mimic.get("offset")) == pytest.approx(expected_offset) + first_result = ET.tostring(root) + _urdf_mimic_joints_sync(root, str(path)) + assert ET.tostring(root) == first_result diff --git a/autodata_tests/interfaces/motion_planners/test_collision_spheres.py b/autodata_tests/interfaces/motion_planners/test_collision_spheres.py new file mode 100644 index 0000000..041cfee --- /dev/null +++ b/autodata_tests/interfaces/motion_planners/test_collision_spheres.py @@ -0,0 +1,63 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Collision geometry and generated model contracts.""" + +from autodata_interfaces.motion_planners.curobo import collision_spheres +from autodata_interfaces.motion_planners.curobo.robot_config import curobo_robot_config_create + + +def test_cache_reuses_geometry_and_invalidates_geometry_changes(tmp_path, monkeypatch): + calls = [] + + def fit(meshes, config, link_name): + calls.append(link_name) + return (collision_spheres.CollisionSphere((0.0, 0.0, 0.0), 0.1),) + + monkeypatch.setattr(collision_spheres, "_fit_link", fit) + model = tmp_path / "model.urdf" + cache = tmp_path / "cache" + + def load(name, size="1 1 1", origin="0 0 0", config=None): + model.write_text( + f'' + f'' + ) + return collision_spheres.collision_spheres_fit_urdf(model, cache_dir=cache, config=config) + + first = load("first_export") + assert load("another_export").cache_key == first.cache_key + assert calls == ["body"] + assert load("another_export", size="1 1 2").cache_key != first.cache_key + assert load("another_export", origin="0 0 1").cache_key != first.cache_key + assert ( + load("another_export", config=collision_spheres.CollisionSphereFitConfig(inflation_m=0.02)).cache_key + != first.cache_key + ) + assert len(calls) == 4 + + +def test_locked_auxiliary_joints_preserve_collision_geometry(tmp_path): + """Planning fixes the commanded hand without removing it from the collision model.""" + model = tmp_path / "model.urdf" + model.write_text( + '' + '' + '' + '' + '' + '' + '' + ) + spheres = {name: (collision_spheres.CollisionSphere((0.0, 0.0, 0.0), 0.01),) for name in ("tool", "finger")} + options = dict(auxiliary_joint_names=("finger",), attachment_sphere_count=0) + query = curobo_robot_config_create(model, "tool", {"shoulder": 0.1, "finger": -0.2}, spheres, **options) + planning = curobo_robot_config_create( + model, "tool", {"shoulder": 0.1, "finger": -0.2}, spheres, lock_auxiliary_joints=True, **options + ) + query, planning = query["robot_cfg"]["kinematics"], planning["robot_cfg"]["kinematics"] + assert query["cspace"]["joint_names"] == ["shoulder", "finger"] + assert planning["cspace"]["joint_names"] == ["shoulder"] + assert planning["lock_joints"] == {"finger": -0.2} + assert planning["collision_link_names"] == query["collision_link_names"] + assert planning["collision_spheres"] == query["collision_spheres"] diff --git a/autodata_tests/interfaces/motion_planners/test_curobo_planner_cfg.py b/autodata_tests/interfaces/motion_planners/test_curobo_planner_cfg.py index 7de22cd..d627909 100644 --- a/autodata_tests/interfaces/motion_planners/test_curobo_planner_cfg.py +++ b/autodata_tests/interfaces/motion_planners/test_curobo_planner_cfg.py @@ -7,6 +7,9 @@ downloaded. Skipped where ``curobo`` is unavailable. """ +import torch +from types import SimpleNamespace + import pytest # Skip on the specific submodule: a bare "curobo" can resolve to an unrelated namespace package. @@ -31,3 +34,30 @@ def test_planner_profile_registry_contents(): def test_from_profile_rejects_unknown_profile_name(): with pytest.raises(AssertionError, match="Unknown planner profile"): CuroboPlannerCfg.from_profile("franka_stack_cube_bin_typo") + + +@pytest.mark.parametrize("tool_override, expected", [(None, "panda_hand"), ("custom_tool", "custom_tool")]) +def test_attachment_capture_resolves_the_default_tool(tool_override, expected): + """Attachment metadata uses the model's tool unless an explicit override is configured.""" + from autodata_interfaces.motion_planners.curobo.curobo_planner import CuroboPlanner + + pose = SimpleNamespace( + inverse=lambda: SimpleNamespace(transform_points=lambda points: points), get_matrix=lambda: torch.eye(4) + ) + geometry = SimpleNamespace( + get_link_spheres=lambda link: torch.tensor([[0.0, 0.0, 0.0, 0.01], [0.0, 0.0, 0.0, -10.0]]) + ) + planner = SimpleNamespace( + config=SimpleNamespace( + attached_object_link_name="attached_object", ee_link_name=tool_override, surface_sphere_radius=0.01 + ), + robot_cfg={"kinematics": {"ee_link": "panda_hand"}}, + motion_gen=SimpleNamespace(kinematics=SimpleNamespace(kinematics_config=geometry)), + _object_collision_spheres={}, + ) + captured = CuroboPlanner._object_collision_spheres_capture( + planner, "cube", "/World/cube", SimpleNamespace(pose=pose) + ) + + assert captured.tool_frame == expected + assert len(captured.spheres) == 1 diff --git a/autodata_tests/interfaces/motion_planners/test_plan_visualizer.py b/autodata_tests/interfaces/motion_planners/test_plan_visualizer.py new file mode 100644 index 0000000..997976b --- /dev/null +++ b/autodata_tests/interfaces/motion_planners/test_plan_visualizer.py @@ -0,0 +1,70 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Planning playback uses one clock and keeps whole-robot checks separate.""" + +import numpy as np +import torch +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +pytest.importorskip("rerun") +pytest.importorskip("curobo.geom.sdf.world") + +from autodata_interfaces.motion_planners.curobo import plan_visualizer as module # noqa: E402 + + +@pytest.fixture +def visualizer(monkeypatch): + """Build a small kinematic preview without starting a simulator or viewer.""" + value = object.__new__(module.PlanVisualizer) + value.robot_name = "left" + value.debug = False + value.save_path = None + value._base_pose_in_env = np.eye(4) + value._world_scene = None + value._current_frame = 0 + value._plan_frame = 0 + value._active_plan_root = "world/plans" + value._sphere_entities = {"robot": [], "attached": [], "target": []} + value._motion_gen_ref = SimpleNamespace( + kinematics=SimpleNamespace( + get_robot_as_spheres=lambda q: [[SimpleNamespace(position=[float(q[0]), 0.0, 0.0], radius=0.01)]] + ) + ) + monkeypatch.setattr(module.rr, "log", Mock()) + monkeypatch.setattr(module.rr, "set_time", Mock()) + monkeypatch.setattr(module.rr, "send_blueprint", Mock()) + return value + + +@pytest.mark.parametrize("save_path", [None, "plans.rrd"]) +def test_consecutive_plans_share_playback_and_clear_previous_entities(visualizer, save_path): + """Live and saved previews animate both arms without stale markers or separate clocks.""" + visualizer.save_path = save_path + plan = SimpleNamespace(position=torch.tensor([[0.0], [1.0]])) + for arm in ("left", "right"): + visualizer.robot_name = arm + visualizer.visualize_plan(plan, torch.eye(4), ee_positions=np.zeros((2, 3))) + visualizer.animate_spheres_along_path(plan, robot_spheres_at_start=[object()], interpolation_steps=1) + assert visualizer._plan_frame == 4 + times = module.rr.set_time.call_args_list + assert {call.args[0] for call in times} == {"planning"} + assert {call.kwargs["sequence"] for call in times} == {0, 1, 2, 3} + logs = module.rr.log.call_args_list + assert not any(call.kwargs.get("static", False) for call in logs) + assert any(call.args[0] == "world/plans/0000_left" and isinstance(call.args[1], module.rr.Clear) for call in logs) + assert sum(call.args[0].endswith("/robot_animation") for call in logs) == 4 + module.rr.send_blueprint.assert_not_called() + + +def test_scheduled_robot_does_not_switch_planning_view(visualizer): + """The full-state preview keeps its own timeline without changing the selected view.""" + spheres = torch.tensor([[[0.0, 0.0, 0.0, 0.01]], [[1.0, 0.0, 0.0, 0.01]]]) + index = visualizer.animate_collision_spheres(spheres) + assert index == 0 + assert visualizer._plan_frame == 0 + assert {call.args[0] for call in module.rr.set_time.call_args_list} == {"full_state_schedule_0"} + module.rr.send_blueprint.assert_not_called() diff --git a/autodata_utils/pose_math.py b/autodata_utils/pose_math.py index f4dacfa..d064a66 100644 --- a/autodata_utils/pose_math.py +++ b/autodata_utils/pose_math.py @@ -196,3 +196,21 @@ def quat_unique(quat: torch.Tensor) -> torch.Tensor: assert quat.shape[-1] == 4, f"quat last dim must be 4, got {quat.shape[-1]}" sign = torch.where(quat[..., 3:4] < 0, -torch.ones_like(quat[..., 3:4]), torch.ones_like(quat[..., 3:4])) return quat * sign + + +def pose_errors(actual_poses: torch.Tensor, target_poses: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """Return translation [m] and geodesic rotation [rad] errors. + + Args: + actual_poses: Observed homogeneous poses with shape (..., 4, 4). + target_poses: Corresponding targets with the same shape. + + Returns: + Translation errors [m] and rotation errors [rad], each with the input batch shape. + """ + + assert actual_poses.shape == target_poses.shape and actual_poses.shape[-2:] == (4, 4) + position_error = torch.linalg.vector_norm(actual_poses[..., :3, 3] - target_poses[..., :3, 3], dim=-1) + relative_rotation = actual_poses[..., :3, :3].transpose(-1, -2) @ target_poses[..., :3, :3] + cosine = torch.clamp((relative_rotation.diagonal(dim1=-2, dim2=-1).sum(-1) - 1.0) * 0.5, -1.0, 1.0) + return position_error, torch.acos(cosine) From e09fba55d33794c321c8d657f65fb5e8e1f98fcd Mon Sep 17 00:00:00 2001 From: Neel Jawale Date: Tue, 17 Nov 2026 17:07:31 -0800 Subject: [PATCH 2/4] Fix multi-arm planner world state and legacy sampling Preserve obstacle enable states and object-relative geometry transforms in shared collision worlds. Keep optimized samples for legacy workflows and use the control period for named planning groups. Fix IK fallback, sphere fitting, fixed tool links, and Rerun timing. Signed-off-by: Neel Jawale --- .../bimanual_embodiment_adapter.py | 6 +- autodata_interfaces/env/pink_ik_action.py | 19 +- .../curobo/collision_spheres.py | 4 +- .../motion_planners/curobo/curobo_planner.py | 148 ++++++++++--- .../curobo/curobo_planner_cfg.py | 3 + .../motion_planners/curobo/plan_visualizer.py | 9 +- .../motion_planners/curobo/planner_factory.py | 18 +- .../motion_planners/curobo/robot_config.py | 17 +- .../test_bimanual_embodiment_adapter.py | 6 + .../interfaces/env/test_pink_ik_action.py | 23 ++- .../motion_planners/test_collision_spheres.py | 33 +++ .../test_curobo_planner_cfg.py | 6 + .../motion_planners/test_curobo_world.py | 194 ++++++++++++++++++ .../motion_planners/test_plan_visualizer.py | 19 ++ 14 files changed, 446 insertions(+), 59 deletions(-) create mode 100644 autodata_tests/interfaces/motion_planners/test_curobo_world.py diff --git a/autodata_interfaces/embodiments/bimanual_embodiment_adapter.py b/autodata_interfaces/embodiments/bimanual_embodiment_adapter.py index e92a1b5..15a426c 100644 --- a/autodata_interfaces/embodiments/bimanual_embodiment_adapter.py +++ b/autodata_interfaces/embodiments/bimanual_embodiment_adapter.py @@ -354,7 +354,8 @@ def set_joint_posture_target( joint_positions: Posture target with shape (J,) [rad, m]. env_id: Environment controller to update. """ - self._planning_action_term().set_joint_posture_target(joint_names, joint_positions, env_id) + if self.planning_model_action_term is not None: + self._planning_action_term().set_joint_posture_target(joint_names, joint_positions, env_id) def reset_joint_posture_target(self, env_id: int = 0) -> None: """Restore the planning action's default posture reference. @@ -362,7 +363,8 @@ def reset_joint_posture_target(self, env_id: int = 0) -> None: Args: env_id: Environment controller to update. """ - self._planning_action_term().reset_joint_posture_target(env_id) + if self.planning_model_action_term is not None: + self._planning_action_term().reset_joint_posture_target(env_id) def get_planning_root_pose( self, diff --git a/autodata_interfaces/env/pink_ik_action.py b/autodata_interfaces/env/pink_ik_action.py index 1b958e6..8b9c82e 100644 --- a/autodata_interfaces/env/pink_ik_action.py +++ b/autodata_interfaces/env/pink_ik_action.py @@ -191,6 +191,7 @@ def solve_joint_trajectory( current = initial_joint_positions.detach().cpu().numpy().copy() solutions: list[torch.Tensor] = [] from pink import solve_ik + from pink.exceptions import NoSolutionFound, NotWithinConfigurationLimits try: for sample in range(sample_count): @@ -214,13 +215,17 @@ def solve_joint_trajectory( current[np.asarray(controlled_ids)] = solution.detach().cpu().numpy() else: controller.pink_configuration.update(current[controller.isaac_lab_to_pink_ordering]) - velocity = solve_ik( - controller.pink_configuration, - frame_tasks, - self._sim_dt, - solver="daqp", - safety_break=controller.cfg.fail_on_joint_limit_violation, - ) + try: + velocity = solve_ik( + controller.pink_configuration, + frame_tasks, + self._sim_dt, + solver="daqp", + safety_break=controller.cfg.fail_on_joint_limit_violation, + ) + except (NoSolutionFound, NotWithinConfigurationLimits): + converged = False + break joint_delta = velocity * self._sim_dt current[np.asarray(controlled_ids)] += joint_delta[ controller.pink_to_isaac_lab_controlled_ordering diff --git a/autodata_interfaces/motion_planners/curobo/collision_spheres.py b/autodata_interfaces/motion_planners/curobo/collision_spheres.py index af093ab..40a26de 100644 --- a/autodata_interfaces/motion_planners/curobo/collision_spheres.py +++ b/autodata_interfaces/motion_planners/curobo/collision_spheres.py @@ -286,11 +286,11 @@ def _fit_link( tangent_mesh = tangent_mesh.convex_hull candidates = points[: config.candidates_per_geometry] centers, radii = trimesh.proximity.max_tangent_sphere(tangent_mesh, candidates) - radii = np.asarray(radii, dtype=np.float64) + config.inflation_m + radii = np.asarray(radii, dtype=np.float64) keep = np.isfinite(radii) & (radii > 0.0) & (radii <= 0.5 * np.linalg.norm(mesh.extents)) surface_parts.append(points) center_parts.append(np.asarray(centers, dtype=np.float64)[keep]) - radius_parts.append(radii[keep]) + radius_parts.append(radii[keep] + config.inflation_m) points = np.concatenate(surface_parts) centers = np.concatenate(center_parts) diff --git a/autodata_interfaces/motion_planners/curobo/curobo_planner.py b/autodata_interfaces/motion_planners/curobo/curobo_planner.py index 40e7a3d..8784807 100644 --- a/autodata_interfaces/motion_planners/curobo/curobo_planner.py +++ b/autodata_interfaces/motion_planners/curobo/curobo_planner.py @@ -319,8 +319,10 @@ def __init__( self.planning_root_frame_name = str(robot_cfg["kinematics"]["base_link"]) self.root_pose_source_frame_name = config.root_pose_source_frame_name - # Load world configuration using the config's method - world_cfg: WorldConfig = self.config.get_world_config() + # Named robot groups use the live stage unless a configured world is explicitly requested. + world_cfg: WorldConfig = ( + self.config.get_world_config() if self.config.include_configured_world else WorldConfig() + ) self._configured_world_config = world_cfg.get_collision_check_world() # Synchronize before rollout construction: exported zero velocities are not valid bounds. @@ -359,7 +361,6 @@ def __init__( world_coll_checker=collision_world_source.motion_gen.world_coll_checker, ) self._collision_world_owner: CuroboPlanner = collision_world_source or self - self._collision_world_active_context: CuroboPlanner | None = None self._kinematics = self.motion_gen.kinematics self._kinematic_robot_cfg = robot_cfg if config.kinematic_robot_config_file is not None: @@ -446,6 +447,9 @@ def __init__( # Cache object mappings # Only recompute when objects are added/removed, not when poses change self._cached_object_mappings: dict[str, str] | None = None + self._object_obstacle_transforms: dict[str, torch.Tensor] = ( + collision_world_source._object_obstacle_transforms if collision_world_source is not None else {} + ) # ===================================================================================== # DEVICE CONVERSION UTILITIES @@ -589,6 +593,13 @@ def _initialize_static_world(self, *, activate: bool = True) -> None: that don't change during the simulation. Dynamic objects are synchronized separately in update_world() to maintain performance. """ + if not activate: + owner = self._collision_world_owner + assert self.config.include_configured_world == owner.config.include_configured_world + assert self.planning_root_frame_name == owner.planning_root_frame_name + self._static_world_config = owner._static_world_config + return + _usd_mesh_missing_scales_fill(self.usd_helper.stage) # Prim scoping for obstacle extraction comes from the Datastream (collision-world source), # not from direct env access. @@ -621,19 +632,32 @@ def _initialize_static_world(self, *, activate: bool = True) -> None: combined_world.add_obstacle(obstacle) self._static_world_config = combined_world - if activate: - self._static_world_activate() + self._static_world_base_pose = self._base_pose_in_env.clone() + self.motion_gen.clear_world_cache() + self.motion_gen.update_world(self._static_world_config) - def _static_world_activate(self) -> None: - """Install this context's world in its shared fixed-capacity collision checker.""" + def _static_world_refresh(self) -> None: + """Keep shared world geometry in the current planning-root frame without resetting enable flags.""" owner = self._collision_world_owner - if owner._collision_world_active_context is self: + if owner is not self: + owner._refresh_base_frame_transform() + owner._static_world_refresh() + return + if torch.allclose(self._static_world_base_pose, self._base_pose_in_env, atol=1e-6, rtol=0.0): return - # Rebuild the cache so pinned cuRobo cannot retain an unlisted bootstrap cuboid. - owner.motion_gen.clear_world_cache() - owner.motion_gen.update_world(self._static_world_config) - owner._collision_world_active_context = self + transform = self._env_to_base_transform @ self._static_world_base_pose + world = self.motion_gen.world_coll_checker.world_model + for obstacle in world: + pose = self._make_pose(position=obstacle.pose[:3], quaternion=obstacle.pose[3:], quat_is_xyzw=False) + moved = transform.to(pose.position) @ pose.get_matrix().reshape(4, 4) + pose_list = self._object_pose_to_curobo_list(moved) + self.motion_gen.world_coll_checker.update_obstacle_pose( + obstacle.name, + self._make_pose(position=pose_list[:3], quaternion=pose_list[3:], quat_is_xyzw=False), + update_cpu_reference=True, + ) + self._static_world_base_pose = self._base_pose_in_env.clone() def _transform_world_config_to_base_frame(self, world_config: WorldConfig) -> None: """Express env-relative cuRobo obstacles in the live planning-root frame.""" @@ -1165,15 +1189,25 @@ def _world_obstacles_disabled(self, obstacle_paths: tuple[str, ...]) -> Iterator assert all( isinstance(path, str) and path and path == path.strip() for path in obstacle_paths ), "obstacle_paths must contain unique, non-empty, trimmed strings" - disabled_paths: list[str] = [] + checker = self.motion_gen.world_coll_checker + disabled_paths: list[tuple[str, bool]] = [] try: for path in obstacle_paths: - self.motion_gen.world_coll_checker.enable_obstacle(path, enable=False) - disabled_paths.append(path) + for names, tensors in ( + (getattr(checker, "_env_mesh_names", None), getattr(checker, "_mesh_tensor_list", None)), + (getattr(checker, "_env_obbs_names", None), getattr(checker, "_cube_tensor_list", None)), + ): + if names is not None and path in names[0]: + enabled = bool(tensors[2][0, names[0].index(path)].item()) + break + else: + raise KeyError(f"unknown collision obstacle {path!r}") + checker.enable_obstacle(path, enable=False) + disabled_paths.append((path, enabled)) yield finally: - for path in reversed(disabled_paths): - self.motion_gen.world_coll_checker.enable_obstacle(path, enable=True) + for path, enabled in reversed(disabled_paths): + checker.enable_obstacle(path, enable=enabled) def joint_positions_world_collision_witness( self, @@ -1334,7 +1368,8 @@ def get_object_pose(self, object_name: str) -> Pose | None: """Retrieve object pose from cuRobo's collision world model. Searches the collision world model for the specified object and returns its current - pose. This is useful for attachment calculations and debugging collision world state. + root pose, accounting for any child-geometry transform. This is used for attachment + calculations and debugging collision world state. The method handles both mesh and cuboid object types automatically. Args: @@ -1363,7 +1398,14 @@ def get_object_pose(self, object_name: str) -> Pose | None: for obj in obj_list: if obj.name and object_path == str(obj.name): if obj.pose is not None: - return Pose.from_list(obj.pose, tensor_args=self.tensor_args) + pose = Pose.from_list(obj.pose, tensor_args=self.tensor_args) + object_from_obstacle = self._object_obstacle_transform(object_name, object_path) + root_from_object = pose.get_matrix().reshape(4, 4) @ torch.linalg.inv(object_from_obstacle).to( + pose.position + ) + return Pose.from_list( + self._object_pose_to_curobo_list(root_from_object), tensor_args=self.tensor_args + ) self.logger.debug(f"Object {object_name} found in mappings but pose not available") return None @@ -1461,7 +1503,7 @@ def update_world(self, object_pose_overrides: Mapping[str, torch.Tensor] | None Updates all dynamic object poses in cuRobo's collision world to match their current positions in Isaac Lab. This ensures collision checking uses accurate object positions after simulation steps, resets, or manual object movements. Static world geometry - is loaded once during initialization and not updated here for performance. + is loaded once and re-expressed only when the planning root moves. The method validates that the set of objects hasn't changed at runtime, as cuRobo requires world model reinitialization when objects are added or removed. @@ -1477,7 +1519,7 @@ def update_world(self, object_pose_overrides: Mapping[str, torch.Tensor] | None # Refresh the env-relative -> robot base frame transform before syncing geometry, so # object, goal, and planned poses are reconciled against the current base pose. self._refresh_base_frame_transform() - self._static_world_activate() + self._static_world_refresh() # Establish validation baseline on first call, validate on subsequent calls if self._expected_objects is None: @@ -1575,11 +1617,10 @@ def _sync_object_poses_with_isaaclab( """ # Object poses enter in the Datastream's env-relative frame and are converted to the # planning-root frame before updating cuRobo's collision world. - object_mappings = self._get_object_mappings() world_model = self.motion_gen.world_coll_checker.world_model object_poses = self.datastream.get_object_poses(env_ids=[self.env_id]) pose_overrides = dict(object_pose_overrides or {}) - unknown_overrides = set(pose_overrides) - set(object_mappings) + unknown_overrides = set(pose_overrides) - set(object_poses) assert not unknown_overrides, f"object-pose overrides reference unknown obstacles: {sorted(unknown_overrides)}" static_objects = getattr(self.config, "static_objects", []) @@ -1587,7 +1628,7 @@ def _is_static(name: str) -> bool: return any(static_name in name.lower() for static_name in static_objects) updates: list[tuple[str, str, list[float]]] = [] - for object_name, object_path in object_mappings.items(): + for object_name in object_poses: if _is_static(object_name): continue if object_name in pose_overrides: @@ -1596,8 +1637,15 @@ def _is_static(name: str) -> bool: pose_env = object_poses[object_name][0] else: continue - pose_list = self._object_pose_to_curobo_list(self._pose_env_to_base(pose_env)) - updates.append((object_name, object_path, pose_list)) + try: + obstacle_paths = self.world_object_obstacle_paths(object_name) + except KeyError: + assert object_name not in pose_overrides, f"object-pose override has no obstacles: {object_name!r}" + continue + for object_path in obstacle_paths: + child_pose = pose_env @ self._object_obstacle_transform(object_name, object_path).to(pose_env) + pose_list = self._object_pose_to_curobo_list(self._pose_env_to_base(child_pose)) + updates.append((object_name, object_path, pose_list)) updated_count = 0 for object_name, object_path, pose_list in updates: @@ -1618,6 +1666,44 @@ def _is_static(name: str) -> bool: self.logger.debug(f"Updated {updated_count} object poses in collision checker") + def _object_obstacle_transform(self, object_name: str, obstacle_path: str) -> torch.Tensor: + """Cache the obstacle's rigid transform relative to its authored scene-object root. + + Args: + object_name: Scene object containing the obstacle. + obstacle_path: Collision-world name of the object's geometry prim. + + Returns: + Object-relative obstacle transform with shape ``(4, 4)`` [m]. + """ + from pxr import Gf, UsdGeom + + if obstacle_path not in self._object_obstacle_transforms: + stage = self.datastream.get_usd_stage() + root = stage.GetPrimAtPath(self.datastream.get_object_prim_path(object_name, self.env_id)) + env = stage.GetPrimAtPath(self.datastream.get_env_prim_path(self.env_id)) + authored = Gf.Transform(UsdGeom.XformCache().ComputeRelativeTransform(root, env)[0]) + env_from_object = torch.eye(4, device=self.datastream.device) + env_from_object[:3, :3] = torch.as_tensor( + np.asarray(Gf.Matrix4d().SetRotate(authored.GetRotation()))[:3, :3].T.copy(), + dtype=env_from_object.dtype, + device=env_from_object.device, + ) + env_from_object[:3, 3] = env_from_object.new_tensor(tuple(authored.GetTranslation())) + obstacle = next( + value for value in self.motion_gen.world_coll_checker.world_model if value.name == obstacle_path + ) + root_from_obstacle = ( + self._make_pose(position=obstacle.pose[:3], quaternion=obstacle.pose[3:], quat_is_xyzw=False) + .get_matrix() + .reshape(4, 4) + .to(env_from_object) + ) + self._object_obstacle_transforms[obstacle_path] = ( + torch.linalg.inv(env_from_object) @ self._base_pose_in_env @ root_from_obstacle + ) + return self._object_obstacle_transforms[obstacle_path] + def _object_pose_to_curobo_list(self, pose_mat: torch.Tensor) -> list[float]: """Decompose a 4x4 pose into cuRobo's ``[x, y, z, qw, qx, qy, qz]`` list. @@ -2715,9 +2801,10 @@ def _plan_to_contact_pose( self.motion_gen.rollout_fn.robot_self_collision_constraint.enable_cost() if result.success.item(): - # The optimizer's sample period can differ from the controller's fixed period. - self._current_plan = result.get_interpolated_plan() - self.logger.debug(f"Using interpolated plan with {len(self._current_plan.position)} waypoints") + self._current_plan = ( + result.get_interpolated_plan() if self.config.interpolate_plan else result.optimized_plan + ) + self.logger.debug(f"Using plan with {len(self._current_plan.position)} waypoints") self._current_plan = self._planning_joint_state_expand(self._current_plan) common_js_names: list[str] = [ @@ -2861,6 +2948,7 @@ def _plan_to_contact( device=position.device, dtype=position.dtype, ) + offset = self._env_to_base_transform[:3, :3].to(offset) @ offset retreat_pose = self._make_pose( position=position + offset, quaternion=ee_pose.quaternion, @@ -2881,6 +2969,7 @@ def _plan_to_contact( device=position.device, dtype=position.dtype, ) + offset = self._env_to_base_transform[:3, :3].to(offset) @ offset approach_pose = self._make_pose( position=position + offset, quaternion=goal_pose.quaternion, @@ -3467,6 +3556,7 @@ def _set_gripper_state(self, has_attached_objects: bool) -> None: if not locked_joints: return self.motion_gen.update_locked_joints(locked_joints, self.robot_cfg) + self._joint_limits_sync(self.motion_gen.kinematics.get_joint_limits()) def _count_active_spheres(self) -> dict[str, int]: """Count active collision spheres by category for debugging. diff --git a/autodata_interfaces/motion_planners/curobo/curobo_planner_cfg.py b/autodata_interfaces/motion_planners/curobo/curobo_planner_cfg.py index 229e81b..b86fa87 100644 --- a/autodata_interfaces/motion_planners/curobo/curobo_planner_cfg.py +++ b/autodata_interfaces/motion_planners/curobo/curobo_planner_cfg.py @@ -114,6 +114,9 @@ class CuroboPlannerCfg: interpolation_dt: float = 0.05 """Time step for interpolating waypoints.""" + interpolate_plan: bool = False + """Return controller-rate samples; False preserves legacy SkillGen optimizer waypoints.""" + max_joint_velocity: float | None = None """Optional planning speed cap [rad/s, m/s], also bounded by the live actuator limits.""" diff --git a/autodata_interfaces/motion_planners/curobo/plan_visualizer.py b/autodata_interfaces/motion_planners/curobo/plan_visualizer.py index 62b9df2..899d424 100644 --- a/autodata_interfaces/motion_planners/curobo/plan_visualizer.py +++ b/autodata_interfaces/motion_planners/curobo/plan_visualizer.py @@ -161,6 +161,7 @@ def __init__( # Store visualization state self._current_frame = 0 self._plan_frame = 0 + self._schedule_timelines: dict[int, str] = {} self._active_plan_root = "world/plans" self._world_scene = None self._sphere_entities: dict[str, list[str]] = {"robot": [], "attached": [], "target": []} @@ -703,6 +704,9 @@ def animate_plan( not attempt to render the full robot geometry—only key points—keeping the data transfer to the viewer minimal. + End-effector markers share the current interval with :meth:`animate_spheres_along_path`, + which advances the planning cursor after both overlays have been logged. + Args: ee_positions: Array of shape (T, 3) with planner-base end-effector positions. object_positions: Mapping from object name to an array (T, 3) with that @@ -770,6 +774,7 @@ def animate_collision_spheres( index = self._current_frame self._current_frame += 1 timeline = f"{timeline_prefix}_{index}" + self._schedule_timelines[index] = timeline entity_path = f"world/schedules/{index:04d}/robot_spheres" rr.reset_time() @@ -801,7 +806,7 @@ def animate_object_collision_spheres(self, spheres: torch.Tensor, *, schedule_in assert spheres.ndim == 3 and spheres.shape[-1] == 4 and len(spheres) > 0 assert type(schedule_index) is int and schedule_index >= 0 values = spheres.detach().cpu().numpy() - timeline = f"full_state_schedule_{schedule_index}" + timeline = self._schedule_timelines[schedule_index] entity_path = f"world/schedules/{schedule_index:04d}/object_spheres" for tick, frame in enumerate(values): valid = np.isfinite(frame).all(axis=1) & (frame[:, 3] > 0.0) @@ -1029,5 +1034,5 @@ def set_motion_generator_reference(self, motion_gen: Any) -> None: def mark_idle(self) -> None: """Clear the active arm preview between episodes, retaining its recorded history.""" - self._clear_visualization() self._plan_frame += 1 + self._clear_visualization() diff --git a/autodata_interfaces/motion_planners/curobo/planner_factory.py b/autodata_interfaces/motion_planners/curobo/planner_factory.py index 441f546..9642f1e 100644 --- a/autodata_interfaces/motion_planners/curobo/planner_factory.py +++ b/autodata_interfaces/motion_planners/curobo/planner_factory.py @@ -65,6 +65,7 @@ _SPHERE_FIT_KEYS = set(CollisionSphereFitConfig.__dataclass_fields__) _PLANNER_KEYS = { "world_config_file", + "include_configured_world", "static_objects", "world_ignore_substrings", "num_trajopt_seeds", @@ -127,6 +128,9 @@ def curobo_planning_context_create( ) -> CuroboPlanningContext: """Build arm-local planners and one collision-only full-state context. + All contexts use live-stage obstacles. Set ``planner.include_configured_world`` in + the description to also load ``world_config_file``. Plan samples use the environment's control period. + Args: datastream: Bound environment, embodiment and task interface. description_path: Planning-groups YAML file. @@ -220,6 +224,9 @@ def _curobo_planners_create( assert type(env_id) is int and env_id >= 0, "env_id must be non-negative" description = _description_load(description_path) + planner_settings = dict(description["planner"]) + planner_settings["interpolation_dt"] = float(datastream.get_env().step_dt) + planner_settings.setdefault("include_configured_world", False) _action_target_frames_validate(datastream, description["planning_groups"]) controller_model_path = datastream.get_robot_planning_model_path() assert ( @@ -331,14 +338,16 @@ def _curobo_planners_create( planning_group_name=group_name, ee_link_name=tool_link, root_pose_source_frame_name=description["root_pose_source_frame"], - include_configured_world=True, initial_auxiliary_joint_positions=initial_auxiliary_positions, - hand_link_names=list(chains[group_name].contact_link_names), + hand_link_names=[ + name for name in chains[group_name].contact_link_names if name in collision_links_by_group[group_name] + ], attached_object_link_name=ATTACHED_OBJECT_LINK_NAME, extra_collision_spheres={}, visualize_plan=False, visualize_spheres=False, - **description["planner"], + interpolate_plan=True, + **planner_settings, ) eef_name = group["eef_name"] planners[eef_name] = CuroboPlanner(datastream=datastream, config=planner_config, env_id=env_id) @@ -375,13 +384,12 @@ def _curobo_planners_create( planning_group_name=f"{description['name']}_full_state", ee_link_name=tool_links[0], root_pose_source_frame_name=description["root_pose_source_frame"], - include_configured_world=False, extra_collision_spheres={}, visualize_plan=False, visualize_spheres=False, planning_enabled=False, use_native_self_collision=False, - **description["planner"], + **planner_settings, ) full_state = CuroboPlanner( datastream=datastream, diff --git a/autodata_interfaces/motion_planners/curobo/robot_config.py b/autodata_interfaces/motion_planners/curobo/robot_config.py index 907acd6..9b7c819 100644 --- a/autodata_interfaces/motion_planners/curobo/robot_config.py +++ b/autodata_interfaces/motion_planners/curobo/robot_config.py @@ -238,15 +238,14 @@ def curobo_arm_chain( - contact_joints ): contact_joints.update(followers) - contact_links = {tool_link} - for joint_name in contact_joints: - queue = deque([model.joints[joint_name].child_link]) - while queue: - link_name = queue.popleft() - if link_name in contact_links: - continue - contact_links.add(link_name) - queue.extend(children[link_name]) + contact_links: set[str] = set() + queue = deque([tool_link, *(model.joints[name].child_link for name in contact_joints)]) + while queue: + link_name = queue.popleft() + if link_name in contact_links: + continue + contact_links.add(link_name) + queue.extend(children[link_name]) owned_collision_links = ({root_name, *(joint.child_link for joint in chain)} | contact_links) & collision_links return CuroboArmChain( root_link=root_name, diff --git a/autodata_tests/interfaces/embodiments/test_bimanual_embodiment_adapter.py b/autodata_tests/interfaces/embodiments/test_bimanual_embodiment_adapter.py index cb53e30..1c3f620 100644 --- a/autodata_tests/interfaces/embodiments/test_bimanual_embodiment_adapter.py +++ b/autodata_tests/interfaces/embodiments/test_bimanual_embodiment_adapter.py @@ -54,6 +54,12 @@ def _bound(embodiment_adapter: AbsolutePoseWholeBodyBimanualAdapter, left_pos, r return embodiment_adapter +def test_optional_posture_hooks_do_not_require_a_planning_action(): + adapter = _embodiment_adapter() + adapter.set_joint_posture_target(("joint",), torch.zeros(1)) + adapter.reset_joint_posture_target() + + def test_coupled_joint_solving_delegates_named_targets_to_action(monkeypatch): adapter = _embodiment_adapter() adapter.planning_model_action_term = "arms" diff --git a/autodata_tests/interfaces/env/test_pink_ik_action.py b/autodata_tests/interfaces/env/test_pink_ik_action.py index 2c569a3..37907d5 100644 --- a/autodata_tests/interfaces/env/test_pink_ik_action.py +++ b/autodata_tests/interfaces/env/test_pink_ik_action.py @@ -8,6 +8,7 @@ import torch import xml.etree.ElementTree as ET from types import SimpleNamespace +from unittest.mock import Mock import pytest @@ -42,8 +43,8 @@ def find_joints(requested, *, preserve_order): assert action._controlled_joint_names == ["arm_a", "arm_b", *names] -@pytest.mark.parametrize("valid", [True, False]) -def test_coupled_action_restores_targets_after_success_or_rejection(valid): +@pytest.mark.parametrize("valid, failed_seed", [(True, False), (False, False), (True, True)]) +def test_coupled_action_restores_targets_after_success_or_rejection(valid, failed_seed, monkeypatch): pin = pytest.importorskip("pinocchio") frame = SimpleNamespace(frame="tool", transform_target_to_base=pin.SE3(np.eye(3), np.ones(3))) @@ -72,7 +73,12 @@ def update_configuration(q): configuration.update = update_configuration controller = SimpleNamespace( - cfg=SimpleNamespace(variable_input_tasks=(frame, posture), joint_names=("joint",), base_link_name="base"), + cfg=SimpleNamespace( + variable_input_tasks=(frame, posture), + joint_names=("joint",), + base_link_name="base", + fail_on_joint_limit_violation=True, + ), pink_configuration=configuration, isaac_lab_to_pink_ordering=np.array([0]), compute=lambda q, dt: torch.tensor(q.copy()), @@ -95,6 +101,15 @@ def base_link_pose(): action._get_base_link_frame_transform = base_link_pose initial = NamedJointTrajectory(("joint",), torch.zeros(1, 1)) seeds = NamedJointTrajectory(("joint",), torch.zeros(2, 1)) + if failed_seed: + from pink.exceptions import NoSolutionFound + + error = NoSolutionFound.__new__(NoSolutionFound) + Exception.__init__(error, "invalid seed") + solver = Mock(side_effect=error) + monkeypatch.setattr("pink.solve_ik", solver) + frame.compute_error = lambda configuration: np.zeros(6) if configuration.q[0] > 0.5 else np.ones(6) + seeds = NamedJointTrajectory(("joint",), torch.ones(2, 1)) args = ({"tool": torch.eye(4).repeat(2, 1, 1)}, {"tool": seeds}, initial, 0.01, 0.02) assert action.get_action_target_frame_names() == ("tool",) @@ -106,6 +121,8 @@ def base_link_pose(): action.solve_joint_trajectory(*args, lambda names, positions, sample: False) assert np.array_equal(frame.transform_target_to_base.translation, np.ones(3)) assert np.array_equal(posture.target_q, np.array([0.3])) + if failed_seed: + solver.assert_called_once() @pytest.mark.parametrize( diff --git a/autodata_tests/interfaces/motion_planners/test_collision_spheres.py b/autodata_tests/interfaces/motion_planners/test_collision_spheres.py index 041cfee..cd6b7db 100644 --- a/autodata_tests/interfaces/motion_planners/test_collision_spheres.py +++ b/autodata_tests/interfaces/motion_planners/test_collision_spheres.py @@ -61,3 +61,36 @@ def test_locked_auxiliary_joints_preserve_collision_geometry(tmp_path): assert planning["lock_joints"] == {"finger": -0.2} assert planning["collision_link_names"] == query["collision_link_names"] assert planning["collision_spheres"] == query["collision_spheres"] + + +def test_small_geometry_keeps_valid_candidates_before_inflation(monkeypatch): + import numpy as np + import trimesh + + monkeypatch.setattr( + trimesh.proximity, + "max_tangent_sphere", + lambda mesh, points: (np.zeros_like(points), np.full(len(points), 0.005)), + ) + spheres = collision_spheres._fit_link( + (trimesh.creation.box(extents=(0.01, 0.01, 0.01)),), + collision_spheres.CollisionSphereFitConfig(inflation_m=0.01), + "small_link", + ) + assert spheres and all(sphere.radius == 0.015 for sphere in spheres) + + +def test_fixed_tool_descendants_keep_their_collision_geometry(tmp_path): + from autodata_interfaces.motion_planners.curobo.robot_config import curobo_arm_chain + + model = tmp_path / "fixed_finger.urdf" + model.write_text( + '' + '' + '' + '' + '' + ) + chain = curobo_arm_chain(model, "tool") + assert "finger" in chain.collision_link_names + assert "finger" in chain.contact_link_names diff --git a/autodata_tests/interfaces/motion_planners/test_curobo_planner_cfg.py b/autodata_tests/interfaces/motion_planners/test_curobo_planner_cfg.py index d627909..b103ca7 100644 --- a/autodata_tests/interfaces/motion_planners/test_curobo_planner_cfg.py +++ b/autodata_tests/interfaces/motion_planners/test_curobo_planner_cfg.py @@ -36,6 +36,12 @@ def test_from_profile_rejects_unknown_profile_name(): CuroboPlannerCfg.from_profile("franka_stack_cube_bin_typo") +def test_legacy_defaults_keep_configured_world_and_optimized_samples(): + config = CuroboPlannerCfg() + assert config.include_configured_world + assert not config.interpolate_plan + + @pytest.mark.parametrize("tool_override, expected", [(None, "panda_hand"), ("custom_tool", "custom_tool")]) def test_attachment_capture_resolves_the_default_tool(tool_override, expected): """Attachment metadata uses the model's tool unless an explicit override is configured.""" diff --git a/autodata_tests/interfaces/motion_planners/test_curobo_world.py b/autodata_tests/interfaces/motion_planners/test_curobo_world.py new file mode 100644 index 0000000..8c1cfc0 --- /dev/null +++ b/autodata_tests/interfaces/motion_planners/test_curobo_world.py @@ -0,0 +1,194 @@ +# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Collision-world frames, obstacle state and plan sampling without simulator startup.""" + +import math +import torch +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +pytest.importorskip("curobo.geom.sdf.world") +from curobo.geom.types import Cuboid, WorldConfig # noqa: E402 +from curobo.types.base import TensorDeviceType # noqa: E402 +from pxr import Usd, UsdGeom # noqa: E402 + +from autodata_interfaces.motion_planners.curobo.curobo_planner import CuroboPlanner # noqa: E402 + + +def _planner(world): + """Create a CPU-only planner shell with a mutable native world and enable flags.""" + planner = object.__new__(CuroboPlanner) + planner.tensor_args = TensorDeviceType(device=torch.device("cpu")) + planner.env_id = 0 + planner.logger = Mock() + planner.datastream = SimpleNamespace(device="cpu") + planner.config = SimpleNamespace(static_objects=[], include_configured_world=True) + planner._base_pose_in_env = torch.eye(4) + planner._env_to_base_transform = torch.eye(4) + planner._base_frame_is_identity = True + planner._static_world_base_pose = torch.eye(4) + planner._static_world_config = world + planner._collision_world_owner = planner + planner._cached_object_mappings = None + planner._object_obstacle_transforms = {} + planner.primitive_types = ["cuboid"] + names = [obstacle.name for obstacle in world.cuboid or []] + flags = torch.ones(1, len(names), dtype=torch.uint8) + + def enable(name, enable=True): + flags[0, names.index(name)] = enable + + def update(name, pose, **kwargs): + next(obstacle for obstacle in world if obstacle.name == name).pose = planner._object_pose_to_curobo_list( + pose.get_matrix().reshape(4, 4) + ) + + checker = SimpleNamespace( + world_model=world, + _env_obbs_names=[names], + _cube_tensor_list=[None, None, flags], + enable_obstacle=enable, + update_obstacle_pose=update, + ) + planner.motion_gen = SimpleNamespace(world_coll_checker=checker) + return planner, flags + + +def test_nested_exclusions_restore_the_original_enable_flags(): + world = WorldConfig( + cuboid=[Cuboid(name=name, pose=[0, 0, 0, 1, 0, 0, 0], dims=[1, 1, 1]) for name in ("held", "wall")] + ) + planner, flags = _planner(world) + flags[0, 0] = 0 + with planner._world_obstacles_disabled(("held", "wall")): + with planner._world_obstacles_disabled(("wall",)): + assert not flags.any() + assert not flags.any() + assert flags.tolist() == [[0, 1]] + + +def test_shared_context_keeps_the_owner_world_and_disabled_obstacles(): + world = WorldConfig(cuboid=[Cuboid(name="held", pose=[0, 0, 0, 1, 0, 0, 0], dims=[1, 1, 1])]) + owner, flags = _planner(world) + flags.zero_() + shared, _ = _planner(WorldConfig()) + owner.planning_root_frame_name = shared.planning_root_frame_name = "base" + shared._collision_world_owner = owner + shared._initialize_static_world(activate=False) + assert shared._static_world_config is world + assert not flags.any() + + +@pytest.mark.parametrize("rotate", [False, True]) +def test_root_motion_reexpresses_the_world_without_reenabling_obstacles(rotate): + world = WorldConfig(cuboid=[Cuboid(name="wall", pose=[3, 0, 0, 1, 0, 0, 0], dims=[1, 1, 1])]) + planner, flags = _planner(world) + flags.zero_() + planner._base_pose_in_env[0, 3] = 1 + if rotate: + planner._base_pose_in_env[:3, :3] = torch.tensor([[0, -1, 0], [1, 0, 0], [0, 0, 1]]) + planner._env_to_base_transform = torch.linalg.inv(planner._base_pose_in_env) + planner._static_world_refresh() + expected = [0, -2, 0] if rotate else [2, 0, 0] + assert world.cuboid[0].pose[:3] == pytest.approx(expected, abs=1e-6) + assert not flags.any() + planner._static_world_refresh() + assert world.cuboid[0].pose[:3] == pytest.approx(expected, abs=1e-6) + + +@pytest.mark.parametrize("child_count", [1, 2]) +@pytest.mark.parametrize("rotate", [False, True]) +def test_object_pose_sync_preserves_child_offsets_and_compound_geometry(child_count, rotate): + root_path = "/World/envs/env_0/Object" + stage = Usd.Stage.CreateInMemory() + env = UsdGeom.Xform.Define(stage, "/World/envs/env_0") + root = UsdGeom.Xform.Define(stage, root_path) + root.AddTranslateOp().Set((3, 0, 0)) + if rotate: + root.AddRotateZOp().Set(90) + world = WorldConfig( + cuboid=[ + Cuboid( + name=f"{root_path}/part{index}", + pose=( + [3, index / 4, 0, math.sqrt(0.5), 0, 0, math.sqrt(0.5)] + if rotate + else [3 + index / 4, 0, 0, 1, 0, 0, 0] + ), + dims=[0.1] * 3, + ) + for index in range(1, child_count + 1) + ] + ) + planner, _ = _planner(world) + live_pose = torch.eye(4) + live_pose[0, 3] = 10 + planner.datastream = SimpleNamespace( + device="cpu", + get_usd_stage=lambda: stage, + get_env_prim_path=lambda index: str(env.GetPath()), + get_object_prim_path=lambda name, index: root_path, + get_object_poses=lambda **kwargs: {"object": live_pose.unsqueeze(0)}, + ) + planner._sync_object_poses_with_isaaclab() + assert [obstacle.pose[0] for obstacle in world] == pytest.approx( + [10 + index / 4 for index in range(1, child_count + 1)] + ) + if child_count == 1: + assert torch.allclose(planner.get_object_pose("object").position, torch.tensor([[10.0, 0, 0]])) + else: + assert planner._get_object_mappings() == {} + + +@pytest.mark.parametrize("retreat, approach", [(1.0, 0.0), (0.0, 1.0)]) +def test_world_offsets_are_rotated_into_the_planning_frame(retreat, approach): + planner, _ = _planner(WorldConfig()) + planner.config = SimpleNamespace(approach_direction=(0, 0, -1), approach_retreat_frame="world") + planner._env_to_base_transform[:3, :3] = torch.tensor([[1, 0, 0], [0, 0, 1], [0, -1, 0]]) + goal = planner._make_pose(position=[0, 0, 0]) + planner.get_ee_pose = lambda state: goal + planner._plan_to_contact_pose = Mock(return_value=False) + assert not planner._plan_to_contact(None, goal, retreat, approach) + target = planner._plan_to_contact_pose.call_args.kwargs["goal_pose"] + assert torch.allclose(target.position, torch.tensor([[0.0, 1.0, 0.0]])) + + +def test_gripper_lock_reapplies_live_joint_limits(): + planner, _ = _planner(WorldConfig()) + planner.config = SimpleNamespace(gripper_closed_positions={"finger": 0.1}) + planner.robot_cfg = {} + planner.motion_gen.update_locked_joints = Mock() + planner.motion_gen.kinematics = SimpleNamespace(get_joint_limits=lambda: "limits") + planner._joint_limits_sync = Mock() + planner._set_gripper_state(True) + planner._joint_limits_sync.assert_called_once_with("limits") + + +@pytest.mark.parametrize("interpolate", [False, True]) +def test_legacy_and_controller_rate_plan_sampling_are_explicit(interpolate): + planner, _ = _planner(WorldConfig()) + planner.config = SimpleNamespace(hand_link_names=[], planning_group_name="arm", interpolate_plan=interpolate) + planner.datastream.get_robot_joint_names = lambda: ["joint"] + optimized = SimpleNamespace(position=torch.zeros(2, 1), joint_names=["joint"]) + interpolated = SimpleNamespace(position=torch.zeros(5, 1), joint_names=["joint"]) + for value in (optimized, interpolated): + value.get_ordered_joint_state = lambda names, value=value: value + planner.motion_gen.plan_single = Mock( + return_value=SimpleNamespace( + success=torch.tensor(True), + optimized_plan=optimized, + get_interpolated_plan=lambda: interpolated, + ) + ) + planner.motion_gen.rollout_fn = SimpleNamespace( + primitive_collision_constraint=Mock(), + robot_self_collision_constraint=Mock(), + ) + planner._count_active_spheres = lambda: {"total": 0, "robot_links": 0, "attached_objects": 0} + planner._planning_joint_state_expand = lambda state: state + planner.plan_config = None + assert planner._plan_to_contact_pose(None, None, contact=False) + assert planner.current_plan is (interpolated if interpolate else optimized) diff --git a/autodata_tests/interfaces/motion_planners/test_plan_visualizer.py b/autodata_tests/interfaces/motion_planners/test_plan_visualizer.py index 997976b..da78e6f 100644 --- a/autodata_tests/interfaces/motion_planners/test_plan_visualizer.py +++ b/autodata_tests/interfaces/motion_planners/test_plan_visualizer.py @@ -27,6 +27,7 @@ def visualizer(monkeypatch): value._world_scene = None value._current_frame = 0 value._plan_frame = 0 + value._schedule_timelines = {} value._active_plan_root = "world/plans" value._sphere_entities = {"robot": [], "attached": [], "target": []} value._motion_gen_ref = SimpleNamespace( @@ -68,3 +69,21 @@ def test_scheduled_robot_does_not_switch_planning_view(visualizer): assert visualizer._plan_frame == 0 assert {call.args[0] for call in module.rr.set_time.call_args_list} == {"full_state_schedule_0"} module.rr.send_blueprint.assert_not_called() + + +def test_end_effector_markers_share_the_sphere_animation_interval(visualizer): + visualizer.animate_plan(np.zeros((3, 3))) + assert visualizer._plan_frame == 0 + visualizer.animate_spheres_along_path( + SimpleNamespace(position=torch.zeros(3, 1)), robot_spheres_at_start=[object()], interpolation_steps=1 + ) + assert visualizer._plan_frame == 3 + visualizer.mark_idle() + assert visualizer._plan_frame == 4 + + +def test_object_overlay_uses_the_custom_robot_timeline(visualizer): + spheres = torch.tensor([[[0.0, 0.0, 0.0, 0.01]]]) + index = visualizer.animate_collision_spheres(spheres, timeline_prefix="inspection") + visualizer.animate_object_collision_spheres(spheres, schedule_index=index) + assert {call.args[0] for call in module.rr.set_time.call_args_list} == {"inspection_0"} From cdf357fdc8c64344dc3e3107b76c259e5c866108 Mon Sep 17 00:00:00 2001 From: Neel Jawale Date: Thu, 19 Nov 2026 09:45:46 -0800 Subject: [PATCH 3/4] Address planner interface and collision review comments Use native self-collision padding offsets, reject mixed reference frames, and align object prim queries with the object inventory. Reuse pose error calculations, clarify model roles, support saved planner recordings, and add focused regressions. Signed-off-by: Neel Jawale --- autodata_interfaces/datastream/datastream.py | 25 +++++++---- .../motion_planners/curobo/curobo_planner.py | 19 ++++---- .../curobo/curobo_planner_cfg.py | 11 ++++- .../interfaces/datastream/test_datastream.py | 21 ++++++++- .../motion_planners/test_curobo_world.py | 45 +++++++++++++++++++ .../motion_planners/test_plan_visualizer.py | 13 ++++++ 6 files changed, 113 insertions(+), 21 deletions(-) diff --git a/autodata_interfaces/datastream/datastream.py b/autodata_interfaces/datastream/datastream.py index 3ad5afa..f92f001 100644 --- a/autodata_interfaces/datastream/datastream.py +++ b/autodata_interfaces/datastream/datastream.py @@ -233,7 +233,6 @@ def get_robot_eef_pose(self, env_ids: Sequence[int] | None, eef_name: str) -> to def get_robot_joint_positions( self, env_ids: Sequence[int] | None = None, - *, joint_names: Sequence[str] | None = None, ) -> torch.Tensor: """Read joint positions [rad, m] through the embodiment adapter. @@ -417,7 +416,7 @@ def actions_to_passthrough_actions(self, actions: torch.Tensor) -> dict[str, tor def passthrough_actions_to_joint_positions( self, passthrough_action_dict: dict[str, torch.Tensor] ) -> dict[str, torch.Tensor]: - """Apply passthrough commands as externally controlled articulation positions.""" + """Convert passthrough commands to named joint positions without changing robot state.""" return self.embodiment_adapter.passthrough_actions_to_joint_positions(passthrough_action_dict) @@ -610,24 +609,32 @@ def get_env_prim_path(self, env_id: int) -> str: return f"/World/envs/env_{env_id}" def get_object_prim_path(self, object_ref: str, env_id: int) -> str: - """Return the exact environment-specific root prim for one rigid scene object. + """Return the environment-specific root prim for a rigid object or non-robot articulation. Args: - object_ref: Exact key in the live scene's rigid-object mapping. + object_ref: Scene object name, using the same inventory as :meth:`get_object_poses`. env_id: Environment index. + + Returns: + Absolute USD prim path for the selected object's root. """ scene = self.env.scene assert type(env_id) is int and 0 <= env_id < len(scene.env_prim_paths), "env_id is out of range" - if object_ref not in scene.rigid_objects: - raise KeyError(f"unknown rigid scene object {object_ref!r}") - prim_pattern = scene.rigid_objects[object_ref].cfg.prim_path - assert isinstance(prim_pattern, str) and prim_pattern, "rigid-object prim path must be non-empty" + robot_name = getattr(self.embodiment_adapter, "robot_asset_name", "robot") + if object_ref in scene.rigid_objects: + asset = scene.rigid_objects[object_ref] + elif object_ref != robot_name and object_ref in getattr(scene, "articulations", {}): + asset = scene.articulations[object_ref] + else: + raise KeyError(f"unknown scene object {object_ref!r}") + prim_pattern = asset.cfg.prim_path + assert isinstance(prim_pattern, str) and prim_pattern, "object prim path must be non-empty" if prim_pattern == scene.env_regex_ns or prim_pattern.startswith(f"{scene.env_regex_ns}/"): prim_path = scene.env_prim_paths[env_id] + prim_pattern[len(scene.env_regex_ns) :] else: prim_path = prim_pattern - assert scene.stage.GetPrimAtPath(prim_path).IsValid(), f"rigid-object prim does not exist: {prim_path}" + assert scene.stage.GetPrimAtPath(prim_path).IsValid(), f"object prim does not exist: {prim_path}" return prim_path def get_robot_prim_path(self, env_id: int) -> str: diff --git a/autodata_interfaces/motion_planners/curobo/curobo_planner.py b/autodata_interfaces/motion_planners/curobo/curobo_planner.py index 8784807..101d56c 100644 --- a/autodata_interfaces/motion_planners/curobo/curobo_planner.py +++ b/autodata_interfaces/motion_planners/curobo/curobo_planner.py @@ -428,6 +428,7 @@ def __init__( recording_id=f"curobo_plan_{env_id}", debug=config.debug_planner, base_pose_in_env=self._base_pose_in_env, + save_path=self.config.rerun_output, ) self.plan_visualizer.set_motion_generator_reference(self.motion_gen) @@ -501,6 +502,10 @@ def _refresh_base_frame_transform(self) -> None: base pose (env-relative) and caches the forward and inverse transforms used to map object, goal, and planned poses between the two frames. """ + reference_pose = self.datastream.embodiment_adapter.get_reference_frame_pose(env_ids=[self.env_id]) + assert ( + reference_pose is None + ), "cuRobo requires environment-relative poses; configured embodiment reference frames are not supported" if self.root_pose_source_frame_name is None: self._base_pose_in_env = self.datastream.get_robot_root_pose(env_ids=[self.env_id])[0] else: @@ -874,12 +879,9 @@ def _self_collision_pair_data( dtype=torch.long, device=self.tensor_args.device, ) - buffers = self._kinematic_robot_cfg["kinematics"]["self_collision_buffer"] - sphere_offsets = torch.tensor( - [float(buffers[name]) for name in link_names], - dtype=self.tensor_args.dtype, - device=self.tensor_args.device, - ) + # Native offsets remove world-only padding before adding the self-collision margin. + sphere_offsets = self._kinematics.self_collision_config.offset.detach().clone().reshape(-1) + assert sphere_offsets.shape == (sphere_count,), "cuRobo self-collision offsets must match its spheres" self._self_collision_pair_cache = pair_indices, sphere_offsets, link_names return self._self_collision_pair_cache @@ -2422,10 +2424,7 @@ def _solve_ik( self.logger.debug(f"IK candidate FK failed: {error}") return None target_poses = target_pose.to(device=actual_poses.device, dtype=actual_poses.dtype).expand_as(actual_poses) - position_error = torch.linalg.vector_norm(actual_poses[:, :3, 3] - target_poses[:, :3, 3], dim=-1) - relative_rotation = actual_poses[:, :3, :3].transpose(-1, -2) @ target_poses[:, :3, :3] - cosine = torch.clamp((relative_rotation.diagonal(dim1=-2, dim2=-1).sum(-1) - 1.0) * 0.5, -1.0, 1.0) - rotation_error = torch.acos(cosine) + position_error, rotation_error = PoseUtils.pose_errors(actual_poses, target_poses) accepted = ( torch.isfinite(solutions).all(dim=-1) & torch.isfinite(actual_poses).all(dim=(-2, -1)) diff --git a/autodata_interfaces/motion_planners/curobo/curobo_planner_cfg.py b/autodata_interfaces/motion_planners/curobo/curobo_planner_cfg.py index b86fa87..6e6b9fa 100644 --- a/autodata_interfaces/motion_planners/curobo/curobo_planner_cfg.py +++ b/autodata_interfaces/motion_planners/curobo/curobo_planner_cfg.py @@ -40,7 +40,12 @@ class CuroboPlannerCfg: """cuRobo robot configuration file (path defined by curobo api).""" kinematic_robot_config_file: str | None = None - """Optional state-query model with auxiliary joints held fixed during motion planning.""" + """Optional FK/collision model that retains movable auxiliary joints, such as fingers. + + ``robot_config_file`` supplies the motion-planning model, where these joints may be locked. + This model instead evaluates their recorded positions without adding them to the planning + search. ``None`` uses the motion-planning model for both planning and state queries. + """ robot_name: str = "" """Robot name for visualization and identification.""" @@ -55,6 +60,7 @@ class CuroboPlannerCfg: """Live articulation link corresponding to the cuRobo kinematic root. ``None`` preserves the legacy behavior of using the articulation root. + Planner poses must be environment-relative; configured embodiment reference frames are not supported. """ initial_auxiliary_joint_positions: dict[str, float] = {} @@ -117,6 +123,9 @@ class CuroboPlannerCfg: interpolate_plan: bool = False """Return controller-rate samples; False preserves legacy SkillGen optimizer waypoints.""" + rerun_output: str | None = None + """Optional Rerun recording path; None opens the viewer when plan visualization is enabled.""" + max_joint_velocity: float | None = None """Optional planning speed cap [rad/s, m/s], also bounded by the live actuator limits.""" diff --git a/autodata_tests/interfaces/datastream/test_datastream.py b/autodata_tests/interfaces/datastream/test_datastream.py index d1c539f..4bc4f8c 100644 --- a/autodata_tests/interfaces/datastream/test_datastream.py +++ b/autodata_tests/interfaces/datastream/test_datastream.py @@ -86,6 +86,25 @@ def _datastream(): return datastream, task, embodiment_adapter, env +@pytest.mark.parametrize("object_name", ["cube_1", "door"]) +@pytest.mark.parametrize("env_id", [0, 1]) +def test_object_prim_paths_cover_rigid_and_articulated_objects(object_name, env_id): + datastream, _, _, env = _datastream() + scene = env.scene + scene.env_prim_paths = ["/World/envs/env_0", "/World/envs/env_1"] + scene.env_regex_ns = "/World/envs/env_.*" + scene.stage = SimpleNamespace(GetPrimAtPath=lambda path: SimpleNamespace(IsValid=lambda: True)) + scene.rigid_objects["cube_1"].cfg = SimpleNamespace(prim_path=f"{scene.env_regex_ns}/Cube") + scene.articulations = { + "robot": scene["robot"], + "door": SimpleNamespace(cfg=SimpleNamespace(prim_path=f"{scene.env_regex_ns}/Door")), + } + expected = "Cube" if object_name == "cube_1" else "Door" + assert datastream.get_object_prim_path(object_name, env_id) == f"/World/envs/env_{env_id}/{expected}" + with pytest.raises(KeyError, match="unknown scene object"): + datastream.get_object_prim_path("robot", env_id) + + # --------------------------------------------------------------------------------------------------- # Construction invariants # --------------------------------------------------------------------------------------------------- @@ -348,6 +367,6 @@ def test_get_scene_state_passthrough(): def test_robot_joint_positions_preserve_requested_order(): datastream, _, _, _ = _datastream() assert torch.equal( - datastream.get_robot_joint_positions(env_ids=[0], joint_names=("j6", "j1")), + datastream.get_robot_joint_positions([0], ("j6", "j1")), torch.tensor([[0.6, 0.1]]), ) diff --git a/autodata_tests/interfaces/motion_planners/test_curobo_world.py b/autodata_tests/interfaces/motion_planners/test_curobo_world.py index 8c1cfc0..1e8c964 100644 --- a/autodata_tests/interfaces/motion_planners/test_curobo_world.py +++ b/autodata_tests/interfaces/motion_planners/test_curobo_world.py @@ -70,6 +70,51 @@ def test_nested_exclusions_restore_the_original_enable_flags(): assert flags.tolist() == [[0, 1]] +@pytest.mark.parametrize("root_name", [None, "base"]) +def test_configured_embodiment_frame_is_rejected_before_world_conversion(root_name): + planner, _ = _planner(WorldConfig()) + planner.root_pose_source_frame_name = root_name + planner.datastream.embodiment_adapter = SimpleNamespace( + get_reference_frame_pose=lambda **kwargs: torch.eye(4).unsqueeze(0) + ) + with pytest.raises(AssertionError, match="configured embodiment reference frames"): + planner._refresh_base_frame_transform() + + +def test_self_collision_offsets_remove_native_world_padding(tmp_path): + from curobo.cuda_robot_model.cuda_robot_generator import CudaRobotGenerator, CudaRobotGeneratorConfig + + urdf = tmp_path / "two_links.urdf" + urdf.write_text( + '' + '' + '' + ) + generator = CudaRobotGenerator( + CudaRobotGeneratorConfig( + base_link="base", + ee_link="tip", + urdf_path=str(urdf), + tensor_args=TensorDeviceType(device=torch.device("cpu")), + collision_link_names=["base", "tip"], + collision_spheres={name: [{"center": [0, 0, 0], "radius": 0.1}] for name in ("base", "tip")}, + collision_sphere_buffer=0.05, + self_collision_buffer={}, + self_collision_ignore={"base": [], "tip": []}, + ) + ) + planner, _ = _planner(WorldConfig()) + planner._kinematics = SimpleNamespace(self_collision_config=generator.self_collision_config) + planner._self_collision_pair_cache = None + planner._self_collision_ignore = {"base": (), "tip": ()} + planner.collision_sphere_link_names = lambda count: ("base", "tip") + spheres = torch.tensor([ + [[0, 0, 0, 0.15], [0.25, 0, 0, 0.15]], + [[0, 0, 0, 0.15], [0.15, 0, 0, 0.15]], + ]) + assert planner._collision_spheres_self_collisions(spheres, 0).tolist() == [False, True] + + def test_shared_context_keeps_the_owner_world_and_disabled_obstacles(): world = WorldConfig(cuboid=[Cuboid(name="held", pose=[0, 0, 0, 1, 0, 0, 0], dims=[1, 1, 1])]) owner, flags = _planner(world) diff --git a/autodata_tests/interfaces/motion_planners/test_plan_visualizer.py b/autodata_tests/interfaces/motion_planners/test_plan_visualizer.py index da78e6f..3de2286 100644 --- a/autodata_tests/interfaces/motion_planners/test_plan_visualizer.py +++ b/autodata_tests/interfaces/motion_planners/test_plan_visualizer.py @@ -87,3 +87,16 @@ def test_object_overlay_uses_the_custom_robot_timeline(visualizer): index = visualizer.animate_collision_spheres(spheres, timeline_prefix="inspection") visualizer.animate_object_collision_spheres(spheres, schedule_index=index) assert {call.args[0] for call in module.rr.set_time.call_args_list} == {"inspection_0"} + + +def test_idle_clear_follows_a_static_only_preview(visualizer): + times, clears = [], [] + module.rr.set_time.side_effect = lambda *args, **kwargs: times.append(kwargs["sequence"]) + module.rr.log.side_effect = lambda path, value, **kwargs: ( + clears.append(times[-1]) if isinstance(value, module.rr.Clear) else None + ) + visualizer.visualize_plan(SimpleNamespace(position=torch.zeros(2, 1)), torch.eye(4)) + preview_tick = max(times) + clears.clear() + visualizer.mark_idle() + assert clears and min(clears) > preview_tick From f3d607dd40c4d0ab46def92e8ce93a2215d773a8 Mon Sep 17 00:00:00 2001 From: Neel Jawale Date: Sat, 28 Nov 2026 17:37:26 -0800 Subject: [PATCH 4/4] Keep planner collision defaults off the live USD stage Signed-off-by: Neel Jawale --- .../motion_planners/curobo/curobo_planner.py | 43 +++++++++++++------ .../motion_planners/test_curobo_world.py | 26 ++++++++++- 2 files changed, 53 insertions(+), 16 deletions(-) diff --git a/autodata_interfaces/motion_planners/curobo/curobo_planner.py b/autodata_interfaces/motion_planners/curobo/curobo_planner.py index 101d56c..0476703 100644 --- a/autodata_interfaces/motion_planners/curobo/curobo_planner.py +++ b/autodata_interfaces/motion_planners/curobo/curobo_planner.py @@ -37,24 +37,38 @@ from autodata_utils import pose_math as PoseUtils if TYPE_CHECKING: + from pxr import Usd + from autodata_interfaces.datastream.datastream import Datastream from autodata_interfaces.motion_planners.curobo.plan_visualizer import PlanVisualizer -def _usd_mesh_missing_scales_fill(stage: Any) -> None: - """Supply identity scale where cuRobo's USD reader requires an authored mesh value.""" +def _usd_collision_stage(stage: Usd.Stage) -> Usd.Stage: + """Supply cuRobo's mesh defaults without editing simulated collision shapes. + + Args: + stage: Live simulation stage, including session-layer overrides. + + Returns: + Separate stage with reader-only defaults in its own session layer. + """ - from pxr import Gf, Sdf, UsdGeom + from pxr import Gf, Sdf, Usd, UsdGeom - for prim in stage.Traverse(): - if not prim.IsA(UsdGeom.Mesh): - continue - scale = prim.GetAttribute("xformOp:scale") - if scale and scale.Get() is not None: - continue - if not scale: - scale = prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Float3) - scale.Set(Gf.Vec3f(1.0)) + session = Sdf.Layer.CreateAnonymous() + session.TransferContent(stage.GetSessionLayer()) + reader_stage = Usd.Stage.Open(stage.GetRootLayer(), session) + with Usd.EditContext(reader_stage, session): + for prim in reader_stage.Traverse(): + if not prim.IsA(UsdGeom.Mesh): + continue + scale = prim.GetAttribute("xformOp:scale") + if scale and scale.Get() is not None: + continue + if not scale: + scale = prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Float3) + scale.Set(Gf.Vec3f(1.0)) + return reader_stage def _self_collision_fallback_buffers_reset_install(motion_gen: MotionGen) -> None: @@ -605,7 +619,8 @@ def _initialize_static_world(self, *, activate: bool = True) -> None: self._static_world_config = owner._static_world_config return - _usd_mesh_missing_scales_fill(self.usd_helper.stage) + geometry_reader = UsdHelper() + geometry_reader.load_stage(_usd_collision_stage(self.usd_helper.stage)) # Prim scoping for obstacle extraction comes from the Datastream (collision-world source), # not from direct env access. env_prim_path = self.datastream.get_env_prim_path(self.env_id) @@ -624,7 +639,7 @@ def _initialize_static_world(self, *, activate: bool = True) -> None: # USD articulation-link transforms need not equal the live controller root. Extract in # the env frame, then use the same live root transform as goals and dynamic objects. - self._static_world_config = self.usd_helper.get_obstacles_from_stage( + self._static_world_config = geometry_reader.get_obstacles_from_stage( only_paths=[env_prim_path], reference_prim_path=env_prim_path, ignore_substring=ignore_list, diff --git a/autodata_tests/interfaces/motion_planners/test_curobo_world.py b/autodata_tests/interfaces/motion_planners/test_curobo_world.py index 1e8c964..b6accf4 100644 --- a/autodata_tests/interfaces/motion_planners/test_curobo_world.py +++ b/autodata_tests/interfaces/motion_planners/test_curobo_world.py @@ -13,9 +13,31 @@ pytest.importorskip("curobo.geom.sdf.world") from curobo.geom.types import Cuboid, WorldConfig # noqa: E402 from curobo.types.base import TensorDeviceType # noqa: E402 -from pxr import Usd, UsdGeom # noqa: E402 +from pxr import Sdf, Usd, UsdGeom # noqa: E402 -from autodata_interfaces.motion_planners.curobo.curobo_planner import CuroboPlanner # noqa: E402 +from autodata_interfaces.motion_planners.curobo.curobo_planner import CuroboPlanner, _usd_collision_stage # noqa: E402 + + +@pytest.mark.parametrize("scale_value", [None, (2, 3, 4)]) +def test_collision_reader_preserves_live_layers_and_session_overrides(scale_value): + stage = Usd.Stage.CreateInMemory() + mesh = UsdGeom.Mesh.Define(stage, "/object/mesh").GetPrim() + mesh.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Float3) + if scale_value is not None: + mesh.GetAttribute("xformOp:scale").Set(scale_value) + UsdGeom.Mesh.Define(stage, "/object/missing_scale") + with Usd.EditContext(stage, stage.GetSessionLayer()): + UsdGeom.Xformable(stage.GetPrimAtPath("/object")).AddTranslateOp().Set((1, 2, 3)) + before = [layer.ExportToString() for layer in (stage.GetRootLayer(), stage.GetSessionLayer())] + + reader = _usd_collision_stage(stage) + + assert [layer.ExportToString() for layer in (stage.GetRootLayer(), stage.GetSessionLayer())] == before + assert reader.GetRootLayer() == stage.GetRootLayer() + assert reader.GetSessionLayer() != stage.GetSessionLayer() + assert reader.GetPrimAtPath("/object").GetAttribute("xformOp:translate").Get() == (1, 2, 3) + assert reader.GetPrimAtPath("/object/mesh").GetAttribute("xformOp:scale").Get() == (scale_value or (1, 1, 1)) + assert reader.GetPrimAtPath("/object/missing_scale").GetAttribute("xformOp:scale").Get() == (1, 1, 1) def _planner(world):