π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry)!: make So2/Se2 hat and vee the Lie algebra generators (#5414)
Dipak Chaudharib151fac109d6
diff --git a/changelog.d/5414.breaking.md b/changelog.d/5414.breaking.mdnew file mode 100644index 000000000..7c4011540--- /dev/null+++ b/changelog.d/5414.breaking.md@@ -0,0 +1,7 @@+`So2.hat` / `So2.vee` and `Se2.hat` / `Se2.vee` now use the standard Lie algebra generators. `So2.hat(theta)` used to+return the symmetric `[[0, theta], [theta, 0]]` and `So2.vee` read its `[0, 1]` entry; it now returns+`[[0, -theta], [theta, 0]]` and `vee` reads `[1, 0]`. `Se2.hat(v)` used to put `(v_x, v_y)` in the bottom row+below that symmetric block; it now returns `[[0, -theta, v_x], [theta, 0, v_y], [0, 0, 0]]`, and `Se2.vee` reads the+translation from the last column. `vee(hat(v))` is still the identity, and `matrix_exp(hat(v))` now equals+`exp(v).matrix()`, as it already did for `So3` / `Se3`. Code that builds or reads these matrices in the old layout+gets different values. (#5414)diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.pyindex 84cf8db6e..3197d9453 100644--- a/kornia/geometry/liegroup/se2.py+++ b/kornia/geometry/liegroup/se2.py@@ -66,9 +66,10 @@ class Se2(nn.Module):interprets the block as ``z = m00 + i m10``.- ``t`` is always a tensor registered as module state, whichever constructor built the pose; a ``Vector2``passed to the constructor is unwrapped. ``g * p`` returns a ``Vector2`` only when ``p`` is one.- - Known defects: ``hat`` and ``vee`` put the translation in the bottom row and the angle in a symmetric block- (`#4929 <https://github.com/kornia/kornia/issues/4929>`_), and ``.to()`` a real dtype breaks the ``So2``- rotation (`#4923 <https://github.com/kornia/kornia/issues/4923>`_).+ - ``hat`` returns the se(2) generator :math:`[[0, -\theta, v_x], [\theta, 0, v_y], [0, 0, 0]]` and ``vee``+ reads it back, so ``matrix_exp(hat(v))`` equals ``exp(v).matrix()``.+ - Known defects: ``.to()`` a real dtype breaks the ``So2`` rotation+ (`#4923 <https://github.com/kornia/kornia/issues/4923>`_).Example:>>> so2 = So2.identity(1)@@ -250,9 +251,10 @@ class Se2(nn.Module):@staticmethoddef hat(v: torch.Tensor) -> torch.Tensor:- """Convert a tangent vector to the matrix that :meth:`vee` inverts. Returns ``v.shape[:-1] + (3, 3)``.+ r"""Convert a tangent vector to the se(2) generator. Returns ``v.shape[:-1] + (3, 3)``.- The matrix is not the se(2) generator (`#4929 <https://github.com/kornia/kornia/issues/4929>`_).+ For :math:`v = (v_x, v_y, \theta)` the matrix is :math:`[[0, -\theta, v_x], [\theta, 0, v_y], [0, 0, 0]]`.+ :meth:`vee` inverts it, and its matrix exponential is the pose :meth:`exp` returns.Args:v: vector of shape :math:`(B, 3)` or :math:`(3,)`.@@ -260,9 +262,9 @@ class Se2(nn.Module):Example:>>> v = torch.tensor([1.0, 2.0, 0.5])>>> Se2.hat(v)- tensor([[0.0000, 0.5000, 0.0000],- [0.5000, 0.0000, 0.0000],- [1.0000, 2.0000, 0.0000]])+ tensor([[ 0.0000, -0.5000, 1.0000],+ [ 0.5000, 0.0000, 2.0000],+ [ 0.0000, 0.0000, 0.0000]])"""# check_v_shape@@ -270,16 +272,16 @@ class Se2(nn.Module):is_single = KORNIA_CHECK_SHAPE(v, ["3"], raises=False)if not (is_batch or is_single):raise ValueError(f"Invalid input shape, we expect [B, 3], [3] Got: {v.shape}")- upsilon = torch.stack((v[..., 0], v[..., 1]), -1)+ upsilon = v[..., :2]theta = v[..., 2]- col0 = torch.cat((So2.hat(theta), upsilon.unsqueeze(-2)), -2)- return F.pad(col0, (0, 1))+ top = torch.cat((So2.hat(theta), upsilon.unsqueeze(-1)), -1)+ return F.pad(top, (0, 0, 0, 1)) # zero bottom row@staticmethoddef vee(omega: torch.Tensor) -> torch.Tensor:"""Read the tangent vector back from a :meth:`hat` matrix.- It reads kornia's layout, not the se(2) generator (`#4929 <https://github.com/kornia/kornia/issues/4929>`_).+ It reads the translation from the last column and the angle from the ``[1, 0]`` entry.Args:omega: 3x3-matrix built by :meth:`hat`, of shape :math:`(B, 3, 3)` or :math:`(3, 3)`.@@ -299,7 +301,7 @@ class Se2(nn.Module):is_single = KORNIA_CHECK_SHAPE(omega, ["3", "3"], raises=False)if not (is_batch or is_single):raise ValueError(f"Invalid input size, we expect [B, 3, 3] or [3, 3]. Got: {omega.shape}")- upsilon = omega[..., 2, :2]+ upsilon = omega[..., :2, 2]theta = So2.vee(omega[..., :2, :2])return torch.cat((upsilon, theta[..., None]), -1)diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.pyindex 767ba8f27..c3293cd83 100644--- a/kornia/geometry/liegroup/so2.py+++ b/kornia/geometry/liegroup/so2.py@@ -47,11 +47,10 @@ class So2(nn.Module):displayed on y-down image axes. For a unit rotation, ``matrix()`` is the transpose of:func:`~kornia.geometry.conversions.angle_to_rotation_matrix`, which takes degrees.``log`` returns the angle in :math:`[-\pi, \pi]`, and ``adjoint()`` is the 2x2 identity.- - Known defects: ``hat`` returns the symmetric :math:`[[0, \theta], [\theta, 0]]` instead of the generator- :math:`[[0, -\theta], [\theta, 0]]`, and ``vee`` reads its ``[0, 1]`` entry- (`#4929 <https://github.com/kornia/kornia/issues/4929>`_); ``.to()`` a real dtype keeps the real part of- ``z``, drops its imaginary part and makes ``matrix()`` raise- (`#4923 <https://github.com/kornia/kornia/issues/4923>`_).+ - ``hat`` returns the so(2) generator :math:`[[0, -\theta], [\theta, 0]]` and ``vee`` reads its ``[1, 0]``+ entry, so ``matrix_exp(hat(theta))`` equals ``exp(theta).matrix()``.+ - Known defects: ``.to()`` a real dtype keeps the real part of ``z``, drops its imaginary part and makes+ ``matrix()`` raise (`#4923 <https://github.com/kornia/kornia/issues/4923>`_).Example:>>> real = torch.tensor([0.6])@@ -182,11 +181,10 @@ class So2(nn.Module):@staticmethoddef hat(theta: torch.Tensor) -> torch.Tensor:- """Convert an angle to the matrix that :meth:`vee` inverts.+ r"""Convert an angle to the so(2) generator :math:`[[0, -\theta], [\theta, 0]]`, which :meth:`vee` inverts.The output has shape :math:`(2, 2)` or :math:`(B, 2, 2)`; a :math:`(B, 1)` angle is squeezed to :math:`(B,)`.-- The matrix is not the so(2) generator (`#4929 <https://github.com/kornia/kornia/issues/4929>`_).+ Its matrix exponential is the rotation :meth:`exp` returns.Args:theta: angle in radians of shape :math:`(B,)` or :math:`()`; :math:`(B, 1)` is squeezed to :math:`(B,)`.@@ -194,8 +192,8 @@ class So2(nn.Module):Example:>>> 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]])"""# check_so2_theta_shape@@ -207,9 +205,9 @@ class So2(nn.Module):if is_column:theta = theta.squeeze(-1) # (B, 1) would give (B, 1, 2, 2), which vee() rejects (#4932)z = torch.zeros_like(theta)- row0 = torch.stack((z, theta), -1)+ row0 = torch.stack((z, -theta), -1)row1 = torch.stack((theta, z), -1)- return torch.stack((row0, row1), -1)+ return torch.stack((row0, row1), -2)@staticmethoddef vee(omega: torch.Tensor) -> torch.Tensor:@@ -217,8 +215,7 @@ class So2(nn.Module):Returns a scalar or a :math:`(B,)` vector, respectively.- It reads the ``[0, 1]`` entry, which is :math:`-\theta` for the so(2) generator- (`#4929 <https://github.com/kornia/kornia/issues/4929>`_).+ It reads the ``[1, 0]`` entry, :math:`\theta` in the so(2) generator :math:`[[0, -\theta], [\theta, 0]]`.Args:omega: 2x2-matrix built by :meth:`hat`.@@ -235,7 +232,7 @@ class So2(nn.Module):is_single = KORNIA_CHECK_SHAPE(omega, ["2", "2"], raises=False)if not (is_batch or is_single):raise ValueError(f"Invalid input size, we expect [B, 2, 2] or [2, 2]. Got: {omega.shape}")- return omega[..., 0, 1]+ return omega[..., 1, 0]def matrix(self) -> torch.Tensor:"""Return a matrix of shape ``z.shape + (2, 2)`` for each stored complex number.diff --git a/tests/geometry/liegroup/test_se2.py b/tests/geometry/liegroup/test_se2.pyindex ae64ca844..7b68d005d 100644--- a/tests/geometry/liegroup/test_se2.py+++ b/tests/geometry/liegroup/test_se2.py@@ -283,20 +283,32 @@ class TestSe2(BaseTester):self.assert_close(g.log(), v, rtol=8 * eps, atol=8 * eps)@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])- def test_wart_se2_hat_and_vee_layout_4929(self, device, dtype, batch_size):- # https://github.com/kornia/kornia/issues/4929: hat places translation in the bottom row and has a symmetric- # rotation block; vee reads that same non-generator layout, so vee(hat(v)) conceals the defect.+ def test_convention_se2_hat_and_vee_are_the_generator_4929(self, device, dtype, batch_size):+ # https://github.com/kornia/kornia/issues/4929: hat used to put the translation in the bottom row and the+ # angle in a symmetric block, and vee read that layout. Pin both separately, since vee(hat(v)) round-trips+ # either way.v = self._make_rand_data(device, dtype, (batch_size, 2))theta = self._make_rand_data(device, dtype, (batch_size, 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())+ self.assert_close(s_hat[..., :2, 2], v)+ self.assert_close(s_hat[..., :2, :2].squeeze(), So2.hat(theta.squeeze(-1)).squeeze())+ self.assert_close(s_hat[..., 2, :], torch.zeros_like(s_hat[..., 2, :]))omega = self._make_rand_data(device, dtype, input_shape=(batch_size, 3, 3))recovered = Se2.vee(omega)- self.assert_close(torch.stack((recovered[..., 0], recovered[..., 1]), -1), omega[..., 2, :2])- self.assert_close(recovered[..., -1], omega[..., 0, 1])+ self.assert_close(recovered[..., :2], omega[..., :2, 2])+ self.assert_close(recovered[..., -1], omega[..., 1, 0])self.assert_close(Se2.vee(s_hat), torch.cat((v, theta), -1))+ @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])+ def test_matrix_exp_of_hat_is_exp(self, device, dtype, batch_size):+ if dtype == torch.bfloat16:+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")+ v = self._make_rand_data(device, dtype, (batch_size, 3))+ # The reference runs in float64 on the CPU: MPS has no float64 and CPU matrix_exp has no+ # half-precision kernel.+ expm = torch.linalg.matrix_exp(Se2.hat(v).cpu().double()).to(device=device, dtype=dtype)+ self.assert_close(expm, Se2.exp(v).matrix())+@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])def test_identity(self, device, dtype, batch_size):s = Se2.random(batch_size)diff --git a/tests/geometry/liegroup/test_so2.py b/tests/geometry/liegroup/test_so2.pyindex b12b4105d..de1cdd1bc 100644--- a/tests/geometry/liegroup/test_so2.py+++ b/tests/geometry/liegroup/test_so2.py@@ -181,17 +181,29 @@ class TestSo2(BaseTester):self.assert_close(So2.exp(theta).log(), theta.flatten())@pytest.mark.parametrize("batch_size", [None, 1, 2, 5])- def test_wart_so2_hat_and_vee_layout_4929(self, device, dtype, batch_size):- # https://github.com/kornia/kornia/issues/4929: hat is symmetric rather than the so(2) generator and vee- # reads its upper-right entry. Keep both layouts together because vee(hat(theta)) conceals the defect.+ def test_convention_so2_hat_and_vee_are_the_generator_4929(self, device, dtype, batch_size):+ # https://github.com/kornia/kornia/issues/4929: hat used to be the symmetric [[0, t], [t, 0]] and vee read+ # its [0, 1] entry. Pin both layouts separately, because vee(hat(theta)) round-trips either way.theta = self._make_rand_data(device, dtype, (batch_size,))m = So2.hat(theta)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))+ expected = torch.stack((-theta, theta), -1).reshape(-1, 2, 1)+ self.assert_close((m @ o).reshape(-1, 2, 1), expected)+ self.assert_close(m.transpose(-1, -2), -m)omega = self._make_rand_data(device, dtype, (batch_size, 2, 2))- self.assert_close(So2.vee(omega), omega[..., 0, 1])+ self.assert_close(So2.vee(omega), omega[..., 1, 0])self.assert_close(So2.vee(m), theta)+ @pytest.mark.parametrize("batch_size", [None, 1, 2, 5])+ def test_matrix_exp_of_hat_is_exp(self, device, dtype, batch_size):+ if dtype == torch.bfloat16:+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")+ theta = self._make_rand_data(device, dtype, (batch_size,))+ # The reference runs in float64 on the CPU: MPS has no float64 and CPU matrix_exp has no+ # half-precision kernel.+ expm = torch.linalg.matrix_exp(So2.hat(theta).cpu().double()).to(device=device, dtype=dtype)+ self.assert_close(expm, So2.exp(theta).matrix())+@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,))