Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

quaternion, so3 and se3 as non batched (#1997)

Edgar Ribadaa9aa253b2b
diff --git a/kornia/core/__init__.py b/kornia/core/__init__.py
index 875e97795..0ab237246 100644
--- a/kornia/core/__init__.py
+++ b/kornia/core/__init__.py
@@ -13,6 +13,7 @@ from ._backend import (
tensor,
where,
zeros,
+ zeros_like,
)
__all__ = [
@@ -30,4 +31,5 @@ __all__ = [
"where",
"eye",
"zeros",
+ "zeros_like",
]
diff --git a/kornia/core/_backend.py b/kornia/core/_backend.py
index 3e5804a50..9aab4ace4 100644
--- a/kornia/core/_backend.py
+++ b/kornia/core/_backend.py
@@ -17,6 +17,7 @@ normalize = F.normalize
pad = F.pad
eye = torch.eye
zeros = torch.zeros
+zeros_like = torch.zeros_like
where = torch.where
# constructors
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index 932b40de5..0faa79920 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -1,12 +1,14 @@
# kornia.geometry.so3 module inspired by Sophus-sympy.
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/se3.py
-from kornia.core import Tensor, as_tensor, concatenate, eye, pad, where
-from kornia.geometry.liegroup._utils import squared_norm
+from typing import Optional
+
+from kornia.core import Module, Parameter, Tensor, concatenate, eye, pad, tensor, where
from kornia.geometry.liegroup.so3 import So3
+from kornia.geometry.linalg import batched_dot_product
from kornia.testing import KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
-class Se3:
+class Se3(Module):
r"""Base class to represent the Se3 group.
The SE(3) is the group of rigid body transformations about the origin of three-dimensional Euclidean
@@ -15,13 +17,14 @@ class Se3:
Example:
>>> from kornia.geometry.quaternion import Quaternion
- >>> q = Quaternion.identity(batch_size=1)
- >>> s = Se3(So3(q), torch.ones((1, 3)))
+ >>> q = Quaternion.identity()
+ >>> s = Se3(So3(q), torch.ones(3))
>>> s.r
- real: tensor([[1.]], grad_fn=<SliceBackward0>)
- vec: tensor([[0., 0., 0.]], grad_fn=<SliceBackward0>)
+ Parameter containing:
+ tensor([1., 0., 0., 0.], requires_grad=True)
>>> s.t
- tensor([[1., 1., 1.]])
+ Parameter containing:
+ tensor([1., 1., 1.], requires_grad=True)
"""
def __init__(self, r: So3, t: Tensor) -> None:
@@ -36,17 +39,19 @@ class Se3:
Example:
>>> from kornia.geometry.quaternion import Quaternion
>>> q = Quaternion.identity(batch_size=1)
- >>> s = Se3(So3(q), torch.ones((1,3)))
+ >>> s = Se3(So3(q), torch.ones((1, 3)))
>>> s.r
- real: tensor([[1.]], grad_fn=<SliceBackward0>)
- vec: tensor([[0., 0., 0.]], grad_fn=<SliceBackward0>)
+ Parameter containing:
+ tensor([[1., 0., 0., 0.]], requires_grad=True)
>>> s.t
- tensor([[1., 1., 1.]])
+ Parameter containing:
+ tensor([[1., 1., 1.]], requires_grad=True)
"""
+ super().__init__()
KORNIA_CHECK_TYPE(r, So3)
KORNIA_CHECK_SHAPE(t, ["B", "3"])
self._r = r
- self._t = t
+ self._t = Parameter(t)
def __repr__(self) -> str:
return f"rotation: {self.r}\ntranslation: {self.t}"
@@ -63,11 +68,23 @@ class Se3:
Return:
The resulting Se3 transformation.
"""
- KORNIA_CHECK_TYPE(right, Se3)
- # https://github.com/strasdat/Sophus/blob/master/sympy/sophus/se3.py#L97
- r = self.r * right.r
- t = self.t + self.r * right.t
- return Se3(r, t)
+ if isinstance(right, Se3):
+ KORNIA_CHECK_TYPE(right, Se3)
+ # https://github.com/strasdat/Sophus/blob/master/sympy/sophus/se3.py#L97
+ r = self.so3 * right.so3
+ t = self.t + self.so3 * right.t
+ return Se3(r, t)
+ elif isinstance(right, Tensor):
+ KORNIA_CHECK_TYPE(right, Tensor)
+ KORNIA_CHECK_SHAPE(right, ["B", "N"])
+ return self.so3 * right + self.t
+ else:
+ raise TypeError(f"Unsupported type: {type(right)}")
+
+ @property
+ def so3(self) -> So3:
+ """Return the underlying rotation(So3)."""
+ return self._r
@property
def r(self) -> So3:
@@ -90,23 +107,25 @@ class Se3:
>>> v = torch.zeros((1, 6))
>>> s = Se3.exp(v)
>>> s.r
- real: tensor([[1.]], grad_fn=<SliceBackward0>)
- vec: tensor([[0., 0., 0.]], grad_fn=<SliceBackward0>)
+ Parameter containing:
+ tensor([[1., 0., 0., 0.]], requires_grad=True)
>>> s.t
- tensor([[0., 0., 0.]])
+ Parameter containing:
+ tensor([[0., 0., 0.]], requires_grad=True)
"""
KORNIA_CHECK_SHAPE(v, ["B", "6"])
- t = v[..., 0:3]
+ upsilon = v[..., :3]
omega = v[..., 3:]
omega_hat = So3.hat(omega)
- theta = squared_norm(omega).sqrt()
+ omega_hat_sq = omega_hat @ omega_hat
+ theta = batched_dot_product(omega, omega).sqrt()
R = So3.exp(omega)
V = (
eye(3, device=v.device, dtype=v.dtype)
- + ((1 - theta.cos()) / (theta**2))[..., None] * omega_hat
- + ((theta - theta.sin()) / (theta**3))[..., None] * (omega_hat @ omega_hat)
+ + ((1 - theta.cos()) / (theta**2))[..., None, None] * omega_hat
+ + ((theta - theta.sin()) / (theta**3))[..., None, None] * omega_hat_sq
)
- U = where(theta != 0.0, (t.reshape(-1, 1, 3) * V).sum(-1), t)
+ U = where(theta[..., None] != 0.0, (upsilon[..., None, :] * V).sum(-1), upsilon)
return Se3(R, U)
def log(self) -> Tensor:
@@ -114,42 +133,45 @@ class Se3:
Example:
>>> from kornia.geometry.quaternion import Quaternion
- >>> q = Quaternion.identity(batch_size=1)
- >>> Se3(So3(q), torch.zeros((1,3))).log()
- tensor([[0., 0., 0., 0., 0., 0.]], grad_fn=<CatBackward0>)
+ >>> q = Quaternion.identity()
+ >>> Se3(So3(q), torch.zeros(3)).log()
+ tensor([0., 0., 0., 0., 0., 0.], grad_fn=<CatBackward0>)
"""
omega = self.r.log()
- theta = squared_norm(omega).sqrt()
+ theta = batched_dot_product(omega, omega).sqrt()
omega_hat = So3.hat(omega)
+ omega_hat_sq = omega_hat @ omega_hat
V_inv = (
eye(3, device=omega.device, dtype=omega.dtype)
- 0.5 * omega_hat
- + ((1 - theta * (theta / 2).cos() / (2 * (theta / 2).sin())) / theta.pow(2))[..., None]
- * (omega_hat @ omega_hat)
+ + ((1 - theta * (theta / 2).cos() / (2 * (theta / 2).sin())) / theta.pow(2))[..., None, None] * omega_hat_sq
)
- t = where(theta != 0.0, (self.t.reshape(-1, 1, 3) * V_inv).sum(-1), self.t)
+ t = where(theta[..., None] != 0.0, (self.t[..., None, :] * V_inv).sum(-1), self.t)
return concatenate((t, omega), -1)
@staticmethod
def hat(v) -> Tensor:
- """Converts elements from vector space to lie algebra. Returns matrix of shape :math:`(B,4,4)`.
+ """Converts elements from vector space to lie algebra.
Args:
- v: vector of shape :math:`(B,6)`.
+ v: vector of shape :math:`(B, 6)`.
+
+ Returns:
+ matrix of shape :math:`(B, 4, 4)`.
Example:
- >>> v = torch.ones((1,6))
+ >>> v = torch.ones((1, 6))
>>> m = Se3.hat(v)
>>> m
- tensor([[[ 0., 0., -1., 1.],
- [ 0., 1., 0., -1.],
- [ 0., -1., 1., 0.],
- [ 0., 1., 1., 1.]]])
+ tensor([[[ 0., -1., 1., 1.],
+ [ 1., 0., -1., 1.],
+ [-1., 1., 0., 1.],
+ [ 0., 0., 0., 0.]]])
"""
KORNIA_CHECK_SHAPE(v, ["B", "6"])
- t, omega = v[..., None, :3], v[..., 3:]
- rt = concatenate((So3.hat(omega), t), 1)
- return pad(rt, (1, 0, 0, 0)) # add zeros left column
+ upsilon, omega = v[..., :3], v[..., 3:]
+ rt = concatenate((So3.hat(omega), upsilon[..., None]), -1)
+ return pad(rt, (0, 0, 0, 1)) # add zeros bottom
@staticmethod
def vee(omega) -> Tensor:
@@ -162,46 +184,50 @@ class Se3:
vector of shape :math:`(B,6)`.
Example:
- >>> v = torch.ones((1,6))
+ >>> v = torch.ones((1, 6))
>>> omega_hat = Se3.hat(v)
>>> Se3.vee(omega_hat)
tensor([[1., 1., 1., 1., 1., 1.]])
"""
KORNIA_CHECK_SHAPE(omega, ["B", "4", "4"])
- t = omega[..., 3, 1:]
- v = So3.vee(omega[..., 0:3, 1:])
- return concatenate((t, v), 1)
+ head = omega[..., :3, -1]
+ tail = So3.vee(omega[..., :3, :3])
+ return concatenate((head, tail), -1)
@classmethod
- def identity(cls, batch_size: int, device=None, dtype=None) -> 'Se3':
+ def identity(cls, batch_size: Optional[int] = None, device=None, dtype=None) -> 'Se3':
"""Create a Se3 group representing an identity rotation and zero translation.
Args:
batch_size: the batch size of the underlying data.
Example:
- >>> s = Se3.identity(batch_size=1)
+ >>> s = Se3.identity()
>>> s.r
- real: tensor([[1.]], grad_fn=<SliceBackward0>)
- vec: tensor([[0., 0., 0.]], grad_fn=<SliceBackward0>)
+ Parameter containing:
+ tensor([1., 0., 0., 0.], requires_grad=True)
>>> s.t
- tensor([[0., 0., 0.]])
+ Parameter containing:
+ tensor([0., 0., 0.], requires_grad=True)
"""
- t: Tensor = as_tensor(batch_size * [[0.0, 0.0, 0.0]], device=device, dtype=dtype)
+ t: Tensor = tensor([0.0, 0.0, 0.0], device=device, dtype=dtype)
+ if batch_size is not None:
+ t = t.repeat(batch_size, 1)
+
return cls(So3.identity(batch_size, device, dtype), t)
def matrix(self) -> Tensor:
"""Returns the matrix representation of shape :math:`(B, 4, 4)`.
Example:
- >>> s = Se3(So3.identity(batch_size=1), torch.ones((1,3)))
+ >>> s = Se3(So3.identity(), torch.ones(3))
>>> s.matrix()
- tensor([[[1., 0., 0., 1.],
- [0., 1., 0., 1.],
- [0., 0., 1., 1.],
- [0., 0., 0., 1.]]], grad_fn=<CopySlices>)
+ tensor([[1., 0., 0., 1.],
+ [0., 1., 0., 1.],
+ [0., 0., 1., 1.],
+ [0., 0., 0., 1.]], grad_fn=<CopySlices>)
"""
- rt = concatenate((self.r.matrix(), self.t.reshape(-1, 3, 1)), 2)
+ rt = concatenate((self.r.matrix(), self.t[..., None]), -1)
rt_4x4 = pad(rt, (0, 0, 0, 1)) # add last row zeros
rt_4x4[..., -1, -1] = 1.0
return rt_4x4
@@ -210,13 +236,14 @@ class Se3:
"""Returns the inverse transformation.
Example:
- >>> s = Se3(So3.identity(batch_size=1), torch.ones((1,3)))
+ >>> s = Se3(So3.identity(), torch.ones(3))
>>> s_inv = s.inverse()
>>> s_inv.r
- real: tensor([[1.]], grad_fn=<SliceBackward0>)
- vec: tensor([[-0., -0., -0.]], grad_fn=<SliceBackward0>)
+ Parameter containing:
+ tensor([1., -0., -0., -0.], requires_grad=True)
>>> s_inv.t
- tensor([[-1., -1., -1.]], grad_fn=<SliceBackward0>)
+ Parameter containing:
+ tensor([-1., -1., -1.], requires_grad=True)
"""
r_inv = self.r.inverse()
return Se3(r_inv, r_inv * (-1 * self.t))
diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.py
index 66ada48b7..47ecba39a 100644
--- a/kornia/geometry/liegroup/so3.py
+++ b/kornia/geometry/liegroup/so3.py
@@ -1,12 +1,14 @@
# kornia.geometry.so3 module inspired by Sophus-sympy.
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py
-from kornia.core import Tensor, concatenate, stack, tensor, where, zeros
-from kornia.geometry.liegroup._utils import squared_norm
+from typing import Optional
+
+from kornia.core import Module, Tensor, concatenate, stack, tensor, where, zeros, zeros_like
+from kornia.geometry.linalg import batched_dot_product
from kornia.geometry.quaternion import Quaternion
from kornia.testing import KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
-class So3:
+class So3(Module):
r"""Base class to represent the So3 group.
The SO(3) is the group of all rotations about the origin of three-dimensional Euclidean space
@@ -16,11 +18,11 @@ class So3:
We internally represent the rotation by a unit quaternion.
Example:
- >>> q = Quaternion.identity(batch_size=1)
+ >>> q = Quaternion.identity()
>>> s = So3(q)
>>> s.q
- real: tensor([[1.]], grad_fn=<SliceBackward0>)
- vec: tensor([[0., 0., 0.]], grad_fn=<SliceBackward0>)
+ Parameter containing:
+ tensor([1., 0., 0., 0.], requires_grad=True)
"""
def __init__(self, q: Quaternion) -> None:
@@ -35,11 +37,11 @@ class So3:
>>> data = torch.ones((2, 4))
>>> q = Quaternion(data)
>>> So3(q)
- real: tensor([[1.],
- [1.]], grad_fn=<SliceBackward0>)
- vec: tensor([[1., 1., 1.],
- [1., 1., 1.]], grad_fn=<SliceBackward0>)
+ Parameter containing:
+ tensor([[1., 1., 1., 1.],
+ [1., 1., 1., 1.]], requires_grad=True)
"""
+ super().__init__()
KORNIA_CHECK_TYPE(q, Quaternion)
self._q = q
@@ -63,8 +65,9 @@ class So3:
return So3(self.q * right.q)
elif isinstance(right, Tensor):
KORNIA_CHECK_SHAPE(right, ["B", "3"])
- w = zeros(right.shape[0], 1).to(right.device, right.dtype)
- return (self.q * Quaternion(concatenate((w, right), 1)) * self.q.conj()).vec
+ w = zeros(*right.shape[:-1], 1, device=right.device, dtype=right.dtype)
+ quat = Quaternion(concatenate((w, right), -1))
+ return (self.q * quat * self.q.conj()).vec
else:
raise TypeError(f"Not So3 or Tensor type. Got: {type(right)}")
@@ -83,16 +86,15 @@ class So3:
v: vector of shape :math:`(B,3)`.
Example:
- >>> v = torch.zeros((2,3))
- >>> s = So3.identity(batch_size=1).exp(v)
+ >>> v = torch.zeros((2, 3))
+ >>> s = So3.identity().exp(v)
>>> s
- real: tensor([[1.],
- [1.]], grad_fn=<SliceBackward0>)
- vec: tensor([[0., 0., 0.],
- [0., 0., 0.]], grad_fn=<SliceBackward0>)
+ Parameter containing:
+ tensor([[1., 0., 0., 0.],
+ [1., 0., 0., 0.]], requires_grad=True)
"""
KORNIA_CHECK_SHAPE(v, ["B", "3"])
- theta = squared_norm(v).sqrt()
+ theta = batched_dot_product(v, v).sqrt()[..., None]
theta_nonzeros = theta != 0.0
theta_half = 0.5 * theta
# TODO: uncomment me after deprecate pytorch 10.2
@@ -101,7 +103,7 @@ class So3:
w = where(theta_nonzeros, theta_half.cos(), tensor(1.0, device=v.device, dtype=v.dtype))
b = where(theta_nonzeros, theta_half.sin() / theta, tensor(0.0, device=v.device, dtype=v.dtype))
xyz = b * v
- return So3(Quaternion(concatenate((w, xyz), 1)))
+ return So3(Quaternion(concatenate((w, xyz), -1)))
def log(self) -> Tensor:
"""Converts elements of lie group to elements of lie algebra.
@@ -113,9 +115,13 @@ class So3:
tensor([[0., 0., 0.],
[0., 0., 0.]], grad_fn=<WhereBackward0>)
"""
- theta = squared_norm(self.q.vec).sqrt()
+ theta = batched_dot_product(self.q.vec, self.q.vec).sqrt()
# NOTE: this differs from https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py#L33
- omega = where(theta != 0, 2 * self.q.real.acos() * self.q.vec / theta, 2 * self.q.vec / self.q.real)
+ omega = where(
+ theta[..., None] != 0,
+ 2 * self.q.real[..., None].acos() * self.q.vec / theta[..., None],
+ 2 * self.q.vec / self.q.real[..., None],
+ )
return omega
@staticmethod
@@ -134,13 +140,12 @@ class So3:
[-1., 1., 0.]]])
"""
KORNIA_CHECK_SHAPE(v, ["B", "3"])
- v = v[..., None, None]
- a, b, c = v[:, 0], v[:, 1], v[:, 2]
- z = zeros(v.shape[0], 1, 1, device=v.device, dtype=v.dtype)
- row0 = concatenate((z, -c, b), 2)
- row1 = concatenate((c, z, -a), 2)
- row2 = concatenate((-b, a, z), 2)
- return concatenate((row0, row1, row2), 1)
+ a, b, c = v[..., 0], v[..., 1], v[..., 2]
+ z = zeros_like(a)
+ row0 = stack((z, -c, b), -1)
+ row1 = stack((c, z, -a), -1)
+ row2 = stack((-b, a, z), -1)
+ return stack((row0, row1, row2), -2)
@staticmethod
def vee(omega) -> Tensor:
@@ -162,7 +167,7 @@ class So3:
"""
KORNIA_CHECK_SHAPE(omega, ["B", "3", "3"])
a, b, c = omega[..., 2, 1], omega[..., 0, 2], omega[..., 1, 0]
- return stack((a, b, c), 1)
+ return stack((a, b, c), -1)
def matrix(self) -> Tensor:
r"""Convert the quaternion to a rotation matrix of shape :math:`(B,3,3)`.
@@ -175,28 +180,28 @@ class So3:
2xz-2yw & 2yz+2xw & 1-2x^2-2y^2\end{bmatrix}
Example:
- >>> s = So3.identity(batch_size=1)
+ >>> s = So3.identity()
>>> m = s.matrix()
>>> m
- tensor([[[1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.]]], grad_fn=<CatBackward0>)
+ tensor([[1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.]], grad_fn=<StackBackward0>)
"""
w = self.q.w[..., None]
x, y, z = self.q.x[..., None], self.q.y[..., None], self.q.z[..., None]
q0 = 1 - 2 * y**2 - 2 * z**2
q1 = 2 * x * y - 2 * z * w
q2 = 2 * x * z + 2 * y * w
- row0 = concatenate((q0, q1, q2), 2)
+ row0 = concatenate((q0, q1, q2), -1)
q0 = 2 * x * y + 2 * z * w
q1 = 1 - 2 * x**2 - 2 * z**2
q2 = 2 * y * z - 2 * x * w
- row1 = concatenate((q0, q1, q2), 2)
+ row1 = concatenate((q0, q1, q2), -1)
q0 = 2 * x * z - 2 * y * w
q1 = 2 * y * z + 2 * x * w
q2 = 1 - 2 * x**2 - 2 * y**2
- row2 = concatenate((q0, q1, q2), 2)
- return concatenate((row0, row1, row2), 1)
+ row2 = concatenate((q0, q1, q2), -1)
+ return stack((row0, row1, row2), -2)
@classmethod
def from_matrix(cls, matrix: Tensor) -> 'So3':
@@ -206,28 +211,32 @@ class So3:
matrix: the rotation matrix to convert of shape :math:`(B,3,3)`.
Example:
- >>> m = torch.eye(3)[None]
+ >>> m = torch.eye(3)
>>> s = So3.from_matrix(m)
>>> s
- real: tensor([[1.]], grad_fn=<SliceBackward0>)
- vec: tensor([[0., 0., 0.]], grad_fn=<SliceBackward0>)
+ Parameter containing:
+ tensor([1., 0., 0., 0.], requires_grad=True)
"""
return cls(Quaternion.from_matrix(matrix))
@classmethod
- def identity(cls, batch_size: int, device=None, dtype=None) -> 'So3':
+ def identity(cls, batch_size: Optional[int] = None, device=None, dtype=None) -> 'So3':
"""Create a So3 group representing an identity rotation.
Args:
batch_size: the batch size of the underlying data.
Example:
+ >>> s = So3.identity()
+ >>> s
+ Parameter containing:
+ tensor([1., 0., 0., 0.], requires_grad=True)
+
>>> s = So3.identity(batch_size=2)
>>> s
- real: tensor([[1.],
- [1.]], grad_fn=<SliceBackward0>)
- vec: tensor([[0., 0., 0.],
- [0., 0., 0.]], grad_fn=<SliceBackward0>)
+ Parameter containing:
+ tensor([[1., 0., 0., 0.],
+ [1., 0., 0., 0.]], requires_grad=True)
"""
return cls(Quaternion.identity(batch_size, device, dtype))
@@ -235,9 +244,9 @@ class So3:
"""Returns the inverse transformation.
Example:
- >>> s = So3.identity(batch_size=1)
+ >>> s = So3.identity()
>>> s.inverse()
- real: tensor([[1.]], grad_fn=<SliceBackward0>)
- vec: tensor([[-0., -0., -0.]], grad_fn=<SliceBackward0>)
+ Parameter containing:
+ tensor([1., -0., -0., -0.], requires_grad=True)
"""
return So3(self.q.conj())
diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.py
index b56c976f9..0a32656a0 100644
--- a/kornia/geometry/quaternion.py
+++ b/kornia/geometry/quaternion.py
@@ -3,9 +3,9 @@
# https://github.com/KieranWynn/pyquaternion/blob/master/pyquaternion/quaternion.py
# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Quaternion.h
from math import pi
-from typing import Tuple, Union
+from typing import Optional, Tuple, Union
-from kornia.core import Module, Parameter, Tensor, as_tensor, concatenate, rand, stack, where
+from kornia.core import Module, Parameter, Tensor, concatenate, rand, stack, tensor, where
from kornia.geometry.conversions import (
QuaternionCoeffOrder,
angle_axis_to_quaternion,
@@ -13,7 +13,8 @@ from kornia.geometry.conversions import (
quaternion_to_rotation_matrix,
rotation_matrix_to_quaternion,
)
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
+from kornia.geometry.linalg import batched_dot_product
+from kornia.testing import KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
class Quaternion(Module):
@@ -44,10 +45,7 @@ class Quaternion(Module):
[1., 0., 0., 0.],
[1., 0., 0., 0.]], requires_grad=True)
>>> q.real
- tensor([[1.],
- [1.],
- [1.],
- [1.]], grad_fn=<SliceBackward0>)
+ tensor([1., 1., 1., 1.], grad_fn=<SelectBackward0>)
>>> q.vec
tensor([[0., 0., 0.],
[0., 0., 0.],
@@ -72,7 +70,7 @@ class Quaternion(Module):
self._data = Parameter(data)
def __repr__(self) -> str:
- return f"real: {self.real}\nvec: {self.vec}"
+ return f"{self.data}"
def __getitem__(self, idx) -> 'Quaternion':
return Quaternion(self.data[idx].reshape(1, -1))
@@ -81,9 +79,9 @@ class Quaternion(Module):
"""Inverts the sign of the quaternion data.
Example:
- >>> q = Quaternion.identity(batch_size=1)
+ >>> q = Quaternion.identity()
>>> -q.data
- tensor([[-1., -0., -0., -0.]], grad_fn=<NegBackward0>)
+ tensor([-1., -0., -0., -0.], grad_fn=<NegBackward0>)
"""
return Quaternion(-self.data)
@@ -94,12 +92,12 @@ class Quaternion(Module):
right: the quaternion to add.
Example:
- >>> q1 = Quaternion.identity(batch_size=1)
- >>> q2 = Quaternion(Tensor([[2., 0., 1., 1.]]))
+ >>> q1 = Quaternion.identity()
+ >>> q2 = Quaternion(tensor([2., 0., 1., 1.]))
>>> q3 = q1 + q2
>>> q3.data
Parameter containing:
- tensor([[3., 0., 1., 1.]], requires_grad=True)
+ tensor([3., 0., 1., 1.], requires_grad=True)
"""
KORNIA_CHECK_TYPE(right, Quaternion)
return Quaternion(self.data + right.data)
@@ -111,12 +109,12 @@ class Quaternion(Module):
right: the quaternion to subtract.
Example:
- >>> q1 = Quaternion(Tensor([[2., 0., 1., 1.]]))
- >>> q2 = Quaternion.identity(batch_size=1)
+ >>> q1 = Quaternion(tensor([2., 0., 1., 1.]))
+ >>> q2 = Quaternion.identity()
>>> q3 = q1 - q2
>>> q3.data
Parameter containing:
- tensor([[1., 0., 1., 1.]], requires_grad=True)
+ tensor([1., 0., 1., 1.], requires_grad=True)
"""
KORNIA_CHECK_TYPE(right, Quaternion)
return Quaternion(self.data - right.data)
@@ -125,13 +123,13 @@ class Quaternion(Module):
KORNIA_CHECK_TYPE(right, Quaternion)
# NOTE: borrowed from sophus sympy. Produce less multiplications compared to others.
# https://github.com/strasdat/Sophus/blob/785fef35b7d9e0fc67b4964a69124277b7434a44/sympy/sophus/quaternion.py#L19
- new_real = self.real * right.real - self._batched_squared_norm(self.vec, right.vec)
- new_vec = self.real * right.vec + right.real * self.vec + self.vec.cross(right.vec)
- return Quaternion(concatenate((new_real, new_vec), -1))
+ new_real = self.real * right.real - batched_dot_product(self.vec, right.vec)
+ new_vec = self.real[..., None] * right.vec + right.real[..., None] * self.vec + self.vec.cross(right.vec)
+ return Quaternion(concatenate((new_real[..., None], new_vec), -1))
def __div__(self, right: Union[Tensor, 'Quaternion']) -> 'Quaternion':
if isinstance(right, Tensor):
- return Quaternion(self.data / right)
+ return Quaternion(self.data / right[..., None])
KORNIA_CHECK_TYPE(right, Quaternion)
return self * right.inv()
@@ -145,10 +143,10 @@ class Quaternion(Module):
t: raised exponent.
Example:
- >>> q = Quaternion(torch.tensor([1., .5, 0., 0.]))
+ >>> q = Quaternion(tensor([1., .5, 0., 0.]))
>>> q_pow = q**2
"""
- theta = self.polar_angle
+ theta = self.polar_angle[..., None]
vec_norm = self.vec.norm(dim=-1, keepdim=True)
n = where(vec_norm != 0, self.vec / vec_norm, self.vec * 0)
w = (t * theta).cos()
@@ -157,12 +155,12 @@ class Quaternion(Module):
@property
def data(self) -> Tensor:
- """Return the underlying data with shape :math:`(B,4).`"""
+ """Return the underlying data with shape :math:`(B, 4).`"""
return self._data
@property
def coeffs(self) -> Tensor:
- """Return the underlying data with shape :math:`(B,4)`.
+ """Return the underlying data with shape :math:`(B, 4)`.
Alias for :func:`~kornia.geometry.quaternion.Quaternion.data`
"""
@@ -170,7 +168,7 @@ class Quaternion(Module):
@property
def real(self) -> Tensor:
- """Return the real part with shape :math:`(B,1)`.
+ """Return the real part with shape :math:`(B,)`.
Alias for :func:`~kornia.geometry.quaternion.Quaternion.w`
"""
@@ -178,12 +176,12 @@ class Quaternion(Module):
@property
def vec(self) -> Tensor:
- """Return the vector with the imaginary part with shape :math:`(B,3)`."""
+ """Return the vector with the imaginary part with shape :math:`(B, 3)`."""
return self.data[..., 1:]
@property
def q(self) -> Tensor:
- """Return the underlying data with shape :math:`(B,4)`.
+ """Return the underlying data with shape :math:`(B, 4)`.
Alias for :func:`~kornia.geometry.quaternion.Quaternion.data`
"""
@@ -191,7 +189,7 @@ class Quaternion(Module):
@property
def scalar(self) -> Tensor:
- """Return a scalar with the real with shape :math:`(B,1)`.
+ """Return a scalar with the real with shape :math:`(B,)`.
Alias for :func:`~kornia.geometry.quaternion.Quaternion.w`
"""
@@ -199,27 +197,27 @@ class Quaternion(Module):
@property
def w(self) -> Tensor:
- """Return the :math:`q_w` with shape :math:`(B,1)`."""
- return self.data[..., 0:1]
+ """Return the :math:`q_w` with shape :math:`(B,)`."""
+ return self.data[..., 0]
@property
def x(self) -> Tensor:
- """Return the :math:`q_x` with shape :math:`(B,1)`."""
- return self.data[..., 1:2]
+ """Return the :math:`q_x` with shape :math:`(B,)`."""
+ return self.data[..., 1]
@property
def y(self) -> Tensor:
- """Return the :math:`q_y` with shape :math:`(B,1)`."""
- return self.data[..., 2:3]
+ """Return the :math:`q_y` with shape :math:`(B,)`."""
+ return self.data[..., 2]
@property
def z(self) -> Tensor:
- """Return the :math:`q_z` with shape :math:`(B,1)`."""
- return self.data[..., 3:4]
+ """Return the :math:`q_z` with shape :math:`(B,)`."""
+ return self.data[..., 3]
@property
def shape(self) -> Tuple[int, ...]:
- """Return the shape of the underlying data with shape :math:`(B,4)`."""
+ """Return the shape of the underlying data with shape :math:`(B, 4)`."""
return tuple(self.data.shape)
@property
@@ -227,22 +225,22 @@ class Quaternion(Module):
"""Return the polar angle with shape :math:`(B,1)`.
Example:
- >>> q = Quaternion.identity(batch_size=1)
+ >>> q = Quaternion.identity()
>>> q.polar_angle
- tensor([[0.]], grad_fn=<AcosBackward0>)
+ tensor(0., grad_fn=<AcosBackward0>)
"""
return (self.scalar / self.norm()).acos()
def matrix(self) -> Tensor:
- """Convert the quaternion to a rotation matrix of shape :math:`(B,3,3)`.
+ """Convert the quaternion to a rotation matrix of shape :math:`(B, 3, 3)`.
Example:
- >>> q = Quaternion.identity(batch_size=1)
+ >>> q = Quaternion.identity()
>>> m = q.matrix()
>>> m
- tensor([[[1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.]]], grad_fn=<ViewBackward0>)
+ tensor([[1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.]], grad_fn=<SqueezeBackward1>)
"""
return quaternion_to_rotation_matrix(self.data, order=QuaternionCoeffOrder.WXYZ)
@@ -251,7 +249,7 @@ class Quaternion(Module):
"""Create a quaternion from a rotation matrix.
Args:
- matrix: the rotation matrix to convert of shape :math:`(B,3,3)`.
+ matrix: the rotation matrix to convert of shape :math:`(B, 3, 3)`.
Example:
>>> m = torch.eye(3)[None]
@@ -267,7 +265,7 @@ class Quaternion(Module):
"""Create a quaternion from axis-angle representation.
Args:
- axis_angle: rotation vector of shape :math:`(B,3)`.
+ axis_angle: rotation vector of shape :math:`(B, 3)`.
Example:
>>> axis_angle = torch.tensor([[1., 0., 0.]])
@@ -279,21 +277,21 @@ class Quaternion(Module):
return cls(angle_axis_to_quaternion(axis_angle, order=QuaternionCoeffOrder.WXYZ))
@classmethod
- def identity(cls, batch_size: int, device=None, dtype=None) -> 'Quaternion':
+ def identity(cls, batch_size: Optional[int] = None, device=None, dtype=None) -> 'Quaternion':
"""Create a quaternion representing an identity rotation.
Args:
batch_size: the batch size of the underlying data.
Example:
- >>> q = Quaternion.identity(batch_size=2)
+ >>> q = Quaternion.identity()
>>> q.data
Parameter containing:
- tensor([[1., 0., 0., 0.],
- [1., 0., 0., 0.]], requires_grad=True)
+ tensor([1., 0., 0., 0.], requires_grad=True)
"""
- data: Tensor = as_tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=dtype)
- data = data.repeat(batch_size, 1)
+ data: Tensor = tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=dtype)
+ if batch_size is not None:
+ data = data.repeat(batch_size, 1)
return cls(data)
@classmethod
@@ -310,15 +308,15 @@ class Quaternion(Module):
>>> q = Quaternion.from_coeffs(1., 0., 0., 0.)
>>> q.data
Parameter containing:
- tensor([[1., 0., 0., 0.]], requires_grad=True)
+ tensor([1., 0., 0., 0.], requires_grad=True)
"""
- return cls(as_tensor([[w, x, y, z]]))
+ return cls(tensor([w, x, y, z]))
# TODO: update signature
# def random(cls, shape: Optional[List] = None, device = None, dtype = None) -> 'Quaternion':
@classmethod
- def random(cls, batch_size: int) -> 'Quaternion':
- """Create a random unit quaternion of shape :math:`(B,4)`.
+ def random(cls, batch_size: Optional[int] = None, device=None, dtype=None) -> 'Quaternion':
+ """Create a random unit quaternion of shape :math:`(B, 4)`.
Uniformly distributed across the rotation space as per: http://planning.cs.uiuc.edu/node198.html
@@ -326,9 +324,12 @@ class Quaternion(Module):
batch_size: the batch size of the underlying data.
Example:
+ >>> q = Quaternion.random()
>>> q = Quaternion.random(batch_size=2)
"""
- r1, r2, r3 = rand(3, batch_size)
+ rand_shape = (batch_size,) if batch_size is not None else ()
+
+ r1, r2, r3 = rand((3,) + rand_shape, device=device, dtype=dtype)
q1 = (1.0 - r1).sqrt() * ((2 * pi * r2).sin())
q2 = (1.0 - r1).sqrt() * ((2 * pi * r2).cos())
q3 = r1.sqrt() * (2 * pi * r3).sin()
@@ -345,8 +346,8 @@ class Quaternion(Module):
t: interpolation ratio, range [0-1]
Example:
- >>> q0 = Quaternion.identity(batch_size=1)
- >>> q1 = Quaternion(torch.tensor([[1., .5, 0., 0.]]))
+ >>> q0 = Quaternion.identity()
+ >>> q1 = Quaternion(torch.tensor([1., .5, 0., 0.]))
>>> q2 = q0.slerp(q1, .3)
"""
KORNIA_CHECK_TYPE(q1, Quaternion)
@@ -354,23 +355,23 @@ class Quaternion(Module):
q1 = q1.normalize()
return q0 * (q0.inv() * q1) ** t
- def norm(self) -> Tensor:
- return self.data.norm(p=2, dim=-1, keepdim=True)
+ # TODO: add docs
+ def norm(self, keepdim: bool = False) -> Tensor:
+ # p==2, dim|axis==-1, keepdim
+ return self.data.norm(2, -1, keepdim)
+ # TODO: add docs
def normalize(self) -> 'Quaternion':
return Quaternion(normalize_quaternion(self.data))
+ # TODO: add docs
def conj(self) -> 'Quaternion':
- return Quaternion(concatenate((self.real, -self.vec), -1))
+ return Quaternion(concatenate((self.real[..., None], -self.vec), -1))
+ # TODO: add docs
def inv(self) -> 'Quaternion':
return self.conj() / self.squared_norm()
+ # TODO: add docs
def squared_norm(self) -> Tensor:
- return self._batched_squared_norm(self.vec) + self.real**2
-
- def _batched_squared_norm(self, x, y=None):
- if y is None:
- y = x
- KORNIA_CHECK(x.shape == y.shape)
- return (x[..., None, :] @ y[..., :, None])[..., 0]
+ return batched_dot_product(self.vec, self.vec) + self.real**2
diff --git a/test/geometry/liegroup/test_se3.py b/test/geometry/liegroup/test_se3.py
index 33799efa9..39b55fa1f 100644
--- a/test/geometry/liegroup/test_se3.py
+++ b/test/geometry/liegroup/test_se3.py
@@ -8,11 +8,14 @@ from kornia.testing import BaseTester
class TestSe3(BaseTester):
def _make_rand_se3d(self, device, dtype, batch_size) -> Se3:
- q = Quaternion.random(batch_size)
- q = q.to(device, dtype)
- t = torch.rand(batch_size, 3, device=device, dtype=dtype)
+ q = Quaternion.random(batch_size, device, dtype)
+ t = self._make_rand_data(device, dtype, batch_size, dims=3)
return Se3(So3(q), t)
+ def _make_rand_data(self, device, dtype, batch_size, dims):
+ shape = [] if batch_size is None else [batch_size]
+ return torch.rand(shape + [dims], device=device, dtype=dtype)
+
def test_smoke(self, device, dtype):
q = Quaternion.from_coeffs(1.0, 0.0, 0.0, 0.0)
q = q.to(device, dtype)
@@ -44,7 +47,7 @@ class TestSe3(BaseTester):
def test_module(self, device, dtype):
pass
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_init(self, device, dtype, batch_size):
s1: Se3 = self._make_rand_se3d(device, dtype, batch_size)
s2 = Se3(s1.r, s1.t)
@@ -54,8 +57,7 @@ class TestSe3(BaseTester):
@pytest.mark.parametrize("batch_size", (1, 2, 5))
def test_getitem(self, device, dtype, batch_size):
- q = Quaternion.random(batch_size)
- q = q.to(device, dtype)
+ q = Quaternion.random(batch_size, device, dtype)
t = torch.rand(batch_size, 3, device=device, dtype=dtype)
s = Se3(So3(q), t)
for i in range(batch_size):
@@ -63,84 +65,87 @@ class TestSe3(BaseTester):
self.assert_close(s1.r.q.data[0], q.data[i])
self.assert_close(s1.t[0], t[i])
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_mul(self, device, dtype, batch_size):
s1 = Se3.identity(batch_size, device, dtype)
s2: Se3 = self._make_rand_se3d(device, dtype, batch_size)
s1s2 = s1 * s2
s2s2inv = s2 * s2.inverse()
+ zeros_vec = torch.zeros(3, device=device, dtype=dtype)
+ if batch_size is not None:
+ zeros_vec = zeros_vec.repeat(batch_size, 1)
+ so3_expected = So3.identity(batch_size, device, dtype)
self.assert_close(s1s2.r.q.data, s2.r.q.data)
self.assert_close(s1s2.t, s2.t)
- self.assert_close(s2s2inv.r.q.data, So3.identity(batch_size, device, dtype).q.data)
- self.assert_close(s2s2inv.t, torch.zeros((batch_size, 3)).to(device, dtype))
-
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ self.assert_close(s2s2inv.r.q.data, so3_expected.q.data)
+ self.assert_close(s2s2inv.t, zeros_vec)
+
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
+ def test_mul_point(self, device, dtype, batch_size):
+ world_pose_s1: Se3 = self._make_rand_se3d(device, dtype, batch_size)
+ world_pose_s2: Se3 = self._make_rand_se3d(device, dtype, batch_size)
+ pt_in_world = self._make_rand_data(device, dtype, batch_size, dims=3)
+ s1_pose_s2: Se3 = world_pose_s1.inverse() * world_pose_s2
+ pt_in_s1 = world_pose_s1.inverse() * pt_in_world
+ pt_in_s2 = world_pose_s2.inverse() * pt_in_world
+ pt_in_s1_in_s2 = s1_pose_s2.inverse() * pt_in_s1
+ pt_in_s2_in_s1 = s1_pose_s2 * pt_in_s2
+ self.assert_close(pt_in_s1, pt_in_s2_in_s1)
+ self.assert_close(pt_in_s2, pt_in_s1_in_s2)
+
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_exp(self, device, dtype, batch_size):
- omega = torch.zeros((batch_size, 3), device=device, dtype=dtype)
- t = torch.rand(batch_size, 3, device=device, dtype=dtype)
+ omega = torch.zeros(3, device=device, dtype=dtype)
+ t = torch.rand(3, device=device, dtype=dtype)
+ if batch_size is not None:
+ omega = omega.repeat(batch_size, 1)
+ t = t.repeat(batch_size, 1)
s = Se3.exp(torch.cat((t, omega), -1))
- self.assert_close(s.r.q.data, Quaternion.identity(batch_size).to(device, dtype).data)
+ quat_expected = Quaternion.identity(batch_size, device, dtype)
+ self.assert_close(s.r.q.data, quat_expected.data)
self.assert_close(s.t, t)
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_log(self, device, dtype, batch_size):
- q = Quaternion.identity(batch_size)
- q = q.to(device, dtype)
- t = torch.rand(batch_size, 3, device=device, dtype=dtype)
+ q = Quaternion.identity(batch_size, device, dtype)
+ t = self._make_rand_data(device, dtype, batch_size, dims=3)
s = Se3(So3(q), t)
- zero_vec = torch.zeros((batch_size, 3), device=device, dtype=dtype)
+ zero_vec = torch.zeros(3, device=device, dtype=dtype)
+ if batch_size is not None:
+ zero_vec = zero_vec.repeat(batch_size, 1)
self.assert_close(s.log(), torch.cat((t, zero_vec), -1))
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_exp_log(self, device, dtype, batch_size):
- a = torch.rand(batch_size, 6, device=device, dtype=dtype)
+ a = self._make_rand_data(device, dtype, batch_size, dims=6)
b = Se3.exp(a).log()
self.assert_close(b, a)
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
- def test_hat(self, device, dtype, batch_size):
- t = torch.rand(batch_size, 3, device=device, dtype=dtype)
- omega = torch.tensor([1, 2, 3]).repeat(batch_size, 1)
- omega = omega.to(device, dtype)
- omega_hat = Se3.hat(torch.cat((t, omega), 1))
- assert omega_hat.shape == torch.Size([batch_size, 4, 4])
- self.assert_close(omega_hat[:, 3, 1:], t)
- self.assert_close(omega_hat[:, 0:3, 1:].unique()[-3:], torch.tensor([1, 2, 3]).to(device, dtype))
-
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
- def test_vee(self, device, dtype, batch_size):
- omega_hat = torch.Tensor([[[0, 9, 5, 1], [0, 10, 6, 2], [0, 11, 7, 3], [0, 12, 8, 4]]]).repeat(batch_size, 1, 1)
- omega_hat = omega_hat.to(device, dtype)
- expected = torch.tensor([[12.0, 8.0, 4.0, 7.0, 1.0, 10.0]]).repeat(batch_size, 1)
- expected = expected.to(device, dtype)
- self.assert_close(Se3.vee(omega_hat), expected)
-
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_hat_vee(self, device, dtype, batch_size):
- a = torch.rand(batch_size, 6, device=device, dtype=dtype)
+ a = self._make_rand_data(device, dtype, batch_size, dims=6)
omega_hat = Se3.hat(a)
b = Se3.vee(omega_hat)
self.assert_close(b, a)
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_matrix(self, device, dtype, batch_size):
- q = Quaternion.random(batch_size)
- q = q.to(device, dtype)
- t = torch.rand((batch_size, 3))
- t = t.to(device, dtype)
+ q = Quaternion.random(batch_size, device, dtype)
+ t = self._make_rand_data(device, dtype, batch_size, dims=3)
rot = So3(q)
s = Se3(rot, t)
- assert s.matrix().shape == torch.Size([batch_size, 4, 4])
- self.assert_close(s.matrix()[..., 0:3, 0:3], rot.matrix())
- self.assert_close(s.matrix()[..., 0:3, 3], t)
-
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ rot_mat = s.matrix()
+ assert rot_mat.shape[-2:] == (4, 4)
+ if batch_size is not None:
+ assert rot_mat.shape[0] == batch_size
+ self.assert_close(rot_mat[..., 0:3, 0:3], rot.matrix())
+ self.assert_close(rot_mat[..., 0:3, 3], t)
+
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_inverse(self, device, dtype, batch_size):
- q = Quaternion.random(batch_size)
- q = q.to(device, dtype)
+ q = Quaternion.random(batch_size, device, dtype)
rot = So3(q)
- t = torch.rand((batch_size, 3))
- t = t.to(device, dtype)
+ t = self._make_rand_data(device, dtype, batch_size, dims=3)
sinv = Se3(rot, t).inverse()
self.assert_close(sinv.r.inverse().q.data, q.data)
self.assert_close(sinv.t, sinv.r * (-1 * t))
diff --git a/test/geometry/liegroup/test_so3.py b/test/geometry/liegroup/test_so3.py
index 4752656aa..d2c00a7cf 100644
--- a/test/geometry/liegroup/test_so3.py
+++ b/test/geometry/liegroup/test_so3.py
@@ -7,6 +7,10 @@ from kornia.testing import BaseTester
class TestSo3(BaseTester):
+ def _make_rand_data(self, device, dtype, batch_size, dims):
+ shape = [] if batch_size is None else [batch_size]
+ return torch.rand(shape + [dims], device=device, dtype=dtype)
+
def test_smoke(self, device, dtype):
q = Quaternion.from_coeffs(1.0, 0.0, 0.0, 0.0)
q = q.to(device, dtype)
@@ -34,10 +38,9 @@ class TestSo3(BaseTester):
def test_module(self, device, dtype):
pass
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_init(self, device, dtype, batch_size):
- q = Quaternion.identity(batch_size)
- q = q.to(device, dtype)
+ q = Quaternion.identity(batch_size, device, dtype)
s1 = So3(q)
s2 = So3(s1.q)
assert isinstance(s2, So3)
@@ -45,32 +48,27 @@ class TestSo3(BaseTester):
@pytest.mark.parametrize("batch_size", (1, 2, 5))
def test_getitem(self, device, dtype, batch_size):
- q = Quaternion.random(batch_size)
- q = q.to(device, dtype)
+ q = Quaternion.random(batch_size, device, dtype)
s = So3(q)
for i in range(batch_size):
s1 = s[i]
self.assert_close(s1.q.data[0], q.data[i])
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_mul(self, device, dtype, batch_size):
- q1 = Quaternion.identity(batch_size)
- q1 = q1.to(device, dtype)
- q2 = Quaternion.random(batch_size)
- q2 = q2.to(device, dtype)
- t = torch.rand(batch_size, 3, device=device, dtype=dtype)
+ q1 = Quaternion.identity(batch_size, device, dtype)
+ q2 = Quaternion.random(batch_size, device, dtype)
+ t = self._make_rand_data(device, dtype, batch_size, dims=3)
s1 = So3(q1)
s2 = So3(q2)
self.assert_close((s1 * s2).q.data, s2.q.data)
self.assert_close((s2 * s2.inverse()).q.data, s1.q.data)
self.assert_close((s1 * t), t)
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_unit_norm(self, device, dtype, batch_size):
- q1 = Quaternion.random(batch_size)
- q1 = q1.to(device, dtype)
- q2 = Quaternion.random(batch_size)
- q2 = q2.to(device, dtype)
+ q1 = Quaternion.random(batch_size, device, dtype)
+ q2 = Quaternion.random(batch_size, device, dtype)
s1 = So3(q1)
s2 = So3(q2)
s3 = s1 * s2
@@ -78,7 +76,14 @@ class TestSo3(BaseTester):
s5 = s2.inverse()
s6 = s3.inverse()
- ones_vec = torch.tensor([[1.0]], device=device, dtype=dtype)
+ ones_vec = torch.tensor(1.0, device=device, dtype=dtype)
+ if batch_size is None:
+ self.assert_close(s1.q.norm(), ones_vec)
+ return
+
+ if batch_size is not None:
+ ones_vec = ones_vec[None]
+
for i in range(batch_size):
self.assert_close(s1[i].q.norm(), ones_vec)
self.assert_close(s2[i].q.norm(), ones_vec)
@@ -87,58 +92,63 @@ class TestSo3(BaseTester):
self.assert_close(s5[i].q.norm(), ones_vec)
self.assert_close(s6[i].q.norm(), ones_vec)
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_exp(self, device, dtype, batch_size):
- q = Quaternion.identity(batch_size)
- q = q.to(device, dtype)
+ q = Quaternion.identity(batch_size, device, dtype)
s = So3(q)
- zero_vec = torch.zeros((batch_size, 3), device=device, dtype=dtype)
+ zero_vec = 0 * self._make_rand_data(device, dtype, batch_size, dims=3)
self.assert_close(s.exp(zero_vec).q.data, q.data) # exp of zero vec is identity
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_log(self, device, dtype, batch_size):
- q = Quaternion.identity(batch_size)
- q = q.to(device, dtype)
+ q = Quaternion.identity(batch_size, device, dtype)
s = So3(q)
- zero_vec = torch.zeros((batch_size, 3), device=device, dtype=dtype)
+ zero_vec = 0 * self._make_rand_data(device, dtype, batch_size, dims=3)
self.assert_close(s.log(), zero_vec) # log of identity quat is zero vec
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_exp_log(self, device, dtype, batch_size):
- q = Quaternion.random(batch_size)
- q = q.to(device, dtype)
+ q = Quaternion.random(batch_size, device, dtype)
s = So3(q)
- a = torch.rand(batch_size, 3, device=device, dtype=dtype)
+ a = self._make_rand_data(device, dtype, batch_size, dims=3)
b = s.exp(a).log()
self.assert_close(b, a)
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_hat(self, device, dtype, batch_size):
- v = torch.tensor([1, 2, 3]).repeat(batch_size, 1)
- v = v.to(device, dtype)
- self.assert_close(So3.hat(v).unique()[-3:], v[0, :])
-
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ v = torch.tensor([1, 2, 3], device=device, dtype=dtype)
+ expected = v
+ if batch_size is not None:
+ v = v.repeat(batch_size, 1)
+ hat = So3.hat(v)
+ if batch_size is None:
+ hat = hat[None]
+ self.assert_close(hat.unique()[-3:], expected)
+
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_vee(self, device, dtype, batch_size):
- omega = torch.Tensor([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]).repeat(batch_size, 1, 1)
- omega = omega.to(device, dtype)
- expected = torch.tensor([[8, 3, 4]]).repeat(batch_size, 1)
- expected = expected.to(device, dtype)
+ omega = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], device=device, dtype=dtype)
+ expected = torch.tensor([8, 3, 4], device=device, dtype=dtype)
+ if batch_size is not None:
+ omega = omega.repeat(batch_size, 1, 1)
+ expected = expected.repeat(batch_size, 1)
self.assert_close(So3.vee(omega), expected)
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_hat_vee(self, device, dtype, batch_size):
- a = torch.rand(batch_size, 3, device=device, dtype=dtype)
+ a = self._make_rand_data(device, dtype, batch_size, dims=3)
omega = So3.hat(a)
b = So3.vee(omega)
self.assert_close(b, a)
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_matrix(self, device, dtype, batch_size):
- q = Quaternion.random(batch_size)
- q = q.to(device, dtype)
+ q = Quaternion.random(batch_size, device, dtype)
r = So3(q).matrix()
- for i in range(batch_size):
+ if batch_size is None:
+ q = Quaternion(q.data[None])
+ r = r[None]
+ for i in range(r.shape[0]):
q1 = q[i]
r1 = r[i, :, :]
pvec = torch.rand(3, device=device, dtype=dtype)
@@ -148,26 +158,31 @@ class TestSo3(BaseTester):
self.assert_close(rp_, qp_.vec) # p_ = R*p = q*p*q_inv
self.assert_close(rp_.norm(), pvec.norm())
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_ortho(self, device, dtype, batch_size):
- q = Quaternion.random(batch_size)
- q = q.to(device, dtype)
+ q = Quaternion.random(batch_size, device, dtype)
b_R_a = So3(q).matrix()
a_R_b = So3(q).inverse().matrix()
a_R_a = (So3(q) * So3(q).inverse()).matrix()
eye_mat = torch.eye(3, device=device, dtype=dtype)
-
- self.assert_close(a_R_a, eye_mat[None].repeat(batch_size, 1, 1))
-
- for i in range(batch_size):
- self.assert_close(a_R_a[i, :, :], eye_mat)
- self.assert_close(a_R_b[i, :, :] @ b_R_a[i, :, :], eye_mat)
- self.assert_close(b_R_a[i, :, :] @ a_R_b[i, :, :], eye_mat)
-
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ if batch_size is None:
+ eye_mat = eye_mat[None]
+ a_R_a = a_R_a[None]
+ a_R_b = a_R_b[None]
+ b_R_a = b_R_a[None]
+ if batch_size is not None:
+ eye_mat = eye_mat.repeat(batch_size, 1, 1)
+
+ self.assert_close(a_R_a, eye_mat)
+
+ for i in range(eye_mat.shape[0]):
+ self.assert_close(a_R_a[i, :, :], eye_mat[i])
+ self.assert_close(a_R_b[i, :, :] @ b_R_a[i, :, :], eye_mat[i])
+ self.assert_close(b_R_a[i, :, :] @ a_R_b[i, :, :], eye_mat[i])
+
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_inverse(self, device, dtype, batch_size):
- q = Quaternion.random(batch_size)
- q = q.to(device, dtype)
+ q = Quaternion.random(batch_size, device, dtype)
self.assert_close(So3(q).inverse().inverse().q.data, q.data)
self.assert_close(So3(q).inverse().inverse().matrix(), So3(q).matrix())
diff --git a/test/geometry/test_quaternion.py b/test/geometry/test_quaternion.py
index c741d2f44..540779cc6 100644
--- a/test/geometry/test_quaternion.py
+++ b/test/geometry/test_quaternion.py
@@ -6,6 +6,10 @@ from kornia.testing import assert_close
class TestQuaternion:
+ def _make_rand_data(self, device, dtype, batch_size):
+ shape = [] if batch_size is None else [batch_size]
+ return torch.rand(shape + [4], device=device, dtype=dtype)
+
def assert_close(self, actual, expected, rtol=None, atol=None):
if isinstance(actual, Quaternion):
actual = actual.data.data
@@ -21,19 +25,18 @@ class TestQuaternion:
def test_smoke(self, device, dtype):
q = Quaternion.from_coeffs(1.0, 0.0, 0.0, 0.0)
q = q.to(device, dtype)
- q_data = torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype)
+ q_data = torch.tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=dtype)
assert isinstance(q, Quaternion)
- assert q.shape == (1, 4)
+ assert q.shape == (4,)
self.assert_close(q.data, q_data)
self.assert_close(q.q, q_data)
- self.assert_close(q.real, q_data[..., :1])
- self.assert_close(q.scalar, q_data[..., :1])
+ self.assert_close(q.real, q_data[..., 0])
+ self.assert_close(q.scalar, q_data[..., 0])
self.assert_close(q.vec, q_data[..., 1:])
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_init(self, device, dtype, batch_size):
- q1 = Quaternion.identity(batch_size)
- q1 = q1.to(device, dtype)
+ q1 = Quaternion.identity(batch_size, device, dtype)
q2 = Quaternion(q1.data)
assert isinstance(q2, Quaternion)
self.assert_close(q1, q2)
@@ -48,38 +51,37 @@ class TestQuaternion:
with pytest.raises(Exception):
_ = Quaternion(1, [0, 0, 0])
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_random(self, device, dtype, batch_size):
- q = Quaternion.random(batch_size)
- q = q.to(device, dtype)
+ q = Quaternion.random(batch_size, device, dtype)
q_n = q.normalize().norm()
self.assert_close(q_n, q_n.new_ones(q_n.shape))
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_minus(self, device, dtype, batch_size):
- data = torch.rand(batch_size, 4, device=device, dtype=dtype)
+ data = self._make_rand_data(device, dtype, batch_size)
q = Quaternion(data)
q = q.to(device, dtype)
self.assert_close(-q, -data)
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_add(self, device, dtype, batch_size):
- d1 = torch.rand(batch_size, 4, device=device, dtype=dtype)
- d2 = torch.rand(batch_size, 4, device=device, dtype=dtype)
- q1 = Quaternion(d1).to(device, dtype)
- q2 = Quaternion(d2).to(device, dtype)
+ d1 = self._make_rand_data(device, dtype, batch_size)
+ d2 = self._make_rand_data(device, dtype, batch_size)
+ q1 = Quaternion(d1)
+ q2 = Quaternion(d2)
q3 = q1 + q2
assert isinstance(q3, Quaternion)
self.assert_close(q3, d1 + d2)
q1 += q2
self.assert_close(q1, q3)
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_subtract(self, device, dtype, batch_size):
- d1 = torch.rand(batch_size, 4, device=device, dtype=dtype)
- d2 = torch.rand(batch_size, 4, device=device, dtype=dtype)
- q1 = Quaternion(d1).to(device, dtype)
- q2 = Quaternion(d2).to(device, dtype)
+ d1 = self._make_rand_data(device, dtype, batch_size)
+ d2 = self._make_rand_data(device, dtype, batch_size)
+ q1 = Quaternion(d1)
+ q2 = Quaternion(d2)
q3 = q1 - q2
assert isinstance(q3, Quaternion)
self.assert_close(q3, d1 - d2)
@@ -130,12 +132,10 @@ class TestQuaternion:
self.assert_close(k / k, one)
self.assert_close(i / -j, k)
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_pow(self, device, dtype, batch_size):
- q = Quaternion.random(batch_size)
- q = q.to(device, dtype)
- q1 = Quaternion.identity(batch_size)
- q1 = q1.to(device, dtype)
+ q = Quaternion.random(batch_size, device, dtype)
+ q1 = Quaternion.identity(batch_size, device, dtype)
self.assert_close(q**0, q1)
self.assert_close(q**1, q)
self.assert_close(q**2, q * q)
@@ -144,53 +144,44 @@ class TestQuaternion:
self.assert_close((q1**1), q1)
self.assert_close((q1**2), q1)
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_inverse(self, device, dtype, batch_size):
- q1 = Quaternion.random(batch_size)
- q1 = q1.to(device, dtype)
- q2 = Quaternion.identity(batch_size)
- q2 = q2.to(device, dtype)
+ q1 = Quaternion.random(batch_size, device, dtype)
+ q2 = Quaternion.identity(batch_size, device, dtype)
self.assert_close(q1 * q1.inv(), q2, rtol=1e-4, atol=1e-4)
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_conjugate(self, device, dtype, batch_size):
- q1 = Quaternion.random(batch_size)
- q1 = q1.to(device, dtype)
- q2 = Quaternion.random(batch_size)
- q2 = q2.to(device, dtype)
+ q1 = Quaternion.random(batch_size, device, dtype)
+ q2 = Quaternion.random(batch_size, device, dtype)
self.assert_close((q1 * q2).conj(), q2.conj() * q1.conj())
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_double_conjugate(self, device, dtype, batch_size):
- q1 = Quaternion.random(batch_size)
- q1 = q1.to(device, dtype)
+ q1 = Quaternion.random(batch_size, device, dtype)
self.assert_close(q1, q1.conj().conj())
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_norm(self, device, dtype, batch_size):
- q1 = Quaternion.random(batch_size)
- q1 = q1.to(device, dtype)
- q2 = Quaternion.random(batch_size)
- q2 = q2.to(device, dtype)
+ q1 = Quaternion.random(batch_size, device, dtype)
+ q2 = Quaternion.random(batch_size, device, dtype)
self.assert_close((q1 * q2).norm(), q1.norm() * q2.norm())
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_norm_shape(self, device, dtype, batch_size):
- q = Quaternion.random(batch_size)
- q = q.to(device, dtype)
- self.assert_close(q.norm().shape, torch.Size([batch_size, 1]))
+ q = Quaternion.random(batch_size, device, dtype)
+ expected_shape = () if batch_size is None else (batch_size,)
+ self.assert_close(tuple(q.norm().shape), expected_shape)
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_normalize(self, device, dtype, batch_size):
- q1 = Quaternion.random(batch_size)
- q1 = q1.to(device, dtype)
+ q1 = Quaternion.random(batch_size, device, dtype)
q1_n = q1.normalize().norm()
self.assert_close(q1_n, q1_n.new_ones(q1_n.shape))
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_matrix(self, device, dtype, batch_size):
- q1 = Quaternion.random(batch_size)
- q1 = q1.to(device, dtype)
+ q1 = Quaternion.random(batch_size, device, dtype)
m1 = q1.matrix()
q2 = Quaternion.from_matrix(m1)
for (qq1, qq2) in zip(q1.data, q2.data):
@@ -201,27 +192,27 @@ class TestQuaternion:
@pytest.mark.parametrize("batch_size", (1, 2, 5))
def test_getitem(self, device, dtype, batch_size):
- q = Quaternion.random(batch_size)
- q = q.to(device, dtype)
+ q = Quaternion.random(batch_size, device, dtype)
for i in range(batch_size):
q1 = q[i]
self.assert_close(q1.data[0], q.data[i])
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_axis_angle(self, device, dtype, batch_size):
- q1 = Quaternion.random(batch_size)
- q1 = q1.to(device, dtype)
- angle = 2 * q1.scalar.arccos()
+ q1 = Quaternion.random(batch_size, device, dtype)
+ angle = 2 * q1.scalar.arccos()[..., None]
axis = q1.vec / (angle / 2).sin()
axis_angle = axis * angle
q2 = Quaternion.from_axis_angle(axis_angle)
q2 = q2.to(device, dtype)
self.assert_close(q1, q2)
- @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_slerp(self, device, dtype, batch_size):
for axis in torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]):
- axis = axis.repeat(batch_size, 1).to(device, dtype)
+ axis = axis.to(device, dtype)
+ if batch_size is not None:
+ axis = axis.repeat(batch_size, 1)
q1 = Quaternion.from_axis_angle(axis * 0)
q1.to(device, dtype)
q2 = Quaternion.from_axis_angle(axis * 3.14159)