"""Pick-place state machine and grasp-quaternion solver for Task E.""" import torch from isaaclab.utils.math import matrix_from_quat, quat_from_matrix from .config import ( STEPS, STATE_ORDER, OBJ_STATE_STEP_OVERRIDES, CARRY_Z, PLACE_HEIGHT, RETRACT_POS_X, RETRACT_POS_Y, GRASP_Z_OFFSET, OBJ_GRASP_Z_OFFSETS, OBJ_CLOSE_Z_OFFSETS, OBJ_GRASP_YAW_OFFSETS, BASKET_CENTER_X, BASKET_CENTER_Y, DEFAULT_PLACE_QUAT_W, OBJ_GRASP_CENTER_OFFSETS, OBJ_CARRY_Z, OBJ_PLACE_HEIGHTS, OBJ_PLACE_XY_OFFSETS, OBJ_TRANSPORT_GRIPPER_CMDS, OBJ_KEEP_GRASP_QUAT_STATES, OBJ_TRANSPORT_PUSH_BIASES, OBJ_MANIPULATION_MODES, OBJ_PUSH_GRIPPER_CMDS, OBJ_PUSH_APPROACH_CLEARANCE, OBJ_PUSH_X_GAINS, OBJ_PUSH_MAX_X_CORRECTIONS, OBJ_PUSH_Y_GAINS, OBJ_PUSH_MAX_Y_CORRECTIONS, OBJ_PUSH_MIN_BEHIND, OBJ_SERVO_TO_BASKET_STATES, OBJ_SERVO_XY_GAINS, OBJ_SERVO_MAX_XY, OBJ_SERVO_HOLD_STATES, OBJ_SERVO_EXTRA_STEPS, BASKET_IN_X, BASKET_IN_Y, ) def _build_grasp_matrix(long_axis: torch.Tensor, grip_z: torch.Tensor) -> torch.Tensor: """Build a right-handed gripper rotation matrix given the object's long axis. The Piper gripper jaw opens along its LOCAL Y axis, so local Y must be perpendicular to the object's long axis. Frame layout (columns of R_grip): col 0 (local X) = align_dir ∥ long_axis col 1 (local Y) = jaw_dir ⊥ long_axis ← jaw opening direction col 2 (local Z) = grip_z pointing down Right-hand check: col0 × col1 = align_dir × jaw_dir = grip_z ✓ """ jaw_dir = torch.linalg.cross(long_axis, grip_z) # ⊥ long_axis, in XY plane jaw_dir = jaw_dir / jaw_dir.norm().clamp(min=1e-6) align_dir = torch.linalg.cross(jaw_dir, grip_z) # ∥ long_axis align_dir = align_dir / align_dir.norm().clamp(min=1e-6) return torch.stack([align_dir, jaw_dir, grip_z], dim=1) # (3, 3) def compute_grasp_quat(obj_quat_w: torch.Tensor, device: str) -> torch.Tensor: """Compute a top-down grasp quaternion for the object. Finds the object axis most aligned with the world XY-plane (the long axis), builds a gripper frame where the jaw (local Y) is perpendicular to that axis, then picks the candidate orientation closest to the default top-down pose. Parameters ---------- obj_quat_w : (4,) tensor, (w, x, y, z) device : torch device string Returns ------- grasp_quat : (4,) tensor, (w, x, y, z) """ R_obj = matrix_from_quat(obj_quat_w.unsqueeze(0)).squeeze(0) # (3, 3) grip_z = torch.tensor([0.0, 0.0, -1.0], device=device) default_quat = torch.tensor(DEFAULT_PLACE_QUAT_W, dtype=torch.float32, device=device) # Project each object column-axis onto XY plane; keep the most horizontal one(s) norms, axes_xy = [], [] for col in range(3): ax = torch.tensor([R_obj[0, col].item(), R_obj[1, col].item(), 0.0], device=device) norms.append(ax.norm().item()) axes_xy.append(ax) best_norm = max(norms) candidates = [ axes_xy[c] / max(norms[c], 1e-6) for c in range(3) if norms[c] >= best_norm - 1e-3 ] # Among candidates, pick the one whose grasp frame is closest to the default orientation best_cos = -2.0 long_axis = candidates[0] for cand in candidates: q_cand = quat_from_matrix(_build_grasp_matrix(cand, grip_z).unsqueeze(0)).squeeze(0) cos_sim = torch.abs((q_cand * default_quat).sum()).item() if cos_sim > best_cos: best_cos = cos_sim long_axis = cand R_grip = _build_grasp_matrix(long_axis, grip_z) # (3, 3) return quat_from_matrix(R_grip.unsqueeze(0)).squeeze(0) # (4,) w,x,y,z def _quat_mul(q1: torch.Tensor, q2: torch.Tensor) -> torch.Tensor: w1, x1, y1, z1 = q1.unbind() w2, x2, y2, z2 = q2.unbind() return torch.stack([ w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2, ]) class PickPlaceStateMachine: """Finite state machine that sequences pick-and-place for multiple objects. States (in order): INIT → PRE_GRASP → REACH → CLOSE → LIFT → TRANSPORT → PLACE → OPEN → RETRACT → (next object or done) """ def __init__(self, object_indices: list[int], device: str): self._obj_indices = object_indices self._device = device self._grasp_quat_cache: dict[int, torch.Tensor] = {} self.reset() def reset(self) -> None: self._ptr = 0 self._state_idx = 0 self._count = 0 self.done = False self._cached_obj_pos: torch.Tensor | None = None self._servo_extra_counts: dict[tuple[int, str], int] = {} self._grasp_quat_cache.clear() def set_grasp_quat(self, obj_idx: int, obj_quat_w: torch.Tensor) -> None: """Pre-compute and cache the grasp quaternion for one object.""" grasp_quat = compute_grasp_quat(obj_quat_w, self._device) yaw = OBJ_GRASP_YAW_OFFSETS.get(obj_idx, 0.0) if abs(yaw) > 1e-6: half = torch.tensor(0.5 * yaw, dtype=torch.float32, device=self._device) yaw_quat = torch.stack([ torch.cos(half), torch.tensor(0.0, dtype=torch.float32, device=self._device), torch.tensor(0.0, dtype=torch.float32, device=self._device), torch.sin(half), ]) grasp_quat = _quat_mul(yaw_quat, grasp_quat) grasp_quat = grasp_quat / grasp_quat.norm().clamp(min=1e-6) self._grasp_quat_cache[obj_idx] = grasp_quat def tick(self, obj_pos: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, str]: """Advance the state machine by one step. Parameters ---------- obj_pos : (3,) tensor — current object position in world frame Returns ------- ee_pos_des : (3,) target EE position ee_quat_des : (4,) target EE orientation (w,x,y,z) gripper_cmd : "open" | "close" """ s = self.state d = self._device # Freeze object position at start of PRE_GRASP to avoid drift during descent if s == "PRE_GRASP" and self._count == 0: self._cached_obj_pos = obj_pos.clone() if s in ("REACH", "CLOSE", "LIFT") and self._cached_obj_pos is not None: obj_pos = self._cached_obj_pos ee_pos, gripper = self._get_target_pos_gripper(s, obj_pos, d) ee_quat = self._get_target_quat(s, d) self._count += 1 if self._count >= self._get_state_steps(s): if self._should_hold_servo_state(s, obj_pos): self._count = self._get_state_steps(s) - 1 return ee_pos, ee_quat, gripper self._count = 0 if s == "RETRACT": self._ptr += 1 self._cached_obj_pos = None if self._ptr >= len(self._obj_indices): self.done = True return ee_pos, ee_quat, gripper self._state_idx = STATE_ORDER.index("PRE_GRASP") else: self._state_idx += 1 return ee_pos, ee_quat, gripper # ------------------------------------------------------------------ # # Properties # ------------------------------------------------------------------ # @property def state(self) -> str: return STATE_ORDER[self._state_idx] @property def current_object_key(self) -> str: return f"object_{self._obj_indices[self._ptr]}" # ------------------------------------------------------------------ # # Private helpers # ------------------------------------------------------------------ # def _get_target_pos_gripper( self, s: str, obj_pos: torch.Tensor, d: str ) -> tuple[torch.Tensor, str]: if self._is_push_mode(): return self._get_push_target_pos_gripper(s, obj_pos, d) grasp_pos = self._get_grasp_pos(obj_pos, d) if s == "INIT": return torch.tensor([RETRACT_POS_X, RETRACT_POS_Y, CARRY_Z], device=d), "open" elif s == "PRE_GRASP": p = grasp_pos.clone(); p[2] = CARRY_Z return p, "open" elif s == "REACH": p = grasp_pos.clone(); p[2] += self._get_grasp_z_offset() return p, "open" elif s == "CLOSE": p = grasp_pos.clone(); p[2] += self._get_close_z_offset() return p, "close" elif s == "LIFT": p = grasp_pos.clone(); p[2] = self._get_carry_z() return p, self._get_transport_gripper_cmd() elif s == "TRANSPORT": servo = self._get_object_servo_target(s, obj_pos, grasp_pos, self._get_carry_z(), d) if servo is not None: return servo, self._get_transport_gripper_cmd() x, y = self._get_place_xy() return torch.tensor([x, y, self._get_carry_z()], device=d), self._get_transport_gripper_cmd() elif s == "PLACE": servo = self._get_object_servo_target(s, obj_pos, grasp_pos, self._get_place_height(), d) if servo is not None: return servo, self._get_transport_gripper_cmd() x, y = self._get_place_xy() return torch.tensor([x, y, self._get_place_height()], device=d), self._get_transport_gripper_cmd() elif s == "OPEN": servo = self._get_object_servo_target(s, obj_pos, grasp_pos, self._get_place_height(), d) if servo is not None: return servo, "open" x, y = self._get_place_xy() return torch.tensor([x, y, self._get_place_height()], device=d), "open" elif s == "LIFT_RETRACT": return torch.tensor([BASKET_CENTER_X, BASKET_CENTER_Y, CARRY_Z], device=d), "open" elif s == "RETRACT": return torch.tensor([RETRACT_POS_X, RETRACT_POS_Y, CARRY_Z], device=d), "open" else: raise ValueError(f"Unknown state: {s}") def _get_grasp_pos(self, obj_pos: torch.Tensor, d: str) -> torch.Tensor: cur_idx = self._obj_indices[min(self._ptr, len(self._obj_indices) - 1)] offset = OBJ_GRASP_CENTER_OFFSETS.get(cur_idx, (0.0, 0.0, 0.0)) return obj_pos + torch.tensor(offset, dtype=torch.float32, device=d) def _get_current_obj_idx(self) -> int: return self._obj_indices[min(self._ptr, len(self._obj_indices) - 1)] def _is_push_mode(self) -> bool: return OBJ_MANIPULATION_MODES.get(self._get_current_obj_idx(), "pick") == "push" def _get_push_gripper_cmd(self) -> str: cur_idx = self._get_current_obj_idx() return OBJ_PUSH_GRIPPER_CMDS.get(cur_idx, self._get_transport_gripper_cmd()) def _get_push_target_pos_gripper( self, s: str, obj_pos: torch.Tensor, d: str ) -> tuple[torch.Tensor, str]: """Low table-contact pushing primitive for objects that do not pinch reliably.""" cur_idx = self._get_current_obj_idx() contact_obj_pos = self._cached_obj_pos if self._cached_obj_pos is not None else obj_pos start = self._get_grasp_pos(contact_obj_pos, d) z_low = self._get_place_height() if s == "INIT": return torch.tensor([RETRACT_POS_X, RETRACT_POS_Y, CARRY_Z], device=d), "open" if s == "PRE_GRASP": p = start.clone() p[2] = z_low + OBJ_PUSH_APPROACH_CLEARANCE.get(cur_idx, 0.14) return p, "open" if s in ("REACH", "CLOSE", "LIFT"): p = start.clone() p[2] = z_low return p, self._get_push_gripper_cmd() if s in ("TRANSPORT", "PLACE"): place_x, place_y = self._get_place_xy() target_xy = torch.tensor([place_x, place_y], dtype=torch.float32, device=d) start_xy = contact_obj_pos[:2] x_err = place_x - obj_pos[0] x_gain = OBJ_PUSH_X_GAINS.get(cur_idx, 0.55) x_max = OBJ_PUSH_MAX_X_CORRECTIONS.get(cur_idx, 0.08) x_corr = torch.clamp(x_err * x_gain, min=-x_max, max=x_max) progress = 1.0 if s == "TRANSPORT": progress = min((self._count + 1) / max(self._get_state_steps(s), 1), 1.0) progress = min(progress * 1.35, 1.0) ref_xy = start_xy + (target_xy - start_xy) * progress p_live = torch.cat([ ref_xy, torch.tensor([z_low], dtype=torch.float32, device=d), ]) offset = torch.tensor( OBJ_GRASP_CENTER_OFFSETS.get(cur_idx, (0.0, 0.0, 0.0)), dtype=torch.float32, device=d, ) p_live = p_live + offset p_live[0] = p_live[0] + x_corr # Keep the pusher on the rear side of the object. If the reference # sweep gets ahead of a lagging object, contact is lost or the object # is knocked sideways instead of being driven into the basket. min_behind = OBJ_PUSH_MIN_BEHIND.get(cur_idx, 0.03) p_live[1] = torch.maximum( p_live[1], obj_pos[1] + torch.tensor(min_behind, dtype=torch.float32, device=d), ) # During the hold phase, apply a bounded inward preload without # allowing the pusher centre to cross in front of the object. y_err = place_y - obj_pos[1] y_gain = OBJ_PUSH_Y_GAINS.get(cur_idx, 0.85) y_max = OBJ_PUSH_MAX_Y_CORRECTIONS.get(cur_idx, 0.22) inward = torch.clamp(y_err * y_gain, min=-y_max, max=0.0) p_live[1] = torch.maximum(p_live[1] + inward, obj_pos[1] + min_behind) p_live[2] = z_low if s == "TRANSPORT": p = start + (p_live - start) * min(progress * 3.0, 1.0) else: p = p_live return p, self._get_push_gripper_cmd() if s == "OPEN": p = self._get_grasp_pos(obj_pos, d) p[2] = z_low return p, "open" if s == "LIFT_RETRACT": x, y = self._get_place_xy() return torch.tensor([x, y, CARRY_Z], device=d), "open" if s == "RETRACT": return torch.tensor([RETRACT_POS_X, RETRACT_POS_Y, CARRY_Z], device=d), "open" raise ValueError(f"Unknown state: {s}") def _get_grasp_z_offset(self) -> float: cur_idx = self._get_current_obj_idx() return OBJ_GRASP_Z_OFFSETS.get(cur_idx, GRASP_Z_OFFSET) def _get_close_z_offset(self) -> float: cur_idx = self._get_current_obj_idx() return OBJ_CLOSE_Z_OFFSETS.get(cur_idx, self._get_grasp_z_offset()) def _get_carry_z(self) -> float: cur_idx = self._get_current_obj_idx() return OBJ_CARRY_Z.get(cur_idx, CARRY_Z) def _get_place_height(self) -> float: cur_idx = self._get_current_obj_idx() return OBJ_PLACE_HEIGHTS.get(cur_idx, PLACE_HEIGHT) def _get_place_xy(self) -> tuple[float, float]: cur_idx = self._get_current_obj_idx() dx, dy = OBJ_PLACE_XY_OFFSETS.get(cur_idx, (0.0, 0.0)) return BASKET_CENTER_X + dx, BASKET_CENTER_Y + dy def _get_transport_gripper_cmd(self) -> str: cur_idx = self._get_current_obj_idx() return OBJ_TRANSPORT_GRIPPER_CMDS.get(cur_idx, "close") def _get_state_steps(self, s: str) -> int: cur_idx = self._get_current_obj_idx() return OBJ_STATE_STEP_OVERRIDES.get(cur_idx, {}).get(s, STEPS[s]) def _get_transport_push_bias(self) -> tuple[float, float, float] | None: cur_idx = self._get_current_obj_idx() return OBJ_TRANSPORT_PUSH_BIASES.get(cur_idx) def _get_object_servo_target( self, s: str, obj_pos: torch.Tensor, grasp_pos: torch.Tensor, z: float, d: str, ) -> torch.Tensor | None: cur_idx = self._get_current_obj_idx() if s not in OBJ_SERVO_TO_BASKET_STATES.get(cur_idx, ()): push_bias = self._get_transport_push_bias() if push_bias is None: return None p = grasp_pos + torch.tensor(push_bias, dtype=torch.float32, device=d) p[2] = z return p x, y = self._get_place_xy() target_xy = torch.tensor([x, y], dtype=torch.float32, device=d) xy_error = target_xy - obj_pos[:2] gain = OBJ_SERVO_XY_GAINS.get(cur_idx, 1.0) max_xy = OBJ_SERVO_MAX_XY.get(cur_idx, 0.25) correction = xy_error * gain norm = torch.linalg.norm(correction).clamp(min=1e-6) if norm.item() > max_xy: correction = correction / norm * max_xy if s == "TRANSPORT": progress = min((self._count + 1) / max(self._get_state_steps(s), 1), 1.0) correction = correction * max(0.15, progress) p = grasp_pos.clone() p[:2] = p[:2] + correction push_bias = self._get_transport_push_bias() if push_bias is not None: p = p + torch.tensor(push_bias, dtype=torch.float32, device=d) p[2] = z return p def _should_hold_servo_state(self, s: str, obj_pos: torch.Tensor) -> bool: cur_idx = self._get_current_obj_idx() if s not in OBJ_SERVO_HOLD_STATES.get(cur_idx, ()): return False dx = abs(float(obj_pos[0].item() - BASKET_CENTER_X)) dy = abs(float(obj_pos[1].item() - BASKET_CENTER_Y)) if dx <= BASKET_IN_X * 0.85 and dy <= BASKET_IN_Y * 0.85: return False key = (cur_idx, s) count = self._servo_extra_counts.get(key, 0) if count >= OBJ_SERVO_EXTRA_STEPS.get(cur_idx, 0): return False self._servo_extra_counts[key] = count + 1 return True def _get_target_quat(self, s: str, d: str) -> torch.Tensor: default_quat = torch.tensor(DEFAULT_PLACE_QUAT_W, dtype=torch.float32, device=d) cur_idx = self._get_current_obj_idx() if self._is_push_mode() and s in ("REACH", "CLOSE", "LIFT", "TRANSPORT", "PLACE", "OPEN"): return self._grasp_quat_cache.get(cur_idx, default_quat) if s in OBJ_KEEP_GRASP_QUAT_STATES.get(cur_idx, ("REACH", "CLOSE", "LIFT")): return self._grasp_quat_cache.get(cur_idx, default_quat) return default_quat