Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

implement angle_axis to quaternion

edgarribae8fc6eb799f9
diff --git a/test/test_conversions.py b/test/test_conversions.py
index 1f4a23d9b..194ea88da 100644
--- a/test/test_conversions.py
+++ b/test/test_conversions.py
@@ -13,6 +13,48 @@ from common import TEST_DEVICES
# based on:
# https://github.com/ceres-solver/ceres-solver/blob/master/internal/ceres/rotation_test.cc#L271
+class TestAngleAxisToQuaternion:
+
+ def test_smoke(self):
+ angle_axis = torch.zeros(3)
+ quaternion = tgm.angle_axis_to_quaternion(angle_axis)
+ assert quaternion.shape == (4,)
+
+ @pytest.mark.parametrize("batch_size", (1, 3, 8))
+ def test_smoke_batch(self, batch_size):
+ angle_axis = torch.zeros(batch_size, 3)
+ quaternion = tgm.angle_axis_to_quaternion(angle_axis)
+ assert quaternion.shape == (batch_size, 4)
+
+ def test_zero_angle(self):
+ angle_axis = torch.Tensor([0, 0, 0])
+ expected = torch.Tensor([1, 0, 0, 0])
+ quaternion = tgm.angle_axis_to_quaternion(angle_axis)
+ assert utils.check_equal_torch(quaternion, expected)
+
+ def test_small_angle(self):
+ theta = 1e-2
+ angle_axis = torch.Tensor([theta, 0, 0])
+ expected = torch.Tensor([np.cos(theta/2), np.sin(theta/2), 0, 0])
+ quaternion = tgm.angle_axis_to_quaternion(angle_axis)
+ assert utils.check_equal_torch(quaternion, expected)
+
+ def test_x_rotation(self):
+ half_sqrt2 = 0.5 * np.sqrt(2)
+ angle_axis = torch.Tensor([tgm.pi / 2, 0, 0])
+ expected = torch.Tensor([half_sqrt2, half_sqrt2, 0, 0])
+ quaternion = tgm.angle_axis_to_quaternion(angle_axis)
+ assert utils.check_equal_torch(quaternion, expected)
+
+ def test_gradcheck(self):
+ eps = 1e-12
+ angle_axis = torch.Tensor([0, 0, 0]) + eps
+ angle_axis = utils.tensor_to_gradcheck_var(angle_axis)
+ # evaluate function gradient
+ assert gradcheck(tgm.angle_axis_to_quaternion, (angle_axis,),
+ raise_exception=True)
+
+
class TestQuaternionToAngleAxis:
def test_smoke(self):
@@ -202,7 +244,6 @@ def test_rotation_matrix_to_angle_axis_gradcheck(batch_size, device_type):
(rmat,), raise_exception=True)
@pytest.mark.parametrize("device_type", TEST_DEVICES)
def test_rotation_matrix_to_angle_axis(device_type):
device = torch.device(device_type)
diff --git a/torchgeometry/core/conversions.py b/torchgeometry/core/conversions.py
index bb1e9feff..b4d3c8898 100644
--- a/torchgeometry/core/conversions.py
+++ b/torchgeometry/core/conversions.py
@@ -1,6 +1,8 @@
import torch
import torch.nn as nn
+import torchgeometry as tgm
+
__all__ = [
# functional api
"pi",
@@ -12,6 +14,7 @@ __all__ = [
"rotation_matrix_to_angle_axis",
"rotation_matrix_to_quaternion",
"quaternion_to_angle_axis",
+ "angle_axis_to_quaternion",
"rtvec_to_pose",
# layer api
"RadToDeg",
@@ -23,7 +26,7 @@ __all__ = [
"""Constant with number pi
"""
-pi = torch.Tensor([3.141592653589793])
+pi = torch.Tensor([3.14159265358979323846])
def rad2deg(tensor):
@@ -327,8 +330,8 @@ def quaternion_to_angle_axis(quaternion: torch.Tensor) -> torch.Tensor:
- Output: :math:`(*, 3)`
Example:
- >>> quaterion = torch.rand(2, 4) # Nx4
- >>> angle_axis = tgm.quaternion_to_angle_axis(quaterion) # Nx3
+ >>> quaternion = torch.rand(2, 4) # Nx4
+ >>> angle_axis = tgm.quaternion_to_angle_axis(quaternion) # Nx3
"""
if not torch.is_tensor(quaternion):
raise TypeError("Input type is not a torch.Tensor. Got {}".format(
@@ -338,16 +341,21 @@ def quaternion_to_angle_axis(quaternion: torch.Tensor) -> torch.Tensor:
raise ValueError("Input must be a tensor of shape Nx4 or 4. Got {}"
.format(quaternion.shape))
# unpack input and compute conversion
- q0: torch.Tensor = quaternion[..., 0]
q1: torch.Tensor = quaternion[..., 1]
q2: torch.Tensor = quaternion[..., 2]
q3: torch.Tensor = quaternion[..., 3]
- sin_squared: torch.Tensor = q1 * q1 + q2 * q2 + q3 * q3
+ sin_squared_theta: torch.Tensor = q1 * q1 + q2 * q2 + q3 * q3
+
+ sin_theta: torch.Tensor = torch.sqrt(sin_squared_theta)
+ cos_theta: torch.Tensor = quaternion[..., 0]
+ two_theta: torch.Tensor = 2.0 * torch.where(
+ cos_theta < 0.0,
+ torch.atan2(-sin_theta, -cos_theta),
+ torch.atan2(sin_theta, cos_theta))
- sin_theta: torch.Tensor = torch.sqrt(sin_squared)
+ k_pos: torch.Tensor = two_theta / sin_theta
k_neg: torch.Tensor = 2.0 * torch.ones_like(sin_theta)
- k_pos: torch.Tensor = 2.0 * torch.atan2(sin_theta, q0) / sin_theta
- k: torch.Tensor = torch.where(sin_squared > 0.0, k_pos, k_neg)
+ k: torch.Tensor = torch.where(sin_squared_theta > 0.0, k_pos, k_neg)
angle_axis: torch.Tensor = torch.zeros_like(quaternion)[..., :3]
angle_axis[..., 0] += q1 * k
@@ -355,6 +363,57 @@ def quaternion_to_angle_axis(quaternion: torch.Tensor) -> torch.Tensor:
angle_axis[..., 2] += q3 * k
return angle_axis
+# based on: https://github.com/facebookresearch/QuaterNet/blob/master/common/quaternion.py#L138
+
+def angle_axis_to_quaternion(angle_axis: torch.Tensor) -> torch.Tensor:
+ """Convert an angle axis to a quaternion.
+
+ Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h
+
+ Args:
+ angle_axis (torch.Tensor): tensor with angle axis.
+
+ Return:
+ torch.Tensor: tensor with quaternion.
+
+ Shape:
+ - Input: :math:`(*, 3)` where `*` means, any number of dimensions
+ - Output: :math:`(*, 4)`
+
+ Example:
+ >>> angle_axis = torch.rand(2, 4) # Nx4
+ >>> quaternion = tgm.angle_axis_to_quaternion(angle_axis) # Nx3
+ """
+ if not torch.is_tensor(angle_axis):
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(
+ type(angle_axis)))
+
+ if not angle_axis.shape[-1] == 3:
+ raise ValueError("Input must be a tensor of shape Nx3 or 3. Got {}"
+ .format(angle_axis.shape))
+ # unpack input and compute conversion
+ a0: torch.Tensor = angle_axis[..., 0:1]
+ a1: torch.Tensor = angle_axis[..., 1:2]
+ a2: torch.Tensor = angle_axis[..., 2:3]
+ theta_squared: torch.Tensor = a0 * a0 + a1 * a1 + a2 * a2
+
+ theta: torch.Tensor = torch.sqrt(theta_squared)
+ half_theta: torch.Tensor = theta * 0.5
+
+ mask: torch.Tensor = theta_squared > 0.0
+ ones: torch.Tensor = torch.ones_like(half_theta)
+
+ k_neg: torch.Tensor = 0.5 * ones
+ k_pos: torch.Tensor = torch.sin(half_theta) / theta
+ k: torch.Tensor = torch.where(mask, k_pos, k_neg)
+ w: torch.Tensor = torch.where(mask, torch.cos(half_theta), ones)
+
+ quaternion: torch.Tensor = torch.zeros_like(angle_axis)
+ quaternion[..., 0:1] += a0 * k
+ quaternion[..., 1:2] += a1 * k
+ quaternion[..., 2:3] += a2 * k
+ return torch.cat([w, quaternion], dim=-1)
+
# TODO: add below funtionalities
# - pose_to_rtvec