Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(geometry): convention blocks and pins for So2, Se2 and Se3 (batch 9b) (#4977)

Dmytro Mishkin92a1bbbcb095
diff --git a/changelog.d/4977.added.md b/changelog.d/4977.added.md
new file mode 100644
index 000000000..62e7a7d7a
--- /dev/null
+++ b/changelog.d/4977.added.md
@@ -0,0 +1 @@
+Convention blocks for `So2`, `Se2` and `Se3` (tangent order, direction, `log` range, adjoint and matrix layouts, composition order) and 25 convention and wart pins; the warts are documented and linked (#4923, #4929, #4931, #4932, #4942), not fixed.
diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.py
index 1e74d7ecb..5c1991681 100644
--- a/kornia/geometry/liegroup/se2.py
+++ b/kornia/geometry/liegroup/se2.py
@@ -52,7 +52,25 @@ class Se2(nn.Module):
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:
+
+ Convention:
+ - ``matrix()`` is the 3x3 :math:`[[R, t], [0, 1]]`. ``a * b`` is ``a.matrix() @ b.matrix()`` and ``g * p`` is
+ :math:`R p + t`, as in :class:`~kornia.geometry.liegroup.Se3`, but an unbatched pose also transforms
+ :math:`(N, 2)` points and a batched one a single :math:`(2,)` point. The rotation is an
+ :class:`~kornia.geometry.liegroup.So2`, whose storage and direction conventions apply.
+ - The tangent vector is :math:`(v_x, v_y, \theta)`, angle last: ``exp`` rotates by :math:`\theta` and
+ translates by :math:`V(\theta) (v_x, v_y)`, and ``log`` returns :math:`\theta` in :math:`[-\pi, \pi]`.
+ ``adjoint()`` is :math:`[[R, (t_y, -t_x)^\top], [0, 1]]`.
+ - ``from_matrix`` ignores the bottom row. In eager execution, it checks approximately that the rotation block
+ has the form :math:`[[a, -b], [b, a]]`, a rotation scaled by :math:`\sqrt{a^2 + b^2}`, and keeps the scale
+ as a non-unit ``z`` that ``log`` drops; it rejects a reflection. Graph export omits the value check and
+ interprets the block as ``z = m00 + i m10``.
+ - 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>`_); for ``identity``, ``random`` and any pose
+ composed with or inverted from one, ``t`` and ``g * points`` are a ``Vector2`` instead of a tensor
+ (`#4931 <https://github.com/kornia/kornia/issues/4931>`_), and ``state_dict`` and ``.to()`` skip that
+ translation, while ``.to()`` a real dtype breaks the ``So2`` rotation
+ (`#4923 <https://github.com/kornia/kornia/issues/4923>`_).
Example:
>>> so2 = So2.identity(1)
@@ -118,13 +136,13 @@ class Se2(nn.Module):
def __mul__(self, right: torch.Tensor) -> torch.Tensor: ...
def __mul__(self, right: Se2 | torch.Tensor) -> Se2 | torch.Tensor:
- """Compose two Se2 transformations.
+ """Compose two Se2 transformations, or transform points.
Args:
- right: the other Se2 transformation.
+ right: the other Se2 transformation, or points of shape :math:`(B, 2)` or :math:`(2,)`.
Return:
- The resulting Se2 transformation.
+ The resulting Se2 transformation, or the transformed points.
"""
so2 = self.so2
@@ -235,16 +253,19 @@ class Se2(nn.Module):
@staticmethod
def hat(v: torch.Tensor) -> torch.Tensor:
- """Convert elements from vector space to lie algebra. Returns matrix of shape :math:`(B, 3, 3)`.
+ """Convert a tangent vector to the matrix that :meth:`vee` inverts. Returns ``v.shape[:-1] + (3, 3)``.
+
+ The matrix is not the se(2) generator (`#4929 <https://github.com/kornia/kornia/issues/4929>`_).
Args:
- v: vector of shape:math:`(B, 3)`.
+ v: vector of shape :math:`(B, 3)` or :math:`(3,)`.
Example:
- >>> theta = torch.tensor(3.1415/2)
- >>> So2.hat(theta)
- tensor([[0.0000, 1.5707],
- [1.5707, 0.0000]])
+ >>> 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]])
"""
# check_v_shape
@@ -259,13 +280,15 @@ class Se2(nn.Module):
@staticmethod
def vee(omega: torch.Tensor) -> torch.Tensor:
- """Convert elements from lie algebra to vector space.
+ """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>`_).
Args:
- omega: 3x3-matrix representing lie algebra of shape :math:`(B, 3, 3)`.
+ omega: 3x3-matrix built by :meth:`hat`, of shape :math:`(B, 3, 3)` or :math:`(3, 3)`.
Returns:
- vector of shape :math:`(B, 3)`.
+ vector of shape :math:`(B, 3)` or :math:`(3,)`.
Example:
>>> v = torch.ones(3)
@@ -378,7 +401,7 @@ class Se2(nn.Module):
device: Union[str, torch.device, None] = None,
dtype: Union[torch.dtype, None] = None,
) -> Se2:
- """Create a Se2 group representing a random transformation.
+ """Create a Se2 group from ``So2.random`` and a translation drawn from :math:`U[0, 1)`.
Args:
batch_size: the batch size of the underlying data.
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index 2dff847ed..aa6e2524c 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -15,7 +15,7 @@
# limitations under the License.
#
-# kornia.geometry.so3 module inspired by Sophus-sympy.
+# kornia.geometry.se3 module inspired by Sophus-sympy.
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/se3.py
from __future__ import annotations
@@ -41,6 +41,24 @@ class Se3(nn.Module):
space :math:`R^3` under the operation of composition.
See more: https://ingmec.ual.es/~jlblanco/papers/jlblanco2010geometry3D_techrep.pdf
+ Convention:
+ - The tangent vector is :math:`[\upsilon, \omega]`, translation first
+ (:doc:`Conventions </get-started/conventions>` maps it onto Sophus and GTSAM): ``exp`` rotates by
+ ``So3.exp(omega)`` and translates by :math:`V(\omega) \upsilon`, ``hat`` is
+ :math:`[[\hat\omega, \upsilon], [0, 0]]`, and ``log`` is principal, with :math:`|\omega| \le \pi`.
+ - ``matrix()`` is the 4x4 :math:`[[R, t], [0, 1]]`. When both rotations are unit, ``a * b`` is
+ ``a.matrix() @ b.matrix()``, so ``b`` acts first, and ``g * p`` is :math:`R p + t`. ``adjoint()`` is
+ :math:`[[R, \hat t R], [0, R]]`.
+ - The rotation is an :class:`~kornia.geometry.liegroup.So3`, whose storage and point-shape conventions
+ apply, including its non-unit quaternion defect (`#4942 <https://github.com/kornia/kornia/issues/4942>`_).
+ ``from_matrix`` ignores the bottom row.
+ - Known defects: for ``identity``, ``random``, ``from_qxyz`` and any pose composed with or inverted from one,
+ ``t`` is a ``Vector3``, which rejects tensor indexing such as ``t[..., 0]``
+ (`#4931 <https://github.com/kornia/kornia/issues/4931>`_); ``state_dict`` and ``.to()`` skip such a
+ translation, and skip the rotation unless its quaternion is an ``nn.Parameter``, so ``load_state_dict`` can
+ restore one pose's translation next to another pose's rotation
+ (`#4923 <https://github.com/kornia/kornia/issues/4923>`_).
+
Example:
>>> q = Quaternion.identity()
>>> s = Se3(q, torch.ones(3))
@@ -55,10 +73,11 @@ class Se3(nn.Module):
def __init__(self, rotation: Quaternion | So3, translation: Vector3 | torch.Tensor) -> None:
"""Construct the base class.
- Internally represented by a unit quaternion `q` and a translation 3-vector.
+ Internally represented by an So3 rotation and a translation 3-vector.
Args:
- rotation: So3 group encompassing a rotation.
+ rotation: So3 group encompassing a rotation, or a Quaternion to wrap in one; it is not normalised
+ (`#4942 <https://github.com/kornia/kornia/issues/4942>`_).
translation: Vector3 or translation torch.Tensor with the shape of :math:`(B, 3)`.
Example:
@@ -104,13 +123,14 @@ class Se3(nn.Module):
return Se3(_r, _t)
def __mul__(self, right: Se3) -> Se3 | Vector3 | torch.Tensor:
- """Compose two Se3 transformations.
+ """Compose two Se3 transformations, or transform points.
Args:
- right: the other Se3 transformation.
+ right: the other Se3 transformation, or points as a tensor or ``Vector3`` with the batch shape of the
+ pose and a last dimension of 3.
Return:
- The resulting Se3 transformation.
+ The resulting Se3 transformation, or the transformed points.
"""
so3 = self.so3
@@ -180,9 +200,8 @@ class Se3(nn.Module):
nonzero = theta_sq > 0
# sqrt has an unbounded derivative at 0, so it is taken on a substituted 1 at omega = 0 and
# the where selects the exact 0 (kornia#4229's shape). The coefficients of V are finite there
- # (1/2 and 1/6) and even in theta, so V @ upsilon is taken for every element: the former
- # fallback to upsilon at the identity did not depend on omega and made d t / d omega = 0
- # there instead of -0.5 [upsilon]_x (kornia#4953). The value is unchanged, V(0) = I exactly.
+ # (1/2 and 1/6) and even in theta, so V @ upsilon is taken for every element, which keeps
+ # d t / d omega = -0.5 [upsilon]_x at the identity (kornia#4953); V(0) = I exactly.
safe_theta_sq = torch.where(nonzero, theta_sq, torch.ones_like(theta_sq))
theta = torch.where(nonzero, safe_theta_sq.sqrt(), torch.zeros_like(theta_sq))
R = So3.exp(omega)
@@ -217,8 +236,8 @@ class Se3(nn.Module):
t = _unwrap(self.t)
omega_hat = So3.hat(omega)
omega_hat_sq = omega_hat @ omega_hat
- # c is finite at theta = 0 (1/12), so V^-1 @ t is taken for every element; the former fallback
- # to t at the identity made d upsilon / d q_vec = 0 there instead of [t]_x (kornia#4953).
+ # c is finite at theta = 0 (1/12), so V^-1 @ t is taken for every element, which keeps
+ # d upsilon / d q_vec = [t]_x at the identity (kornia#4953).
_, _, c = _so3_small_angle_coefficients(theta)
V_inv = (
torch.eye(3, device=omega.device, dtype=omega.dtype) - 0.5 * omega_hat + c[..., None, None] * omega_hat_sq
@@ -342,16 +361,17 @@ class Se3(nn.Module):
@classmethod
def from_qxyz(cls, qxyz: torch.Tensor) -> Se3:
- """Create a Se3 group a quaternion and translation vector.
+ """Create a Se3 group from a quaternion and a translation vector.
Args:
- qxyz: torch.Tensor of shape :math:`(B, 7)`.
+ qxyz: torch.Tensor of shape :math:`(B, 7)` laid out as ``[qw, qx, qy, qz, x, y, z]``, scalar first; the
+ quaternion is not normalised (`#4942 <https://github.com/kornia/kornia/issues/4942>`_).
Example:
- >>> qxyz = torch.tensor([1., 2., 3., 0., 0., 0., 1.])
+ >>> qxyz = torch.tensor([0., 0., 0., 1., 0., 0., 1.])
>>> s = Se3.from_qxyz(qxyz)
>>> s.r
- tensor([1., 2., 3., 0.])
+ tensor([0., 0., 0., 1.])
>>> s.t
x: 0.0
y: 0.0
diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.py
index fe3638017..67f21a6c5 100644
--- a/kornia/geometry/liegroup/so2.py
+++ b/kornia/geometry/liegroup/so2.py
@@ -37,14 +37,31 @@ class So2(nn.Module):
: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 torch.complex number.
+ Convention:
+ - Stores the rotation as a complex number ``z`` of shape :math:`()`, :math:`(B,)`, or :math:`(B, 1)`.
+ For unit :math:`z = \cos\theta + i \sin\theta`, ``matrix()`` is
+ :math:`[[\cos\theta, -\sin\theta], [\sin\theta, \cos\theta]]`. Non-unit ``z = a + i b`` is accepted
+ and produces :math:`[[a, -b], [b, a]]`, which rotates and scales by :math:`|z|`. The complex storage rules
+ out bfloat16.
+ - A positive angle rotates the x axis toward the y axis: counter-clockwise in a y-up frame, clockwise as
+ 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>`_); an accepted :math:`(B, 1)` ``z`` or angle
+ yields :math:`(B, 1, 2, 2)` from ``matrix()`` or ``hat()``, which ``vee()`` rejects, and times
+ :math:`(B, 2)` points returns :math:`(B, B, 2)`, every rotation applied to every point
+ (`#4932 <https://github.com/kornia/kornia/issues/4932>`_); ``.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([1.0])
- >>> imag = torch.tensor([2.0])
+ >>> real = torch.tensor([0.6])
+ >>> imag = torch.tensor([0.8])
>>> So2(torch.complex(real, imag))
Parameter containing:
- tensor([1.+2.j], requires_grad=True)
+ tensor([0.6000+0.8000j], requires_grad=True)
"""
@@ -54,14 +71,14 @@ class So2(nn.Module):
Internally represented by torch.complex number `z`.
Args:
- z: Complex number with the shape of :math:`(B, 1)` or :math:`(B)`.
+ z: Complex number with the shape of :math:`(B,)`, :math:`(B, 1)`, or :math:`()`.
Example:
- >>> real = torch.tensor(1.0)
- >>> imag = torch.tensor(2.0)
+ >>> real = torch.tensor(0.6)
+ >>> imag = torch.tensor(0.8)
>>> So2(torch.complex(real, imag)).z
Parameter containing:
- tensor(1.+2.j, requires_grad=True)
+ tensor(0.6000+0.8000j, requires_grad=True)
"""
super().__init__()
@@ -91,10 +108,11 @@ class So2(nn.Module):
"""Perform a left-multiplication either rotation concatenation or point-transform.
Args:
- right: the other So2 transformation.
+ right: the other So2 transformation, or points of shape :math:`(B, 2)` or :math:`(2,)` as a tensor or
+ a ``Vector2``.
Return:
- The resulting So2 transformation.
+ The resulting So2 transformation, or the rotated points with the type of ``right``.
"""
z = self.z
@@ -120,7 +138,7 @@ class So2(nn.Module):
@property
def z(self) -> torch.Tensor:
- """Return the underlying data with shape :math:`(B, 1)`."""
+ """Return the underlying complex number, with the shape it was constructed with."""
return self._z
@staticmethod
@@ -128,7 +146,7 @@ class So2(nn.Module):
"""Convert elements of lie algebra to elements of lie group.
Args:
- theta: angle in radians of shape :math:`(B, 1)` or :math:`(B)`.
+ theta: angle in radians of shape :math:`(B,)`, :math:`(B, 1)`, or :math:`()`.
Example:
>>> v = torch.tensor([3.1415/2])
@@ -150,20 +168,24 @@ class So2(nn.Module):
"""Convert elements of lie group to elements of lie algebra.
Example:
- >>> real = torch.tensor([1.0])
- >>> imag = torch.tensor([3.0])
+ >>> real = torch.tensor([0.6])
+ >>> imag = torch.tensor([0.8])
>>> So2(torch.complex(real, imag)).log()
- tensor([1.2490], grad_fn=<Atan2Backward0>)
+ tensor([0.9273], grad_fn=<Atan2Backward0>)
"""
return self.z.imag.atan2(self.z.real)
@staticmethod
def hat(theta: torch.Tensor) -> torch.Tensor:
- """Convert elements from vector space to lie algebra. Returns matrix of shape :math:`(B, 2, 2)`.
+ """Convert an angle to the matrix that :meth:`vee` inverts for scalar or :math:`(B,)` input.
+
+ The output has shape ``theta.shape + (2, 2)``; see the class convention for :math:`(B, 1)`.
+
+ The matrix is not the so(2) generator (`#4929 <https://github.com/kornia/kornia/issues/4929>`_).
Args:
- theta: angle in radians of shape :math:`(B)`.
+ theta: angle in radians of shape :math:`(B,)`, :math:`(B, 1)`, or :math:`()`.
Example:
>>> theta = torch.tensor(3.1415/2)
@@ -185,10 +207,15 @@ class So2(nn.Module):
@staticmethod
def vee(omega: torch.Tensor) -> torch.Tensor:
- """Convert elements from lie algebra to vector space. Returns vector of shape :math:`(B,)`.
+ r"""Read the angle back from a :meth:`hat` matrix of shape :math:`(2, 2)` or :math:`(B, 2, 2)`.
+
+ 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>`_).
Args:
- omega: 2x2-matrix representing lie algebra.
+ omega: 2x2-matrix built by :meth:`hat`.
Example:
>>> v = torch.ones(3)
@@ -205,7 +232,7 @@ class So2(nn.Module):
return omega[..., 0, 1]
def matrix(self) -> torch.Tensor:
- """Convert the torch.complex number to a rotation matrix of shape :math:`(B, 2, 2)`.
+ """Return a matrix of shape ``z.shape + (2, 2)`` for each stored complex number.
Example:
>>> s = So2.identity()
@@ -299,7 +326,7 @@ class So2(nn.Module):
device: Union[str, torch.device, None] = None,
dtype: Union[torch.dtype, None] = None,
) -> So2:
- """Create a So2 group representing a random rotation.
+ r"""Create a So2 group with a unit rotation whose angle is drawn from :math:`U[-\pi, \pi)`.
Args:
batch_size: the batch size of the underlying data.
diff --git a/tests/geometry/liegroup/test_se2.py b/tests/geometry/liegroup/test_se2.py
index 9933a47fd..f7ad7b65f 100644
--- a/tests/geometry/liegroup/test_se2.py
+++ b/tests/geometry/liegroup/test_se2.py
@@ -23,7 +23,7 @@ import torch
from kornia.geometry.liegroup import Se2, So2
from kornia.geometry.vector import Vector2
-from testing.base import BaseTester
+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
class TestSe2(BaseTester):
@@ -282,26 +282,19 @@ 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_hat(self, device, dtype, batch_size):
+ 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.
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())
-
- @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
- def test_vee(self, device, dtype, batch_size):
omega = self._make_rand_data(device, dtype, input_shape=(batch_size, 3, 3))
- v = Se2.vee(omega)
- self.assert_close(torch.stack((v[..., 0], v[..., 1]), -1), omega[..., 2, :2])
- self.assert_close(v[..., -1], omega[..., 0, 1])
-
- @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
- def test_hat_vee(self, device, dtype, batch_size):
- a = self._make_rand_data(device, dtype, (batch_size, 3))
- omega_hat = Se2.hat(a)
- b = Se2.vee(omega_hat)
- self.assert_close(b, a)
+ 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(Se2.vee(s_hat), torch.cat((v, theta), -1))
@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_identity(self, device, dtype, batch_size):
@@ -421,3 +414,133 @@ class TestSe2(BaseTester):
assert converted.t.grad_fn is not None
converted.t.sum().backward()
assert v.grad is not None
+
+ def test_wart_se2_vector2_translation_is_not_registered_or_moved_4923(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ # https://github.com/kornia/kornia/issues/4923: identity and random keep their Vector2 translation outside
+ # module state, so it is absent from state_dict() and .to() leaves it at its original dtype. Cast to a
+ # complex dtype so this pin does not depend on So2's separate real-cast defect under the same issue.
+ for pose in (Se2.identity(1, device, dtype), Se2.random(1, device, dtype)):
+ assert "_translation" not in pose.state_dict()
+ pose.to(torch.complex64)
+ assert pose.r.z.dtype == torch.complex64
+ assert pose.t.data.dtype == dtype
+
+ def test_convention_se2_tangent_is_vx_vy_theta_with_V(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ # The tangent is (vx, vy, theta), angle last, and exp translates by V(theta) (vx, vy), V = [[a, -b], [b, a]]
+ # with a = sin(theta) / theta and b = (1 - cos(theta)) / theta. Reference, float64:
+ # a, b = math.sin(0.3) / 0.3, (1 - math.cos(0.3)) / 0.3; (a - 2 * b, b + 2 * a) and (2 * a - b, 2 * b + a).
+ v = torch.tensor([1.0, 2.0, 0.3], device=device, dtype=dtype)
+ g = Se2.exp(v)
+ self.assert_close(g.so2.log(), v[2])
+ t_expected = torch.tensor([0.6873106163751718, 2.1190130806569103], device=device, dtype=dtype)
+ assert (t_expected - v[:2]).abs().max() > 0.1 # V is not the identity at this angle
+ self.assert_close(g.t, t_expected)
+ # V couples the two slots: swapping vx and vy does not swap the translation
+ swapped = Se2.exp(v[[1, 0, 2]]).t
+ self.assert_close(swapped, torch.tensor([1.8212563414942837, 1.2828240947004255], device=device, dtype=dtype))
+
+ def test_convention_se2_adjoint_conjugates_the_tangent(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ # g exp(v) = exp(Ad(g) v) g, with Ad(g) = [[R, (ty, -tx)], [0, 0, 1]] for the (vx, vy, theta) tangent.
+ g = Se2.exp(torch.tensor([0.5, -1.0, 0.7], device=device, dtype=dtype))
+ v = torch.tensor([0.3, 0.2, -0.4], device=device, dtype=dtype)
+ ad_v = (g.adjoint() @ v[:, None])[:, 0]
+ assert (ad_v - v).abs().max() > 0.1 # g does not commute with exp(v)
+ self.assert_close((g * Se2.exp(v)).matrix(), (Se2.exp(ad_v) * g).matrix())
+
+ def test_convention_se2_composition_is_left_matrix_product(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ # a * b is the matrix product a b: b acts first on a point.
+ a = Se2.exp(torch.tensor([1.0, -0.5, 0.9], device=device, dtype=dtype))
+ b = Se2.exp(torch.tensor([-0.3, 2.0, -0.4], device=device, dtype=dtype))
+ ab, ba = a.matrix() @ b.matrix(), b.matrix() @ a.matrix()
+ assert (ab - ba).abs().max() > 0.1 # a non-commuting pair
+ self.assert_close((a * b).matrix(), ab)
+ p = torch.tensor([0.7, -1.3], device=device, dtype=dtype)
+ self.assert_close((a * b) * p, a * (b * p))
+
+ def test_convention_se2_point_action_broadcasts_the_pose(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ # Unlike Se3, an unbatched pose transforms (N, 2) points and a batched pose a single (2,) point.
+ v = torch.tensor([[1.0, -0.5, 0.9], [-0.3, 2.0, -0.4]], device=device, dtype=dtype)
+ p = torch.tensor([[0.7, -1.3], [2.0, 0.5], [-1.0, 1.0]], device=device, dtype=dtype)
+ g0 = Se2.exp(v[0])
+ self.assert_close(g0 * p, p @ g0.so2.matrix().mT + g0.t)
+ g = Se2.exp(v)
+ self.assert_close(g * p[0], torch.stack([Se2.exp(v[i]) * p[0] for i in range(2)]))
+
+ def test_convention_se2_log_is_principal(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ # The angle of log is in [-pi, pi], and the translation part is taken with that angle, so exp(log(g)) = g.
+ # Reference, float64: scipy.linalg.logm(scipy.linalg.expm([[0, -3.5, 1], [3.5, 0, 2], [0, 0, 0]])), whose
+ # entries (0, 2), (1, 2), (1, 0) are vx, vy, theta.
+ g = Se2.exp(torch.tensor([1.0, 2.0, 3.5], device=device, dtype=dtype))
+ expected = torch.tensor(
+ [-0.7951958020513128, -1.5903916041026287, -2.7831853071795862], device=device, dtype=dtype
+ )
+ self.assert_close(g.log(), expected)
+ self.assert_close(Se2.exp(g.log()).matrix(), g.matrix())
+
+ def test_convention_se2_from_matrix_ignores_the_bottom_row(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ # from_matrix reads the rotation block, validated by So2.from_matrix, and the last column; it does not
+ # check the bottom row.
+ v = torch.tensor([1.0, 2.0, 0.3], device=device, dtype=dtype)
+ clean = Se2.exp(v).matrix().detach()
+ junk = clean.clone()
+ junk[2] = torch.tensor([0.5, -4.0, 7.0], device=device, dtype=dtype)
+ self.assert_close(Se2.from_matrix(junk).matrix(), clean)
+ # A scaled rotation block is accepted and its scale kept in z, which log drops.
+ scaled = clean.clone()
+ scaled[:2, :2] *= 2.0
+ g = Se2.from_matrix(scaled)
+ self.assert_close(g.matrix(), scaled)
+ self.assert_close(g.log()[2], v[2])
+ reflection = clean.clone()
+ reflection[:2, :2] = torch.tensor([[1.0, 0.0], [0.0, -1.0]], device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="Invalid SO2 rotation matrix"):
+ Se2.from_matrix(reflection)
+
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_convention_se2_from_matrix_omits_rotation_value_validation_during_export(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ # Graph export cannot read rotation values, so from_matrix keeps m00 + i m10 and omits eager validation.
+ reflection = torch.tensor([[1.0, 0.0], [0.0, -1.0]], device=device, dtype=dtype)
+ matrix = torch.eye(3, device=device, dtype=dtype)
+ matrix[:2, :2] = reflection
+ with pytest.raises(ValueError):
+ Se2.from_matrix(matrix)
+
+ class FromMatrix(torch.nn.Module):
+ def forward(self, input):
+ return Se2.from_matrix(input).matrix()
+
+ expected = torch.eye(3, device=device, dtype=dtype)
+ exported = torch.export.export(FromMatrix(), (matrix,)).module()
+ self.assert_close(exported(matrix), expected)
+
+ def test_wart_se2_identity_point_action_returns_a_vector2_4931(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ p = torch.tensor([[1.0, 2.0]], device=device, dtype=dtype)
+ from_exp = Se2.exp(torch.zeros(1, 3, device=device, dtype=dtype))
+ identity = Se2.identity(1, device, dtype)
+ self.assert_close(identity.matrix(), from_exp.matrix()) # the same group element
+ assert isinstance(from_exp * p, torch.Tensor)
+ # https://github.com/kornia/kornia/issues/4931: identity stores its translation as a Vector2 and __mul__ adds
+ # it without unwrapping, so the point action of the identity returns a Vector2, not a tensor.
+ out = identity * p
+ assert isinstance(out, Vector2)
+ assert not isinstance(out, torch.Tensor)
+ self.assert_close(out.data, p)
+ assert isinstance((from_exp * identity) * p, Vector2) # a product with the identity inherits it
diff --git a/tests/geometry/liegroup/test_se3.py b/tests/geometry/liegroup/test_se3.py
index d5455b926..efda0cafe 100644
--- a/tests/geometry/liegroup/test_se3.py
+++ b/tests/geometry/liegroup/test_se3.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+import math
+
import pytest
import torch
@@ -412,3 +414,114 @@ class TestSe3(BaseTester):
assert moved.t.dtype == other and moved.t.grad_fn is not None
moved.t.sum().backward()
assert v.grad is not None
+
+ def test_convention_se3_tangent_is_upsilon_omega_with_V(self, device, dtype):
+ # The tangent is (upsilon, omega), translation part first: exp rotates by the rotation vector omega and
+ # translates by V(omega) upsilon. Reference, float64: m = scipy.linalg.expm of
+ # [[0, 0.3, 0.2, 1], [-0.3, 0, -0.4, -2], [-0.2, 0.4, 0, 3], [0, 0, 0, 0]]; t = m[:3, 3], R = m[:3, :3].
+ v = torch.tensor([1.0, -2.0, 3.0, 0.4, 0.2, -0.3], device=device, dtype=dtype)
+ g = Se3.exp(v)
+ t_expected = torch.tensor(
+ [0.8932266973410874, -2.666342656131567, 2.413407159033739], device=device, dtype=dtype
+ )
+ r_expected = torch.tensor(
+ [
+ [0.9365557269934556, 0.32475143364814213, 0.13190859175670216],
+ [-0.24666617456316434, 0.8779917826797222, -0.4102270442977377],
+ [-0.24903648038416887, 0.35166309998400436, 0.9023934261437778],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ assert (t_expected - v[:3]).abs().max() > 0.1 # V is not the identity at this rotation
+ self.assert_close(g.t, t_expected)
+ self.assert_close(g.r.matrix(), r_expected)
+ self.assert_close(g.r.log(), v[3:])
+
+ def test_convention_se3_hat_layout(self, device, dtype):
+ # hat(upsilon, omega) = [[hat(omega), upsilon], [0, 0]]: the cross-product matrix of omega in the top-left
+ # block, upsilon in the last column, a zero bottom row. Its matrix exponential is exp(v).matrix().
+ v = torch.tensor([1.0, -2.0, 3.0, 0.4, 0.2, -0.3], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [[0.0, 0.3, 0.2, 1.0], [-0.3, 0.0, -0.4, -2.0], [-0.2, 0.4, 0.0, 3.0], [0.0, 0.0, 0.0, 0.0]],
+ device=device,
+ dtype=dtype,
+ )
+ m = Se3.hat(v)
+ self.assert_close(m, expected)
+ # matrix_exp has no half-precision kernel and MPS has no float64: take it in float64 on the CPU. Move first,
+ # then cast: on torch 2.14 a single m.to("cpu", torch.float64) from MPS returns zeros.
+ m_exp = torch.linalg.matrix_exp(m.cpu().double()).to(device=device, dtype=dtype)
+ self.assert_close(m_exp, Se3.exp(v).matrix())
+
+ def test_convention_se3_adjoint_conjugates_the_tangent(self, device, dtype):
+ # g exp(v) = exp(Ad(g) v) g, with Ad(g) = [[R, hat(t) R], [0, R]] for the (upsilon, omega) tangent.
+ g = Se3.exp(torch.tensor([1.0, -2.0, 3.0, 0.4, 0.2, -0.3], device=device, dtype=dtype))
+ v = torch.tensor([0.3, 0.1, -0.2, -0.1, 0.3, 0.05], device=device, dtype=dtype)
+ ad_v = (g.adjoint() @ v[:, None])[:, 0]
+ assert (ad_v - v).abs().max() > 0.1 # g does not commute with exp(v)
+ self.assert_close((g * Se3.exp(v)).matrix(), (Se3.exp(ad_v) * g).matrix())
+
+ def test_convention_se3_composition_is_left_matrix_product(self, device, dtype):
+ # With unit rotations from exp, a * b is the matrix product a b: b acts first on a point. Non-unit
+ # quaternions violate this #4942 precondition.
+ a = Se3.exp(torch.tensor([1.0, -2.0, 3.0, 0.4, 0.2, -0.3], device=device, dtype=dtype))
+ b = Se3.exp(torch.tensor([0.3, 0.1, -0.2, -0.1, 0.3, 0.05], device=device, dtype=dtype))
+ self.assert_close(a.r.q.norm(), torch.ones((), device=device, dtype=dtype))
+ self.assert_close(b.r.q.norm(), torch.ones((), device=device, dtype=dtype))
+ ab, ba = a.matrix() @ b.matrix(), b.matrix() @ a.matrix()
+ assert (ab - ba).abs().max() > 0.1 # a non-commuting pair
+ self.assert_close((a * b).matrix(), ab)
+ p = torch.tensor([0.7, -1.3, 2.1], device=device, dtype=dtype)
+ self.assert_close((a * b) * p, a * (b * p))
+
+ def test_convention_se3_from_qxyz_is_wxyz_then_xyz(self, device, dtype):
+ # The seven numbers are the quaternion (w, x, y, z), then the translation (x, y, z).
+ # Reference: 95 * scipy.spatial.transform.Rotation.from_quat(q).as_matrix(), which takes (x, y, z, w), for
+ # q = (1, -3, 2, 9) (the wxyz reading) and q = (9, 1, -3, 2) (the xyzw reading).
+ q = torch.tensor([9.0, 1.0, -3.0, 2.0], dtype=torch.float64) / math.sqrt(95.0)
+ qxyz = torch.cat((q, torch.tensor([5.0, 6.0, 7.0], dtype=torch.float64))).to(device=device, dtype=dtype)
+ wxyz = torch.tensor([[69.0, -42.0, -50.0], [30.0, 85.0, -30.0], [58.0, 6.0, 75.0]], device=device, dtype=dtype)
+ xyzw = torch.tensor(
+ [[75.0, 30.0, -50.0], [6.0, -85.0, -42.0], [-58.0, 30.0, -69.0]], device=device, dtype=dtype
+ )
+ assert (wxyz - xyzw).abs().max() > 50.0 # the two readings differ
+ g = Se3.from_qxyz(qxyz)
+ self.assert_close(g.r.matrix(), wxyz / 95.0)
+ self.assert_close(g.t.data, torch.tensor([5.0, 6.0, 7.0], device=device, dtype=dtype))
+
+ def test_convention_se3_from_matrix_ignores_the_bottom_row(self, device, dtype):
+ # from_matrix reads the rotation block and the last column; it does not check the bottom row.
+ clean = Se3.exp(torch.tensor([1.0, -2.0, 3.0, 0.4, 0.2, -0.3], device=device, dtype=dtype)).matrix().detach()
+ junk = clean.clone()
+ junk[3] = torch.tensor([0.5, -4.0, 7.0, 2.0], device=device, dtype=dtype)
+ self.assert_close(Se3.from_matrix(junk).matrix(), clean)
+
+ def test_wart_se3_translation_type_depends_on_constructor_4931(self, device, dtype):
+ from_exp = Se3.exp(torch.zeros(1, 6, device=device, dtype=dtype))
+ identity = Se3.identity(1, device, dtype)
+ self.assert_close(identity.matrix(), from_exp.matrix()) # the same group element
+ assert isinstance(from_exp.t, torch.Tensor)
+ # https://github.com/kornia/kornia/issues/4931: identity stores its translation as a Vector3, which is not a
+ # tensor, so tensor indexing of the translation fails for it and works for the exp-built element.
+ assert isinstance(identity.t, Vector3)
+ assert not isinstance(identity.t, torch.Tensor)
+ self.assert_close(from_exp.t[..., 0], torch.zeros(1, device=device, dtype=dtype))
+ with pytest.raises(RuntimeError):
+ identity.t[..., 0]
+ assert isinstance((from_exp * identity).t, Vector3) # a product with the identity inherits it
+
+ def test_wart_se3_load_state_dict_restores_translation_not_rotation_4923(self, device, dtype):
+ src = Se3.exp(torch.tensor([[1.0, -2.0, 3.0, 0.4, 0.2, -0.3]], device=device, dtype=dtype))
+ dst = Se3(Quaternion.identity(1, device, dtype), torch.zeros(1, 3, device=device, dtype=dtype))
+ eye = torch.eye(3, device=device, dtype=dtype)[None]
+ assert (src.r.matrix() - eye).abs().max() > 0.1 # the source rotation is not the identity
+ # https://github.com/kornia/kornia/issues/4923: the quaternion is not registered, so the state dict holds
+ # only the translation; loading reports every key matched, restores the translation and keeps the old
+ # rotation.
+ assert list(src.state_dict()) == ["_translation"]
+ assert list(Se3.identity(1, device, dtype).state_dict()) == [] # a Vector3 translation is not saved either
+ result = dst.load_state_dict(src.state_dict())
+ assert not result.missing_keys and not result.unexpected_keys
+ self.assert_close(dst.t, src.t.detach())
+ self.assert_close(dst.r.matrix(), eye)
diff --git a/tests/geometry/liegroup/test_so2.py b/tests/geometry/liegroup/test_so2.py
index f8f644db2..5471e6bcf 100644
--- a/tests/geometry/liegroup/test_so2.py
+++ b/tests/geometry/liegroup/test_so2.py
@@ -15,9 +15,13 @@
# limitations under the License.
#
+import math
+import warnings
+
import pytest
import torch
+from kornia.geometry.conversions import angle_to_rotation_matrix
from kornia.geometry.liegroup import So2
from kornia.geometry.vector import Vector2
@@ -176,24 +180,16 @@ class TestSo2(BaseTester):
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):
+ 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.
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))
-
- @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
- def test_vee(self, device, dtype, batch_size):
omega = self._make_rand_data(device, dtype, (batch_size, 2, 2))
- theta = So2.vee(omega)
- self.assert_close(omega[..., 0, 1], theta)
-
- @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
- def test_hat_vee(self, device, dtype, batch_size):
- a = self._make_rand_data(device, dtype, (batch_size,))
- omega = So2.hat(a)
- b = So2.vee(omega)
- self.assert_close(b, a)
+ self.assert_close(So2.vee(omega), omega[..., 0, 1])
+ self.assert_close(So2.vee(m), theta)
@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_matrix(self, device, dtype, batch_size):
@@ -283,3 +279,86 @@ class TestSo2(BaseTester):
self.assert_close(restored.matrix(), s.matrix().detach())
s.to(device).matrix().sum().backward()
assert theta.grad is not None
+
+ def test_convention_so2_positive_angle_rotates_x_toward_y(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ # A positive angle turns the x axis toward the y axis, counter-clockwise in a y-up frame, and matrix() is
+ # [[cos, -sin], [sin, cos]]. Reference: math.cos(0.3), math.sin(0.3).
+ c, s = 0.955336489125606, 0.29552020666133955
+ g = So2.exp(torch.tensor(0.3, device=device, dtype=dtype))
+ axes = torch.tensor([[1.0, 0.0], [0.0, 1.0]], device=device, dtype=dtype)
+ rotated = g * axes
+ assert rotated[0, 1] > 0.25 # x moved toward +y
+ self.assert_close(rotated, torch.tensor([[c, s], [-s, c]], device=device, dtype=dtype))
+ self.assert_close(g.matrix(), torch.tensor([[c, -s], [s, c]], device=device, dtype=dtype))
+
+ def test_convention_so2_is_transpose_of_angle_to_rotation_matrix(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ # kornia.geometry.conversions.angle_to_rotation_matrix takes degrees and returns [[cos, sin], [-sin, cos]],
+ # the transpose of So2's matrix: the same angle turns the other way.
+ theta = torch.tensor([0.3, -1.2], device=device, dtype=dtype)
+ m = So2.exp(theta).matrix()
+ assert (m - m.mT).abs().max() > 0.5 # a non-symmetric fixture, so a transpose is visible
+ self.assert_close(m, angle_to_rotation_matrix(torch.rad2deg(theta)).mT)
+
+ def test_convention_so2_log_is_principal(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ # log returns the angle in [-pi, pi], so exp(3.5) logs to 3.5 - 2 pi. Reference: 3.5 - 2 * math.pi.
+ theta = torch.tensor([3.5, -3.5, 0.3], device=device, dtype=dtype)
+ g = So2.exp(theta)
+ expected = torch.tensor([3.5 - 2 * math.pi, 2 * math.pi - 3.5, 0.3], device=device, dtype=dtype)
+ self.assert_close(g.log(), expected)
+ self.assert_close(So2.exp(g.log()).matrix(), g.matrix())
+
+ def test_convention_so2_from_matrix_rejects_a_reflection(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ # from_matrix checks m00 == m11 and m01 == -m10. The first reflection fails only the diagonal check, the
+ # axis swap only the off-diagonal one.
+ for reflection in ([[1.0, 0.0], [0.0, -1.0]], [[0.0, 1.0], [1.0, 0.0]]):
+ reflection = torch.tensor(reflection, device=device, dtype=dtype)
+ assert torch.linalg.det(reflection.float()) < 0
+ with pytest.raises(ValueError, match="Invalid SO2 rotation matrix"):
+ So2.from_matrix(reflection)
+ rotation = So2.exp(torch.tensor(0.3, device=device, dtype=dtype)).matrix().detach()
+ self.assert_close(So2.from_matrix(rotation).log(), torch.tensor(0.3, device=device, dtype=dtype))
+
+ def test_wart_so2_column_angle_outer_broadcasts_4932(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ theta = torch.tensor([0.3, 0.5, 0.7], device=device, dtype=dtype)
+ p = torch.tensor([[1.0, 0.0], [0.0, 1.0], [2.0, 3.0]], device=device, dtype=dtype)
+ paired = So2.exp(theta) * p # the (B,) layout rotates point i by angle i
+ assert paired.shape == (3, 2)
+ # https://github.com/kornia/kornia/issues/4932: the accepted (B, 1) layout keeps its singleton axis in
+ # matrix() and hat(), but vee() rejects the latter. Multiplication broadcasts z against (B,) coordinates,
+ # so entry [i, j] is R(theta_i) p_j: every rotation applied to every point.
+ column = theta[:, None]
+ assert So2.exp(column).matrix().shape == (3, 1, 2, 2)
+ column_hat = So2.hat(column)
+ assert column_hat.shape == (3, 1, 2, 2)
+ with pytest.raises(ValueError):
+ So2.vee(column_hat)
+ out = So2.exp(column) * p
+ assert out.shape == (3, 3, 2)
+ self.assert_close(out.diagonal(dim1=0, dim2=1).mT, paired)
+ self.assert_close(out[0, 2], So2.exp(theta[0]) * p[2])
+
+ def test_wart_so2_real_dtype_cast_drops_the_imaginary_part_4923(self, device, dtype):
+ if dtype == torch.bfloat16:
+ pytest.skip("torch has no complex bfloat16 dtype, which So2 stores its rotation in")
+ theta = torch.tensor([0.3, -1.2], device=device, dtype=dtype)
+ g = So2.exp(theta)
+ assert g.z.is_complex()
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore") # torch warns, once per process, that the cast discards the imaginary part
+ cast = g.to(torch.float32)
+ # https://github.com/kornia/kornia/issues/4923: nn.Module.to(float32) casts the complex state z to a real
+ # tensor, which keeps cos(theta) and drops sin(theta), so the rotation is lost and matrix() raises.
+ assert not cast.z.is_complex()
+ self.assert_close(cast.z, theta.cos().float())
+ with pytest.raises(RuntimeError):
+ cast.matrix()