Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Integrate vector to liegroups (#2344)

Christie Jacob11b075e2af15
diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.py
index dd3450cb2..17d62801f 100644
--- a/kornia/geometry/liegroup/se2.py
+++ b/kornia/geometry/liegroup/se2.py
@@ -1,6 +1,8 @@
# kornia.geometry.se2 module inspired by Sophus-sympy.
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/se2.py
-from typing import Optional, Tuple, Union, overload
+from __future__ import annotations
+
+from typing import overload
from kornia.core import (
Device,
@@ -19,6 +21,7 @@ from kornia.core import (
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_TYPE
from kornia.geometry.liegroup._utils import check_se2_omega_shape, check_se2_r_t_shape, check_v_shape
from kornia.geometry.liegroup.so2 import So2
+from kornia.geometry.vector import Vector2
class Se2(Module):
@@ -39,7 +42,7 @@ class Se2(Module):
tensor([[1., 1.]], requires_grad=True)
"""
- def __init__(self, rotation: So2, translation: Tensor) -> None:
+ def __init__(self, rotation: So2, translation: Vector2 | Tensor) -> None:
"""Constructor for the base class.
Internally represented by a complex number `z` and a translation 2-vector.
@@ -61,18 +64,25 @@ class Se2(Module):
super().__init__()
KORNIA_CHECK_TYPE(rotation, So2)
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
- check_se2_r_t_shape(rotation, translation)
- self._rotation = rotation
- self._translation = Parameter(translation)
+ # KORNIA_CHECK_TYPE(translation, (Vector3, Tensor))
+ if not isinstance(translation, (Vector2, Tensor)):
+ raise TypeError(f"translation type is {type(translation)}")
+ self._translation: Vector2 | Parameter
+ self._rotation: So2 = rotation
+ if isinstance(translation, Tensor):
+ check_se2_r_t_shape(rotation, translation) # TODO remove
+ self._translation = Parameter(translation)
+ else:
+ self._translation = translation
def __repr__(self) -> str:
return f"rotation: {self.r}\ntranslation: {self.t}"
- def __getitem__(self, idx: Union[int, slice]) -> 'Se2':
+ def __getitem__(self, idx: int | slice) -> Se2:
return Se2(self._rotation[idx], self._translation[idx])
@overload
- def __mul__(self, right: 'Se2') -> 'Se2':
+ def __mul__(self, right: Se2) -> Se2:
...
@overload
@@ -95,10 +105,9 @@ class Se2(Module):
_r = so2 * right.so2
_t = t + so2 * right.t
return Se2(_r, _t)
- elif isinstance(right, Tensor):
- KORNIA_CHECK_TYPE(right, Tensor)
+ elif isinstance(right, (Vector2, Tensor)):
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
- check_se2_r_t_shape(so2, right)
+ # check_se2_r_t_shape(so2, risght)
return so2 * right + t
else:
raise TypeError(f"Unsupported type: {type(right)}")
@@ -114,7 +123,7 @@ class Se2(Module):
return self._rotation
@property
- def t(self) -> Tensor:
+ def t(self) -> Vector2 | Parameter:
"""Return the underlying translation vector of shape :math:`(B,2)`."""
return self._translation
@@ -124,12 +133,12 @@ class Se2(Module):
return self._rotation
@property
- def translation(self) -> Tensor:
+ def translation(self) -> Vector2 | Parameter:
"""Return the underlying translation vector of shape :math:`(B,2)`."""
return self._translation
@staticmethod
- def exp(v: Tensor) -> 'Se2':
+ def exp(v: Tensor) -> Se2:
"""Converts elements of lie algebra to elements of lie group.
Args:
@@ -175,7 +184,7 @@ class Se2(Module):
row0 = stack((a, half_theta), -1)
row1 = stack((-half_theta, a), -1)
V_inv = stack((row0, row1), -2)
- upsilon = V_inv @ self.t[..., None]
+ upsilon = V_inv @ self.t.data[..., None]
return stack((upsilon[..., 0, 0], upsilon[..., 1, 0], theta), -1)
@staticmethod
@@ -221,7 +230,7 @@ class Se2(Module):
return concatenate((upsilon, theta[..., None]), -1)
@classmethod
- def identity(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> 'Se2':
+ def identity(cls, batch_size: int | None = None, device: Device | None = None, dtype: Dtype = None) -> Se2:
"""Create a Se2 group representing an identity rotation and zero translation.
Args:
@@ -233,14 +242,14 @@ class Se2(Module):
Parameter containing:
tensor([1.+0.j], requires_grad=True)
>>> s.t
- Parameter containing:
- tensor([[0., 0.]], requires_grad=True)
+ x: tensor([0.])
+ y: tensor([0.])
"""
t: Tensor = tensor([0.0, 0.0], device=device, dtype=dtype)
if batch_size is not None:
KORNIA_CHECK(batch_size >= 1, msg="batch_size must be positive")
t = t.repeat(batch_size, 1)
- return cls(So2.identity(batch_size, device, dtype), t)
+ return cls(So2.identity(batch_size, device, dtype), Vector2(t))
def matrix(self) -> Tensor:
"""Returns the matrix representation of shape :math:`(B, 3, 3)`.
@@ -252,12 +261,12 @@ class Se2(Module):
[0., 1., 1.],
[0., 0., 1.]]], grad_fn=<CopySlices>)
"""
- rt = concatenate((self.r.matrix(), self.t[..., None]), -1)
+ rt = concatenate((self.r.matrix(), self.t.data[..., None]), -1)
rt_3x3 = pad(rt, (0, 0, 0, 1)) # add last row zeros
rt_3x3[..., -1, -1] = 1.0
return rt_3x3
- def inverse(self) -> 'Se2':
+ def inverse(self) -> Se2:
"""Returns the inverse transformation.
Example:
@@ -275,7 +284,7 @@ class Se2(Module):
return Se2(r_inv, t_inv)
@classmethod
- def random(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> 'Se2':
+ def random(cls, batch_size: int | None = None, device: Device | None = None, dtype: Dtype = None) -> Se2:
"""Create a Se2 group representing a random transformation.
Args:
@@ -286,16 +295,16 @@ class Se2(Module):
>>> s = Se2.random(batch_size=3)
"""
r = So2.random(batch_size, device, dtype)
- shape: Tuple[int, ...]
+ shape: tuple[int, ...]
if batch_size is None:
shape = (2,)
else:
KORNIA_CHECK(batch_size >= 1, msg="batch_size must be positive")
shape = (batch_size, 2)
- return cls(r, rand(shape, device=device, dtype=dtype))
+ return cls(r, Vector2(rand(shape, device=device, dtype=dtype)))
@classmethod
- def trans(cls, x: Tensor, y: Tensor) -> "Se2":
+ def trans(cls, x: Tensor, y: Tensor) -> Se2:
"""Construct a translation only Se2 instance.
Args:
@@ -309,7 +318,7 @@ class Se2(Module):
return cls(rotation, stack((x, y), -1))
@classmethod
- def trans_x(cls, x: Tensor) -> "Se2":
+ def trans_x(cls, x: Tensor) -> Se2:
"""Construct a x-axis translation.
Args:
@@ -319,7 +328,7 @@ class Se2(Module):
return cls.trans(x, zs)
@classmethod
- def trans_y(cls, y: Tensor) -> "Se2":
+ def trans_y(cls, y: Tensor) -> Se2:
"""Construct a y-axis translation.
Args:
@@ -339,5 +348,5 @@ class Se2(Module):
[0., 0., 1.]], grad_fn=<CopySlices>)
"""
rt = self.matrix()
- rt[..., 0:2, 2] = stack((self.t[..., 1], -self.t[..., 0]), -1)
+ rt[..., 0:2, 2] = stack((self.t.data[..., 1], -self.t.data[..., 0]), -1)
return rt
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index 9a1782457..307ca27d8 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -1,6 +1,6 @@
# kornia.geometry.so3 module inspired by Sophus-sympy.
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/se3.py
-from typing import Optional, Tuple, Union
+from __future__ import annotations
from kornia.core import (
Device,
@@ -11,7 +11,6 @@ from kornia.core import (
concatenate,
eye,
pad,
- rand,
stack,
tensor,
where,
@@ -20,6 +19,7 @@ from kornia.core import (
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_TYPE
from kornia.geometry.liegroup.so3 import So3
from kornia.geometry.linalg import batched_dot_product
+from kornia.geometry.vector import Vector3
class Se3(Module):
@@ -41,14 +41,14 @@ class Se3(Module):
tensor([1., 1., 1.], requires_grad=True)
"""
- def __init__(self, rotation: So3, translation: Tensor) -> None:
+ def __init__(self, rotation: So3, translation: Vector3 | Tensor) -> None:
"""Constructor for the base class.
Internally represented by a unit quaternion `q` and a translation 3-vector.
Args:
rotation: So3 group encompassing a rotation.
- translation: translation vector with the shape of :math:`(B, 3)`.
+ translation: Vector3 or translation tensor with the shape of :math:`(B, 3)`.
Example:
>>> from kornia.geometry.quaternion import Quaternion
@@ -63,17 +63,24 @@ class Se3(Module):
"""
super().__init__()
KORNIA_CHECK_TYPE(rotation, So3)
+ # KORNIA_CHECK_TYPE(translation, (Vector3, Tensor))
+ if not isinstance(translation, (Vector3, Tensor)):
+ raise TypeError(f"translation type is {type(translation)}")
# KORNIA_CHECK_SHAPE(t, ["B", "3"]) # FIXME: resolve shape bugs. @edgarriba
- self._rotation = rotation
- self._translation = Parameter(translation)
+ self._translation: Vector3 | Parameter
+ self._rotation: So3 = rotation
+ if isinstance(translation, Tensor):
+ self._translation = Parameter(translation)
+ else:
+ self._translation = translation
def __repr__(self) -> str:
return f"rotation: {self.r}\ntranslation: {self.t}"
- def __getitem__(self, idx: Union[int, slice]) -> 'Se3':
+ def __getitem__(self, idx: int | slice) -> Se3:
return Se3(self._rotation[idx], self._translation[idx])
- def __mul__(self, right: "Se3") -> "Se3":
+ def __mul__(self, right: Se3) -> Se3 | Vector3 | Tensor:
"""Compose two Se3 transformations.
Args:
@@ -85,15 +92,13 @@ class Se3(Module):
so3 = self.so3
t = self.t
if isinstance(right, Se3):
- KORNIA_CHECK_TYPE(right, Se3)
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/se3.py#L97
_r = so3 * right.so3
_t = t + so3 * right.t
return Se3(_r, _t)
- elif isinstance(right, Tensor):
- KORNIA_CHECK_TYPE(right, Tensor)
+ elif isinstance(right, (Vector3, Tensor)):
# KORNIA_CHECK_SHAPE(right, ["B", "N"]) # FIXME: resolve shape bugs. @edgarriba
- return so3 * right + t
+ return so3 * right + t.data
else:
raise TypeError(f"Unsupported type: {type(right)}")
@@ -108,7 +113,7 @@ class Se3(Module):
return self._rotation
@property
- def t(self) -> Tensor:
+ def t(self) -> Vector3 | Parameter:
"""Return the underlying translation vector of shape :math:`(B,3)`."""
return self._translation
@@ -118,12 +123,12 @@ class Se3(Module):
return self._rotation
@property
- def translation(self) -> Tensor:
+ def translation(self) -> Vector3 | Parameter:
"""Return the underlying translation vector of shape :math:`(B,3)`."""
return self._translation
@staticmethod
- def exp(v: Tensor) -> 'Se3':
+ def exp(v: Tensor) -> Se3:
"""Converts elements of lie algebra to elements of lie group.
Args:
@@ -165,6 +170,7 @@ class Se3(Module):
"""
omega = self.r.log()
theta = batched_dot_product(omega, omega).sqrt()
+ t = self.t.data
omega_hat = So3.hat(omega)
omega_hat_sq = omega_hat @ omega_hat
V_inv = (
@@ -172,7 +178,7 @@ class Se3(Module):
- 0.5 * omega_hat
+ ((1 - theta * (theta / 2).cos() / (2 * (theta / 2).sin())) / theta.pow(2))[..., None, None] * omega_hat_sq
)
- t = where(theta[..., None] != 0.0, (self.t[..., None, :] * V_inv).sum(-1), self.t)
+ t = where(theta[..., None] != 0.0, (t[..., None, :] * V_inv).sum(-1), t)
return concatenate((t, omega), -1)
@staticmethod
@@ -221,7 +227,7 @@ class Se3(Module):
return concatenate((head, tail), -1)
@classmethod
- def identity(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> 'Se3':
+ def identity(cls, batch_size: int | None = None, device: Device | None = None, dtype: Dtype = None) -> Se3:
"""Create a Se3 group representing an identity rotation and zero translation.
Args:
@@ -233,14 +239,15 @@ class Se3(Module):
Parameter containing:
tensor([1., 0., 0., 0.], requires_grad=True)
>>> s.t
- Parameter containing:
- tensor([0., 0., 0.], requires_grad=True)
+ x: 0.0
+ y: 0.0
+ z: 0.0
"""
t = tensor([0.0, 0.0, 0.0], device=device, dtype=dtype)
if batch_size is not None:
t = t.repeat(batch_size, 1)
- return cls(So3.identity(batch_size, device, dtype), t)
+ return cls(So3.identity(batch_size, device, dtype), Vector3(t))
def matrix(self) -> Tensor:
"""Returns the matrix representation of shape :math:`(B, 4, 4)`.
@@ -253,12 +260,12 @@ class Se3(Module):
[0., 0., 1., 1.],
[0., 0., 0., 1.]], grad_fn=<CopySlices>)
"""
- rt = concatenate((self.r.matrix(), self.t[..., None]), -1)
+ rt = concatenate((self.r.matrix(), self.t.data[..., None]), -1)
rt_4x4 = pad(rt, (0, 0, 0, 1)) # add last row zeros
rt_4x4[..., -1, -1] = 1.0
return rt_4x4
- def inverse(self) -> 'Se3':
+ def inverse(self) -> Se3:
"""Returns the inverse transformation.
Example:
@@ -275,7 +282,7 @@ class Se3(Module):
return Se3(r_inv, r_inv * (-1 * self.t))
@classmethod
- def random(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> 'Se3':
+ def random(cls, batch_size: int | None = None, device: Device | None = None, dtype: Dtype = None) -> Se3:
"""Create a Se3 group representing a random transformation.
Args:
@@ -285,17 +292,18 @@ class Se3(Module):
>>> s = Se3.random()
>>> s = Se3.random(batch_size=3)
"""
- r = So3.random(batch_size, device, dtype)
- shape: Tuple[int, ...]
+ shape: tuple[int, ...]
if batch_size is None:
- shape = (3,)
+ shape = ()
else:
KORNIA_CHECK(batch_size >= 1, msg="batch_size must be positive")
- shape = (batch_size, 3)
- return cls(r, rand(shape, device=device, dtype=dtype))
+ shape = (batch_size,)
+ r = So3.random(batch_size, device, dtype)
+ t = Vector3.random(shape, device, dtype)
+ return cls(r, t)
@classmethod
- def rot_x(cls, x: Tensor) -> "Se3":
+ def rot_x(cls, x: Tensor) -> Se3:
"""Construct a x-axis rotation.
Args:
@@ -305,7 +313,7 @@ class Se3(Module):
return cls(So3.rot_x(x), stack((zs, zs, zs), -1))
@classmethod
- def rot_y(cls, y: Tensor) -> "Se3":
+ def rot_y(cls, y: Tensor) -> Se3:
"""Construct a y-axis rotation.
Args:
@@ -315,7 +323,7 @@ class Se3(Module):
return cls(So3.rot_y(y), stack((zs, zs, zs), -1))
@classmethod
- def rot_z(cls, z: Tensor) -> "Se3":
+ def rot_z(cls, z: Tensor) -> Se3:
"""Construct a z-axis rotation.
Args:
@@ -325,7 +333,7 @@ class Se3(Module):
return cls(So3.rot_z(z), stack((zs, zs, zs), -1))
@classmethod
- def trans(cls, x: Tensor, y: Tensor, z: Tensor) -> "Se3":
+ def trans(cls, x: Tensor, y: Tensor, z: Tensor) -> Se3:
"""Construct a translation only Se3 instance.
Args:
@@ -341,7 +349,7 @@ class Se3(Module):
return cls(rotation, stack((x, y, z), -1))
@classmethod
- def trans_x(cls, x: Tensor) -> "Se3":
+ def trans_x(cls, x: Tensor) -> Se3:
"""Construct a x-axis translation.
Args:
@@ -351,7 +359,7 @@ class Se3(Module):
return cls.trans(x, zs, zs)
@classmethod
- def trans_y(cls, y: Tensor) -> "Se3":
+ def trans_y(cls, y: Tensor) -> Se3:
"""Construct a y-axis translation.
Args:
@@ -361,7 +369,7 @@ class Se3(Module):
return cls.trans(zs, y, zs)
@classmethod
- def trans_z(cls, z: Tensor) -> "Se3":
+ def trans_z(cls, z: Tensor) -> Se3:
"""Construct a z-axis translation.
Args:
diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.py
index 4cf862dcf..4f65774e9 100644
--- a/kornia/geometry/liegroup/so2.py
+++ b/kornia/geometry/liegroup/so2.py
@@ -1,6 +1,8 @@
# kornia.geometry.so2 module inspired by Sophus-sympy.
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so2.py
-from typing import Optional, Union, overload
+from __future__ import annotations
+
+from typing import overload
from kornia.core import Device, Dtype, Module, Parameter, Tensor, complex, rand, stack, tensor, zeros_like
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
@@ -10,6 +12,7 @@ from kornia.geometry.liegroup._utils import (
check_so2_theta_shape,
check_so2_z_shape,
)
+from kornia.geometry.vector import Vector2
class So2(Module):
@@ -53,11 +56,11 @@ class So2(Module):
def __repr__(self) -> str:
return f"{self.z}"
- def __getitem__(self, idx: Union[int, slice]) -> 'So2':
+ def __getitem__(self, idx: int | slice) -> So2:
return So2(self._z[idx])
@overload
- def __mul__(self, right: 'So2') -> 'So2':
+ def __mul__(self, right: So2) -> So2:
...
@overload
@@ -76,14 +79,19 @@ class So2(Module):
z = self.z
if isinstance(right, So2):
return So2(z * right.z)
- elif isinstance(right, Tensor):
+ elif isinstance(right, (Vector2, Tensor)):
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
- check_so2_t_shape(right)
- x = right[..., 0]
- y = right[..., 1]
+ if isinstance(right, Tensor):
+ check_so2_t_shape(right)
+ x = right.data[..., 0]
+ y = right.data[..., 1]
real = z.real
imag = z.imag
- return stack((real * x - imag * y, imag * x + real * y), -1)
+ out = stack((real * x - imag * y, imag * x + real * y), -1)
+ if isinstance(right, Tensor):
+ return out
+ else:
+ return Vector2(out)
else:
raise TypeError(f"Not So2 or Tensor type. Got: {type(right)}")
@@ -93,7 +101,7 @@ class So2(Module):
return self._z
@staticmethod
- def exp(theta: Tensor) -> 'So2':
+ def exp(theta: Tensor) -> So2:
"""Converts elements of lie algebra to elements of lie group.
Args:
@@ -173,7 +181,7 @@ class So2(Module):
return stack((row0, row1), -2)
@classmethod
- def from_matrix(cls, matrix: Tensor) -> 'So2':
+ def from_matrix(cls, matrix: Tensor) -> So2:
"""Create So2 from a rotation matrix.
Args:
@@ -192,7 +200,7 @@ class So2(Module):
return cls(z)
@classmethod
- def identity(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> 'So2':
+ def identity(cls, batch_size: int | None = None, device: Device | None = None, dtype: Dtype = None) -> So2:
"""Create a So2 group representing an identity rotation.
Args:
@@ -212,7 +220,7 @@ class So2(Module):
imag_data = imag_data.repeat(batch_size)
return cls(complex(real_data, imag_data))
- def inverse(self) -> 'So2':
+ def inverse(self) -> So2:
"""Returns the inverse transformation.
Example:
@@ -224,7 +232,7 @@ class So2(Module):
return So2(1 / self.z)
@classmethod
- def random(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> 'So2':
+ def random(cls, batch_size: int | None = None, device: Device | None = None, dtype: Dtype = None) -> So2:
"""Create a So2 group representing a random rotation.
Args:
diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.py
index 615f15056..175f54a3d 100644
--- a/kornia/geometry/liegroup/so3.py
+++ b/kornia/geometry/liegroup/so3.py
@@ -1,11 +1,12 @@
# kornia.geometry.so3 module inspired by Sophus-sympy.
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py
-from typing import Optional, Union
+from __future__ import annotations
from kornia.core import Device, Dtype, Module, Tensor, concatenate, stack, tensor, where, zeros, zeros_like
from kornia.core.check import KORNIA_CHECK_TYPE
from kornia.geometry.linalg import batched_dot_product
from kornia.geometry.quaternion import Quaternion
+from kornia.geometry.vector import Vector3
class So3(Module):
@@ -48,7 +49,7 @@ class So3(Module):
def __repr__(self) -> str:
return f"{self.q}"
- def __getitem__(self, idx: Union[int, slice]) -> 'So3':
+ def __getitem__(self, idx: int | slice) -> So3:
return So3(self._q[idx])
def __mul__(self, right):
@@ -63,11 +64,15 @@ class So3(Module):
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py#L98
if isinstance(right, So3):
return So3(self.q * right.q)
- elif isinstance(right, Tensor):
+ elif isinstance(right, (Tensor, Vector3)):
# KORNIA_CHECK_SHAPE(right, ["B", "3"]) # FIXME: resolve shape bugs. @edgarriba
w = zeros(*right.shape[:-1], 1, device=right.device, dtype=right.dtype)
- quat = Quaternion(concatenate((w, right), -1))
- return (self.q * quat * self.q.conj()).vec
+ quat = Quaternion(concatenate((w, right.data), -1))
+ out = (self.q * quat * self.q.conj()).vec
+ if isinstance(right, Tensor):
+ return out
+ elif isinstance(right, Vector3):
+ return Vector3(out)
else:
raise TypeError(f"Not So3 or Tensor type. Got: {type(right)}")
@@ -77,7 +82,7 @@ class So3(Module):
return self._q
@staticmethod
- def exp(v: Tensor) -> 'So3':
+ def exp(v: Tensor) -> So3:
"""Converts elements of lie algebra to elements of lie group.
See more: https://vision.in.tum.de/_media/members/demmeln/nurlanov2021so3log.pdf
@@ -125,11 +130,11 @@ class So3(Module):
return omega
@staticmethod
- def hat(v: Tensor) -> Tensor:
+ def hat(v: Vector3 | Tensor) -> Tensor:
"""Converts elements from vector space to lie algebra. Returns matrix of shape :math:`(B,3,3)`.
Args:
- v: vector of shape :math:`(B,3)`.
+ v: Vector3 or tensor of shape :math:`(B,3)`.
Example:
>>> v = torch.ones((1,3))
@@ -140,7 +145,10 @@ class So3(Module):
[-1., 1., 0.]]])
"""
# KORNIA_CHECK_SHAPE(v, ["B", "3"]) # FIXME: resolve shape bugs. @edgarriba
- a, b, c = v[..., 0], v[..., 1], v[..., 2]
+ if isinstance(v, Tensor):
+ a, b, c = v[..., 0], v[..., 1], v[..., 2]
+ else:
+ a, b, c = v.x, v.y, v.z
z = zeros_like(a)
row0 = stack((z, -c, b), -1)
row1 = stack((c, z, -a), -1)
@@ -204,7 +212,7 @@ class So3(Module):
return stack((row0, row1, row2), -2)
@classmethod
- def from_matrix(cls, matrix: Tensor) -> 'So3':
+ def from_matrix(cls, matrix: Tensor) -> So3:
"""Create So3 from a rotation matrix.
Args:
@@ -220,7 +228,7 @@ class So3(Module):
return cls(Quaternion.from_matrix(matrix))
@classmethod
- def identity(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> 'So3':
+ def identity(cls, batch_size: int | None = None, device: Device | None = None, dtype: Dtype = None) -> So3:
"""Create a So3 group representing an identity rotation.
Args:
@@ -240,7 +248,7 @@ class So3(Module):
"""
return cls(Quaternion.identity(batch_size, device, dtype))
- def inverse(self) -> 'So3':
+ def inverse(self) -> So3:
"""Returns the inverse transformation.
Example:
@@ -252,7 +260,7 @@ class So3(Module):
return So3(self.q.conj())
@classmethod
- def random(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> 'So3':
+ def random(cls, batch_size: int | None = None, device: Device | None = None, dtype: Dtype = None) -> So3:
"""Create a So3 group representing a random rotation.
Args:
@@ -265,7 +273,7 @@ class So3(Module):
return cls(Quaternion.random(batch_size, device, dtype))
@classmethod
- def rot_x(cls, x: Tensor) -> "So3":
+ def rot_x(cls, x: Tensor) -> So3:
"""Construct a x-axis rotation.
Args:
@@ -275,7 +283,7 @@ class So3(Module):
return cls.exp(stack((x, zs, zs), -1))
@classmethod
- def rot_y(cls, y: Tensor) -> "So3":
+ def rot_y(cls, y: Tensor) -> So3:
"""Construct a z-axis rotation.
Args:
@@ -285,7 +293,7 @@ class So3(Module):
return cls.exp(stack((zs, y, zs), -1))
@classmethod
- def rot_z(cls, z: Tensor) -> "So3":
+ def rot_z(cls, z: Tensor) -> So3:
"""Construct a z-axis rotation.
Args:
diff --git a/test/geometry/liegroup/test_se2.py b/test/geometry/liegroup/test_se2.py
index d58f21017..b443b3f12 100644
--- a/test/geometry/liegroup/test_se2.py
+++ b/test/geometry/liegroup/test_se2.py
@@ -2,6 +2,7 @@ import pytest
import torch
from kornia.geometry.liegroup import Se2, So2
+from kornia.geometry.vector import Vector2
from kornia.testing import BaseTester
@@ -120,6 +121,26 @@ class TestSe2(BaseTester):
self.assert_close(s2_pose_s2.r.z.imag, so2_expected.z.imag)
self.assert_close(s2_pose_s2.t, zeros_vec)
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
+ def test_mul_vector(self, device, dtype, batch_size):
+ s1 = Se2.identity(batch_size, device, dtype)
+ if batch_size is None:
+ shape = ()
+ else:
+ shape = (batch_size,)
+ s2 = Se2(So2.identity(batch_size, device, dtype), Vector2.random(shape, device, dtype))
+ s1_pose_s2 = s1 * s2
+ s2_pose_s2 = s2 * s2.inverse()
+ zeros_vec = torch.zeros(2, device=device, dtype=dtype)
+ if batch_size is not None:
+ zeros_vec = zeros_vec.repeat(batch_size, 1)
+ so2_expected = So2.identity(batch_size, device, dtype)
+ self.assert_close(s1_pose_s2.r.z, s2.r.z)
+ self.assert_close(s1_pose_s2.t, s2.t)
+ self.assert_close(s2_pose_s2.r.z.real, so2_expected.z.real)
+ self.assert_close(s2_pose_s2.r.z.imag, so2_expected.z.imag)
+ self.assert_close(s2_pose_s2.t, zeros_vec)
+
@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_exp(self, device, dtype, batch_size):
t = self._make_rand_data(device, dtype, (batch_size, 2))
diff --git a/test/geometry/liegroup/test_se3.py b/test/geometry/liegroup/test_se3.py
index 93bf61043..054e57778 100644
--- a/test/geometry/liegroup/test_se3.py
+++ b/test/geometry/liegroup/test_se3.py
@@ -4,6 +4,7 @@ import torch
from kornia.geometry.conversions import QuaternionCoeffOrder, euler_from_quaternion, rotation_matrix_to_quaternion
from kornia.geometry.liegroup import Se3, So3
from kornia.geometry.quaternion import Quaternion
+from kornia.geometry.vector import Vector3
from kornia.testing import BaseTester
@@ -13,6 +14,15 @@ class TestSe3(BaseTester):
t = self._make_rand_data(device, dtype, batch_size, dims=3)
return Se3(So3(q), t)
+ def _make_rand_se3d_vec(self, device, dtype, batch_size) -> Se3:
+ q = Quaternion.random(batch_size, device, dtype)
+ if batch_size is None:
+ shape = ()
+ else:
+ shape = (batch_size,)
+ t = Vector3.random(shape, device, dtype)
+ return Se3(So3(q), t)
+
def _make_rand_data(self, device, dtype, batch_size, dims):
shape = [] if batch_size is None else [batch_size]
return torch.rand(shape + [dims], device=device, dtype=dtype)
@@ -94,6 +104,35 @@ class TestSe3(BaseTester):
self.assert_close(pt_in_s1, pt_in_s2_in_s1)
self.assert_close(pt_in_s2, pt_in_s1_in_s2)
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
+ def test_mul_vector(self, device, dtype, batch_size):
+ world_pose_s1: Se3 = self._make_rand_se3d(device, dtype, batch_size)
+ world_pose_s2: Se3 = self._make_rand_se3d_vec(device, dtype, batch_size)
+ if batch_size is None:
+ shape = ()
+ else:
+ shape = (batch_size,)
+ pt_in_world = Vector3.random(shape, device, dtype)
+ s1_pose_s2: Se3 = world_pose_s1.inverse() * world_pose_s2
+ pt_in_s1 = world_pose_s1.inverse() * pt_in_world
+ pt_in_s2 = world_pose_s2.inverse() * pt_in_world
+ pt_in_s1_in_s2 = s1_pose_s2.inverse() * pt_in_s1
+ pt_in_s2_in_s1 = s1_pose_s2 * pt_in_s2
+ s3 = Se3.identity(batch_size, device, dtype)
+ s4: Se3 = self._make_rand_se3d_vec(device, dtype, batch_size)
+ s3s4 = s3 * s4
+ s4s4inv = s4 * s4.inverse()
+ zeros_vec = torch.zeros(3, device=device, dtype=dtype)
+ if batch_size is not None:
+ zeros_vec = zeros_vec.repeat(batch_size, 1)
+ so3_expected = So3.identity(batch_size, device, dtype)
+ self.assert_close(pt_in_s1, pt_in_s2_in_s1)
+ self.assert_close(pt_in_s2, pt_in_s1_in_s2)
+ self.assert_close(s3s4.r.q.data, s4.r.q.data)
+ self.assert_close(s3s4.t, s4.t)
+ self.assert_close(s4s4inv.r.q.data, so3_expected.q.data)
+ self.assert_close(s4s4inv.t, zeros_vec)
+
@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_exp(self, device, dtype, batch_size):
omega = torch.zeros(3, device=device, dtype=dtype)
diff --git a/test/geometry/liegroup/test_so2.py b/test/geometry/liegroup/test_so2.py
index 9f1c996cf..767ef86f0 100644
--- a/test/geometry/liegroup/test_so2.py
+++ b/test/geometry/liegroup/test_so2.py
@@ -2,6 +2,7 @@ import pytest
import torch
from kornia.geometry.liegroup import So2
+from kornia.geometry.vector import Vector2
from kornia.testing import BaseTester
@@ -120,6 +121,18 @@ class TestSo2(BaseTester):
self.assert_close((s1 * t1), t1)
self.assert_close((So2.identity(device=device, dtype=dtype) * t2), t2)
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
+ def test_mul_vector(self, device, dtype, batch_size):
+ s1 = So2.identity(batch_size, device, dtype)
+ if batch_size is None:
+ shape = ()
+ else:
+ shape = (batch_size,)
+ t1 = Vector2.random(shape, device, dtype)
+ t2 = Vector2.random(shape, device, dtype)
+ self.assert_close((s1 * t1), t1)
+ self.assert_close((So2.identity(device=device, dtype=dtype) * t2), t2)
+
@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_exp(self, device, dtype, batch_size):
theta = self._make_rand_data(device, dtype, (batch_size, 1))
diff --git a/test/geometry/liegroup/test_so3.py b/test/geometry/liegroup/test_so3.py
index 1facd354c..b80de73b5 100644
--- a/test/geometry/liegroup/test_so3.py
+++ b/test/geometry/liegroup/test_so3.py
@@ -4,6 +4,7 @@ import torch
from kornia.geometry.conversions import euler_from_quaternion
from kornia.geometry.liegroup import So3
from kornia.geometry.quaternion import Quaternion
+from kornia.geometry.vector import Vector3
from kornia.testing import BaseTester
@@ -66,6 +67,21 @@ class TestSo3(BaseTester):
self.assert_close((s2 * s2.inverse()).q.data, s1.q.data)
self.assert_close((s1 * t), t)
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
+ def test_mul_vec(self, device, dtype, batch_size):
+ q1 = Quaternion.identity(batch_size, device, dtype)
+ q2 = Quaternion.random(batch_size, device, dtype)
+ if batch_size is None:
+ shape = ()
+ else:
+ shape = (batch_size,)
+ t = Vector3.random(shape, device, dtype)
+ s1 = So3(q1)
+ s2 = So3(q2)
+ self.assert_close((s1 * s2).q.data, s2.q.data)
+ self.assert_close((s2 * s2.inverse()).q.data, s1.q.data)
+ self.assert_close((s1 * t), t)
+
@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
def test_unit_norm(self, device, dtype, batch_size):
q1 = Quaternion.random(batch_size, device, dtype)