π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Liegroups (#1887)
Edgar Riba8dba21df49c6
diff --git a/docs/source/geometry.liegroup.rst b/docs/source/geometry.liegroup.rstnew file mode 100644index 000000000..324b8317e--- /dev/null+++ b/docs/source/geometry.liegroup.rst@@ -0,0 +1,12 @@+kornia.geometry.liegroup+==========================++.. currentmodule:: kornia.geometry.liegroup++.. autoclass:: So3+ :members:+ :special-members:++.. autoclass:: Se3+ :members:+ :special-members:\ No newline at end of filediff --git a/docs/source/geometry.rst b/docs/source/geometry.rstindex f6899e5b3..a1b817585 100644--- a/docs/source/geometry.rst+++ b/docs/source/geometry.rst@@ -52,6 +52,7 @@ transforms, camera, conversions, linalg and depth. We next describe each of themgeometry.depthgeometry.epipolargeometry.homography+ geometry.liegroupgeometry.linalggeometry.linegeometry.quaterniondiff --git a/kornia/core/__init__.py b/kornia/core/__init__.pyindex f907b5129..f1c78d916 100644--- a/kornia/core/__init__.py+++ b/kornia/core/__init__.py@@ -1,4 +1,4 @@-from ._backend import Device, Module, Parameter, Tensor, as_tensor, concatenate, normalize, rand, stack, tensor, where+from ._backend import Device, Module, Parameter, Tensor, as_tensor, concatenate, normalize, rand, stack, tensor, where, eye, zeros, zeros_like__all__ = ["concatenate",@@ -12,4 +12,7 @@ __all__ = ["as_tensor","rand","where",+ "eye",+ "zeros",+ "zeros_like"]diff --git a/kornia/core/_backend.py b/kornia/core/_backend.pyindex 0abb6a41a..0a7df0376 100644--- a/kornia/core/_backend.py+++ b/kornia/core/_backend.py@@ -14,6 +14,9 @@ Parameter = torch.nn.Parameterconcatenate = torch.catstack = torch.stacknormalize = F.normalize+eye = torch.eye+zeros_like = torch.zeros_like+zeros = torch.zeroswhere = torch.where# constructorsdiff --git a/kornia/geometry/__init__.py b/kornia/geometry/__init__.pyindex ae5b8e4ac..c32a4e9aa 100644--- a/kornia/geometry/__init__.py+++ b/kornia/geometry/__init__.py@@ -5,6 +5,7 @@ from .conversions import *from .depth import *from .epipolar import *from .homography import *+from .liegroup import *from .linalg import *from .line import *from .ransac import *diff --git a/kornia/geometry/liegroup/__init__.py b/kornia/geometry/liegroup/__init__.pynew file mode 100644index 000000000..e46e64ca7--- /dev/null+++ b/kornia/geometry/liegroup/__init__.py@@ -0,0 +1,4 @@+from .so3 import So3+from .se3 import Se3++__all__ = ["So3", "Se3"]diff --git a/kornia/geometry/liegroup/_utils.py b/kornia/geometry/liegroup/_utils.pynew file mode 100644index 000000000..24aa50d37--- /dev/null+++ b/kornia/geometry/liegroup/_utils.py@@ -0,0 +1,13 @@+from kornia.core import Tensor+from kornia.testing import KORNIA_CHECK+++def squared_norm(x, y=None) -> Tensor:+ return _batched_squared_norm(x, y)+++def _batched_squared_norm(x, y=None):+ if y is None:+ y = x+ KORNIA_CHECK(x.shape == y.shape)+ return (x[..., None, :] @ y[..., :, None])[..., 0]diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.pynew file mode 100644index 000000000..dbdfea97e--- /dev/null+++ b/kornia/geometry/liegroup/se3.py@@ -0,0 +1,210 @@+# 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, where, zeros+from kornia.geometry.liegroup import So3+from kornia.geometry.liegroup._utils import squared_norm+from kornia.testing import KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE+++class Se3:+ 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+ space :math:`R^3` under the operation of composition.+ See more: https://ingmec.ual.es/~jlblanco/papers/jlblanco2010geometry3D_techrep.pdf++ Example:+ >>> q = Quaternion.identity(batch_size=1)+ >>> s = Se3(So3(q), torch.ones((1, 3)))+ >>> s+ rotation: real: tensor([[1.]], grad_fn=<SliceBackward0>)+ vec: tensor([[0., 0., 0.]], grad_fn=<SliceBackward0>)+ translation: tensor([[1., 1., 1.]])+ """++ def __init__(self, r: So3, t: Tensor) -> None:+ """Constructor for the base class.++ Internally represented by a unit quaternion `q` and a translation 3-vector.++ Args:+ r: So3 group encompassing a rotation.+ t: translation vector with the shape of :math:`(B, 3)`.++ Example:+ >>> q = Quaternion.identity(batch_size=1)+ >>> s = Se3(So3(q), torch.ones((1,3)))+ >>> s+ rotation: real: tensor([[1.]], grad_fn=<SliceBackward0>)+ vec: tensor([[0., 0., 0.]], grad_fn=<SliceBackward0>)+ translation: tensor([[1., 1., 1.]])+ """+ KORNIA_CHECK_TYPE(r, So3)+ KORNIA_CHECK_SHAPE(t, ["B", "3"])+ self._r = r+ self._t = t++ def __repr__(self) -> str:+ return f"rotation: {self.r}\ntranslation: {self.t}"++ def __getitem__(self, idx) -> 'Se3':+ return Se3(self._r[idx], self._t[idx][None])++ def __mul__(self, right: "Se3") -> "Se3":+ 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)++ @property+ def r(self) -> So3:+ """Return the underlying rotation(So3)."""+ return self._r++ @property+ def t(self) -> Tensor:+ """Return the underlying translation vector of shape :math:`(B,3)`."""+ return self._t++ @staticmethod+ def exp(v) -> 'Se3':+ """Converts elements of lie algebra to elements of lie group.++ Args:+ v: vector of shape :math:`(B, 6)`.++ Example:+ >>> v = torch.zeros((1, 6))+ >>> s = Se3.exp(v)+ >>> s+ rotation: real: tensor([[1.]], grad_fn=<SliceBackward0>)+ vec: tensor([[0., 0., 0.]], grad_fn=<SliceBackward0>)+ translation: tensor([[0., 0., 0.]])+ """+ KORNIA_CHECK_SHAPE(v, ["B", "6"])+ t = v[..., 0:3]+ omega = v[..., 3:]+ omega_hat = So3.hat(omega)+ theta = squared_norm(omega).sqrt()+ R = So3.exp(omega)+ V = (+ eye(3).to(v.device, v.dtype)+ + ((1 - theta.cos()) / (theta**2))[..., None] * omega_hat+ + ((theta - theta.sin()) / (theta**3))[..., None] * (omega_hat @ omega_hat)+ )+ U = where(theta != 0.0, (t.reshape(-1, 1, 3) * V).sum(-1), t)+ return Se3(R, U)++ def log(self) -> Tensor:+ """Converts elements of lie group to elements of lie algebra.++ Example:+ >>> q = Quaternion.identity(batch_size=1)+ >>> Se3(So3(q), torch.zeros((1,3))).log()+ tensor([[0., 0., 0., 0., 0., 0.]], grad_fn=<CatBackward0>)+ """+ omega = self.r.log()+ theta = squared_norm(omega).sqrt()+ omega_hat = So3.hat(omega)+ V_inv = (+ eye(3).to(self._t.device, self._t.dtype)+ - 0.5 * omega_hat+ + ((1 - theta * (theta / 2).cos() / (2 * (theta / 2).sin())) / theta.pow(2))[..., None]+ * (omega_hat @ omega_hat)+ )+ t = where(theta != 0.0, (self.t.reshape(-1, 1, 3) * 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)`.++ Args:+ v: vector of shape :math:`(B,6)`.++ Example:+ >>> 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.]]])+ """+ KORNIA_CHECK_SHAPE(v, ["B", "6"])+ t = v[..., 0:3].reshape(-1, 1, 3)+ omega = v[..., 3:]+ rt = concatenate((So3.hat(omega), t.reshape(-1, 1, 3)), 1)+ return concatenate((zeros(v.shape[0], 4, 1).to(rt.device, rt.dtype), rt), -1)++ @staticmethod+ def vee(omega) -> Tensor:+ """Converts elements from lie algebra to vector space.++ Args:+ omega: 4x4-matrix representing lie algebra of shape :math:`(B,4,4)`.++ Returns:+ vector of shape :math:`(B,6)`.++ Example:+ >>> 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)++ @classmethod+ def identity(cls, batch_size: int, 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=2)+ >>> s+ rotation: real: tensor([[1.],+ [1.]], grad_fn=<SliceBackward0>)+ vec: tensor([[0., 0., 0.],+ [0., 0., 0.]], grad_fn=<SliceBackward0>)+ translation: tensor([[0., 0., 0.],+ [0., 0., 0.]])+ """+ t: Tensor = as_tensor([0.0, 0.0, 0.0], device=device, dtype=dtype)+ t = t.repeat(batch_size, 1)+ return cls(So3.identity(batch_size, device, dtype), t.to(device, dtype))++ 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.matrix()+ tensor([[[1., 0., 0., 1.],+ [0., 1., 0., 1.],+ [0., 0., 1., 1.],+ [0., 0., 0., 1.]]], grad_fn=<CatBackward0>)+ """+ rt = concatenate((self.r.matrix(), self.t.reshape(-1, 3, 1)), 2)+ return concatenate(+ (rt, Tensor([0.0, 0.0, 0.0, 1.0]).repeat([self.t.shape[0], 1, 1]).to(rt.device, rt.dtype)), 1+ )++ def inverse(self) -> 'Se3':+ """Returns the inverse transformation.++ Example:+ >>> s = Se3(So3.identity(batch_size=1), torch.ones((1,3)))+ >>> s.inverse()+ rotation: real: tensor([[1.]], grad_fn=<SliceBackward0>)+ vec: tensor([[-0., -0., -0.]], grad_fn=<SliceBackward0>)+ translation: tensor([[-1., -1., -1.]], grad_fn=<SliceBackward0>)+ """+ 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.pynew file mode 100644index 000000000..f35a3aee5--- /dev/null+++ b/kornia/geometry/liegroup/so3.py@@ -0,0 +1,232 @@+# 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, where, zeros, zeros_like+from kornia.geometry.liegroup._utils import squared_norm+from kornia.geometry.quaternion import Quaternion+from kornia.testing import KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE+++class So3:+ 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+ :math:`R^3` under the operation of composition.+ See more: https://en.wikipedia.org/wiki/3D_rotation_group++ We internally represent the rotation by a unit quaternion.++ Example:+ >>> q = Quaternion.identity(batch_size=1)+ >>> s = So3(q)+ >>> s.q+ real: tensor([[1.]], grad_fn=<SliceBackward0>)+ vec: tensor([[0., 0., 0.]], grad_fn=<SliceBackward0>)+ """++ def __init__(self, q: Quaternion) -> None:+ """Constructor for the base class.++ Internally represented by a unit quaternion `q`.++ Args:+ data: Quaternion with the shape of :math:`(B, 4)`.++ Example:+ >>> 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>)+ """+ KORNIA_CHECK_TYPE(q, Quaternion)+ self._q = q++ def __repr__(self) -> str:+ return f"{self.q}"++ def __getitem__(self, idx) -> 'So3':+ return So3(self._q[idx])++ def __mul__(self, right):+ # https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py#L98+ if isinstance(right, 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+ else:+ raise TypeError(f"Not So3 or Tensor type. Got: {type(right)}")++ @property+ def q(self) -> Quaternion:+ """Return the underlying data with shape :math:`(B,4)`."""+ return self._q++ @staticmethod+ def exp(v) -> 'So3':+ """Converts elements of lie algebra to elements of lie group.++ See more: https://vision.in.tum.de/_media/members/demmeln/nurlanov2021so3log.pdf++ Args:+ v: vector of shape :math:`(B,3)`.++ Example:+ >>> v = torch.zeros((2,3))+ >>> s = So3.identity(batch_size=1).exp(v)+ >>> s+ real: tensor([[1.],+ [1.]], grad_fn=<SliceBackward0>)+ vec: tensor([[0., 0., 0.],+ [0., 0., 0.]], grad_fn=<SliceBackward0>)+ """+ KORNIA_CHECK_SHAPE(v, ["B", "3"])+ theta = squared_norm(v).sqrt()+ theta_nonzeros = theta != 0.0+ theta_half = 0.5 * theta+ w = where(theta_nonzeros, theta_half.cos(), Tensor([1.0]).to(v.device, v.dtype))+ b = where(theta_nonzeros, theta_half.sin() / theta, Tensor([0.0]).to(v.device, v.dtype))+ xyz = b * v+ return So3(Quaternion(concatenate((w, xyz), 1)))++ def log(self) -> Tensor:+ """Converts elements of lie group to elements of lie algebra.++ Example:+ >>> data = torch.ones((2, 4))+ >>> q = Quaternion(data)+ >>> So3(q).log()+ tensor([[0., 0., 0.],+ [0., 0., 0.]], grad_fn=<SWhereBackward0>)+ """+ theta = squared_norm(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)+ return omega++ @staticmethod+ def hat(v) -> Tensor:+ """Converts elements from vector space to lie algebra. Returns matrix of shape :math:`(B,3,3)`.++ Args:+ v: vector of shape :math:`(B,3)`.++ Example:+ >>> v = torch.ones((1,3))+ >>> m = So3.hat(v)+ >>> m+ tensor([[[ 0., -1., 1.],+ [ 1., 0., -1.],+ [-1., 1., 0.]]])+ """+ KORNIA_CHECK_SHAPE(v, ["B", "3"])+ a, b, c = v[..., 0, None, None], v[..., 1, None, None], v[..., 2, None, None]+ zeros = zeros_like(v)[..., 0, None, None]+ row0 = concatenate([zeros, -c, b], 2)+ row1 = concatenate([c, zeros, -a], 2)+ row2 = concatenate([-b, a, zeros], 2)+ return concatenate([row0, row1, row2], 1)++ @staticmethod+ def vee(omega) -> Tensor:+ r"""Converts elements from lie algebra to vector space. Returns vector of shape :math:`(B,3)`.++ .. math::+ omega = \begin{bmatrix} 0 & -c & b \\+ c & 0 & -a \\+ -b & a & 0\end{bmatrix}++ Args:+ omega: 3x3-matrix representing lie algebra.++ Example:+ >>> v = torch.ones((1,3))+ >>> omega = So3.hat(v)+ >>> So3.vee(omega)+ tensor([[1., 1., 1.]])+ """+ 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)++ # NOTE: the math style won't render well with sphinx+ def matrix(self) -> Tensor:+ r"""Convert the quaternion to a rotation matrix of shape :math:`(B,3,3)`.++ The matrix is of the form:++ .. math::+ \begin{bmatrix} 1-2y^2-2z^2 & 2xy-2zw & 2xy+2yw \\+ 2xy+2zw & 1-2x^2-2z^2 & 2yz-2xw \\+ 2xz-2yw & 2yz+2xw & 1-2x^2-2y^2\end{bmatrix}++ Example:+ >>> s = So3.identity(batch_size=1)+ >>> m = s.matrix()+ >>> m+ tensor([[[1., 0., 0.],+ [0., 1., 0.],+ [0., 0., 1.]]], grad_fn=<CatBackward0>)+ """+ 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)+ 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)+ 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)++ @classmethod+ def from_matrix(cls, matrix: Tensor) -> 'So3':+ """Create So3 from a rotation matrix.++ Args:+ matrix: the rotation matrix to convert of shape :math:`(B,3,3)`.++ Example:+ >>> m = torch.eye(3)[None]+ >>> s = So3.from_matrix(m)+ >>> s+ real: tensor([[1.]], grad_fn=<SliceBackward0>)+ vec: tensor([[0., 0., 0.]], grad_fn=<SliceBackward0>)+ """+ return cls(Quaternion.from_matrix(matrix))++ @classmethod+ def identity(cls, batch_size: int, 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(batch_size=2)+ >>> s+ real: tensor([[1.],+ [1.]], grad_fn=<SliceBackward0>)+ vec: tensor([[0., 0., 0.],+ [0., 0., 0.]], grad_fn=<SliceBackward0>)+ """+ return cls(Quaternion.identity(batch_size).to(device, dtype))++ def inverse(self) -> 'So3':+ """Returns the inverse transformation.++ Example:+ >>> s = So3.identity(batch_size=1)+ >>> s.inverse()+ real: tensor([[1.]], grad_fn=<SliceBackward0>)+ vec: tensor([[-0., -0., -0.]], grad_fn=<SliceBackward0>)+ """+ return So3(self.q.conj())diff --git a/test/geometry/liegroup/test_se3.py b/test/geometry/liegroup/test_se3.pynew file mode 100644index 000000000..33799efa9--- /dev/null+++ b/test/geometry/liegroup/test_se3.py@@ -0,0 +1,146 @@+import pytest+import torch++from kornia.geometry.liegroup import Se3, So3+from kornia.geometry.quaternion import Quaternion+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)+ return Se3(So3(q), t)++ def test_smoke(self, device, dtype):+ q = Quaternion.from_coeffs(1.0, 0.0, 0.0, 0.0)+ q = q.to(device, dtype)+ t = torch.rand(1, 3, device=device, dtype=dtype)+ s = Se3(So3(q), t)+ assert isinstance(s, Se3)+ assert isinstance(s.r, So3)+ self.assert_close(s.r.q.data, q.data)+ self.assert_close(s.t, t)++ @pytest.mark.parametrize("batch_size", (1, 2, 5))+ def test_cardinality(self, device, dtype, batch_size):+ se: Se3 = self._make_rand_se3d(device, dtype, batch_size)+ assert se.r.q.shape[0] == batch_size++ # TODO: implement me+ def test_exception(self, device, dtype):+ pass++ # TODO: implement me+ def test_gradcheck(self, device):+ pass++ # TODO: implement me+ def test_jit(self, device, dtype):+ pass++ # TODO: implement me+ def test_module(self, device, dtype):+ pass++ @pytest.mark.parametrize("batch_size", (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)+ assert isinstance(s2, Se3)+ self.assert_close(s1.r.q.data, s2.r.q.data)+ self.assert_close(s1.t, s2.t)++ @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)+ t = torch.rand(batch_size, 3, device=device, dtype=dtype)+ s = Se3(So3(q), t)+ for i in range(batch_size):+ s1 = s[i]+ 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))+ 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()+ 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))+ 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)+ s = Se3.exp(torch.cat((t, omega), -1))+ self.assert_close(s.r.q.data, Quaternion.identity(batch_size).to(device, dtype).data)+ self.assert_close(s.t, t)++ @pytest.mark.parametrize("batch_size", (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)+ s = Se3(So3(q), t)+ zero_vec = torch.zeros((batch_size, 3), device=device, dtype=dtype)+ self.assert_close(s.log(), torch.cat((t, zero_vec), -1))++ @pytest.mark.parametrize("batch_size", (1, 2, 5))+ def test_exp_log(self, device, dtype, batch_size):+ a = torch.rand(batch_size, 6, device=device, dtype=dtype)+ 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))+ def test_hat_vee(self, device, dtype, batch_size):+ a = torch.rand(batch_size, 6, device=device, dtype=dtype)+ omega_hat = Se3.hat(a)+ b = Se3.vee(omega_hat)+ self.assert_close(b, a)++ @pytest.mark.parametrize("batch_size", (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)+ 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))+ def test_inverse(self, device, dtype, batch_size):+ q = Quaternion.random(batch_size)+ q = q.to(device, dtype)+ rot = So3(q)+ t = torch.rand((batch_size, 3))+ t = t.to(device, dtype)+ 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.pynew file mode 100644index 000000000..c34c2222b--- /dev/null+++ b/test/geometry/liegroup/test_so3.py@@ -0,0 +1,132 @@+import pytest+import torch++from kornia.geometry.liegroup import So3+from kornia.geometry.quaternion import Quaternion+from kornia.testing import BaseTester+++class TestSo3(BaseTester):+ def test_smoke(self, device, dtype):+ q = Quaternion.from_coeffs(1.0, 0.0, 0.0, 0.0)+ q = q.to(device, dtype)+ s = So3(q)+ assert isinstance(s, So3)+ self.assert_close(s.q.data, q.data)++ # TODO: implement me+ def test_cardinality(self, device, dtype):+ pass++ # TODO: implement me+ def test_exception(self, device, dtype):+ pass++ # TODO: implement me+ def test_gradcheck(self, device):+ pass++ # TODO: implement me+ def test_jit(self, device, dtype):+ pass++ # TODO: implement me+ def test_module(self, device, dtype):+ pass++ @pytest.mark.parametrize("batch_size", (1, 2, 5))+ def test_init(self, device, dtype, batch_size):+ q = Quaternion.identity(batch_size)+ q = q.to(device, dtype)+ s1 = So3(q)+ s2 = So3(s1.q)+ assert isinstance(s2, So3)+ self.assert_close(s1.q.data, s2.q.data)++ @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)+ 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))+ 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)+ 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))+ def test_exp(self, device, dtype, batch_size):+ q = Quaternion.identity(batch_size)+ q = q.to(device, dtype)+ s = So3(q)+ zero_vec = torch.zeros((batch_size, 3), device=device, dtype=dtype)+ 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))+ def test_log(self, device, dtype, batch_size):+ q = Quaternion.identity(batch_size)+ q = q.to(device, dtype)+ s = So3(q)+ zero_vec = torch.zeros((batch_size, 3), device=device, dtype=dtype)+ self.assert_close(s.log(), zero_vec) # log of identity quat is zero vec++ @pytest.mark.parametrize("batch_size", (1, 2, 5))+ def test_exp_log(self, device, dtype, batch_size):+ q = Quaternion.random(batch_size)+ q = q.to(device, dtype)+ s = So3(q)+ a = torch.rand(batch_size, 3, device=device, dtype=dtype)+ b = s.exp(a).log()+ self.assert_close(b, a)++ @pytest.mark.parametrize("batch_size", (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))+ 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)+ self.assert_close(So3.vee(omega), expected)++ @pytest.mark.parametrize("batch_size", (1, 2, 5))+ def test_hat_vee(self, device, dtype, batch_size):+ a = torch.rand(batch_size, 3, device=device, dtype=dtype)+ omega = So3.hat(a)+ b = So3.vee(omega)+ self.assert_close(b, a)++ @pytest.mark.parametrize("batch_size", (1, 2, 5))+ def test_matrix(self, device, dtype, batch_size):+ q = Quaternion.random(batch_size)+ q = q.to(device, dtype)+ r = So3(q).matrix()+ for i in range(batch_size):+ q1 = q[i]+ r1 = r[i, :, :]+ pvec = torch.rand(3, device=device, dtype=dtype)+ pquat = Quaternion(torch.cat([torch.tensor([0]).to(device, dtype), pvec])[None, :])+ qp_ = q1 * pquat * q1.inv()+ rp_ = torch.matmul(r1, pvec)[None, :]+ self.assert_close(rp_, qp_.vec) # p_ = R*p = q*p*q_inv++ @pytest.mark.parametrize("batch_size", (1, 2, 5))+ def test_inverse(self, device, dtype, batch_size):+ q = Quaternion.random(batch_size)+ q = q.to(device, dtype)+ self.assert_close(So3(q).inverse().inverse().q.data, q.data)