π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): check the pose type in NamedPose and raise TypeError for a mixed Se2/Se3 or non-NamedPose product (#5010)
εΊζ’η4d7a06e4a0ad
diff --git a/changelog.d/5010.fixed.md b/changelog.d/5010.fixed.mdnew file mode 100644index 000000000..a8636493a--- /dev/null+++ b/changelog.d/5010.fixed.md@@ -0,0 +1,5 @@+`NamedPose` now rejects a pose that is not an `Se2` or an `Se3` at construction with a `TypeCheckError` (an `So3`,+`So2`, `Quaternion` or tensor used to be accepted and fail later in `.rotation` with `AttributeError`), and+`NamedPose.__mul__` raises a `TypeError` that names the offending type when the right operand is not a `NamedPose` or+holds the other group, instead of an `AttributeError` from inside the dispatch. `from_rt` and `from_matrix` are+unaffected. (#5010)diff --git a/kornia/geometry/pose.py b/kornia/geometry/pose.pyindex 0cc930b70..b11ee096b 100644--- a/kornia/geometry/pose.py+++ b/kornia/geometry/pose.py@@ -21,6 +21,7 @@ import uuidimport torch+from kornia.core.check import KORNIA_CHECK_TYPEfrom kornia.geometry.liegroup import Se2, Se3, So2, So3from kornia.geometry.quaternion import Quaternion@@ -55,9 +56,9 @@ class NamedPose:guaranteed to satisfy this identity (`#4942 <https://github.com/kornia/kornia/issues/4942>`_).The left operand's ``frame_src`` must equal the right operand's ``frame_dst``, otherwise ``*`` raises``ValueError``; :meth:`inverse` inverts the pose and swaps the frame names.- - Known defect: the pose type is not validated, so an ``So3``, ``So2``, ``Quaternion`` or tensor is accepted- and :attr:`rotation` then raises ``AttributeError``; a product of an ``Se3`` pose and an ``Se2`` pose also- raises ``AttributeError`` instead of ``ValueError`` (`#4937 <https://github.com/kornia/kornia/issues/4937>`_).+ - The pose must be an ``Se2`` or an ``Se3``: an ``So3``, ``So2``, ``Quaternion`` or tensor is rejected at+ construction (use :meth:`from_rt` or :meth:`from_matrix` to build a pose from one), and ``*`` raises+ ``TypeError`` for a right operand that is not a ``NamedPose`` or holds the other group.Example:>>> b_from_a = NamedPose(Se3.identity(), frame_src="frame_a", frame_dst="frame_b")@@ -77,7 +78,11 @@ class NamedPose:frame_src: Name of the source frame; a random unique name when omitted or empty.frame_dst: Name of the destination frame; a random unique name when omitted or empty.+ Raises:+ TypeCheckError: if ``dst_from_src`` is not an ``Se2`` or an ``Se3``.+"""+ KORNIA_CHECK_TYPE(dst_from_src, (Se2, Se3))self._dst_from_src = dst_from_srcself._frame_src = frame_src or uuid.uuid4().hexself._frame_dst = frame_dst or uuid.uuid4().hex@@ -97,6 +102,10 @@ class NamedPose:Returns:Composed NamedPose.+ Raises:+ TypeError: if ``other`` is not a ``NamedPose`` or its pose is not of the same group as ``self.pose``.+ ValueError: if ``self.frame_src`` is not ``other.frame_dst``.+Example:>>> b_from_a = NamedPose(Se3.identity(), frame_src="frame_a", frame_dst="frame_b")>>> c_from_b = NamedPose(Se3.identity(), frame_src="frame_b", frame_dst="frame_c")@@ -106,13 +115,15 @@ class NamedPose:frame_src: frame_a -> frame_dst: frame_c)"""+ if not isinstance(other, NamedPose):+ raise TypeError(f"NamedPose can only be composed with a NamedPose, got {type(other)}")if self._frame_src != other._frame_dst:raise ValueError(f"Cannot compose {self} with {other}")- if isinstance(other.pose, Se2):+ if isinstance(self.pose, Se2) and isinstance(other.pose, Se2):return NamedPose(self._dst_from_src._mul_se2(other.pose), other._frame_src, self._frame_dst)- if isinstance(other.pose, Se3):+ if isinstance(self.pose, Se3) and isinstance(other.pose, Se3):return NamedPose(self._dst_from_src._mul_se3(other.pose), other._frame_src, self._frame_dst)- raise ValueError(f"Pose must be either Se2 or Se3, got {type(self._dst_from_src)}")+ raise TypeError(f"Cannot compose an {type(self.pose).__name__} pose with an {type(other.pose).__name__} pose")@propertydef pose(self) -> Se2 | Se3:diff --git a/tests/geometry/test_pose.py b/tests/geometry/test_pose.pyindex 69f5ad4d1..74d2ba7b7 100644--- a/tests/geometry/test_pose.py+++ b/tests/geometry/test_pose.py@@ -20,8 +20,10 @@ import mathimport pytestimport torch+from kornia.core.exceptions import TypeCheckErrorfrom kornia.geometry import NamedPosefrom kornia.geometry.liegroup import Se2, Se3, So2, So3+from kornia.geometry.quaternion import Quaternionfrom testing.base import BaseTester@@ -300,19 +302,42 @@ class TestNamedPoseConventions(BaseTester):)self.assert_close(a_from_b.pose.matrix(), expected_inv)- def test_wart_named_pose_mixed_groups_4937(self, device, dtype):+ def test_named_pose_rejects_wrong_types_4937(self, device, dtype):if dtype == torch.bfloat16:pytest.skip("torch.complex has no bfloat16 overload, so So2 (and an Se2 pose) cannot be built at all")- # https://github.com/kornia/kornia/issues/4937: NamedPose validates no types. Composing an Se3 pose with an- # Se2 pose fails inside the dispatch with an AttributeError; the ValueError branch meant for it is never- # reached.+ # https://github.com/kornia/kornia/issues/4937: the pose type is checked at construction, and composing poses+ # of different groups, or a NamedPose with something else, raises a TypeError that names the offending type.g1, _ = self._poses(device, dtype)se2 = Se2.exp(torch.tensor([0.5, -1.0, 0.3], device=device, dtype=dtype))- with pytest.raises(AttributeError):- NamedPose(g1, frame_src="b", frame_dst="c") * NamedPose(se2, frame_src="a", frame_dst="b")- with pytest.raises(AttributeError):- NamedPose(se2, frame_src="b", frame_dst="c") * NamedPose(g1, frame_src="a", frame_dst="b")- # A rotation-only group is accepted at construction, and its rotation then raises.- so3_pose = NamedPose(So3.identity(device=device, dtype=dtype), frame_src="a", frame_dst="b")- with pytest.raises(AttributeError):- _ = so3_pose.rotation+ for bad, name in (+ (So3.identity(device=device, dtype=dtype), "so3.So3"),+ (So2.identity(device=device, dtype=dtype), "so2.So2"),+ (Quaternion.identity(device=device, dtype=dtype), "quaternion.Quaternion"),+ (g1.matrix(), "torch.Tensor"),+ ):+ with pytest.raises(TypeCheckError, match=rf"expected Se2 \| Se3, got <class '.*{name}'>"):+ NamedPose(bad, frame_src="a", frame_dst="b")+ c_from_b = NamedPose(g1, frame_src="b", frame_dst="c")+ with pytest.raises(TypeError, match="Cannot compose an Se3 pose with an Se2 pose"):+ _ = c_from_b * NamedPose(se2, frame_src="a", frame_dst="b")+ with pytest.raises(TypeError, match="Cannot compose an Se2 pose with an Se3 pose"):+ _ = NamedPose(se2, frame_src="b", frame_dst="c") * NamedPose(g1, frame_src="a", frame_dst="b")+ with pytest.raises(TypeError, match=r"got <class 'kornia.geometry.liegroup.se3.Se3'>"):+ _ = c_from_b * g1+ with pytest.raises(TypeError, match=r"got <class 'torch.Tensor'>"):+ _ = c_from_b * torch.ones(1, 3, device=device, dtype=dtype)++ # A subclass of the group composes with the group, on either side.+ class _Se3(Se3):+ pass++ sub_c_from_b = NamedPose(_Se3(g1.r, g1.t), frame_src="b", frame_dst="c")+ sub_b_from_a = NamedPose(_Se3(g1.r, g1.t), frame_src="a", frame_dst="b")+ self.assert_close((c_from_b * sub_b_from_a).pose.matrix(), g1.matrix() @ g1.matrix())+ self.assert_close((sub_c_from_b * NamedPose(g1, "a", "b")).pose.matrix(), g1.matrix() @ g1.matrix())+ # Two NamedPoses with mismatched frames still fail on the frames first.+ with pytest.raises(ValueError, match="Cannot compose"):+ _ = c_from_b * NamedPose(se2, frame_src="a", frame_dst="x")+ # from_rt keeps accepting rotation-only groups, since it wraps them in an Se2 or an Se3 itself.+ assert isinstance(NamedPose.from_rt(So3.identity(device=device, dtype=dtype), g1.t).pose, Se3)+ assert isinstance(NamedPose.from_rt(So2.identity(device=device, dtype=dtype), se2.t).pose, Se2)