π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): keep the theta^2 terms in axis_angle_to_rotation_matrix's low-angle branch (#5124)
Dipak Chaudhari1f45e33748bc
diff --git a/changelog.d/5124.fixed.md b/changelog.d/5124.fixed.mdnew file mode 100644index 000000000..cdb3ce708--- /dev/null+++ b/changelog.d/5124.fixed.md@@ -0,0 +1 @@+`axis_angle_to_rotation_matrix` is now accurate to float64 rounding for rotations below `1e-3` rad. Its low-angle branch used to drop the `theta**2` terms of Rodrigues' coefficients, an error of `theta**3 / 6` per entry (`1.3e-10` just below the switch), so the result jumped at `theta = 1e-3` and disagreed with the quaternion route by the same amount.diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 49da88c75..45fd240d0 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -459,30 +459,33 @@ def axis_angle_to_rotation_matrix(axis_angle: torch.Tensor) -> torch.Tensor:dim=-2,)- def _compute_rotation_matrix_taylor(axis_angle: torch.Tensor) -> torch.Tensor:+ def _compute_rotation_matrix_taylor(axis_angle: torch.Tensor, theta2: torch.Tensor) -> torch.Tensor:rx, ry, rz = axis_angle.unbind(-1)k_one = torch.ones_like(rx)- k_half = 0.5 * k_one++ # Rodrigues' formula R = I + a [v]x + b [v]x^2, with the series of its+ # coefficients a = sin(theta) / theta and b = (1 - cos(theta)) / theta^2+ # kept to the theta^2 term. Stopping at a = 1 and b = 1/2 left an error of+ # theta^3 / 6 per entry, 1.3e-10 at theta = 1e-3 in float64. The+ # first dropped terms are theta^4 / 120 and theta^4 / 720, which puts the+ # error at theta^5 / 120, below float64 rounding across the branch.+ a = k_one - theta2 / 6.0+ b = 0.5 * k_one - theta2 / 24.0rx2, ry2, rz2 = rx * rx, ry * ry, rz * rzrxry, rxrz, ryrz = rx * ry, rx * rz, ry * rz- # second-order Taylor expansion of Rodrigues' formula:- # R = I + [v]x + [v]x^2 / 2- # the first-order truncation had det = 1 + theta^2; the second-order- # truncation has det = 1 + theta^4 / 4, so the matrix is a rotation to- # the working precision across the whole low-angle branchreturn torch.stack([- k_one - k_half * (ry2 + rz2),- -rz + k_half * rxry,- ry + k_half * rxrz,- rz + k_half * rxry,- k_one - k_half * (rx2 + rz2),- -rx + k_half * ryrz,- -ry + k_half * rxrz,- rx + k_half * ryrz,- k_one - k_half * (rx2 + ry2),+ k_one - b * (ry2 + rz2),+ -a * rz + b * rxry,+ a * ry + b * rxrz,+ a * rz + b * rxry,+ k_one - b * (rx2 + rz2),+ -a * rx + b * ryrz,+ -a * ry + b * rxrz,+ a * rx + b * ryrz,+ k_one - b * (rx2 + ry2),],dim=-1,).reshape(list(axis_angle.shape[:-1]) + [3, 3])@@ -494,7 +497,7 @@ def axis_angle_to_rotation_matrix(axis_angle: torch.Tensor) -> torch.Tensor:# differentiates sqrt at 0. A clamp floor is no guard here: 1e-12 underflows to 0 in float16.safe_theta2 = torch.where(mask, theta2, torch.ones_like(theta2))rot_normal = _compute_rotation_matrix(axis_angle, safe_theta2) # (*,3,3)- rot_taylor = _compute_rotation_matrix_taylor(axis_angle) # (*,3,3)+ rot_taylor = _compute_rotation_matrix_taylor(axis_angle, theta2) # (*,3,3)return torch.where(mask[..., None, None], rot_normal, rot_taylor)diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.pyindex 18363ea56..c6ad51e00 100644--- a/tests/geometry/test_conversions.py+++ b/tests/geometry/test_conversions.py@@ -17,6 +17,7 @@import disimport inspect+import mathimport warningsfrom collections.abc import Iteratorfrom contextlib import contextmanager@@ -2230,9 +2231,9 @@ class TestAngleAxisToRotationMatrix(BaseTester):# det = 0.9999974535249636 and max|R @ R.T - I| = 2.5464750363912714e-06;# (2) theta = 1e-3 takes the low-angle branch, which returned the first-order Taylor# matrix [[1, -rz, ry], [rz, 1, -rx], [-ry, rx, 1]] with det = 1 + theta**2 = 1.000001.- # The low-angle branch now returns the second-order Taylor expansion R = I + [v]x + [v]x^2/2,- # whose determinant is 1 + theta**4 / 4 -- at theta = 1e-3 that is 1 + 2.5e-13, a rotation- # to the working precision -- so both branches must now pass the same orthogonality checks.+ # The low-angle branch now evaluates Rodrigues' formula with the theta**2 terms of its two+ # coefficient series kept (kornia#4838), a rotation to float64 rounding, so both branches+ # must now pass the same orthogonality checks.# The general branch must also agree with the quaternion route on a generic (non-axis# aligned) rotation, which is where the eps defect showed up as an axis-dependent error.# float64 is hardcoded and the dtype fixture dropped because both cells are float64 facts:@@ -2245,8 +2246,9 @@ class TestAngleAxisToRotationMatrix(BaseTester):# (R @ R.T - torch.eye(3, dtype=torch.float64)).abs().max() -> 0.0# t = torch.tensor([[0., 0., 1e-3]], dtype=torch.float64) # theta**2 == 1e-06 exactly# axis_angle_to_rotation_matrix(t)[0].tolist()- # -> [[0.9999995, -0.001, 0.0], [0.001, 0.9999995, 0.0], [0.0, 0.0, 1.0]]- # torch.linalg.det(that).item() -> 1.00000000000025+ # -> [[0.9999995000000417, -0.0009999998333333332, 0.0],+ # [0.0009999998333333332, 0.9999995000000417, 0.0], [0.0, 0.0, 1.0]]+ # torch.linalg.det(that).item() -> 1.0# g = torch.tensor([[1., 2., 3.]], dtype=torch.float64) * 0.6 / math.sqrt(14.0) # generic axis# Rg = axis_angle_to_rotation_matrix(g)[0]# torch.linalg.det(Rg).item() -> 1.0@@ -2282,6 +2284,57 @@ class TestAngleAxisToRotationMatrix(BaseTester):"kornia#3947: axis_angle_to_rotation_matrix disagrees with the quaternion route")+ def test_convention_low_angle_branch_matches_quaternion_route_4838(self, device):+ # Regression test for kornia#4838. Below theta**2 = 1e-6 the function switches to a+ # series form of Rodrigues' formula. That branch used to stop at sin(theta)/theta = 1 and+ # (1 - cos(theta))/theta**2 = 1/2, an error of theta**3 / 6 per entry: 1.3e-10 at+ # theta = 9.99e-4 in float64, next to 1.1e-16 on the general branch just above the switch,+ # and 130 times the 1e-12 the general branch is held to against the quaternion route in+ # test_convention_both_branches_are_orthogonal_3947. Keeping the theta**2 terms of both+ # series puts the error below float64 rounding across the branch.+ # float64 is hardcoded because in float32 the old truncation error (1.7e-10) is below+ # rounding (3e-8 at these angles), so only float64 can tell the two apart.+ # Snippet used to generate the old values (torch only, cpu float64, before the fix):+ # axis = torch.tensor([1., 2., 3.], dtype=torch.float64) / 14.0**0.5+ # v = (9.99e-4 * axis)[None]+ # (axis_angle_to_rotation_matrix(v)+ # - quaternion_to_rotation_matrix(axis_angle_to_quaternion(v))).abs().max() -> 1.3e-10+ _skip_if_dtype_unavailable(device, torch.float64)++ axis = torch.tensor([1.0, 2.0, 3.0], device=device, dtype=torch.float64) / 14.0**0.5+ zero = torch.zeros((), device=device, dtype=torch.float64)+ skew = torch.stack(+ [+ torch.stack([zero, -axis[2], axis[1]]),+ torch.stack([axis[2], zero, -axis[0]]),+ torch.stack([-axis[1], axis[0], zero]),+ ]+ )+ for theta in (1.1e-3, 9.99e-4, 5e-4, 1e-4, 1e-5):+ v = (theta * axis)[None]+ direct = axis_angle_to_rotation_matrix(v)+ quat_route = kornia.geometry.conversions.quaternion_to_rotation_matrix(+ kornia.geometry.conversions.axis_angle_to_quaternion(v)+ )+ assert (direct - quat_route).abs().max().item() < 1e-12, (+ f"kornia#4838: the low-angle branch disagrees with the quaternion route at theta={theta}"+ )+ round_trip = kornia.geometry.conversions.rotation_matrix_to_axis_angle(direct)+ assert (round_trip - v).abs().max().item() < 1e-15, (+ f"kornia#4838: the axis-angle round trip drifted at theta={theta}"+ )+ # Rodrigues' formula from sin and cos, 1 - cos(theta) written as 2 sin(theta / 2)**2 so it does not+ # cancel. The (1 - cos(theta)) / theta**2 coefficient only shows at theta**4 / 24 (4e-14 at 1e-3), below+ # the quaternion-route bound above, so this is the check that pins its theta**2 term.+ expected = (+ torch.eye(3, device=device, dtype=torch.float64)+ + math.sin(theta) * skew+ + 2.0 * math.sin(0.5 * theta) ** 2 * (skew @ skew)+ )+ assert (direct[0] - expected).abs().max().item() < 1e-15, (+ f"kornia#4838: the low-angle branch is not the rotation of its input at theta={theta}"+ )+def test_convention_accepts_any_leading_batch_dimensions_3955(self, device):# Convention: axis_angle_to_rotation_matrix accepts (*, 3) and returns (*, 3, 3) -- what its# own shape guard promises in the message it raises ("Input size must be a (*, 3) tensor")