π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(quaternion): interpolate slerp through the principal log (short arc) (#4945)
Dmytro Mishkin2d64d0392268
diff --git a/changelog.d/4945.fixed.md b/changelog.d/4945.fixed.mdnew file mode 100644index 000000000..0b7986cc8--- /dev/null+++ b/changelog.d/4945.fixed.md@@ -0,0 +1 @@+`Quaternion.slerp` takes the shorter arc between the two rotations whatever the signs of the stored quaternions (it used to go the long way round when their dot product was negative). (#4944)diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.pyindex 763860ebe..64d32acd5 100644--- a/kornia/geometry/quaternion.py+++ b/kornia/geometry/quaternion.py@@ -564,6 +564,13 @@ class Quaternion(nn.Module):def slerp(self, q1: "Quaternion", t: float) -> "Quaternion":"""Return a unit quaternion spherically interpolated between quaternions self.q and q1.+ The interpolation follows the shorter arc between the two rotations, whatever the signs of the stored+ quaternions: ``q1`` and ``-q1`` give the same result, and at ``t = 1`` the output is ``q1`` or ``-q1``.+ The exception is a half turn whose relative quaternion ``self.inv() * q1`` has a real part of exactly zero:+ both arcs are then equally short and the path is not unique. The arc taken follows the sign of the vector+ part of ``self.inv() * q1``, so ``q1`` and ``-q1`` take opposite arcs, and the result is not continuous in+ ``q1`` there.+See more: https://en.wikipedia.org/wiki/SlerpArgs:@@ -579,7 +586,10 @@ class Quaternion(nn.Module):KORNIA_CHECK_TYPE(q1, Quaternion)q0 = self.normalize()q1 = q1.normalize()- return q0 * (q0.inv() * q1) ** t+ # q0 * exp(t * log(q0^-1 q1)): the principal log of the relative rotation selects the shorter arc, and both+ # conversions keep a finite gradient at the identity (q0 == q1).+ rel = quaternion_to_axis_angle((q0.inv() * q1).data)+ return q0 * Quaternion(axis_angle_to_quaternion(t * rel))def norm(self, keepdim: bool = False) -> torch.Tensor:"""Compute the norm (magnitude) of the quaternion.diff --git a/tests/geometry/test_quaternion.py b/tests/geometry/test_quaternion.pyindex 60a50742f..d14be8dd2 100644--- a/tests/geometry/test_quaternion.py+++ b/tests/geometry/test_quaternion.py@@ -15,6 +15,7 @@# limitations under the License.#+import mathfrom typing import Unionimport pytest@@ -333,6 +334,45 @@ class TestQuaternion(BaseTester):q4 = Quaternion.from_axis_angle(axis * t * 3.14159)self.assert_close(q3, q4)+ def test_slerp_takes_the_short_arc(self, device, dtype):+ # q and -q are the same rotation; the interpolation must not depend on the stored sign (#4944).+ # a and b are 0.33 rad apart with dot(a, b) = 0.986, so dot(a, -b) < 0.+ a = Quaternion.from_axis_angle(torch.tensor([[0.3, 0.2, -0.1]], device=device, dtype=dtype))+ b = Quaternion.from_axis_angle(torch.tensor([[0.5, 0.1, 0.15]], device=device, dtype=dtype))+ rel_angle = (a.inv() * b).to_axis_angle().norm()+ for t in (0.25, 0.5, 0.75):+ short = a.slerp(b, t).matrix()+ self.assert_close(a.slerp(-b, t).matrix(), short)+ # the interpolant sits at t times the relative angle from a+ self.assert_close((a.inv() * a.slerp(-b, t)).to_axis_angle().norm(), t * rel_angle)++ def test_slerp_exact_half_turn_follows_the_stored_sign(self, device, dtype):+ # At an exact half turn both arcs are equally short. The arc follows the sign of the vector part of+ # q0^-1 q1, so q1 and -q1 take opposite arcs, each of length t * pi from q0 (see the slerp docstring).+ # Every product below is exact, so the real part of q0^-1 q1 is exactly zero in every dtype.+ q0 = Quaternion(torch.tensor([[0.5, 0.5, 0.5, 0.5]], device=device, dtype=dtype))+ q1 = q0 * Quaternion(torch.tensor([[0.0, 1.0, 0.0, 0.0]], device=device, dtype=dtype))+ for t in (0.25, 0.5):+ for sign in (1.0, -1.0):+ rel = (q0.inv() * q0.slerp(q1 * sign, t)).to_axis_angle()+ expected = torch.tensor([[sign * t * math.pi, 0.0, 0.0]], device=device, dtype=dtype)+ self.assert_close(rel, expected)++ def test_slerp_gradient_is_finite_at_equal_endpoints(self, device, dtype):+ # slerp(q, q, t) = q is smooth in both endpoints; its gradient must not be nan (#4927).+ q = Quaternion.from_axis_angle(torch.tensor([[0.3, 0.2, -0.1]], device=device, dtype=dtype)).data+ q0 = q.clone().requires_grad_(True)+ q1 = q.clone().requires_grad_(True)+ Quaternion(q0).slerp(Quaternion(q1), 0.3).data.sum().backward()+ assert torch.isfinite(q0.grad).all()+ assert torch.isfinite(q1.grad).all()++ def test_slerp_gradcheck(self, device):+ q0 = Quaternion.from_axis_angle(torch.tensor([[0.3, 0.2, -0.1]], device=device, dtype=torch.float64)).data+ q1 = Quaternion.from_axis_angle(torch.tensor([[0.5, 0.1, 0.15]], device=device, dtype=torch.float64)).data+ self.gradcheck(lambda a, b: Quaternion(a).slerp(Quaternion(b), 0.3).data, (q0, q1))+ self.gradcheck(lambda a, b: Quaternion(a).slerp(Quaternion(b), 0.3).data, (q0, q0.detach().clone()))+def test_from_to_euler_values(self, device, dtype):# num_samples = 5# data = 2 * torch.rand(3, num_samples, device=device, dtype=dtype) - 1