File size: 8,515 Bytes
f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b f9c7324 8cb339b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | 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
# Get joint indices
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
# Detect if using torch
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)
|