openpi / droid /scripts /test_rotation_conventions.py
zhicao's picture
Upload folder using huggingface_hub
b584148 verified
Raw
History Blame Contribute Delete
7.75 kB
"""
Test All Rotation Conventions for DROID cartesian_position
Tests multiple Euler angle conventions (both extrinsic and intrinsic)
to find the exact format used by DROID.
"""
import sys
import numpy as np
import tensorflow_datasets as tfds
from pathlib import Path
import argparse
import pybullet as p
import pybullet_data
# Add parent directory to path
sys.path.append(str(Path(__file__).parent.parent))
def rotation_matrix_to_euler_xyz_intrinsic(R):
"""Extract XYZ Euler angles (intrinsic) from rotation matrix."""
sy = np.sqrt(R[0, 0]**2 + R[1, 0]**2)
singular = sy < 1e-6
if not singular:
x = np.arctan2(R[2, 1], R[2, 2])
y = np.arctan2(-R[2, 0], sy)
z = np.arctan2(R[1, 0], R[0, 0])
else:
x = np.arctan2(-R[1, 2], R[1, 1])
y = np.arctan2(-R[2, 0], sy)
z = 0
return np.array([x, y, z])
def euler_to_rotation_matrix(euler, convention='xyz_extrinsic'):
"""
Convert Euler angles to rotation matrix with various conventions.
Args:
euler: [angle1, angle2, angle3] in radians
convention: Rotation convention
- 'xyz_extrinsic': X then Y then Z (fixed frame) = Rz*Ry*Rx
- 'zyx_extrinsic': Z then Y then X (fixed frame) = Rx*Ry*Rz
- 'xyz_intrinsic': X then Y then Z (moving frame) = Rx*Ry*Rz
- 'zyx_intrinsic': Z then Y then X (moving frame) = Rz*Ry*Rx
Returns:
3x3 rotation matrix
"""
r1, r2, r3 = euler
# Individual rotation matrices
Rx = np.array([
[1, 0, 0],
[0, np.cos(r1), -np.sin(r1)],
[0, np.sin(r1), np.cos(r1)]
])
Ry = np.array([
[np.cos(r2), 0, np.sin(r2)],
[0, 1, 0],
[-np.sin(r2), 0, np.cos(r2)]
])
Rz = np.array([
[np.cos(r3), -np.sin(r3), 0],
[np.sin(r3), np.cos(r3), 0],
[0, 0, 1]
])
if convention == 'xyz_extrinsic':
# Fixed frame: rotate X, then Y, then Z
R = Rz @ Ry @ Rx
elif convention == 'zyx_extrinsic':
# Fixed frame: rotate Z, then Y, then X
R = Rx @ Ry @ Rz
elif convention == 'xyz_intrinsic':
# Moving frame: rotate X, then Y, then Z
R = Rx @ Ry @ Rz
elif convention == 'zyx_intrinsic':
# Moving frame: rotate Z, then Y, then X
R = Rz @ Ry @ Rx
else:
raise ValueError(f"Unknown convention: {convention}")
return R
def axis_angle_to_rotation_matrix(axis_angle):
"""Convert axis-angle to rotation matrix using Rodrigues' formula."""
theta = np.linalg.norm(axis_angle)
if theta < 1e-6:
return np.eye(3)
axis = axis_angle / theta
K = np.array([
[0, -axis[2], axis[1]],
[axis[2], 0, -axis[0]],
[-axis[1], axis[0], 0]
])
R = np.eye(3) + np.sin(theta) * K + (1 - np.cos(theta)) * (K @ K)
return R
def quaternion_to_rotation_matrix(quat):
"""Convert quaternion [x, y, z, w] to rotation matrix."""
x, y, z, w = quat
R = np.array([
[1 - 2*(y**2 + z**2), 2*(x*y - w*z), 2*(x*z + w*y)],
[2*(x*y + w*z), 1 - 2*(x**2 + z**2), 2*(y*z - w*x)],
[2*(x*z - w*y), 2*(y*z + w*x), 1 - 2*(x**2 + y**2)]
])
return R
def compute_fk_pose(joint_positions):
"""Compute FK to get end-effector pose."""
client = p.connect(p.DIRECT)
p.setAdditionalSearchPath(pybullet_data.getDataPath())
robot_id = p.loadURDF("franka_panda/panda.urdf", useFixedBase=True)
for i in range(min(7, len(joint_positions))):
p.resetJointState(robot_id, i, joint_positions[i])
ee_link_id = 8
link_state = p.getLinkState(robot_id, ee_link_id)
position = np.array(link_state[4])
orientation_quat = np.array(link_state[5]) # [x, y, z, w]
p.disconnect(client)
return position, orientation_quat
def test_all_conventions(droid_path, episode_index=0, num_samples=5):
"""Test all rotation conventions."""
print(f"Loading episode {episode_index}...")
builder = tfds.builder_from_directory(droid_path)
dataset = builder.as_dataset(split='train')
for idx, episode in enumerate(dataset):
if idx != episode_index:
continue
steps = list(episode['steps'])
print(f" Total steps: {len(steps)}")
sample_indices = np.linspace(0, len(steps)-1, num_samples, dtype=int)
# Test conventions
conventions = [
'xyz_extrinsic',
'zyx_extrinsic',
'xyz_intrinsic',
'zyx_intrinsic',
'axis_angle'
]
results = {conv: [] for conv in conventions}
print(f"\nTesting {num_samples} frames across {len(conventions)} conventions...")
print("=" * 80)
for i, step_idx in enumerate(sample_indices):
step = steps[step_idx]
joint_pos = step['observation']['joint_position'].numpy()
cart_pos = step['observation']['cartesian_position'].numpy()
# Compute FK
fk_pos, fk_quat = compute_fk_pose(joint_pos)
fk_rot = quaternion_to_rotation_matrix(fk_quat)
# Test position
pos_error = np.linalg.norm(fk_pos - cart_pos[:3])
print(f"\nFrame {step_idx}:")
print(f" Position error: {pos_error:.6f} m")
print(f" Rotation params: {cart_pos[3:]}")
print(f" Rotation magnitude: {np.linalg.norm(cart_pos[3:]):.4f}")
# Test each convention
for conv in conventions:
if conv == 'axis_angle':
rot_test = axis_angle_to_rotation_matrix(cart_pos[3:])
else:
rot_test = euler_to_rotation_matrix(cart_pos[3:], convention=conv)
error = np.linalg.norm(rot_test - fk_rot, 'fro')
results[conv].append(error)
print(f" {conv:20s}: {error:.6f}")
# Summary
print("\n" + "=" * 80)
print("SUMMARY - Average Errors")
print("=" * 80)
for conv in conventions:
avg_error = np.mean(results[conv])
std_error = np.std(results[conv])
print(f" {conv:20s}: {avg_error:.6f}{std_error:.6f})")
# Find best
best_conv = min(conventions, key=lambda c: np.mean(results[c]))
best_error = np.mean(results[best_conv])
print(f"\n{'='*80}")
if best_error < 0.1:
print(f"✓ BEST MATCH: {best_conv}")
print(f" Average error: {best_error:.6f}")
else:
print(f"⚠ WARNING: Best match is {best_conv} with error {best_error:.6f}")
print(f" This may indicate a coordinate frame transformation")
print("=" * 80)
return best_conv, results
raise ValueError(f"Episode {episode_index} not found")
def main():
parser = argparse.ArgumentParser(description="Test all rotation conventions for DROID")
parser.add_argument('--droid-path', type=str,
default='/mnt/kevin/data/droid/droid/1.0.0',
help='Path to DROID RLDS dataset')
parser.add_argument('--episode-index', type=int, default=0,
help='Episode index to test')
parser.add_argument('--num-samples', type=int, default=5,
help='Number of frames to test')
args = parser.parse_args()
print("=" * 80)
print("DROID Rotation Convention Test")
print("=" * 80 + "\n")
try:
test_all_conventions(args.droid_path, args.episode_index, args.num_samples)
return 0
except Exception as e:
print(f"\n✗ Test failed: {e}")
import traceback
traceback.print_exc()
return 1
if __name__ == "__main__":
sys.exit(main())