Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

So2 bug fix (#2015)

Christie Jacobb33df9afab2f
diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.py
index 0c24e297d..f42b9f1ce 100644
--- a/kornia/geometry/liegroup/so2.py
+++ b/kornia/geometry/liegroup/so2.py
@@ -2,7 +2,7 @@
# 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.core import Module, Parameter, Tensor, complex, stack, tensor, zeros_like
from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
@@ -20,7 +20,7 @@ class So2(Module):
>>> imag = torch.tensor([2.0])
>>> So2(torch.complex(real, imag))
Parameter containing:
- tensor([[1.+2.j]], requires_grad=True)
+ tensor([1.+2.j], requires_grad=True)
"""
def __init__(self, z: Tensor) -> None:
@@ -32,11 +32,11 @@ class So2(Module):
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))
+ >>> real = torch.tensor(1.0)
+ >>> imag = torch.tensor(2.0)
+ >>> So2(torch.complex(real, imag)).z
Parameter containing:
- tensor([[1.+2.j]], requires_grad=True)
+ tensor(1.+2.j, requires_grad=True)
"""
super().__init__()
KORNIA_CHECK_IS_TENSOR(z)
@@ -45,7 +45,6 @@ class So2(Module):
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:
@@ -76,7 +75,6 @@ class So2(Module):
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)}")
@@ -99,7 +97,7 @@ class So2(Module):
>>> s = So2.exp(v)
>>> s
Parameter containing:
- tensor([[4.6329e-05+1.j]], requires_grad=True)
+ 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
@@ -119,7 +117,7 @@ class So2(Module):
>>> real = torch.tensor([1.0])
>>> imag = torch.tensor([3.0])
>>> So2(torch.complex(real, imag)).log()
- tensor([[1.2490]], grad_fn=<Atan2Backward0>)
+ tensor([1.2490], grad_fn=<Atan2Backward0>)
"""
return self.z.imag.atan2(self.z.real)
@@ -128,13 +126,13 @@ class So2(Module):
"""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)`.
+ theta: angle in radians of shape :math:`(B)`.
Example:
- >>> theta = torch.tensor([3.1415/2])
+ >>> theta = torch.tensor(3.1415/2)
>>> So2.hat(theta)
- tensor([[[0.0000, 1.5707],
- [1.5707, 0.0000]]])
+ 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
@@ -145,24 +143,24 @@ class So2(Module):
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))
+ z = zeros_like(theta)
+ row0 = stack((z, theta), -1)
+ row1 = stack((theta, z), -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)
+ >>> s = So2.identity()
>>> m = s.matrix()
>>> m
- tensor([[[1., -0.],
- [0., 1.]]], grad_fn=<CatBackward0>)
+ tensor([[1., -0.],
+ [0., 1.]], grad_fn=<StackBackward0>)
"""
row0 = stack((self.z.real, -self.z.imag), -1)
row1 = stack((self.z.imag, self.z.real), -1)
- return concatenate((row0, row1), 1)
+ return stack((row0, row1), -2)
@classmethod
def from_matrix(cls, matrix: Tensor) -> 'So2':
@@ -174,9 +172,9 @@ class So2(Module):
Example:
>>> m = torch.eye(2)
>>> s = So2.from_matrix(m)
- >>> s
+ >>> s.z
Parameter containing:
- tensor([[1.+0.j]], requires_grad=True)
+ tensor(1.+0.j, requires_grad=True)
"""
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
matrix_shape = matrix.shape
@@ -187,7 +185,8 @@ class So2(Module):
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]))
+ z = complex(matrix[..., 0, 0], matrix[..., 1, 0])
+ return cls(z)
@classmethod
def identity(cls, batch_size: Optional[int] = None, device=None, dtype=None) -> 'So2':
@@ -200,24 +199,23 @@ class So2(Module):
>>> s = So2.identity(batch_size=2)
>>> s
Parameter containing:
- tensor([[1.+0.j],
- [1.+0.j]], requires_grad=True)
+ 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)
+ 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)
+ real_data = real_data.repeat(batch_size)
+ imag_data = imag_data.repeat(batch_size)
return cls(complex(real_data, imag_data))
def inverse(self) -> 'So2':
"""Returns the inverse transformation.
Example:
- >>> s = So2.identity(batch_size=1)
- >>> s.inverse()
+ >>> s = So2.identity()
+ >>> s.inverse().z
Parameter containing:
- tensor([[1.+0.j]], requires_grad=True)
+ 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.py
index 0e964a7bf..babe88176 100644
--- a/test/geometry/liegroup/test_so2.py
+++ b/test/geometry/liegroup/test_so2.py
@@ -17,27 +17,27 @@ class TestSo2(BaseTester):
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,)])
+ @pytest.mark.parametrize("input_shape", [(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)
+ assert s.z.shape == input_shape
+ assert (s * s).z.shape == input_shape
+ assert s.exp(theta).z.shape == input_shape
+ assert s.log().shape == input_shape
+ if not any(input_shape):
+ expected_hat_shape = (2, 2)
+ else:
+ expected_hat_shape = (input_shape[0], 2, 2)
+ assert s.hat(theta).shape == expected_hat_shape
+ assert s.inverse().z.shape == input_shape
@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
+ assert s.matrix().shape == input_shape
@pytest.mark.parametrize("batch_size", (1, 2, 5))
def test_exception(self, batch_size, device, dtype):
@@ -72,7 +72,7 @@ class TestSo2(BaseTester):
@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])
+ 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)
@@ -80,7 +80,7 @@ class TestSo2(BaseTester):
@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])
+ 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
@@ -92,47 +92,47 @@ class TestSo2(BaseTester):
@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])
+ z = self._make_rand_data(device, dtype, (batch_size, 2))
+ s2 = So2(torch.complex(z[..., 0], z[..., 1]))
+ 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))
+ self.assert_close((s1 * t), t)
@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])
+ 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))
+ self.assert_close(s.z.real, theta.cos())
+ self.assert_close(s.z.imag, theta.sin())
@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])
+ data = self._make_rand_data(device, dtype, (batch_size, 2))
+ z = torch.complex(data[..., 0], data[..., 1])
t = So2(z).log()
- self.assert_close(t, data[..., 1, None].atan2(data[..., 0, None]).reshape(-1, 1))
+ self.assert_close(t, data[..., 1].atan2(data[..., 0]))
@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))
+ theta = self._make_rand_data(device, dtype, (batch_size, 1))
+ self.assert_close(So2.exp(theta).log(), theta)
@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])
+ theta = self._make_rand_data(device, dtype, (batch_size,))
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))
+ o = torch.ones((2, 1), device=device, dtype=dtype)
+ self.assert_close((m @ o).reshape(-1, 2, 1), theta.reshape(-1, 1, 1).repeat(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])
+ 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
@@ -140,8 +140,8 @@ class TestSo2(BaseTester):
@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])
+ data = self._make_rand_data(device, dtype, (batch_size, 2))
+ z = torch.complex(data[..., 0], data[..., 1])
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))
+ self.assert_close(s.inverse().inverse().z.real, z.real)
+ self.assert_close(s.inverse().inverse().z.imag, z.imag)