File size: 2,827 Bytes
0a3f650 | 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 | """Invertible action coordinates with one shared controller contract."""
from typing import Literal
import numpy as np
from scipy.spatial.transform import Rotation
ActionFrame = Literal["absolute", "tcp", "target"]
POSITION_SCALE = 0.1
# ManiSkill 3.0.1 PDEEPoseController scales by config.rot_lower (-0.1).
ROTATION_SCALE = -0.1
def tcp_rotation(tcp: np.ndarray) -> Rotation:
# SAPIEN exposes wxyz; scipy expects xyzw.
return Rotation.from_quat(tcp[..., [4, 5, 6, 3]])
def reference_position(
frame: ActionFrame, tcp: np.ndarray, target: np.ndarray
) -> np.ndarray:
if frame == "absolute":
return np.zeros_like(tcp[..., :3])
if frame == "tcp":
return tcp[..., :3]
if frame == "target":
return target
raise ValueError(frame)
def controller_targets(
tcp: np.ndarray, actions: np.ndarray
) -> tuple[np.ndarray, np.ndarray]:
position = tcp[..., :3] + actions[..., :3] * POSITION_SCALE
raw_rotation = actions[..., 3:6]
raw_rotation = raw_rotation / np.maximum(
np.linalg.norm(raw_rotation, axis=-1, keepdims=True), 1
)
delta = Rotation.from_euler("XYZ", raw_rotation * ROTATION_SCALE)
rotation = (delta * tcp_rotation(tcp)).as_matrix()
return position, rotation
def encode_chunk(position, rotation, gripper, current_tcp, target, frame: ActionFrame):
anchor = reference_position(frame, current_tcp, target)
pos = (position - anchor) / POSITION_SCALE
relative_rotation = tcp_rotation(current_tcp).as_matrix().T @ rotation
rot6d = relative_rotation[..., :, :2].reshape(*relative_rotation.shape[:-2], 6)
return np.concatenate([pos, rot6d, gripper[..., None]], axis=-1).astype(np.float32)
def prediction_to_world(
prediction: np.ndarray, tcp: np.ndarray, target: np.ndarray, frame: ActionFrame
):
position = prediction[:3] * POSITION_SCALE + reference_position(frame, tcp, target)
columns = prediction[3:9].reshape(3, 2)
x = columns[:, 0] / max(np.linalg.norm(columns[:, 0]), 1e-8)
y = columns[:, 1] - x * np.dot(x, columns[:, 1])
y /= max(np.linalg.norm(y), 1e-8)
relative = np.stack([x, y, np.cross(x, y)], axis=1)
current = tcp_rotation(tcp)
desired = current * Rotation.from_matrix(relative)
return position, desired.as_matrix(), float(prediction[9])
def world_to_controller(position, rotation, gripper, tcp):
current = tcp_rotation(tcp)
desired = Rotation.from_matrix(rotation)
delta = (desired * current.inv()).as_euler("XYZ") / ROTATION_SCALE
translation = (position - tcp[:3]) / POSITION_SCALE
return np.clip(np.r_[translation, delta, gripper], -1, 1).astype(np.float32)
def decode_action(prediction, tcp, target, frame: ActionFrame):
return world_to_controller(
*prediction_to_world(prediction, tcp, target, frame), tcp
)
|