π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[feat] liegroup so2 (#1973)
Christie Jacobdc9b93e280fa
diff --git a/docs/source/geometry.liegroup.rst b/docs/source/geometry.liegroup.rstindex d443e6e0e..fa26a0334 100644--- a/docs/source/geometry.liegroup.rst+++ b/docs/source/geometry.liegroup.rst@@ -10,3 +10,7 @@ kornia.geometry.liegroup.. autoclass:: Se3:members::special-members:++.. autoclass:: So2+ :members:+ :special-members:diff --git a/kornia/core/__init__.py b/kornia/core/__init__.pyindex 0ab237246..c39f0afde 100644--- a/kornia/core/__init__.py+++ b/kornia/core/__init__.py@@ -4,6 +4,7 @@ from ._backend import (Parameter,Tensor,as_tensor,+ complex,concatenate,eye,normalize,@@ -31,5 +32,6 @@ __all__ = ["where","eye","zeros",+ "complex","zeros_like",]diff --git a/kornia/core/_backend.py b/kornia/core/_backend.pyindex 9aab4ace4..17de053a3 100644--- a/kornia/core/_backend.py+++ b/kornia/core/_backend.py@@ -19,6 +19,7 @@ eye = torch.eyezeros = torch.zeroszeros_like = torch.zeros_likewhere = torch.where+complex = torch.complex# constructorsas_tensor = torch.as_tensordiff --git a/kornia/geometry/liegroup/__init__.py b/kornia/geometry/liegroup/__init__.pyindex 7034f9ee1..83b9d5506 100644--- a/kornia/geometry/liegroup/__init__.py+++ b/kornia/geometry/liegroup/__init__.py@@ -1,4 +1,5 @@from .se3 import Se3+from .so2 import So2from .so3 import So3-__all__ = ["So3", "Se3"]+__all__ = ["So3", "Se3", "So2"]diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.pynew file mode 100644index 000000000..0c24e297d--- /dev/null+++ b/kornia/geometry/liegroup/so2.py@@ -0,0 +1,223 @@+# 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 kornia.core import Module, Parameter, Tensor, complex, concatenate, pad, stack, tensor+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR+++class So2(Module):+ r"""Base class to represent the So2 group.++ The SO(2) is the group of all rotations about the origin of two-dimensional Euclidean space+ :math:`R^2` under the operation of composition.+ See more: https://en.wikipedia.org/wiki/Orthogonal_group#Special_orthogonal_group++ We internally represent the rotation by a complex number.++ Example:+ >>> real = torch.tensor([1.0])+ >>> imag = torch.tensor([2.0])+ >>> So2(torch.complex(real, imag))+ Parameter containing:+ tensor([[1.+2.j]], requires_grad=True)+ """++ def __init__(self, z: Tensor) -> None:+ """Constructor for the base class.++ Internally represented by complex number `z`.++ Args:+ z: Complex number with the shape of :math:`(B, 1)` or :math:`(B)`.++ Example:+ >>> real = torch.tensor([1.0])+ >>> imag = torch.tensor([2.0])+ >>> So2(torch.complex(real, imag))+ Parameter containing:+ tensor([[1.+2.j]], requires_grad=True)+ """+ super().__init__()+ KORNIA_CHECK_IS_TENSOR(z)+ # TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support+ z_shape = z.shape+ len_z_shape = len(z_shape)+ if (len_z_shape == 2 and z_shape[1] != 1) or (len_z_shape == 0 and not z.numel()) or (len_z_shape > 2):+ raise ValueError(f"Invalid input size, we expect [B, 1], [B] or []. Got: {z.shape}")+ z = z.reshape(-1, 1)+ self._z = Parameter(z)++ def __repr__(self) -> str:+ return f"{self.z}"++ def __getitem__(self, idx: int) -> 'So2':+ return So2(self._z[idx][..., None])++ def __mul__(self, right: Union['So2', Tensor]) -> Union['So2', Tensor]:+ """Performs a left-multiplication either rotation concatenation or point-transform.++ Args:+ right: the other So2 transformation.++ Return:+ The resulting So2 transformation.+ """+ out: Union['So2', Tensor]+ if isinstance(right, So2):+ out = So2(self.z * right.z)+ elif isinstance(right, Tensor):+ # TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support+ right_shape = right.shape+ len_right_shape = len(right_shape)+ if (+ (len_right_shape == 3 and (right_shape[1] != 2 or right_shape[2] != 1))+ or (len_right_shape == 2 and (sum(right.shape) != 3))+ or (len_right_shape > 3 or len_right_shape < 2)+ ):+ raise ValueError(f"Invalid input size, we expect [B, 2, 1], [2, 1] or [1, 2]. Got: {right_shape}")+ right = right.reshape(-1, 2, 1)+ out = self.matrix() @ right+ else:+ raise TypeError(f"Not So2 or Tensor type. Got: {type(right)}")+ return out++ @property+ def z(self) -> Tensor:+ """Return the underlying data with shape :math:`(B, 1)`."""+ return self._z++ @staticmethod+ def exp(theta: Tensor) -> 'So2':+ """Converts elements of lie algebra to elements of lie group.++ Args:+ theta: angle in radians of shape :math:`(B, 1)` or :math:`(B)`.++ Example:+ >>> v = torch.tensor([3.1415/2])+ >>> s = So2.exp(v)+ >>> s+ Parameter containing:+ tensor([[4.6329e-05+1.j]], requires_grad=True)+ """+ # TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support+ theta_shape = theta.shape+ len_theta_shape = len(theta_shape)+ if (+ (len_theta_shape == 2 and theta_shape[1] != 1)+ or (len_theta_shape == 0 and not theta.numel())+ or (len_theta_shape > 2)+ ):+ raise ValueError(f"Invalid input size, we expect [B, 1] or [B]. Got: {theta_shape}")+ return So2(complex(theta.cos(), theta.sin()))++ def log(self) -> Tensor:+ """Converts elements of lie group to elements of lie algebra.++ Example:+ >>> real = torch.tensor([1.0])+ >>> imag = torch.tensor([3.0])+ >>> So2(torch.complex(real, imag)).log()+ tensor([[1.2490]], grad_fn=<Atan2Backward0>)+ """+ return self.z.imag.atan2(self.z.real)++ @staticmethod+ def hat(theta: Tensor) -> Tensor:+ """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, 1)`.++ 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+ theta_shape = theta.shape+ len_theta_shape = len(theta_shape)+ if (+ (len_theta_shape == 2 and theta_shape[1] != 1)+ or (len_theta_shape == 0 and not theta.numel())+ or (len_theta_shape > 2)+ ):+ raise ValueError(f"Invalid input size, we expect [B, 1] or [B]. Got: {theta_shape}")+ theta = theta.reshape(-1, 1)+ row0 = pad(theta, (1, 0))+ row1 = pad(theta, (0, 1))+ return stack((row0, row1), -1)++ def matrix(self) -> Tensor:+ """Convert the complex number to a rotation matrix of shape :math:`(B, 2, 2)`.++ Example:+ >>> s = So2.identity(batch_size=1)+ >>> m = s.matrix()+ >>> m+ tensor([[[1., -0.],+ [0., 1.]]], grad_fn=<CatBackward0>)+ """+ row0 = stack((self.z.real, -self.z.imag), -1)+ row1 = stack((self.z.imag, self.z.real), -1)+ return concatenate((row0, row1), 1)++ @classmethod+ def from_matrix(cls, matrix: Tensor) -> 'So2':+ """Create So2 from a rotation matrix.++ Args:+ matrix: the rotation matrix to convert of shape :math:`(B, 2, 2)`.++ Example:+ >>> m = torch.eye(2)+ >>> s = So2.from_matrix(m)+ >>> s+ Parameter containing:+ tensor([[1.+0.j]], requires_grad=True)+ """+ # TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support+ matrix_shape = matrix.shape+ len_matrix_shape = len(matrix_shape)+ if (+ (len_matrix_shape == 3 and (matrix_shape[1] != 2 or matrix_shape[2] != 2))+ or (len_matrix_shape == 2 and (matrix_shape[0] != 2 or matrix_shape[1] != 2))+ 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}")+ return cls(complex(matrix[..., 0, 0], matrix[..., 1, 0]))++ @classmethod+ def identity(cls, batch_size: Optional[int] = None, device=None, dtype=None) -> 'So2':+ """Create a So2 group representing an identity rotation.++ Args:+ batch_size: the batch size of the underlying data.++ Example:+ >>> s = So2.identity(batch_size=2)+ >>> s+ Parameter containing:+ tensor([[1.+0.j],+ [1.+0.j]], requires_grad=True)+ """+ real_data = tensor([1.0], device=device, dtype=dtype)+ imag_data = tensor([0.0], device=device, dtype=dtype)+ if batch_size is not None:+ KORNIA_CHECK(batch_size >= 1, msg="batch_size must be positive")+ real_data = real_data[None].repeat(batch_size, 1)+ imag_data = imag_data[None].repeat(batch_size, 1)+ return cls(complex(real_data, imag_data))++ def inverse(self) -> 'So2':+ """Returns the inverse transformation.++ Example:+ >>> s = So2.identity(batch_size=1)+ >>> s.inverse()+ Parameter containing:+ tensor([[1.+0.j]], requires_grad=True)+ """+ return So2(1 / self.z)diff --git a/test/geometry/liegroup/test_so2.py b/test/geometry/liegroup/test_so2.pynew file mode 100644index 000000000..0e964a7bf--- /dev/null+++ b/test/geometry/liegroup/test_so2.py@@ -0,0 +1,147 @@+import pytest+import torch++from kornia.geometry.liegroup import So2+from kornia.testing import BaseTester+++class TestSo2(BaseTester):+ def _make_rand_data(self, device, dtype, input_shape):+ batch_size = input_shape[0]+ shape = input_shape[1:] if batch_size is None else input_shape+ return torch.rand(shape, device=device, dtype=dtype)++ def test_smoke(self, device, dtype):+ z = torch.randn(2, 1, dtype=torch.cfloat, device=device)+ s = So2(z)+ assert isinstance(s, So2)+ self.assert_close(s.z.data, z.data)++ @pytest.mark.parametrize("input_shape", [(1, 1), (2, 1), (5, 1), (1,), (2,), (5,)])+ def test_cardinality(self, device, dtype, input_shape):+ z = torch.randn(input_shape, dtype=torch.cfloat, device=device)+ s = So2(z)+ theta = torch.rand(input_shape, dtype=dtype, device=device)+ assert s.z.shape == (input_shape[0], 1)+ assert (s * s).z.shape == (input_shape[0], 1)+ assert s.exp(theta).z.shape == (input_shape[0], 1)+ assert s.log().shape == (input_shape[0], 1)+ assert s.hat(theta).shape == (input_shape[0], 2, 2)+ assert s.inverse().z.shape == (input_shape[0], 1)++ @pytest.mark.parametrize("input_shape", [(1, 2, 2), (2, 2, 2), (5, 2, 2), (2, 2)])+ def test_matrix_cardinality(self, device, dtype, input_shape):+ matrix = torch.rand(input_shape, dtype=dtype, device=device)+ s = So2.from_matrix(matrix)+ if len(input_shape) == 3:+ expected_shape = input_shape+ else:+ expected_shape = (1, 2, 2)+ assert s.matrix().shape == expected_shape++ @pytest.mark.parametrize("batch_size", (1, 2, 5))+ def test_exception(self, batch_size, device, dtype):+ with pytest.raises(ValueError):+ z = torch.randn(batch_size, 2, dtype=torch.cfloat, device=device)+ assert So2(z)+ with pytest.raises(TypeError):+ assert So2.identity(1, device, dtype) * [1.0, 2.0, 1.0]+ with pytest.raises(ValueError):+ theta = torch.rand((2, 2), dtype=dtype, device=device)+ assert So2.exp(theta)+ with pytest.raises(ValueError):+ theta = torch.rand((2, 2), dtype=dtype, device=device)+ assert So2.hat(theta)+ with pytest.raises(ValueError):+ m = torch.rand((2, 2, 1), dtype=dtype, device=device)+ assert So2.from_matrix(m)+ with pytest.raises(Exception):+ assert So2.identity(batch_size=0)++ # 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):+ z = self._make_rand_data(device, dtype, [batch_size, 2])+ s1 = So2(torch.complex(z[..., 0, None], z[..., 1, None]))+ s2 = So2(s1.z)+ assert isinstance(s2, So2)+ self.assert_close(s1.z.data, s2.z.data)++ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))+ def test_getitem(self, device, dtype, batch_size):+ data = self._make_rand_data(device, dtype, [batch_size, 2])+ z = torch.complex(data[..., 0, None], data[..., 1, None])+ s = So2(z)+ n = 1 if batch_size is None else batch_size+ for i in range(n):+ s1 = s[i]+ self.assert_close(s1.z.data[0].real.squeeze(), z.data[i].real.squeeze())+ self.assert_close(s1.z.data[0].imag.squeeze(), z.data[i].imag.squeeze())++ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))+ def test_mul(self, device, dtype, batch_size):+ s1 = So2.identity(batch_size, device, dtype)+ z = self._make_rand_data(device, dtype, [batch_size, 2])+ s2 = So2(torch.complex(z[..., 0, None], z[..., 1, None]))+ t = self._make_rand_data(device, dtype, [batch_size, 2, 1])+ s1_pose_s2 = s1 * s2+ s2_pose_s2 = s2 * s2.inverse()+ self.assert_close(s1_pose_s2.z.real, s2.z.real)+ self.assert_close(s1_pose_s2.z.imag, s2.z.imag)+ self.assert_close(s2_pose_s2.z.real, s1.z.real)+ self.assert_close(s2_pose_s2.z.imag, s1.z.imag)+ self.assert_close((s1 * t), t.reshape(-1, 2, 1))++ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))+ def test_exp(self, device, dtype, batch_size):+ theta = self._make_rand_data(device, dtype, [batch_size, 1])+ s = So2.exp(theta)+ self.assert_close(s.z.real, theta.cos().reshape(-1, 1))+ self.assert_close(s.z.imag, theta.sin().reshape(-1, 1))++ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))+ def test_log(self, device, dtype, batch_size):+ data = self._make_rand_data(device, dtype, [batch_size, 2])+ z = torch.complex(data[..., 0, None], data[..., 1, None])+ t = So2(z).log()+ self.assert_close(t, data[..., 1, None].atan2(data[..., 0, None]).reshape(-1, 1))++ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))+ def test_exp_log(self, device, dtype, batch_size):+ theta = self._make_rand_data(device, dtype, [batch_size, 1])+ self.assert_close(So2.exp(theta).log(), theta.reshape(-1, 1))++ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))+ def test_hat(self, device, dtype, batch_size):+ theta = self._make_rand_data(device, dtype, [batch_size, 1])+ m = So2.hat(theta)+ o = torch.ones((1, 2, 1), device=device, dtype=dtype)+ self.assert_close(m @ o, torch.cat((theta[..., None], theta[..., None]), 1).reshape(-1, 2, 1))++ @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, 1])+ t = self._make_rand_data(device, dtype, [batch_size, 2, 1])+ ss = So2.exp(theta)+ p1 = ss * t+ p2 = ss.matrix() @ t+ self.assert_close(p1, p2)++ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))+ def test_inverse(self, device, dtype, batch_size):+ data = self._make_rand_data(device, dtype, [batch_size, 2])+ z = torch.complex(data[..., 0, None], data[..., 1, None])+ s = So2(z)+ self.assert_close(s.inverse().inverse().z.real, z.real.reshape(-1, 1))+ self.assert_close(s.inverse().inverse().z.imag, z.imag.reshape(-1, 1))