π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): take n = e_x for Quaternion.__pow__ on the negative real axis instead of returning the zero quaternion (#5003)
εΊζ’η2d7dd483a234
diff --git a/changelog.d/5003.fixed.md b/changelog.d/5003.fixed.mdnew file mode 100644index 000000000..81f79088a--- /dev/null+++ b/changelog.d/5003.fixed.md@@ -0,0 +1,3 @@+`Quaternion.__pow__` takes the axis `n = e_x` on the negative real axis (`w < 0`, zero vector part), where `theta = pi`+and the axis is undefined, so a non-integer power there has norm `|q|**t` and angle `t * pi` and `(q**0.5)**2 == q`.+`Quaternion([-2, 0, 0, 0]) ** 0.5` used to be the zero quaternion. Integer powers are unchanged. (#4955)diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.pyindex 794623acb..353d414b2 100644--- a/kornia/geometry/quaternion.py+++ b/kornia/geometry/quaternion.py@@ -309,14 +309,19 @@ class Quaternion(nn.Module):"""Right division (left / self) where left is a scalar or torch.Tensor."""return self.__rtruediv__(left)- def __pow__(self, t: float) -> "Quaternion":+ def __pow__(self, t: Union[float, torch.Tensor]) -> "Quaternion":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()``.+ On the negative real axis (``w < 0`` and a zero vector part) :math:`\theta = \pi` and the axis :math:`n` is+ undefined: for a non-integer ``t`` every unit vector gives a valid power. This method takes :math:`n = e_x`+ there, so ``q**t`` has norm :math:`\|q\|^t` and angle :math:`t\pi`, ``(q**0.5)**2 == q``, and the result is+ the limit from the ``+x`` side of the axis. An integer ``t`` keeps a zero vector part.+Args:- t: raised exponent.+ t: raised exponent, a float or a tensor that broadcasts against ``(..., 1)``.Example:>>> q = Quaternion(torch.tensor([1., .5, 0., 0.]))@@ -333,7 +338,19 @@ class Quaternion(nn.Module):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))+ vec = scale * sin_ratio * self.vec+ # The negative real axis is the branch cut of the power: theta = pi and n = v / |v| is undefined, so the arm+ # above leaves the vector part at 0 and only an integer t gives a valid result there (#4955). Take n = e_x on+ # the cut: add |q|^t sin(t pi) to x, which is 0 there. sin(t pi) is reduced by the nearest integer k so that it+ # is exactly 0 for an integer t, and only the cut is touched, so every other value and an integer t keep the+ # arm above bit for bit. The reduction stays in torch so that a tensor t (0-d or batched) keeps its gradient.+ t_ = torch.as_tensor(t, dtype=scale.dtype, device=scale.device)+ k = t_.detach().round()+ sin_t_pi = (1.0 - 2.0 * k.remainder(2.0)) * torch.sin(pi * (t_ - k))+ on_cut = is_real & (w < 0) & (sin_t_pi != 0)+ vec_x = vec[..., :1]+ vec = torch.cat((torch.where(on_cut, vec_x + scale * sin_t_pi, vec_x), vec[..., 1:]), -1)+ return Quaternion(torch.cat((scale * (t * theta).cos(), vec), -1))@propertydef data(self) -> torch.Tensor:diff --git a/tests/geometry/test_quaternion.py b/tests/geometry/test_quaternion.pyindex 8136c5490..a26439210 100644--- a/tests/geometry/test_quaternion.py+++ b/tests/geometry/test_quaternion.py@@ -187,6 +187,53 @@ class TestQuaternion(BaseTester):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)+ def test_pow_negative_real_axis_4955(self, device, dtype):+ # #4955 (fixed): on the negative real axis theta = pi and the axis n = v / |v| is undefined, so q**t returned+ # |q|**t cos(t pi) in the scalar and zeros elsewhere: [-2, 0, 0, 0]**0.5 was the zero quaternion. n = e_x is+ # taken there, so |q**t| == |q|**t, (q**0.5)**2 == q and the value is the limit from the +x side of the axis.+ eps = torch.finfo(dtype).eps+ q = Quaternion(torch.tensor([[-2.0, 0.0, 0.0, 0.0], [-1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype))+ root = q**0.5+ expected = torch.tensor([[0.0, 2.0**0.5, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]], device=device, dtype=dtype)+ self.assert_close(root.data, expected, rtol=4 * eps, atol=4 * eps)+ self.assert_close(root * root, q, rtol=4 * eps, atol=8 * eps)+ quarter = q**0.25+ self.assert_close(quarter.norm(), q.norm() ** 0.25)+ self.assert_close(quarter.polar_angle, torch.full((2,), math.pi / 4, device=device, dtype=dtype))+ self.assert_close(quarter * quarter, root, rtol=4 * eps, atol=8 * eps)+ self.assert_close((q**-0.5) * root, Quaternion.identity(2, device, dtype), rtol=4 * eps, atol=8 * eps)+ # Just off the axis on the +x side the power is continuous with the value on it.+ delta = math.sqrt(eps)+ near = Quaternion(torch.tensor([-2.0, delta, 0.0, 0.0], device=device, dtype=dtype)) ** 0.5+ self.assert_close(near.data, root.data[0], rtol=0.0, atol=delta)+ # An integer t is not on a branch cut: the vector part stays exactly zero and * and inv() agree, as before.+ for t in (-1.0, 2, 3.0):+ assert torch.equal((q**t).vec, torch.zeros_like(q.vec))+ self.assert_close(q**2, q * q)+ self.assert_close(q**-1, q.inv())+ # For an odd nearest integer k (t = 1.25, -0.75) sin(t pi) = -sin(pi (t - k)): x follows sin(t pi).+ for t in (1.25, -0.75):+ norm_t = torch.tensor([[2.0**t], [1.0]], device=device, dtype=dtype)+ unit = torch.tensor([[math.cos(t * math.pi), math.sin(t * math.pi), 0.0, 0.0]], device=device, dtype=dtype)+ self.assert_close((q**t).data, norm_t * unit, rtol=4 * eps, atol=4 * eps)++ def test_pow_negative_real_axis_gradient_is_finite_4955(self, device, dtype):+ # The output jumps across the cut, so the gradient there has no defined value; it is finite, not nan.+ data = torch.tensor([[-2.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype, requires_grad=True)+ (Quaternion(data) ** 0.5).data.sum().backward()+ assert torch.isfinite(data.grad).all()++ def test_pow_tensor_exponent(self, device, dtype):+ # A tensor t, 0-d or one exponent per quaternion, gives the power of the float t and keeps its gradient.+ q = Quaternion(torch.tensor([[-2.0, 0.0, 0.0, 0.0], [0.5, 0.3, -0.2, 0.1]], device=device, dtype=dtype))+ t = torch.tensor(0.5, device=device, dtype=dtype, requires_grad=True)+ self.assert_close((q**t).data, (q**0.5).data)+ ts = torch.tensor([[1.25], [-0.75]], device=device, dtype=dtype)+ self.assert_close((q**ts).data, torch.stack(((q**1.25).data[0], (q**-0.75).data[1])))+ # x = |q|^t sin(t pi) on the cut: dx/dt = |q|^t (log|q| sin(t pi) + pi cos(t pi)) = sqrt(2) log(2) at 0.5.+ (q**t).data[0, 1].backward()+ self.assert_close(t.grad, torch.tensor(2.0**0.5 * math.log(2.0), device=device, dtype=dtype))+@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