Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): normalise the members of average_quaternions and reject negative or all-zero weights (#4980)

εŒΊζ’“ηb856bf10a03b
diff --git a/changelog.d/4976.added.md b/changelog.d/4976.added.md
index 45c09c832..90405fff2 100644
--- a/changelog.d/4976.added.md
+++ b/changelog.d/4976.added.md
@@ -1 +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, #4942, #4974), not fixed.
+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, #4942), not fixed.
diff --git a/changelog.d/4980.fixed.md b/changelog.d/4980.fixed.md
new file mode 100644
index 000000000..c4acab406
--- /dev/null
+++ b/changelog.d/4980.fixed.md
@@ -0,0 +1,4 @@
+`average_quaternions` now normalises its members before averaging and raises `ValueError` for a negative weight or
+weights that are all zero (#4974). A member's squared norm used to act as an extra weight (one stored as `3 q` counted
+9 times), a negative weight extrapolated past a member, and an all-zero weight divided by zero. Unit members with
+non-negative weights give the same rotation to rounding.
diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.py
index ef509f253..97b928c66 100644
--- a/kornia/geometry/quaternion.py
+++ b/kornia/geometry/quaternion.py
@@ -694,10 +694,10 @@ def average_quaternions(Q: "Quaternion", w: Optional[torch.Tensor] = None) -> "Q
- 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>`_).
+ - ``w`` need not sum to one: scaling it by a positive factor does not change the result. A negative weight,
+ or weights that are all zero, raise ``ValueError``.
+ - The members are normalised first, so only their directions count: a member stored as ``3 * q`` weighs
+ the same as ``q``.
Args:
Q (Quaternion): quaternion object containing data of shape (M, 4).
@@ -707,8 +707,11 @@ def average_quaternions(Q: "Quaternion", w: Optional[torch.Tensor] = None) -> "Q
Returns:
Quaternion: averaged quaternion of shape (1, 4), wrapped back in the Quaternion class.
"""
- data = Q.data
KORNIA_CHECK_TYPE(Q, Quaternion)
+ # the chordal mean is the top eigenvector of sum_i w_i q_i q_i^T, which is sign invariant but weights each member
+ # by its squared norm: a member stored as 3 q counted 9 times (#4974). Every other rotation-valued method depends
+ # only on the direction of q, so normalise the members first.
+ data = Q.normalize().data
M = data.shape[0]
if w is None:
@@ -717,7 +720,12 @@ def average_quaternions(Q: "Quaternion", w: Optional[torch.Tensor] = None) -> "Q
w = w.to(data.device, dtype=data.dtype)
if w.numel() != M:
raise ValueError(f"weights length {w.numel()} must match number of quaternions {M}")
- w = w / w.sum()
+ if bool((w < 0).any()):
+ raise ValueError("weights must be non-negative")
+ w_sum = w.sum()
+ if bool(w_sum == 0):
+ raise ValueError("weights must not all be zero")
+ w = w / w_sum
A = data.T @ torch.diag(w) @ data
orig_dtype = A.dtype
diff --git a/tests/geometry/test_quaternion.py b/tests/geometry/test_quaternion.py
index 89d848edf..6892932fa 100644
--- a/tests/geometry/test_quaternion.py
+++ b/tests/geometry/test_quaternion.py
@@ -537,6 +537,22 @@ 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)
+ # #4974: a negative weight extrapolated past a member, and an all-zero weight divided by zero
+ with pytest.raises(ValueError, match="non-negative"):
+ average_quaternions(Q, w=torch.tensor([1.0, -0.5, 0.5], device=device, dtype=dtype))
+ with pytest.raises(ValueError, match="zero"):
+ average_quaternions(Q, w=torch.zeros(3, device=device, dtype=dtype))
+
+ def test_member_norm_is_not_a_weight_4974(self, device, dtype):
+ # #4974: the members were used as stored, so a member stored as 3 q counted 9 times (the result was scipy's
+ # Rotation.mean with weights [9, 1]). Reference: scipy 1.18.1 Rotation.from_rotvec(rv).mean().as_rotvec().
+ rv = torch.tensor([[0.9, -0.3, 0.2], [-0.2, 1.1, 0.5]], dtype=torch.float64)
+ q = Quaternion.from_axis_angle(rv).data
+ expected = torch.tensor([0.3823365186803238, 0.41998759136458697, 0.3733961630971692], dtype=torch.float64)
+ scaled = torch.stack((3.0 * q[0], q[1])).to(device=device, dtype=dtype)
+ for members in (q.to(device=device, dtype=dtype), scaled):
+ out = average_quaternions(Quaternion(members))
+ self.assert_close(out.to_axis_angle()[0], expected.to(device=device, dtype=dtype))
class TestQuaternionConventions(BaseTester):
@@ -662,19 +678,3 @@ class TestQuaternionConventions(BaseTester):
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_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())