| import carb |
| import math |
| import torch |
| import numpy as np |
| import omni.usd |
| from omni.kit.scripting import BehaviorScript |
| from isaacsim.core.prims import Articulation |
| from omni.isaac.core.prims import XFormPrim |
| from isaacsim.core.utils.types import ArticulationActions |
| from pxr import UsdPhysics |
|
|
|
|
| def find_prim_path_by_name(prim_name: str, root_path: str = "/") -> str: |
| """Recursively find the full path by Prim name""" |
| stage = omni.usd.get_context().get_stage() |
| prim = stage.GetPrimAtPath(root_path) |
|
|
| def _find_prim(current): |
| if current.GetName() == prim_name: |
| return current.GetPath().pathString |
| for child in current.GetChildren(): |
| result = _find_prim(child) |
| if result: |
| return result |
| return None |
|
|
| found_path = _find_prim(prim) |
| if not found_path: |
| raise RuntimeError(f"Prim '{prim_name}' not found under {root_path}") |
| return found_path |
|
|
|
|
| POSSIBLE_ASSET_ROOT_NAMES = ["fridge_E_body_61"] |
| JOINT_NAMES = ["RevoluteJoint_fridge_left", "RevoluteJoint_fridge_right"] |
| JOINT_THRESHOLD = 0.4 |
| LIGHT_PRIM_NAME = "fridge_light" |
|
|
|
|
| class CupboardControl(BehaviorScript): |
| def on_init(self): |
| articulation_root_path = None |
| for root_name in POSSIBLE_ASSET_ROOT_NAMES: |
| try: |
| articulation_root_path = find_prim_path_by_name(root_name) |
| print(f"Found articulation root: {articulation_root_path}") |
| break |
| except RuntimeError: |
| continue |
|
|
| if articulation_root_path is None: |
| raise RuntimeError(f"Could not find articulation root with names: {POSSIBLE_ASSET_ROOT_NAMES}") |
|
|
| self.articulation_root_path = articulation_root_path |
| self.art = None |
| self.initialized = False |
| self.joint_names = JOINT_NAMES |
| self.joint_indices = None |
| self.use_torch = None |
| self.joint_threshold = JOINT_THRESHOLD |
|
|
| self.light_scopes = [XFormPrim(find_prim_path_by_name(LIGHT_PRIM_NAME))] |
| self.light_scopes[0].set_visibility(False) |
|
|
| stage = omni.usd.get_context().get_stage() |
| self.joints_info = {} |
| for joint_name in self.joint_names: |
| joint_prim_path = find_prim_path_by_name(joint_name) |
| joint_prim_obj = stage.GetPrimAtPath(joint_prim_path) |
| joint = UsdPhysics.RevoluteJoint(joint_prim_obj) |
| self.joints_info[joint_name] = { |
| "prim": joint, |
| "lower_limit": joint.GetLowerLimitAttr().Get(), |
| "upper_limit": joint.GetUpperLimitAttr().Get(), |
| } |
|
|
| def on_play(self): |
| self._initialize_articulation() |
|
|
| def on_stop(self): |
| self.light_scopes[0].set_visibility(False) |
|
|
| def on_update(self, current_time: float, delta_time: float): |
| if delta_time <= 0: |
| return |
| if not self.initialized: |
| self._initialize_articulation() |
| if not self.initialized: |
| return |
| self.apply_behavior() |
|
|
| def apply_behavior(self): |
| if not self.initialized or self.art is None: |
| return |
| self.light_control() |
| self.damping_stiffness_change() |
| self.target_pose_control() |
|
|
| def _initialize_articulation(self): |
| """Initialize the articulation object and get joint information""" |
| if self.initialized: |
| return |
|
|
| try: |
| self.art = Articulation(self.articulation_root_path) |
| if self.art is None: |
| return |
|
|
| |
| self.joint_indices = [] |
| for joint_name in self.joint_names: |
| idx = self.art.get_dof_index(joint_name) |
| if idx is not None: |
| self.joint_indices.append(idx) |
| else: |
| print(f"Warning: Could not find joint index for {joint_name}") |
|
|
| if not self.joint_indices: |
| print("Warning: No valid joint indices found") |
| return |
|
|
| |
| positions = self.art.get_joint_positions() |
| self.use_torch = isinstance(positions, torch.Tensor) |
| print(f"Detected platform: {'Isaac Lab (torch)' if self.use_torch else 'Isaac Sim (numpy/math)'}") |
|
|
| self.initialized = True |
| except Exception as e: |
| print(f"Error initializing articulation: {e}") |
| self.initialized = False |
|
|
| def _get_scalar_value(self, value): |
| """Convert a value (potentially a torch.Tensor) to a scalar float""" |
| if isinstance(value, torch.Tensor): |
| return value.item() |
| elif isinstance(value, (list, tuple, np.ndarray)): |
| return float(value[0] if len(value) > 0 else 0.0) |
| else: |
| return float(value) |
|
|
| def light_control(self): |
| positions = self.art.get_joint_positions().squeeze() |
| left_joint_state = self._get_scalar_value(positions[self.joint_indices[0]]) |
| right_joint_state = self._get_scalar_value(positions[self.joint_indices[1]]) |
|
|
| doors_open = [ |
| left_joint_state > math.radians(30), |
| right_joint_state > math.radians(30) |
| ] |
|
|
| current_visibility = self.light_scopes[0].get_visibility() |
| if any(doors_open): |
| if not current_visibility: |
| for light in self.light_scopes: |
| light.set_visibility(True) |
| else: |
| if current_visibility: |
| for light in self.light_scopes: |
| light.set_visibility(False) |
|
|
| def damping_stiffness_change(self): |
| positions = self.art.get_joint_positions().squeeze() |
| stage = omni.usd.get_context().get_stage() |
|
|
| for i, joint_name in enumerate(self.joint_names): |
| if i >= len(self.joint_indices): |
| continue |
| joint_idx = self.joint_indices[i] |
| joint_state = self._get_scalar_value(positions[joint_idx]) |
|
|
| joint_drive_path = stage.GetPrimAtPath(find_prim_path_by_name(joint_name)) |
| joint_drive = UsdPhysics.DriveAPI.Get(joint_drive_path, "angular") |
| joint_drive.GetStiffnessAttr().Set(self.calculate_stiffness(joint_state, i)) |
|
|
| def calculate_stiffness(self, joint_state, joint_idx): |
| """Calculate stiffness value based on joint angle""" |
| max_stiffness = 110 |
| min_stiffness = 2 |
| decay_rate = 8 |
|
|
| joint_name = self.joint_names[joint_idx] |
| threshold_value = abs(math.radians(self.joint_threshold * (self.joints_info[joint_name]['upper_limit'] + self.joints_info[joint_name]['lower_limit']))) |
| if abs(joint_state) >= threshold_value: |
| return min_stiffness |
|
|
| stiffness = max_stiffness * math.exp(-decay_rate * abs(joint_state)) |
| return max(min_stiffness, min(stiffness, max_stiffness)) |
|
|
| def target_pose_control(self): |
| positions = self.art.get_joint_positions().squeeze() |
| targets = [] |
| indices = [] |
|
|
| for i, joint_name in enumerate(self.joint_names): |
| if i >= len(self.joint_indices): |
| continue |
| joint_idx = self.joint_indices[i] |
| joint_state = self._get_scalar_value(positions[joint_idx]) |
|
|
| lower_limit = self.joints_info[joint_name]['lower_limit'] |
| upper_limit = self.joints_info[joint_name]['upper_limit'] |
| threshold_value = math.radians(self.joint_threshold * (upper_limit + lower_limit)) |
|
|
| if abs(lower_limit) <= math.radians(abs(upper_limit)): |
| if joint_state > threshold_value: |
| target = math.radians(upper_limit) |
| else: |
| target = math.radians(lower_limit) |
| else: |
| if joint_state < threshold_value: |
| target = math.radians(lower_limit) |
| else: |
| target = math.radians(upper_limit) |
|
|
| targets.append(target) |
| indices.append(joint_idx) |
|
|
| if not targets: |
| return |
|
|
| if self.use_torch: |
| device = positions.device |
| targets_tensor = torch.tensor(targets, device=device) |
| indices_tensor = torch.tensor(indices, device=device, dtype=torch.long) |
| action = ArticulationActions(joint_positions=targets_tensor, joint_indices=indices_tensor) |
| else: |
| action = ArticulationActions(targets, joint_indices=indices) |
|
|
| self.art.apply_action(action) |
|
|