v2d / simulation /source /v2d_sim /sonic /math_np.py
hk239's picture
Upload v2d project (excluding data and .venv) (part 18)
3f4bb1d verified
Raw History Blame Contribute Delete
2.32 kB
"""Heading / 6D rotation helpers for SONIC observations."""
from __future__ import annotations
import numpy as np
def quat_mul_wxyz(q1: np.ndarray, q2: np.ndarray) -> np.ndarray:
w1, x1, y1, z1 = np.moveaxis(np.asarray(q1, dtype=np.float64), -1, 0)
w2, x2, y2, z2 = np.moveaxis(np.asarray(q2, dtype=np.float64), -1, 0)
return np.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,
],
axis=-1,
)
def quat_inv_wxyz(q: np.ndarray) -> np.ndarray:
q = np.asarray(q, dtype=np.float64)
out = q.copy()
out[..., 1:] *= -1.0
return out
def yaw_quat_wxyz(q: np.ndarray) -> np.ndarray:
"""Yaw-only quaternion from a wxyz rotation (heading)."""
q = np.asarray(q, dtype=np.float64)
w, x, y, z = q[..., 0], q[..., 1], q[..., 2], q[..., 3]
yaw = np.arctan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (y * y + z * z))
hw = 0.5 * yaw
out = np.zeros(q.shape[:-1] + (4,), dtype=np.float64)
out[..., 0] = np.cos(hw)
out[..., 3] = np.sin(hw)
return out
def quat_rotate(q: np.ndarray, v: np.ndarray) -> np.ndarray:
q = np.asarray(q, dtype=np.float64)
v = np.asarray(v, dtype=np.float64)
w, xyz = q[..., 0:1], q[..., 1:]
t = 2.0 * np.cross(xyz, v)
return v + w * t + np.cross(xyz, t)
def rot6d_from_wxyz(q: np.ndarray) -> np.ndarray:
"""First two columns of the rotation matrix, flattened **row-wise**.
``matrix_from_quat(q)[..., :2].reshape(-1)`` in Isaac Lab, i.e.
``[m00, m01, m10, m11, m20, m21]`` -- not column-major.
"""
q = np.asarray(q, dtype=np.float64)
w, x, y, z = q[..., 0], q[..., 1], q[..., 2], q[..., 3]
m00 = 1 - 2 * (y * y + z * z)
m10 = 2 * (x * y + z * w)
m20 = 2 * (x * z - y * w)
m01 = 2 * (x * y - z * w)
m11 = 1 - 2 * (x * x + z * z)
m21 = 2 * (y * z + x * w)
return np.stack([m00, m01, m10, m11, m20, m21], axis=-1)
def heading_rel_6d(robot_quat_wxyz: np.ndarray, ref_quat_wxyz: np.ndarray) -> np.ndarray:
"""quat_mul(inv(heading(robot)), ref) as 6D."""
h = yaw_quat_wxyz(robot_quat_wxyz)
rel = quat_mul_wxyz(quat_inv_wxyz(h), ref_quat_wxyz)
return rot6d_from_wxyz(rel)