Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(geometry): convention blocks and pins for Quaternion and So3, and a Rotations and rigid motions section (batch 9a) (#4976)

Dmytro Mishkinb1effb148dbf
diff --git a/changelog.d/4976.added.md b/changelog.d/4976.added.md
new file mode 100644
index 000000000..2bf46dbb5
--- /dev/null
+++ b/changelog.d/4976.added.md
@@ -0,0 +1 @@
+Convention blocks for `Quaternion`, `average_quaternions` and `So3` (storage, product order, principal `log`, Jacobian sides), a "Rotations and rigid motions" section on the Conventions & Pitfalls page with the scipy / Sophus / Eigen mapping, and 19 convention and wart pins; the warts are documented and linked (#3950, #3952, #3953, #4773, #4923, #4927, #4942, #4974), not fixed.
diff --git a/docs/source/geometry.quaternion.rst b/docs/source/geometry.quaternion.rst
index a9dec5782..c9cd281b7 100644
--- a/docs/source/geometry.quaternion.rst
+++ b/docs/source/geometry.quaternion.rst
@@ -9,3 +9,5 @@ kornia.geometry.quaternion
.. autoclass:: Quaternion
:members:
:special-members:
+
+.. autofunction:: average_quaternions
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index a0fa77512..ec5cae37f 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -100,6 +100,64 @@ Angles and rotations
q = Quaternion.identity()
assert q.data.tolist() == [1.0, 0.0, 0.0, 0.0] # w, x, y, z
+.. _rotation-conventions:
+
+Rotations and rigid motions
+---------------------------
+
+:class:`~kornia.geometry.quaternion.Quaternion` multiplies by the Hamilton product, so ``(q1 * q2).matrix()`` is
+``q1.matrix() @ q2.matrix()``: the right operand acts first. The Lie groups :class:`~kornia.geometry.liegroup.So3`,
+:class:`~kornia.geometry.liegroup.Se3`, :class:`~kornia.geometry.liegroup.So2` and
+:class:`~kornia.geometry.liegroup.Se2` compose the same way and act on a point as ``R p + t``, with ``R`` the
+``matrix()`` of the rotation part. ``So2`` and ``Se2`` do so for any complex number, and a non-unit one also scales by
+its modulus; ``So3`` and ``Se3`` need a unit quaternion
+(`#4942 <https://github.com/kornia/kornia/issues/4942>`_). The tangent vectors of ``Se3`` and ``Se2`` put the
+rotation part, in radians, last: ``[υ, ω]`` and ``[vx, vy, θ]``. ``log`` is principal: its rotation angle is at most
+:math:`\pi` in magnitude. The Jacobians of ``So3`` satisfy
+:math:`\exp(\omega + \delta) \approx \exp(\omega) \exp(J_r \delta) = \exp(J_l \delta) \exp(\omega)`. A transform
+``trans_01`` maps frame-1 coordinates into frame 0, and
+:func:`~kornia.geometry.linalg.relative_transformation` of ``trans_01`` and ``trans_02`` is ``trans_12``;
+:class:`~kornia.geometry.pose.NamedPose` names the same transform ``dst_from_src``.
+
+.. list-table::
+ :header-rows: 1
+
+ * - Topic
+ - kornia
+ - scipy
+ - Sophus
+ - Eigen
+ * - quaternion storage
+ - ``(w, x, y, z)``
+ - ``Rotation.from_quat`` reads ``(x, y, z, w)`` unless ``scalar_first=True``
+ - ``SO3::data()`` exposes Eigen's ``coeffs()`` order: ``(x, y, z, w)``
+ - the ``Quaternion(w, x, y, z)`` constructor is scalar first, ``coeffs()`` is ``(x, y, z, w)``
+ * - composition
+ - ``a * b``, ``b`` acts first
+ - ``r1 * r2``, the same
+ - ``a * b``, the same
+ - ``q1 * q2``, the same
+ * - SE(3) tangent
+ - ``[υ, ω]``, translation first
+ - ``RigidTransform.as_exp_coords`` returns ``[ω, υ]``, rotation first
+ - ``SE3::log`` returns ``[υ, ω]``, the same (GTSAM's ``Pose3`` is ``[ω, υ]``)
+ - ``Isometry3d`` has no tangent or ``log``
+ * - rotation ``log``
+ - principal
+ - ``as_rotvec``, principal
+ - ``SO3::log``, principal
+ - ``AngleAxis(q)``, angle in :math:`[0, \pi]`
+ * - ``slerp``
+ - the short arc
+ - ``Slerp``, the short arc
+ - ``interpolate``, the short arc
+ - ``Quaternion::slerp``, the short arc
+ * - frame naming
+ - ``trans_01`` and ``dst_from_src`` map frame 1 (``src``) into frame 0 (``dst``)
+ - ``tf_A_B`` maps ``B`` into ``A``
+ - ``foo_T_bar`` maps ``bar`` into ``foo``
+ - no frames
+
Transformation matrices and homographies
----------------------------------------
diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.py
index f030c56bf..cde47ee4f 100644
--- a/kornia/geometry/liegroup/so3.py
+++ b/kornia/geometry/liegroup/so3.py
@@ -78,7 +78,30 @@ class So3(nn.Module):
:math:`R^3` under the operation of composition.
See more: https://en.wikipedia.org/wiki/3D_rotation_group
- We internally represent the rotation by a unit quaternion.
+ We internally represent the rotation by a :class:`~kornia.geometry.quaternion.Quaternion`.
+
+ Convention:
+ - The tangent vector is the rotation vector, the axis times the angle in radians, and ``hat(v)`` is its
+ cross-product matrix: ``hat(v) @ p`` equals ``torch.linalg.cross(v, p)``. ``log()`` is
+ ``q.to_axis_angle()``: it reads only the direction of ``q``, within the range limits stated on
+ :class:`~kornia.geometry.quaternion.Quaternion`, and returns the principal vector, of norm at most
+ :math:`\pi`, the same for ``q`` and ``-q`` below a half turn.
+ - For a unit quaternion, ``a * b`` composes like ``a.matrix() @ b.matrix()``, so ``b`` acts first; ``s * p``
+ rotates points ``p`` of shape :math:`(B, 3)`, a tensor or a ``Vector3``, as :math:`R p`; and ``adjoint()``
+ is :math:`R` itself.
+ :ref:`Rotations and rigid motions <rotation-conventions>` compares these with scipy, Sophus and Eigen.
+ - For a small :math:`\delta`,
+ :math:`\exp(\omega + \delta) \approx \exp(\omega) \exp(J_r \delta) = \exp(J_l \delta) \exp(\omega)`,
+ with :math:`J_r` = ``right_jacobian(omega)`` and :math:`J_l` = ``left_jacobian(omega)`` =
+ ``right_jacobian(-omega)``.
+ - Known defects: the quaternion is stored as given, so with a non-unit ``q`` the ``matrix()`` is not a
+ rotation and ``s * p`` scales ``p`` by :math:`|q|^2`
+ (`#4942 <https://github.com/kornia/kornia/issues/4942>`_); ``from_matrix`` accepts a reflection
+ (det :math:`-1`) without error and returns an ``So3`` whose ``matrix()`` is not the input
+ (`#4773 <https://github.com/kornia/kornia/issues/4773>`_); ``exp``, ``identity``, ``random``,
+ ``from_matrix`` and every operation store the quaternion as a plain tensor, which has no ``state_dict()``
+ entry and which ``.to()`` leaves unchanged; only a quaternion built on an ``nn.Parameter`` is saved and moved
+ (`#4923 <https://github.com/kornia/kornia/issues/4923>`_).
Example:
>>> q = Quaternion.identity()
@@ -91,17 +114,15 @@ class So3(nn.Module):
def __init__(self, q: Quaternion) -> None:
"""Construct the base class.
- Internally represented by a unit quaternion `q`.
-
Args:
q: Quaternion with the shape of :math:`(B, 4)`.
Example:
- >>> data = torch.ones((2, 4))
+ >>> data = torch.tensor([[1., 0., 0., 0.], [0., 1., 0., 0.]])
>>> q = Quaternion(data)
>>> So3(q)
- tensor([[1., 1., 1., 1.],
- [1., 1., 1., 1.]])
+ tensor([[1., 0., 0., 0.],
+ [0., 1., 0., 0.]])
"""
super().__init__()
@@ -115,13 +136,13 @@ class So3(nn.Module):
return So3(self._q[idx])
def __mul__(self, right: So3) -> So3:
- """Compose two So3 transformations.
+ """Compose two So3 transformations, or rotate points.
Args:
- right: the other So3 transformation.
+ right: the other So3 transformation, or points of shape :math:`(B, 3)` as a tensor or a ``Vector3``.
Return:
- The resulting So3 transformation.
+ The resulting So3 transformation, or the rotated points of the type of ``right``.
"""
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py#L98
@@ -188,7 +209,8 @@ class So3(nn.Module):
# same rotation, give the same vector with |theta| <= pi (#4925), a rotation below 1e-4 rad in float32 keeps
# its digits instead of collapsing to 0 through 2 * acos(real) (#4897), and the identity keeps the finite
# gradient 2 * vec / real of #4404.
- # NOTE: this differs from https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py#L33
+ # It agrees with Sophus's 2 * atan(|vec| / real) / |vec| * vec away from real = 0:
+ # https://github.com/strasdat/Sophus/blob/main/sympy/sophus/so3.py
return quaternion_to_axis_angle(_unwrap(self.q.data))
@staticmethod
@@ -248,7 +270,7 @@ class So3(nn.Module):
The matrix is of the form:
.. math::
- \begin{bmatrix} 1-2y^2-2z^2 & 2xy-2zw & 2xy+2yw \\
+ \begin{bmatrix} 1-2y^2-2z^2 & 2xy-2zw & 2xz+2yw \\
2xy+2zw & 1-2x^2-2z^2 & 2yz-2xw \\
2xz-2yw & 2yz+2xw & 1-2x^2-2y^2\end{bmatrix}
@@ -382,7 +404,7 @@ class So3(nn.Module):
@classmethod
def rot_y(cls, y: torch.Tensor) -> So3:
- """Construct a z-axis rotation.
+ """Construct a y-axis rotation.
Args:
y: the y-axis rotation angle.
@@ -420,7 +442,7 @@ class So3(nn.Module):
"""Compute the right Jacobian of So3.
Args:
- vec: the input point of shape :math:`(B, 3)`.
+ vec: the tangent vector of shape :math:`(B, 3)`.
Example:
>>> vec = torch.tensor([1., 2., 3.])
@@ -442,7 +464,7 @@ class So3(nn.Module):
"""Alias for right jacobian.
Args:
- vec: the input point of shape :math:`(B, 3)`.
+ vec: the tangent vector of shape :math:`(B, 3)`.
"""
return So3.right_jacobian(vec)
@@ -452,7 +474,7 @@ class So3(nn.Module):
"""Compute the left Jacobian of So3.
Args:
- vec: the input point of shape :math:`(B, 3)`.
+ vec: the tangent vector of shape :math:`(B, 3)`.
Example:
>>> vec = torch.tensor([1., 2., 3.])
@@ -474,7 +496,7 @@ class So3(nn.Module):
"""Alias for left jacobian.
Args:
- vec: the input point of shape :math:`(B, 3)`.
+ vec: the tangent vector of shape :math:`(B, 3)`.
"""
return So3.left_jacobian(vec)
diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.py
index 64d32acd5..b812d873b 100644
--- a/kornia/geometry/quaternion.py
+++ b/kornia/geometry/quaternion.py
@@ -57,6 +57,29 @@ class Quaternion(nn.Module):
Q = \begin{bmatrix} q_w & q_x & q_y & q_z \end{bmatrix}
+ Convention:
+ - ``data`` is ``(w, x, y, z)``, real part first, with shape :math:`(*, 4)`; only the last axis is checked.
+ Other libraries' orders, such as scipy's default ``(x, y, z, w)``, are mapped on
+ :ref:`Rotations and rigid motions <rotation-conventions>`.
+ - ``*`` between quaternions is the Hamilton product, so ``(q1 * q2).matrix()`` is
+ ``q1.matrix() @ q2.matrix()``, ``q1 / q2`` is ``q1 * q2.inv()``, and ``q`` and ``-q`` are the same rotation.
+ A float or tensor operand of ``+``, ``-``, ``*`` or ``/`` is the real quaternion ``[s, 0, 0, 0]``, and a
+ tensor of the shape of ``q.w`` holds one such scalar per quaternion of the batch.
+ - Nothing normalises the stored data or the results of ``*``, ``**`` and ``inv()``. ``matrix()``,
+ ``to_axis_angle()``, ``polar_angle`` and ``slerp`` read only the direction of ``q``: rescaling ``q`` by a
+ positive factor changes their result by roundoff only, as long as its squared components stay within the
+ range of the dtype and its norm stays above ``1e-12``.
+ - Known defects: ``to_euler()`` returns a triple that does not reproduce the rotation for a non-unit ``q``
+ (`#3953 <https://github.com/kornia/kornia/issues/3953>`_) and for most rotations at a pitch of
+ :math:`\pm\pi/2` (`#3950 <https://github.com/kornia/kornia/issues/3950>`_); below a norm of ``1e-12``,
+ ``matrix()`` and ``slerp`` give wrong results, and the zero quaternion's ``matrix()`` is the identity
+ (`#3952 <https://github.com/kornia/kornia/issues/3952>`_); ``polar_angle`` gives a non-finite gradient at
+ the identity and near it, wherever ``w / |q|`` rounds to 1
+ (`#4927 <https://github.com/kornia/kornia/issues/4927>`_); data given as a plain tensor is not
+ registered with ``nn.Module``, so an enclosing module's ``state_dict()``, ``load_state_dict()`` and
+ ``.to()`` skip it, while an ``nn.Parameter`` is saved, restored and moved
+ (`#4923 <https://github.com/kornia/kornia/issues/4923>`_).
+
Example:
>>> q = Quaternion.identity(batch_size=4)
>>> q.data
@@ -80,7 +103,7 @@ class Quaternion(nn.Module):
"""Construct a quaternion from torch.Tensor or parameter data.
Args:
- data: torch.Tensor or parameter containing the quaternion data with the shape of :math:`(B, 4)`.
+ data: torch.Tensor or parameter containing the quaternion data with the shape of :math:`(*, 4)`.
Example:
>>> # Create with torch.tensor(no gradients tracked by default)
@@ -164,7 +187,7 @@ class Quaternion(nn.Module):
Example:
>>> q = Quaternion.identity()
- >>> -q.data
+ >>> (-q).data
tensor([-1., -0., -0., -0.])
"""
@@ -328,8 +351,7 @@ class Quaternion(nn.Module):
def real(self) -> torch.Tensor:
"""Return the real part with shape :math:`(B,)`.
- Alias for
- :func: `~kornia.geometry.quaternion.Quaternion.w`
+ Alias for :attr:`~kornia.geometry.quaternion.Quaternion.w`.
"""
return self.w
@@ -350,8 +372,7 @@ class Quaternion(nn.Module):
def scalar(self) -> torch.Tensor:
"""Return a scalar with the real with shape :math:`(B,)`.
- Alias for
- :func: `~kornia.geometry.quaternion.Quaternion.w`
+ Alias for :attr:`~kornia.geometry.quaternion.Quaternion.w`.
"""
return self.real
@@ -382,7 +403,9 @@ class Quaternion(nn.Module):
@property
def polar_angle(self) -> torch.Tensor:
- """Return the polar angle with shape :math:`(B,1)`.
+ r"""Return the polar angle :math:`\arccos(w / |q|)` in :math:`[0, \pi]`, with shape :math:`(B,)`.
+
+ ``q`` rotates by twice this angle about the axis ``vec``.
Example:
>>> q = Quaternion.identity()
@@ -446,14 +469,14 @@ class Quaternion(nn.Module):
"""Convert the quaternion to a triple of Euler angles (roll, pitch, yaw).
Example:
- >>> q = Quaternion(torch.tensor([2., 0., 1., 1.]))
+ >>> q = Quaternion.from_euler(torch.tensor(0.3), torch.tensor(0.2), torch.tensor(0.1))
>>> roll, pitch, yaw = q.to_euler()
>>> roll
- tensor(2.0344)
+ tensor(0.3000)
>>> pitch
- tensor(1.5708)
+ tensor(0.2000)
>>> yaw
- tensor(2.2143)
+ tensor(0.1000)
"""
return euler_from_quaternion(self.w, self.x, self.y, self.z)
@@ -575,7 +598,8 @@ class Quaternion(nn.Module):
Args:
q1: second quaternion to be interpolated between.
- t: interpolation ratio, range [0-1]
+ t: interpolation ratio, ``0`` at ``self`` and ``1`` at ``q1``. It is not validated: values outside
+ ``[0, 1]`` extrapolate along the same arc. A per-batch ratio has shape :math:`(B, 1)`.
Example:
>>> q0 = Quaternion.identity()
@@ -664,7 +688,16 @@ class Quaternion(nn.Module):
def average_quaternions(Q: "Quaternion", w: Optional[torch.Tensor] = None) -> "Quaternion":
- """Compute (weighted) average of multiple quaternions.
+ r"""Compute (weighted) average of multiple quaternions.
+
+ Convention:
+ - The chordal mean of scipy's ``Rotation.mean``: the eigenvector of
+ :math:`\sum_i w_i q_i q_i^\top / \sum_i w_i` with the largest eigenvalue. ``q_i`` and ``-q_i`` count the
+ same, and the sign of the result is arbitrary.
+ - ``w`` need not sum to one: scaling it by a positive factor does not change the result.
+ - Known defect: the members are not normalised, so a member of norm ``n`` counts with an extra weight
+ ``n**2``, and negative weights are not rejected
+ (`#4974 <https://github.com/kornia/kornia/issues/4974>`_).
Args:
Q (Quaternion): quaternion object containing data of shape (M, 4).
@@ -672,7 +705,7 @@ def average_quaternions(Q: "Quaternion", w: Optional[torch.Tensor] = None) -> "Q
Returns:
- Quaternion: averaged quaternion (shape (4,)), wrapped back in the Quaternion class.
+ Quaternion: averaged quaternion of shape (1, 4), wrapped back in the Quaternion class.
"""
data = Q.data
KORNIA_CHECK_TYPE(Q, Quaternion)
diff --git a/tests/geometry/liegroup/test_so3.py b/tests/geometry/liegroup/test_so3.py
index 26e8d2f05..f8fea194b 100644
--- a/tests/geometry/liegroup/test_so3.py
+++ b/tests/geometry/liegroup/test_so3.py
@@ -15,8 +15,11 @@
# limitations under the License.
#
+import math
+
import pytest
import torch
+from torch import nn
from kornia.geometry.conversions import euler_from_quaternion
from kornia.geometry.liegroup import So3
@@ -482,3 +485,157 @@ class TestSo3(BaseTester):
Jr = So3.right_jacobian(vec)
Jl = So3.left_jacobian(vec)
self.assert_close(Jl, Jr.transpose(-1, -2))
+
+
+class _RotationHolder(nn.Module):
+ """A module that keeps a Quaternion and an So3 as attributes, as a pose-holding model would."""
+
+ def __init__(self, data: torch.Tensor, as_parameter: bool) -> None:
+ super().__init__()
+ self.quat = Quaternion(nn.Parameter(data.clone()) if as_parameter else data.clone())
+ self.rot = So3(Quaternion(nn.Parameter(data.clone()) if as_parameter else data.clone()))
+
+
+class TestSo3Conventions(BaseTester):
+ def test_convention_so3_exp_is_rotation_vector(self, device, dtype):
+ # exp(v) is the rotation by |v| about v / |v|, the matrix exponential of hat(v). Expected matrix from scipy:
+ # Rotation.from_rotvec([0.3, -0.5, 0.2]).as_matrix()
+ v = torch.tensor([[0.3, -0.5, 0.2]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [0.8595338985586632, -0.2602267140480945, -0.43986763295823095],
+ [0.11491695393636675, 0.937032437284918, -0.3297943376922552],
+ [0.4979915370029221, 0.23292116428443665, 0.8353156052067087],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ self.assert_close(So3.exp(v).matrix(), expected)
+ # the opposite vector is the inverse rotation
+ self.assert_close(So3.exp(-v).matrix(), So3.exp(v).inverse().matrix())
+
+ def test_convention_so3_hat_is_cross_product_matrix(self, device, dtype):
+ v = torch.tensor([[0.3, -0.5, 0.2]], device=device, dtype=dtype)
+ p = torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype)
+ # hat(v) @ p = v x p; the transposed matrix would give p x v
+ self.assert_close((So3.hat(v) @ p[..., None])[..., 0], torch.linalg.cross(v, p, dim=-1))
+ self.assert_close(So3.vee(So3.hat(v)), v)
+
+ def test_convention_unit_so3_mul_point_is_R_p(self, device, dtype):
+ s = So3.exp(torch.tensor([[0.3, -0.5, 0.2]], device=device, dtype=dtype))
+ s2 = So3.exp(torch.tensor([[-0.1, 0.4, 0.25]], device=device, dtype=dtype))
+ p = torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype)
+ # s * p rotates the point: R @ p, not R^T @ p. Expected point from scipy:
+ # Rotation.from_rotvec([0.3, -0.5, 0.2]).apply([1.0, 2.0, 3.0])
+ expected = torch.tensor(
+ [[-0.9805224284122186, 0.9995988154294373, 3.469780681191921]], device=device, dtype=dtype
+ )
+ # Composition through rotation matrices requires the unit quaternions constructed by exp().
+ self.assert_close(s.q.norm(), torch.ones(1, device=device, dtype=dtype))
+ self.assert_close(s2.q.norm(), torch.ones(1, device=device, dtype=dtype))
+ self.assert_close(s * p, expected)
+ self.assert_close(s * p, (s.matrix() @ p[..., None])[..., 0])
+ # precondition: the pair does not commute
+ assert ((s * s2).matrix() - (s2 * s).matrix()).abs().max() > 0.1
+ # s * s2 applies s2 first: its matrix is R @ R2, and (s * s2) * p = s * (s2 * p)
+ self.assert_close((s * s2).matrix(), s.matrix() @ s2.matrix())
+ # both sides round the intermediate point, whose components reach 3.5, where one float16 ulp is 2e-3; the
+ # error also lands on the small first component, where the default float16 tolerance allows only 1.4e-3
+ tol = 1e-2 if dtype == torch.float16 else None
+ self.assert_close((s * s2) * p, s * (s2 * p), rtol=tol, atol=tol)
+
+ def test_convention_so3_adjoint_conjugates_the_tangent(self, device, dtype):
+ # Ad(g) xi is the tangent of g exp(xi) g^-1: exp(Ad(g) xi) = g exp(xi) g^-1, with Ad(g) = R
+ g = So3.exp(torch.tensor([[0.7, -0.2, 0.4]], device=device, dtype=dtype))
+ xi = torch.tensor([[0.1, 0.3, -0.2]], device=device, dtype=dtype)
+ moved = (g.adjoint() @ xi[..., None])[..., 0]
+ self.assert_close(So3.exp(moved).matrix(), (g * So3.exp(xi) * g.inverse()).matrix())
+
+ def test_convention_so3_jacobian_sides(self, device, dtype):
+ # exp(w + d) = exp(w) exp(Jr(w) d) = exp(Jl(w) d) exp(w) to first order in d. The references are central
+ # differences in float64 on the CPU with h = 1e-6.
+ w = torch.tensor([[0.7, -0.2, 0.4]], dtype=torch.float64)
+ h = 1e-6
+ base = So3.exp(w)
+ right, left = [], []
+ for i in range(3):
+ step = torch.zeros(1, 3, dtype=torch.float64)
+ step[0, i] = h
+ plus, minus = So3.exp(w + step), So3.exp(w - step)
+ right.append(((base.inverse() * plus).log() - (base.inverse() * minus).log()) / (2 * h))
+ left.append(((plus * base.inverse()).log() - (minus * base.inverse()).log()) / (2 * h))
+ right = torch.stack(right, -1).to(device=device, dtype=dtype)
+ left = torch.stack(left, -1).to(device=device, dtype=dtype)
+ # precondition: the two sides differ by 2 a(theta) hat(w), 0.66 here
+ assert (right - left).abs().max() > 0.1
+ w = w.to(device=device, dtype=dtype)
+ # measured float64 error of the differences: 1e-10
+ tol = 1e-8 if dtype == torch.float64 else None
+ self.assert_close(So3.right_jacobian(w), right, rtol=tol, atol=tol)
+ self.assert_close(So3.left_jacobian(w), left, rtol=tol, atol=tol)
+ self.assert_close(So3.left_jacobian(w), So3.right_jacobian(-w))
+
+ def test_convention_so3_rot_axes_are_right_handed(self, device, dtype):
+ # rot_x, rot_y, rot_z by +theta turn y toward z, z toward x and x toward y
+ theta = torch.tensor([0.3], device=device, dtype=dtype)
+ c, s = math.cos(0.3), math.sin(0.3)
+ cases = [
+ (So3.rot_x, [0.0, 1.0, 0.0], [0.0, c, s]),
+ (So3.rot_y, [0.0, 0.0, 1.0], [s, 0.0, c]),
+ (So3.rot_z, [1.0, 0.0, 0.0], [c, s, 0.0]),
+ ]
+ for rot, p, expected in cases:
+ p = torch.tensor([p], device=device, dtype=dtype)
+ self.assert_close(rot(theta) * p, torch.tensor([expected], device=device, dtype=dtype))
+
+ def test_wart_so3_non_unit_quaternion_not_normalised_4942(self, device, dtype):
+ # #4942 https://github.com/kornia/kornia/issues/4942: So3 stores the quaternion as given, and matrix() and
+ # So3 * p use the unit-quaternion formulas, so a non-unit q gives a matrix that is not a rotation and points
+ # scaled by |q|^2. This test turns red when So3 normalises its quaternion.
+ data = torch.tensor([[2.0, 0.2, -0.6, 0.4]], device=device, dtype=dtype)
+ squared_norm = 4.56
+ s = So3(Quaternion(data))
+ p = torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype)
+ m = s.matrix()
+ # det = m0 . (m1 x m2), written out so it runs where torch.linalg.det has no half-precision kernel
+ det = (m[:, 0] * torch.linalg.cross(m[:, 1], m[:, 2], dim=-1)).sum(-1)
+ assert bool((det > 2.0).all()), det
+ self.assert_close((s * p).norm(dim=-1), squared_norm * p.norm(dim=-1))
+ # control: the same data through Quaternion.matrix(), and through So3 once normalised, is a rotation
+ self.assert_close(So3(Quaternion(data).normalize()).matrix(), Quaternion(data).matrix())
+ self.assert_close((So3(Quaternion(data).normalize()) * p).norm(dim=-1), p.norm(dim=-1))
+ # log() is outside the defect: it reads only the direction of q
+ self.assert_close(s.log(), So3(Quaternion(data).normalize()).log())
+
+ def test_wart_so3_from_matrix_accepts_a_reflection_4773(self, device, dtype):
+ # #4773 https://github.com/kornia/kornia/issues/4773: from_matrix silently returns an apparently valid
+ # result for an improper matrix (det = -1), whose matrix() is not the input. This turns red if it rejects
+ # the input or signals NaN.
+ flip = torch.diag(torch.tensor([-1.0, 1.0, 1.0], device=device, dtype=dtype))
+ s = So3.from_matrix(flip)
+ assert isinstance(s, So3)
+ assert bool(torch.isfinite(s.q.data).all())
+ assert bool(torch.isfinite(s.log()).all())
+ assert bool(((s.matrix() - flip).abs() > 0.5).any())
+
+ def test_wart_rotation_state_not_registered_4923(self, device, dtype):
+ # #4923 https://github.com/kornia/kornia/issues/4923: a Quaternion built from a plain tensor keeps it as an
+ # unregistered attribute, so a module holding it (directly or through So3) saves no key for the rotation,
+ # and load_state_dict reports success while keeping the old rotation. This test turns red when the
+ # rotation is registered.
+ saved = torch.tensor([[0.8, 0.2, -0.4, 0.4]], device=device, dtype=dtype)
+ stale = torch.tensor([[0.0, 0.6, 0.0, 0.8]], device=device, dtype=dtype)
+ source, target = _RotationHolder(saved, as_parameter=False), _RotationHolder(stale, as_parameter=False)
+ assert list(source.state_dict()) == []
+ result = target.load_state_dict(source.state_dict())
+ assert not result.missing_keys and not result.unexpected_keys
+ self.assert_close(target.quat.data, stale)
+ self.assert_close(target.rot.q.data, stale)
+ # control: a rotation stored as an nn.Parameter is saved and restored
+ source, target = _RotationHolder(saved, as_parameter=True), _RotationHolder(stale, as_parameter=True)
+ assert list(source.state_dict()) == ["quat._data", "rot._q._data"]
+ target.load_state_dict(source.state_dict())
+ self.assert_close(target.quat.data, saved)
+ self.assert_close(target.rot.q.data, saved)
diff --git a/tests/geometry/test_quaternion.py b/tests/geometry/test_quaternion.py
index d14be8dd2..8eec8b549 100644
--- a/tests/geometry/test_quaternion.py
+++ b/tests/geometry/test_quaternion.py
@@ -490,3 +490,165 @@ class TestQuaternionAverage(BaseTester):
w = torch.tensor([0.5, 0.5], device=device, dtype=dtype) # wrong length
with pytest.raises(ValueError):
average_quaternions(Q, w=w)
+
+
+class TestQuaternionConventions(BaseTester):
+ def _unit(self, data, device, dtype):
+ # normalised in float64 and rounded once, so the fixture is unit to the working dtype's resolution
+ q = torch.tensor(data, dtype=torch.float64)
+ return (q / q.norm(dim=-1, keepdim=True)).to(device=device, dtype=dtype)
+
+ def test_convention_quaternion_storage_is_wxyz(self, device, dtype):
+ # The data is (w, x, y, z), real part first. Expected matrix from scipy:
+ # Rotation.from_quat([0.8, 0.2, -0.4, 0.4], scalar_first=True).as_matrix()
+ data = torch.tensor([[0.8, 0.2, -0.4, 0.4]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [[[0.36, -0.8, -0.48], [0.48, 0.6, -0.64], [0.8, 0.0, 0.6]]], device=device, dtype=dtype
+ )
+ q = Quaternion(data)
+ self.assert_close(q.w, data[:, 0])
+ self.assert_close(q.vec, data[:, 1:])
+ self.assert_close(q.matrix(), expected)
+ # the same four numbers read as (x, y, z, w) are another rotation, far from this one
+ assert (Quaternion(data[:, [1, 2, 3, 0]]).matrix() - expected).abs().max() > 1.0
+
+ def test_convention_quaternion_mul_is_hamilton_matrix_product(self, device, dtype):
+ q1 = Quaternion(self._unit([[0.9, 0.1, -0.3, 0.2]], device, dtype))
+ q2 = Quaternion(self._unit([[0.7, -0.4, 0.2, 0.5]], device, dtype))
+ # precondition: the pair does not commute (|q1 q2 - q2 q1| = 2 |v1 x v2| = 0.53)
+ assert ((q1 * q2).data - (q2 * q1).data).norm() > 0.1
+ # q1 * q2 is the Hamilton product, the rotation "q2 first, then q1": its matrix is R1 @ R2
+ self.assert_close((q1 * q2).matrix(), q1.matrix() @ q2.matrix())
+ # q1 / q2 divides on the right, q1 * q2^-1; the left quotient q2^-1 * q1 differs by 0.40 for this pair
+ self.assert_close((q1 / q2).data, (q1 * q2.inv()).data)
+ assert ((q1 / q2).data - (q2.inv() * q1).data).abs().max() > 0.1
+
+ def test_convention_quaternion_scalar_operand_is_real_part(self, device, dtype):
+ # A Python number or a tensor operand is the real quaternion (s, 0, 0, 0): + and - move only w, and * and /
+ # scale all four components.
+ data = torch.tensor([[0.75, 0.125, -0.375, 0.25]], device=device, dtype=dtype)
+ q = Quaternion(data)
+ real = torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype)
+ self.assert_close((q + 1.0).data, data + real)
+ self.assert_close((1.0 + q).data, data + real)
+ self.assert_close((q - 0.5).data, data - 0.5 * real)
+ self.assert_close((q + torch.tensor([2.0], device=device, dtype=dtype)).data, data + 2.0 * real)
+ self.assert_close((q * 2.0).data, 2.0 * data)
+ self.assert_close((2.0 * q).data, 2.0 * data)
+ self.assert_close((q * torch.tensor([2.0], device=device, dtype=dtype)).data, 2.0 * data)
+ self.assert_close((q / 2.0).data, 0.5 * data)
+ # a tensor holds one scalar per quaternion of the batch
+ batch = torch.cat((data, 2.0 * data))
+ per_item = torch.tensor([2.0, 3.0], device=device, dtype=dtype)
+ self.assert_close((Quaternion(batch) + per_item).data, batch + per_item[:, None] * real)
+ self.assert_close((Quaternion(batch) * per_item).data, batch * per_item[:, None])
+ self.assert_close((Quaternion(batch) / per_item).data, batch / per_item[:, None])
+
+ def test_convention_quaternion_matrix_normalises(self, device, dtype):
+ data = torch.tensor([[2.0, 0.2, -0.6, 0.4]], device=device, dtype=dtype)
+ q = Quaternion(data)
+ # precondition: |q| = sqrt(4.56) = 2.14, far from unit
+ assert (q.norm() - 1.0).abs().max() > 1.0
+ # matrix() is the rotation of q / |q|, a proper rotation (So3.matrix() is not, #4942)
+ rotation = q.matrix()
+ self.assert_close(rotation, q.normalize().matrix())
+ eye = torch.eye(3, device=device, dtype=dtype)[None]
+ self.assert_close(rotation @ rotation.transpose(-2, -1), eye)
+
+ def test_convention_quaternion_polar_angle_is_half_rotation_angle(self, device, dtype):
+ # polar_angle is the angle a of q = |q| (cos a + n sin a), half the rotation angle, whatever |q|.
+ # The rotation is 0.788 rad about an off-axis unit vector, built in float64 and rounded once.
+ axis_angle = 0.788 * torch.tensor([[0.48, 0.6, 0.64]], dtype=torch.float64)
+ data = Quaternion.from_axis_angle(axis_angle).data.to(device=device, dtype=dtype)
+ expected = torch.tensor([0.394], device=device, dtype=dtype)
+ angle = Quaternion(data).polar_angle
+ assert angle.shape == (1,)
+ self.assert_close(angle, expected)
+ self.assert_close(Quaternion(3.0 * data).polar_angle, expected)
+ # the range is [0, pi]: -q, the same rotation, has the supplementary angle
+ self.assert_close(Quaternion(-data).polar_angle, math.pi - expected)
+
+ def test_convention_quaternion_slerp_normalises_inputs(self, device, dtype):
+ q1 = self._unit([[0.9, 0.1, -0.3, 0.2]], device, dtype)
+ q2 = self._unit([[0.7, -0.4, 0.2, 0.5]], device, dtype)
+ # precondition: dot(q1, q2) = 0.67 > 0, so the short arc ends at q2 itself and not at -q2
+ assert (q1 * q2).sum() > 0.5
+ a, b = Quaternion(2.0 * q1), Quaternion(3.0 * q2)
+ # both endpoints are normalised first, and the result is a unit quaternion
+ self.assert_close(a.slerp(b, 0.0).data, q1)
+ self.assert_close(a.slerp(b, 1.0).data, q2)
+ # Expected value from scipy, whose Slerp also normalises:
+ # Slerp([0, 1], Rotation.from_quat([q1, q2], scalar_first=True))([0.3]).as_quat(scalar_first=True)
+ expected = torch.tensor(
+ [[0.9297807322749576, -0.06174707057580068, -0.1602249202393802, 0.3256118304052157]],
+ device=device,
+ dtype=dtype,
+ )
+ self.assert_close(a.slerp(b, 0.3).data, expected)
+
+ def test_convention_quaternion_slerp_extrapolates_outside_unit_interval(self, device, dtype):
+ q1 = Quaternion(self._unit([[0.9, 0.1, -0.3, 0.2]], device, dtype))
+ q2 = Quaternion(self._unit([[0.7, -0.4, 0.2, 0.5]], device, dtype))
+ # t is not validated or clamped: t = 2 continues the arc by one more step, q1 (q1^-1 q2)^2 = q2 q1^-1 q2,
+ # and t = -1 steps back from q1, q1 (q1^-1 q2)^-1 = q1 q2^-1 q1
+ self.assert_close(q1.slerp(q2, 2.0).data, (q2 * q1.conj() * q2).data)
+ self.assert_close(q1.slerp(q2, -1.0).data, (q1 * q2.conj() * q1).data)
+
+ def test_convention_average_quaternions_is_the_chordal_mean(self, device, dtype):
+ # The weighted chordal (eigenvector) mean of Markley et al., "Averaging Quaternions" (2007), the same as
+ # scipy's Rotation.mean. Expected rotation vectors from scipy:
+ # A, B = Rotation.from_rotvec([0.9, -0.3, 0.2]), Rotation.from_rotvec([-0.2, 1.1, 0.5])
+ # Rotation.concatenate([A, B]).mean(weights=w).as_rotvec() for w = [1, 1] and w = [1, 3]
+ # A normalised linear mean of the quaternions gives [0.084, 0.783, 0.446] for w = [1, 3].
+ rotvecs = torch.tensor([[0.9, -0.3, 0.2], [-0.2, 1.1, 0.5]], dtype=torch.float64)
+ data = Quaternion.from_axis_angle(rotvecs).data.to(device=device, dtype=dtype)
+ uniform = torch.tensor([[0.3823365186803237, 0.41998759136458735, 0.37339616309716916]], dtype=torch.float64)
+ weighted = torch.tensor([[0.02860900532725633, 0.8470541010728433, 0.4576793994589019]], dtype=torch.float64)
+ # a half-precision fixture is off by one rounding of the quaternions, under 1e-2 rad in bfloat16
+ tol = {torch.bfloat16: 2e-2, torch.float16: 3e-3}.get(dtype, 1e-5)
+ # the weights are relative ([1, 3] and [2, 6] agree), and the sign of a member does not matter (-A is A)
+ cases = [(None, uniform), ([1.0, 3.0], weighted), ([2.0, 6.0], weighted)]
+ for members in (data, torch.stack((-data[0], data[1]))):
+ for w, expected in cases:
+ weights = None if w is None else torch.tensor(w, device=device, dtype=dtype)
+ out = average_quaternions(Quaternion(members), w=weights)
+ assert out.shape == (1, 4)
+ # to_axis_angle is the principal log, so the arbitrary sign of the eigenvector does not matter
+ self.assert_close(out.to_axis_angle(), expected.to(device=device, dtype=dtype), rtol=0.0, atol=tol)
+
+ def test_wart_quaternion_polar_angle_gradient_nonfinite_at_identity_4927(self, device, dtype):
+ # #4927 https://github.com/kornia/kornia/issues/4927: polar_angle gives a non-finite gradient at the identity,
+ # the usual initialisation, and near it. This test turns red when the gradient becomes finite at either.
+ identity = torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype, requires_grad=True)
+ Quaternion(identity).polar_angle.sum().backward()
+ assert not bool(torch.isfinite(identity.grad).all()), identity.grad
+ # a half-angle of sqrt(eps) / 2 is small enough that w / |q| rounds to 1, so a fix that guards only the exact
+ # identity leaves this row non-finite
+ h = 0.5 * math.sqrt(torch.finfo(dtype).eps)
+ near = torch.tensor(
+ [[math.cos(h), 0.6 * math.sin(h), 0.0, 0.8 * math.sin(h)]], device=device, dtype=dtype, requires_grad=True
+ )
+ # precondition: the vector part survives the rounding, so this is not the identity again
+ assert bool((near[:, 1:] != 0).any())
+ Quaternion(near).polar_angle.sum().backward()
+ assert not bool(torch.isfinite(near.grad).all()), near.grad
+ # control: away from the identity the same expression has a finite gradient
+ q = self._unit([[0.9, 0.1, -0.3, 0.2]], device, dtype).requires_grad_(True)
+ Quaternion(q).polar_angle.sum().backward()
+ assert bool(torch.isfinite(q.grad).all()), q.grad
+
+ def test_wart_average_quaternions_weights_by_member_norm_4974(self, device, dtype):
+ # https://github.com/kornia/kornia/issues/4974: average_quaternions uses stored q_i q_i^T, so rescaling a
+ # member by 3 weights it by 9, while matrix(), to_axis_angle(), polar_angle and slerp ignore a positive scale.
+ # Negative weights are accepted where scipy's Rotation.mean rejects them. This turns red when members are
+ # normalised or negative weights are rejected.
+ rotvecs = torch.tensor([[0.9, -0.3, 0.2], [-0.2, 1.1, 0.5]], dtype=torch.float64)
+ data = Quaternion.from_axis_angle(rotvecs).data.to(device=device, dtype=dtype)
+ unit = average_quaternions(Quaternion(data)).to_axis_angle()
+ scaled = average_quaternions(Quaternion(torch.stack((3.0 * data[0], data[1])))).to_axis_angle()
+ # the same rotations, one stored at norm 3: scipy's mean with weights [9, 1] is [0.839, -0.208, 0.224], the
+ # unweighted mean [0.382, 0.420, 0.373]
+ assert (scaled - unit).abs().max() > 0.3
+ weights = torch.tensor([1.0, -0.5], device=device, dtype=dtype)
+ out = average_quaternions(Quaternion(data), w=weights)
+ assert bool(torch.isfinite(out.data).all())