π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[feat] Implement se2 (#2019)
Christie Jacob9c15d55324df
diff --git a/docs/source/geometry.liegroup.rst b/docs/source/geometry.liegroup.rstindex fa26a0334..2ccd0226b 100644--- a/docs/source/geometry.liegroup.rst+++ b/docs/source/geometry.liegroup.rst@@ -14,3 +14,7 @@ kornia.geometry.liegroup.. autoclass:: So2:members::special-members:++.. autoclass:: Se2+ :members:+ :special-members:diff --git a/kornia/geometry/liegroup/__init__.py b/kornia/geometry/liegroup/__init__.pyindex 83b9d5506..a46125b57 100644--- a/kornia/geometry/liegroup/__init__.py+++ b/kornia/geometry/liegroup/__init__.py@@ -1,5 +1,6 @@+from .se2 import Se2from .se3 import Se3from .so2 import So2from .so3 import So3-__all__ = ["So3", "Se3", "So2"]+__all__ = ["Se2", "Se3", "So2", "So3"]diff --git a/kornia/geometry/liegroup/_utils.py b/kornia/geometry/liegroup/_utils.pyindex 40fdc72ca..7c21308de 100644--- a/kornia/geometry/liegroup/_utils.py+++ b/kornia/geometry/liegroup/_utils.py@@ -33,3 +33,23 @@ def check_so2_matrix_shape(matrix):or (len_matrix_shape > 3 or len_matrix_shape < 2)):raise ValueError(f"Invalid input size, we expect [B, 2, 2] or [2, 2]. Got: {matrix_shape}")+++def check_se2_t_shape(t):+ check_so2_t_shape(t)+++def check_se2_r_t_shape(r, t):+ if ((len(r.z.shape) == 1) and (len(t.shape) == 2)) or ((len(r.z.shape) == 0) and len(t.shape) == 1):+ check_se2_t_shape(t)+ else:+ raise ValueError(+ f"Invalid input, both the inputs should be either batched or unbatched. Got: {r.z.shape} and {t.shape}"+ )+++def check_v_shape(v):+ v_shape = v.shape+ len_v_shape = len(v_shape)+ if ((len_v_shape == 2) and (v_shape[1] != 3)) or ((len_v_shape == 1) and (v_shape[0] != 3)) or (len_v_shape > 3):+ raise ValueError(f"Invalid input shape, we expect [B, 3], [3] Got: {v_shape}")diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.pynew file mode 100644index 000000000..0bca54b78--- /dev/null+++ b/kornia/geometry/liegroup/se2.py@@ -0,0 +1,260 @@+# kornia.geometry.se2 module inspired by Sophus-sympy.+# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/se2.py+from typing import Optional, Tuple, overload++from kornia.core import Module, Parameter, Tensor, concatenate, pad, rand, stack, tensor, where+from kornia.geometry.liegroup._utils import check_se2_r_t_shape, check_v_shape+from kornia.geometry.liegroup.so2 import So2+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_TYPE+++class Se2(Module):+ r"""Base class to represent the Se2 group.++ The SE(2) is the group of rigid body transformations about the origin of two-dimensional Euclidean+ space :math:`R^2` under the operation of composition.+ See more:++ Example:+ >>> so2 = So2.identity(1)+ >>> t = torch.ones((1, 2))+ >>> se2 = Se2(so2, t)+ >>> se2+ rotation: Parameter containing:+ tensor([1.+0.j], requires_grad=True)+ translation: Parameter containing:+ tensor([[1., 1.]], requires_grad=True)+ """++ def __init__(self, rotation: So2, translation: Tensor) -> None:+ """Constructor for the base class.++ Internally represented by a complex number `z` and a translation 2-vector.++ Args:+ r: So2 group encompassing a rotation.+ t: translation vector with the shape of :math:`(B, 2)`.++ Example:+ >>> so2 = So2.identity(1)+ >>> t = torch.ones((1, 2))+ >>> se2 = Se2(so2, t)+ >>> se2+ rotation: Parameter containing:+ tensor([1.+0.j], requires_grad=True)+ translation: Parameter containing:+ tensor([[1., 1.]], requires_grad=True)+ """+ super().__init__()+ KORNIA_CHECK_TYPE(rotation, So2)+ # TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support+ check_se2_r_t_shape(rotation, translation)+ self._rotation = rotation+ self._translation = Parameter(translation)++ def __repr__(self) -> str:+ return f"rotation: {self.r}\ntranslation: {self.t}"++ def __getitem__(self, idx) -> 'Se2':+ return Se2(self._rotation[idx], self._translation[idx][None])++ @overload+ def __mul__(self, right: 'Se2') -> 'Se2':+ ...++ @overload+ def __mul__(self, right: Tensor) -> Tensor:+ ...++ def __mul__(self, right):+ """Compose two Se2 transformations.++ Args:+ right: the other Se2 transformation.++ Return:+ The resulting Se2 transformation.+ """+ so2 = self.so2+ t = self.t+ if isinstance(right, Se2):+ KORNIA_CHECK_TYPE(right, Se2)+ _r = so2 * right.so2+ _t = t + so2 * right.t+ return Se2(_r, _t)+ elif isinstance(right, Tensor):+ KORNIA_CHECK_TYPE(right, Tensor)+ # TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support+ check_se2_r_t_shape(so2, right)+ return so2 * right + t+ else:+ raise TypeError(f"Unsupported type: {type(right)}")++ @property+ def so2(self) -> So2:+ """Return the underlying rotation(So2)."""+ return self._rotation++ @property+ def r(self) -> So2:+ """Return the underlying rotation(So2)."""+ return self._rotation++ @property+ def t(self) -> Tensor:+ """Return the underlying translation vector of shape :math:`(B,2)`."""+ return self._translation++ @property+ def rotation(self) -> So2:+ """Return the underlying rotation(So2)."""+ return self._rotation++ @property+ def translation(self) -> Tensor:+ """Return the underlying translation vector of shape :math:`(B,2)`."""+ return self._translation++ @staticmethod+ def exp(v) -> 'Se2':+ """Converts elements of lie algebra to elements of lie group.++ Args:+ v: vector of shape :math:`(B, 3)`.++ Example:+ >>> v = torch.ones((1, 3))+ >>> s = Se2.exp(v)+ >>> s.r+ Parameter containing:+ tensor([0.5403+0.8415j], requires_grad=True)+ >>> s.t+ Parameter containing:+ tensor([[0.3818, 1.3012]], requires_grad=True)+ """+ check_v_shape(v)+ theta = v[..., 2]+ so2 = So2.exp(theta)+ z = tensor(0.0, device=v.device, dtype=v.dtype)+ theta_nonzeros = theta != 0.0+ a = where(theta_nonzeros, so2.z.imag / theta, z)+ b = where(theta_nonzeros, (1.0 - so2.z.real) / theta, z)+ x = v[..., 0]+ y = v[..., 1]+ t = stack((a * x - b * y, b * x + a * y), -1)+ return Se2(so2, t)++ def log(self) -> Tensor:+ """Converts elements of lie group to elements of lie algebra.++ Example:+ >>> v = torch.ones((1, 3))+ >>> s = Se2.exp(v).log()+ >>> s+ tensor([[1.0000, 1.0000, 1.0000]], grad_fn=<StackBackward0>)+ """+ theta = self.so2.log()+ half_theta = 0.5 * theta+ denom = self.so2.z.real - 1+ a = where(+ denom != 0, -(half_theta * self.so2.z.imag) / denom, tensor(0.0, device=theta.device, dtype=theta.dtype)+ )+ row0 = stack((a, half_theta), -1)+ row1 = stack((-half_theta, a), -1)+ V_inv = stack((row0, row1), -2)+ upsilon = V_inv @ self.t[..., None]+ return stack((upsilon[..., 0, 0], upsilon[..., 1, 0], theta), -1)++ @staticmethod+ def hat(v):+ """Converts elements from vector space to lie algebra. Returns matrix of shape :math:`(B, 2, 2)`.++ Args:+ theta: angle in radians of shape :math:`(B)`.++ Example:+ >>> theta = torch.tensor(3.1415/2)+ >>> So2.hat(theta)+ tensor([[0.0000, 1.5707],+ [1.5707, 0.0000]])+ """+ # TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support+ check_v_shape(v)+ upsilon = stack((v[..., 0], v[..., 1]), -1)+ theta = v[..., 2]+ col0 = concatenate((So2.hat(theta), upsilon.unsqueeze(-2)), -2)+ return pad(col0, (0, 1))++ @classmethod+ def identity(cls, batch_size: Optional[int] = None, device=None, dtype=None) -> 'Se2':+ """Create a Se2 group representing an identity rotation and zero translation.++ Args:+ batch_size: the batch size of the underlying data.++ Example:+ >>> s = Se2.identity(1)+ >>> s.r+ Parameter containing:+ tensor([1.+0.j], requires_grad=True)+ >>> s.t+ Parameter containing:+ tensor([[0., 0.]], requires_grad=True)+ """+ t: Tensor = tensor([0.0, 0.0], device=device, dtype=dtype)+ if batch_size is not None:+ KORNIA_CHECK(batch_size >= 1, msg="batch_size must be positive")+ t = t.repeat(batch_size, 1)+ return cls(So2.identity(batch_size, device, dtype), t)++ def matrix(self) -> Tensor:+ """Returns the matrix representation of shape :math:`(B, 3, 3)`.++ Example:+ >>> s = Se2(So2.identity(1), torch.ones(1, 2))+ >>> s.matrix()+ tensor([[[1., -0., 1.],+ [0., 1., 1.],+ [0., 0., 1.]]], grad_fn=<CopySlices>)+ """+ rt = concatenate((self.r.matrix(), self.t[..., None]), -1)+ rt_3x3 = pad(rt, (0, 0, 0, 1)) # add last row zeros+ rt_3x3[..., -1, -1] = 1.0+ return rt_3x3++ def inverse(self) -> 'Se2':+ """Returns the inverse transformation.++ Example:+ >>> s = Se2(So2.identity(1), torch.ones(1,2))+ >>> s_inv = s.inverse()+ >>> s_inv.r+ Parameter containing:+ tensor([1.+0.j], requires_grad=True)+ >>> s_inv.t+ Parameter containing:+ tensor([[-1., -1.]], requires_grad=True)+ """+ r_inv: So2 = self.r.inverse()+ t_inv: Tensor = r_inv * (-1 * self.t)+ return Se2(r_inv, t_inv)++ @classmethod+ def random(cls, batch_size: Optional[int] = None, device=None, dtype=None) -> 'Se2':+ """Create a Se2 group representing a random transformation.++ Args:+ batch_size: the batch size of the underlying data.++ Example:+ >>> s = Se2.random()+ >>> s = Se2.random(batch_size=3)+ """+ r = So2.random(batch_size, device, dtype)+ shape: Tuple[int, ...]+ if batch_size is None:+ shape = (2,)+ else:+ KORNIA_CHECK(batch_size >= 1, msg="batch_size must be positive")+ shape = (batch_size, 2)+ return cls(r, rand(shape, device=device, dtype=dtype))diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.pyindex 20b7aff34..da328ee71 100644--- a/kornia/geometry/liegroup/so2.py+++ b/kornia/geometry/liegroup/so2.py@@ -1,6 +1,6 @@# kornia.geometry.so2 module inspired by Sophus-sympy.# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so2.py-from typing import Optional, Union+from typing import Optional, overloadfrom kornia.core import Module, Parameter, Tensor, complex, rand, stack, tensor, zeros_likefrom kornia.geometry.liegroup._utils import (@@ -56,7 +56,15 @@ class So2(Module):def __getitem__(self, idx: int) -> 'So2':return So2(self._z[idx][..., None])- def __mul__(self, right: Union['So2', Tensor]) -> Union['So2', Tensor]:+ @overload+ def __mul__(self, right: 'So2') -> 'So2':+ ...++ @overload+ def __mul__(self, right: Tensor) -> Tensor:+ ...++ def __mul__(self, right):"""Performs a left-multiplication either rotation concatenation or point-transform.Args:@@ -65,20 +73,19 @@ class So2(Module):Return:The resulting So2 transformation."""- out: Union['So2', Tensor]+ z = self.zif isinstance(right, So2):- out = So2(self.z * right.z)+ return So2(z * right.z)elif isinstance(right, Tensor):# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape supportcheck_so2_t_shape(right)x = right[..., 0]y = right[..., 1]- real = self.z.real- imag = self.z.imag- out = stack((real * x - imag * y, imag * x + real * y), -1)+ real = z.real+ imag = z.imag+ return stack((real * x - imag * y, imag * x + real * y), -1)else:raise TypeError(f"Not So2 or Tensor type. Got: {type(right)}")- return out@propertydef z(self) -> Tensor:diff --git a/test/geometry/liegroup/test_se2.py b/test/geometry/liegroup/test_se2.pynew file mode 100644index 000000000..258d5ed36--- /dev/null+++ b/test/geometry/liegroup/test_se2.py@@ -0,0 +1,162 @@+import pytest+import torch++from kornia.geometry.liegroup import Se2, So2+from kornia.testing import BaseTester+++class TestSe2(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):+ z = torch.rand((2,), dtype=torch.cfloat, device=device)+ so2 = So2(z)+ t = torch.rand((1, 2), device=device, dtype=dtype)+ s = Se2(so2, t)+ assert isinstance(s, Se2)+ assert isinstance(s.r, So2)+ self.assert_close(s.r.z.data, z)+ self.assert_close(s.t, t)++ @pytest.mark.parametrize("input_shape", [(1,), (2,), (5,), ()])+ def test_cardinality(self, device, dtype, input_shape):+ t_input_shape = input_shape + (2,)+ z = torch.randn(input_shape + (2,), dtype=dtype, device=device)+ t = torch.randn(t_input_shape, dtype=dtype, device=device)+ s = Se2(So2(torch.complex(z[..., 0], z[..., 1])), t)+ theta = torch.rand(input_shape + (3,), dtype=dtype, device=device)+ assert s.so2.z.shape == input_shape+ assert s.t.shape == t_input_shape+ assert (s * s).so2.z.shape == input_shape+ assert (s * s).t.shape == t_input_shape+ assert s.exp(theta).so2.z.shape == input_shape+ assert s.exp(theta).t.shape == t_input_shape+ assert s.log().shape == input_shape + (3,)+ if not any(input_shape):+ expected_hat_shape = (3, 3)+ else:+ expected_hat_shape = (input_shape[0], 3, 3)+ assert s.hat(theta).shape == expected_hat_shape+ assert s.inverse().so2.z.shape == input_shape+ assert s.inverse().t.shape == t_input_shape++ # 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", (None, 1, 2, 5))+ def test_init(self, device, dtype, batch_size):+ s1 = Se2.random(batch_size, device, dtype)+ s2 = Se2(s1.r, s1.t)+ assert isinstance(s2, Se2)+ self.assert_close(s1.r.z, s2.r.z)+ self.assert_close(s1.t, s2.t)++ @pytest.mark.parametrize("batch_size", (1, 2, 5))+ def test_getitem(self, device, dtype, batch_size):+ z = torch.rand(batch_size, dtype=torch.cfloat, device=device)+ t = torch.rand((batch_size, 2), device=device, dtype=dtype)+ s = Se2(So2(z), t)+ for i in range(batch_size):+ s1 = s[i]+ self.assert_close(s1.r.z, z[i][None])+ self.assert_close(s1.t[0], t[i])++ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))+ def test_mul(self, device, dtype, batch_size):+ s1 = Se2.identity(batch_size, device, dtype)+ s2 = Se2.random(batch_size, device, dtype)+ s1_pose_s2 = s1 * s2+ s2_pose_s2 = s2 * s2.inverse()+ zeros_vec = torch.zeros(2, device=device, dtype=dtype)+ if batch_size is not None:+ zeros_vec = zeros_vec.repeat(batch_size, 1)+ so2_expected = So2.identity(batch_size, device, dtype)+ self.assert_close(s1_pose_s2.r.z, s2.r.z)+ self.assert_close(s1_pose_s2.t, s2.t)+ self.assert_close(s2_pose_s2.r.z.real, so2_expected.z.real)+ self.assert_close(s2_pose_s2.r.z.imag, so2_expected.z.imag)+ self.assert_close(s2_pose_s2.t, zeros_vec)++ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))+ def test_exp(self, device, dtype, batch_size):+ t = self._make_rand_data(device, dtype, batch_size, dims=2)+ theta = torch.zeros(batch_size if batch_size is not None else (), device=device, dtype=dtype)+ z = torch.zeros((batch_size, 2) if batch_size is not None else (2,), device=device, dtype=dtype)+ s = Se2.exp(torch.cat((t, theta[..., None]), -1))+ self.assert_close(s.r.z, So2.exp(theta).z)+ self.assert_close(s.t, z)++ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))+ def test_log(self, device, dtype, batch_size):+ t = self._make_rand_data(device, dtype, batch_size, dims=2)+ s = Se2(So2.identity(batch_size, device, dtype), t)+ s.log()+ 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(), zero_vec)++ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))+ def test_exp_log(self, device, dtype, batch_size):+ a = self._make_rand_data(device, dtype, batch_size, dims=3)+ b = Se2.exp(a).log()+ self.assert_close(b, a, low_tolerance=True)++ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))+ def test_hat(self, device, dtype, batch_size):+ v = self._make_rand_data(device, dtype, batch_size, dims=2)+ theta = self._make_rand_data(device, dtype, batch_size, dims=1)+ s_hat = Se2.hat(torch.cat((v, theta), -1))+ self.assert_close(v, s_hat[..., 2, 0:2])+ self.assert_close(s_hat[..., 0:2, 0:2].squeeze(), So2.hat(theta).squeeze())++ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))+ def test_identity(self, device, dtype, batch_size):+ s = Se2.random(batch_size)+ s_pose_s = s * Se2.identity(batch_size)+ self.assert_close(s_pose_s.so2.z.real, s.so2.z.real)+ self.assert_close(s_pose_s.so2.z.imag, s.so2.z.imag)+ self.assert_close(s.t, s_pose_s.t)++ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))+ def test_matrix(self, device, dtype, batch_size):+ theta = self._make_rand_data(device, dtype, batch_size, dims=1)+ t = self._make_rand_data(device, dtype, batch_size, dims=2)+ s = So2.exp(theta)+ p1 = s * t+ p2 = s.matrix() @ t[..., None]+ self.assert_close(p1, p2.squeeze(-1))++ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))+ def test_inverse(self, device, batch_size, dtype):+ s = Se2.random(batch_size, device, dtype)+ s_in_in = s.inverse().inverse()+ self.assert_close(s_in_in.so2.z.real, s.so2.z.real)+ self.assert_close(s_in_in.so2.z.imag, s.so2.z.imag)+ self.assert_close(s_in_in.t, s.t)++ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))+ def test_random(self, device, dtype, batch_size):+ s = So2.random(batch_size=batch_size, device=device, dtype=dtype)+ t = self._make_rand_data(device, dtype, batch_size, dims=2)+ se2 = Se2(s, t)+ se2_in_se2 = se2.inverse() * se2+ i = Se2.identity(batch_size=batch_size, device=device, dtype=dtype)+ self.assert_close(se2_in_se2.so2.z.real, i.so2.z.real)+ self.assert_close(se2_in_se2.so2.z.imag, i.so2.z.imag)+ self.assert_close(se2_in_se2.t, i.t)