🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): keep the norm in Quaternion.__pow__ (#4951)
Mohammad Hijjawi7e920c74d65d
diff --git a/changelog.d/4951.breaking.md b/changelog.d/4951.breaking.mdnew file mode 100644index 000000000..c4ff265d0--- /dev/null+++ b/changelog.d/4951.breaking.md@@ -0,0 +1,6 @@+`Quaternion.__pow__` now keeps the norm, `q**t == ‖q‖**t (cos tθ + n sin tθ)`, so `q**1 == q`, `q**2 == q * q` and+`q**-1 == q.inv()` for non-unit quaternions. Previously it returned the power of the unit quaternion `q/‖q‖` for every+`q`: `Quaternion([2, 0, 0, 0])**2` was `[1, 0, 0, 0]` and is now `[4, 0, 0, 0]`. Call `q.normalize() ** t` for the old+result. Unit-quaternion results are unchanged up to rounding, and `slerp`, which normalizes its inputs, is not+affected. The gradient of `q**t` is now finite for a nonzero quaternion with a zero vector part, such as the identity,+where it used to be `nan`.diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.pyindex 72055be45..763860ebe 100644--- a/kornia/geometry/quaternion.py+++ b/kornia/geometry/quaternion.py@@ -289,7 +289,10 @@ class Quaternion(nn.Module):return self.__rtruediv__(left)def __pow__(self, t: float) -> "Quaternion":- """Return the power of a quaternion raised to exponent t.+ r"""Return the power of a quaternion raised to exponent t.++ For :math:`q = \|q\| (\cos\theta + n \sin\theta)` this is+ :math:`q^t = \|q\|^t (\cos t\theta + n \sin t\theta)`, so ``q**2 == q * q`` and ``q**-1 == q.inv()``.Args:t: raised exponent.@@ -299,12 +302,17 @@ class Quaternion(nn.Module):>>> q_pow = q**2"""- theta = self.polar_angle[..., None]+ w = self.scalar[..., None]vec_norm = self.vec.norm(dim=-1, keepdim=True)- n = torch.where(vec_norm != 0, self.vec / vec_norm, self.vec * 0)- w = (t * theta).cos()- xyz = (t * theta).sin() * n- return Quaternion(torch.cat((w, xyz), -1))+ theta = torch.atan2(vec_norm, w)+ # On the real axis (|v| = 0) take sin(t * theta) / |v| from its limit t * cos(t * theta) / w, exact when+ # theta = 0 or t is an integer, and keep both arms' denominators nonzero so values and gradients stay finite.+ is_real = vec_norm == 0+ safe_vec_norm = torch.where(is_real, torch.ones_like(vec_norm), vec_norm)+ safe_w = torch.where(w == 0, torch.ones_like(w), w)+ sin_ratio = torch.where(is_real, t * (t * theta).cos() / safe_w, (t * theta).sin() / safe_vec_norm)+ scale = self.norm(keepdim=True) ** t+ return Quaternion(torch.cat((scale * (t * theta).cos(), scale * sin_ratio * self.vec), -1))@propertydef data(self) -> torch.Tensor:diff --git a/tests/geometry/test_quaternion.py b/tests/geometry/test_quaternion.pyindex 8ab61ec90..60a50742f 100644--- a/tests/geometry/test_quaternion.py+++ b/tests/geometry/test_quaternion.py@@ -166,6 +166,42 @@ class TestQuaternion(BaseTester):self.assert_close((q1**1), q1)self.assert_close((q1**2), q1)+ def test_pow_non_unit(self, device, dtype):+ # issue #4926: q**t keeps the norm, |q**t| == |q|**t, so it agrees with * and inv() for non-unit q+ data = [[1.0, 0.5, 0.0, 0.0], [0.5, -0.25, 0.5, 0.25], [1.5, 0.0, 0.5, -0.5], [0.0, 0.0, 0.75, 0.0]]+ q = Quaternion(torch.tensor(data, device=device, dtype=dtype))+ self.assert_close(q**0, Quaternion.identity(4, device, dtype))+ self.assert_close(q**1, q)+ self.assert_close(q**2, q * q)+ self.assert_close(q**-1, q.inv())+ self.assert_close((q**0.5) * (q**0.5), q)+ self.assert_close((q**0.5).norm(), q.norm() ** 0.5)+ # the direction is the power of the unit quaternion, as before+ self.assert_close((q**0.5).normalize(), q.normalize() ** 0.5)++ def test_pow_real_axis(self, device, dtype):+ q = Quaternion(torch.tensor([[2.0, 0.0, 0.0, 0.0], [-2.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype))+ self.assert_close(q**2, q * q)+ self.assert_close(q**-1, q.inv())+ expected = torch.tensor([2.0**0.5, 0.0, 0.0, 0.0], device=device, dtype=dtype)+ self.assert_close((q**0.5).data[0], expected)++ @pytest.mark.parametrize("t", (-1.0, 0.5, 2.0))+ def test_pow_gradcheck(self, device, t):+ # the first quaternion lies on the real axis, where the vector part has zero norm; the last is pure imaginary+ # (w = 0), where the unselected real-axis arm divides by w+ data = torch.tensor(+ [[2.0, 0.0, 0.0, 0.0], [1.0, 0.5, -0.3, 0.2], [0.0, 0.3, -0.4, 0.5]], device=device, dtype=torch.float64+ )+ self.gradcheck(lambda x: (Quaternion(x) ** t).data, (data,))++ @pytest.mark.parametrize("t", (-1.0, 2.0, 3.0))+ def test_pow_gradcheck_negative_real_axis(self, device, t):+ # q = -2 has theta = pi, where the real-axis limit t * cos(t * theta) / w carries the signs of cos(t * pi) and+ # of w. Only integer t: for a non-integer t the negative real axis is a branch cut with no derivative.+ data = torch.tensor([[-2.0, 0.0, 0.0, 0.0]], device=device, dtype=torch.float64)+ self.gradcheck(lambda x: (Quaternion(x) ** t).data, (data,))+@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))def test_quaternion_scalar_multiplication(self, device, dtype, batch_size):"""Test scalar multiplication for issue #3101."""