"""Observed TCP feedback for world-frame position/6D-orientation keypose commands.""" from typing import Any import torch from mani_skill.utils.geometry.rotation_conversions import ( axis_angle_to_matrix, matrix_to_axis_angle, matrix_to_euler_angles, quaternion_to_matrix, ) from pydantic import BaseModel, ConfigDict, PositiveFloat from lim.action_encoding import ROTATION_SCALE, matrix_to_sixd, sixd_to_matrix class KeyposeControlConfig(BaseModel, frozen=True): model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) max_translation_m: PositiveFloat = 0.01 """Maximum requested Cartesian displacement per 20 Hz control step.""" max_rotation_rad: PositiveFloat = 0.05 """Maximum requested SO(3) angle per control step, before controller decoding.""" position_tolerance_m: PositiveFloat = 0.003 """Measured TCP distance required before accepting the target gripper command.""" rotation_tolerance_rad: PositiveFloat = 0.05 """Measured angular distance required before accepting the target gripper command.""" def encode_keypose(pose, gripper): """Input xyz,wxyz; output world xyz, continuous6D rotation, continuous gripper.""" if pose.shape[-1] != 7 or not torch.isfinite(pose).all(): raise ValueError("Expected finite world xyz,wxyz poses") q = pose[..., 3:] if not torch.allclose(q.norm(dim=-1), torch.ones_like(q[..., 0]), atol=1e-4): raise ValueError("Keypose quaternions must be unit length") return torch.cat( [pose[..., :3], matrix_to_sixd(quaternion_to_matrix(q)), gripper[..., None]], -1 ) def keypose_error(current, target): if current.shape[-1] != 7 or target.shape[-1] != 10: raise ValueError("Expected observed TCP7 and target10") if not torch.isfinite(current).all() or not torch.isfinite(target).all(): raise ValueError("Nonfinite observed TCP or keypose target") delta = target[..., :3] - current[..., :3] rotation = sixd_to_matrix(target[..., 3:9]) @ quaternion_to_matrix( current[..., 3:] ).transpose(-1, -2) vector = matrix_to_axis_angle(rotation) return delta, vector def keypose_command(current, target, previous_gripper, config: KeyposeControlConfig): """Pure observed-state controller; audited Panda root axes coincide with world.""" delta, rotation = keypose_error(current, target) position_error = delta.norm(dim=-1) rotation_error = rotation.norm(dim=-1) reached = (position_error <= config.position_tolerance_m) & ( rotation_error <= config.rotation_tolerance_rad ) translation = ( delta * (config.max_translation_m / position_error.clamp_min(1e-8)).clamp(max=1)[ ..., None ] ) vector = ( rotation * (config.max_rotation_rad / rotation_error.clamp_min(1e-8)).clamp(max=1)[ ..., None ] ) # Euler exists ONLY at the installed low-level controller boundary. Targets # and SO(3) error/interpolation never learn or interpolate Euler coordinates. angles = ( matrix_to_euler_angles(axis_angle_to_matrix(vector), "XYZ") / ROTATION_SCALE ) angles = angles / angles.norm(dim=-1, keepdim=True).clamp(min=1) gripper = torch.where(reached, target[..., -1].clamp(-1, 1), previous_gripper) command = torch.cat( [(translation / 0.1).clamp(-1, 1), angles, gripper[..., None]], -1 ) return command, reached, position_error, rotation_error class KeyposeEnvConfig(BaseModel, frozen=True): model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True ) env: Any """Physical vector environment exposing full state25 observations.""" control: KeyposeControlConfig = KeyposeControlConfig() """Pure keypose tracking and gripper synchronization settings.""" class KeyposeEnv: def __init__(self, config: KeyposeEnvConfig): import gymnasium as gym import numpy as np self.config = config self.current = None self.gripper = None self.action_space = gym.spaces.Box( -np.inf, np.inf, (config.env.num_envs, 10), dtype=np.float32 ) self.single_action_space = gym.spaces.Box( -np.inf, np.inf, (10,), dtype=np.float32 ) def __getattr__(self, name): return getattr(self.config.env, name) def remember(self, obs, reset=None): state = torch.as_tensor(obs["state"], dtype=torch.float32) if state.shape[-1] != 25: raise ValueError("Expected audited qpos9,qvel9,TCP7 state layout") self.current = state[:, 18:25].clone() # Panda PDJointPosMimicController maps [-1,1] to [-.01,.04] m. measured = ((state[:, 7:9].mean(-1) + 0.01) / 0.05 * 2 - 1).clamp(-1, 1) if reset is None: self.gripper = measured else: self.gripper = torch.where(torch.as_tensor(reset), measured, self.gripper) def reset(self, *args, **kwargs): obs, info = self.config.env.reset(*args, **kwargs) self.remember(obs) return obs, info def step(self, target): command, _, _, _ = keypose_command( self.current, torch.as_tensor(target), self.gripper, self.config.control ) self.gripper = command[:, -1].clone() result = self.config.env.step(command.numpy()) self.remember(result[0], result[2] | result[3]) return result