π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Add `TensorWrapper`, `Vector3`, `Scalar` and improvements in `fit_plane` (#1987)
Edgar Ribacee1c8f23ede
diff --git a/kornia/core/_backend.py b/kornia/core/_backend.pyindex 17de053a3..71a29ceca 100644--- a/kornia/core/_backend.py+++ b/kornia/core/_backend.py@@ -11,6 +11,7 @@ Module = torch.nn.ModuleParameter = torch.nn.Parameter# functions+# NOTE: ideally we expose what we find in numpyconcatenate = torch.catstack = torch.stacknormalize = F.normalizediff --git a/kornia/core/tensor_wrapper.py b/kornia/core/tensor_wrapper.pynew file mode 100644index 000000000..029f403cf--- /dev/null+++ b/kornia/core/tensor_wrapper.py@@ -0,0 +1,146 @@+# pytorch tensor wrapper class+# insipired by:+# https://github.com/pytorch/pytorch/blob/591dfffa38848de54b7f5f4e49260847024c9281/test/test_overrides.py#L748+import collections+from typing import Any++import torch+from torch import Tensor++# wrap inputs if necessary++# TODO: promote to KORNIA_WRAP+++def wrap(v, cls):+ if type(v) in {tuple, list}:+ return type(v)(wrap(vi, cls) for vi in v)++ return cls(v) if isinstance(v, Tensor) else v+++# TODO: promote to KORNIA_UNWRAP+++def unwrap(v):+ if type(v) in {tuple, list}:+ return type(v)(unwrap(vi) for vi in v)++ return v._data if not isinstance(v, Tensor) else v+++class TensorWrapper:+ def __init__(self, data: Tensor) -> None:+ self.__dict__["_data"] = data+ self.__dict__["used_attrs"] = set()+ self.__dict__["used_calls"] = set()++ @property+ def data(self) -> Tensor:+ return self._data++ def __repr__(self) -> str:+ return f"{self.data}"++ def __getattr__(self, name):+ if name in self.__dict__:+ return self.__dict__[name]+ self.used_attrs.add(name)++ val = getattr(self._data, name)++ # NOTE: not clear is really needed+ # If it's a method+ # if callable(val):+ # c = getattr(type(self._data), name)+ # # Don't append self to args if classmethod/staticmethod+ # if c is val:+ # return lambda *a, **kw: wrap(self.__torch_function__(c, (type(self),), args=a, kwargs=kw), type(self))+ # # Otherwise append self to args+ # return lambda *a, **kw: wrap(+ # #self.__torch_function__(c, (type(self),), args=(self,) + a, kwargs=kw), type(self)+ # )++ return wrap(val, type(self))++ def __setattr__(self, name, value):+ if name in self.__dict__:+ self.__dict__[name] = value++ self.used_attrs.add(name)+ setattr(self._data, name, value)++ def __setitem__(self, key, value):+ self._data[key] = value++ def __getitem__(self, key):+ return wrap(self._data[key], type(self))++ @classmethod+ def __torch_function__(cls, func, types, args=(), kwargs=None):+ if kwargs is None:+ kwargs = {}+ # Find an instance of this class in the arguments+ args_of_this_cls = []+ for a in args:+ if isinstance(a, cls):+ args_of_this_cls.append(a)+ elif isinstance(a, collections.abc.Sequence):+ args_of_this_cls.extend(el for el in a if isinstance(el, cls))+ # assert len(args_of_this_cls) > 0+ for a in args_of_this_cls:+ a.used_calls.add(func)+ args = unwrap(tuple(args))+ kwargs = {k: unwrap(v) for k, v in kwargs.items()}++ return wrap(func(*args, **kwargs), cls)++ # TODO: `def __add__(self, other) -> Self:` when mypy release >0.991+ def __add__(self, other):+ return self.__unary_op__(torch.add, other)++ def __mul__(self, other):+ return self.__unary_op__(torch.mul, other)++ def __sub__(self, other):+ return self.__unary_op__(torch.sub, other)++ def __truediv__(self, other):+ return self.__unary_op__(torch.true_divide, other)++ def __floordiv__(self, other):+ return self.__unary_op__(torch.floor_divide, other)++ def __ge__(self, other):+ return self.__unary_op__(torch.ge, other)++ def __gt__(self, other):+ return self.__unary_op__(torch.gt, other)++ def __lt__(self, other):+ return self.__unary_op__(torch.lt, other)++ def __le__(self, other):+ return self.__unary_op__(torch.le, other)++ def __eq__(self, other):+ return self.__unary_op__(torch.eq, other)++ def __ne__(self, other):+ return self.__unary_op__(torch.ne, other)++ def __bool__(self):+ return self.__unary_op__(Tensor.__bool__)++ def __int__(self):+ return self.__unary_op__(Tensor.__int__)++ def __neg__(self):+ return self.__unary_op__(Tensor.negative)++ def __unary_op__(self, func: Any, other=None):+ args = (self, other) if other is not None else (self,)+ return self.__torch_function__(func, (type(self),), args)++ def __len__(self):+ return len(self._data)diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.pyindex 8998221c5..640d7a7c3 100644--- a/kornia/geometry/linalg.py+++ b/kornia/geometry/linalg.py@@ -1,10 +1,9 @@import torchfrom torch import Tensor+from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneousfrom kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE, check_is_tensor-from .conversions import convert_points_from_homogeneous, convert_points_to_homogeneous-__all__ = ["compose_transformations","relative_transformation",@@ -229,12 +228,12 @@ def point_line_distance(point: Tensor, line: Tensor, eps: float = 1e-9) -> Tensodef batched_dot_product(x: Tensor, y: Tensor, keepdim: bool = False) -> Tensor:"""Return a batched version of .dot()"""- # KORNIA_CHECK_SHAPE(x, ["B", "N"]) # FIXME: resolve shape bugs. @edgarriba- # KORNIA_CHECK_SHAPE(y, ["B", "N"]) # FIXME: resolve shape bugs. @edgarriba+ KORNIA_CHECK_SHAPE(x, ["*", "N"])+ KORNIA_CHECK_SHAPE(y, ["*", "N"])return (x * y).sum(-1, keepdim)-def squared_norm(x: Tensor, keepdim: bool = False) -> Tensor:+def batched_squared_norm(x: Tensor, keepdim: bool = False) -> Tensor:"""Return the squared norm of a vector."""return batched_dot_product(x, x, keepdim)@@ -243,7 +242,6 @@ def euclidean_distance(x: Tensor, y: Tensor, keepdim: bool = False, eps: float ="""Compute the Euclidean distance between two set of n-dimensional points.More: https://en.wikipedia.org/wiki/Euclidean_distance-Args:x: first set of points of shape :math:`(*, N)`.y: second set of points of shape :math:`(*, N)`.@@ -258,7 +256,7 @@ def euclidean_distance(x: Tensor, y: Tensor, keepdim: bool = False, eps: float =# aliases-batched_squared_norm = squared_norm+squared_norm = batched_squared_norm# TODO:# - project_points: from opencvdiff --git a/kornia/geometry/line.py b/kornia/geometry/line.pyindex a034690d7..7bc729dbd 100644--- a/kornia/geometry/line.py+++ b/kornia/geometry/line.py@@ -141,13 +141,13 @@ class ParametrizedLine(Module):- the lambda value used to compute the look at point.- the intersected point."""- dot_prod = batched_dot_product(plane.normal, self.direction)+ dot_prod = batched_dot_product(plane.normal.data, self.direction.data)dot_prod_mask = dot_prod.abs() >= eps# TODO: add check for dot productres_lambda = where(dot_prod_mask,- -(plane.offset + batched_dot_product(plane.normal, self.origin)) / dot_prod,+ -(plane.offset + batched_dot_product(plane.normal.data, self.origin.data)) / dot_prod,torch.empty_like(dot_prod),)diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.pyindex a9e4a499f..6796fdc81 100644--- a/kornia/geometry/plane.py+++ b/kornia/geometry/plane.py@@ -3,27 +3,28 @@from typing import Optional-from kornia.core import Module, Tensor, normalize+from kornia.core import Module, Tensor, stack, where+from kornia.core.tensor_wrapper import unwrap, wrapfrom kornia.geometry.linalg import batched_dot_product-from kornia.testing import KORNIA_CHECK_SHAPE+from kornia.geometry.vector import Scalar, Vector3+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPEfrom kornia.utils.helpers import _torch_svd_cast__all__ = ["Hyperplane", "fit_plane"]-# NOTE: in the near future the constructor will change-# class Hyperplane(Module):-# def __init__(self, n: _VectorType, d: _VectorType) -> None:-# super().__init__()-# self._n = n-# self._d = d+def normalized(v: Tensor, eps: float = 1e-6) -> Tensor:+ return v / batched_dot_product(v, v).add(eps).sqrt()class Hyperplane(Module):- def __init__(self, n: Tensor, d: Tensor) -> None:+ def __init__(self, n: Vector3, d: Scalar) -> None:super().__init__()- # KORNIA_CHECK_SHAPE(n, ["B", "*"]) # FIXME: resolve shape bugs. @edgarriba- # KORNIA_CHECK_SHAPE(d, ["B"]) # FIXME: resolve shape bugs. @edgarriba+ KORNIA_CHECK_TYPE(n, Vector3)+ KORNIA_CHECK_TYPE(d, Scalar)+ # TODO: fix checkers+ # KORNIA_CHECK_SHAPE(n, ["B", "*"])+ # KORNIA_CHECK_SHAPE(d, ["B"])self._n = nself._d = d@@ -33,74 +34,99 @@ class Hyperplane(Module):def __repr__(self) -> str:return str(self)- def __getitem__(self, idx) -> Tensor:- return self.normal if idx == 0 else self.offset-- def __iter__(self):- yield from (self.normal, self.offset)-@property- def normal(self) -> Tensor:+ def normal(self) -> Vector3:return self._n@property- def offset(self) -> Tensor:+ def offset(self) -> Scalar:return self._d+ def abs_distance(self, p: Vector3) -> Scalar:+ return Scalar(self.signed_distance(p).abs())++ # https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h#L145+ # TODO: tests+ def signed_distance(self, p: Vector3) -> Scalar:+ KORNIA_CHECK(isinstance(p, (Vector3, Tensor)))+ return self.normal.dot(p) + self.offset++ # https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h#L154+ # TODO: tests+ def projection(self, p: Vector3) -> Vector3:+ dist = self.signed_distance(p)+ if len(dist.shape) != len(self.normal):+ # non batched plane project a batch of points+ dist = dist[..., None] # Nx1+ # TODO: TypeError: bad operand type for unary -: 'Scalar'+ return p - dist.data * self.normal+ # TODO: make that Vector can subtract Scalar+ # return p - self.signed_distance(p) * self.normal+@classmethod- def from_vector(self, n: Tensor, e: Tensor) -> "Hyperplane":- normal = n- offset = -batched_dot_product(normal, e)- return Hyperplane(normal, offset)+ def from_vector(self, n: Vector3, e: Vector3) -> "Hyperplane":+ normal: Vector3 = n+ offset = -normal.dot(e)+ return Hyperplane(normal, Scalar(offset))@classmethoddef through(cls, p0: Tensor, p1: Tensor, p2: Optional[Tensor] = None) -> "Hyperplane":# 2d caseif p2 is None:- KORNIA_CHECK_SHAPE(p0, ["B", "2"])- KORNIA_CHECK_SHAPE(p1, ["B", "2"])+ # TODO: improve tests+ KORNIA_CHECK_SHAPE(p0, ["*", "2"])+ KORNIA_CHECK(p0.shape == p1.shape)# TODO: implement `.unitOrthonormal`- normal = normalize((p1 - p0), p=2, dim=-1)- offset = -batched_dot_product(p0, normal)- return Hyperplane(normal, offset)+ normal2d = normalized(p1 - p0)+ offset2d = -batched_dot_product(p0, normal2d)+ return Hyperplane(wrap(normal2d, Vector3), wrap(offset2d, Scalar))# 3d case- # KORNIA_CHECK_SHAPE(p0, ["B", "3"]) # FIXME: resolve shape bugs. @edgarriba- # KORNIA_CHECK_SHAPE(p1, ["B", "3"]) # FIXME: resolve shape bugs. @edgarriba- # KORNIA_CHECK_SHAPE(p2, ["B", "3"]) # FIXME: resolve shape bugs. @edgarriba- v0, v1 = (p2 - p1), (p1 - p0)+ KORNIA_CHECK_SHAPE(p0, ["*", "3"])+ KORNIA_CHECK(p0.shape == p1.shape)+ KORNIA_CHECK(p1.shape == p2.shape)+ v0, v1 = (p2 - p0), (p1 - p0)normal = v0.cross(v1)norm = normal.norm(-1)- # TODO: use where+# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h#L108- # general case- normal = normal / (norm + 1e-6)+ def compute_normal_svd(v0, v1):+ # NOTE: for reason TensorWrapper does not stack well+ m = stack((unwrap(v0), unwrap(v1)), -2) # Bx2x3+ _, _, V = _torch_svd_cast(m) # kornia solution lies in the last row+ return wrap(V[..., :, -1], Vector3) # Bx3++ normal_mask = norm <= v0.norm(-1) * v1.norm(-1) * 1e-6+ normal = where(normal_mask, compute_normal_svd(v0, v1), normal / (norm + 1e-6))offset = -batched_dot_product(p0, normal)- return Hyperplane(normal, offset)++ return Hyperplane(wrap(normal, Vector3), wrap(offset, Scalar))# TODO: factor to avoid duplicated from line.py# https://github.com/strasdat/Sophus/blob/23.04-beta/cpp/sophus/geometry/fit_plane.h-def fit_plane(points: Tensor) -> Hyperplane:+def fit_plane(points: Vector3) -> Hyperplane:"""Fit a plane from a set of points using SVD.Args:points: tensor containing a batch of sets of n-dimensional points. The expected- shape of the tensor is :math:`(B, N, D)`.+ shape of the tensor is :math:`(N, D)`.Return:The computed hyperplane object."""- KORNIA_CHECK_SHAPE(points, ["B", "N", "D"])+ # TODO: fix to support more type check here+ # KORNIA_CHECK_SHAPE(points, ["N", "D"])+ if points.shape[-1] != 3:+ raise TypeError("vector must be (*, 3)")mean = points.mean(-2, True)points_centered = points - mean# NOTE: not optimal for 2d points, but for now works for other dimensions_, _, V = _torch_svd_cast(points_centered)- V = V.transpose(-2, -1)# the first left eigenvector is the direction on the fited line- direction = V[..., 0, :] # BxD+ direction = V[..., :, -1] # BxDorigin = mean[..., 0, :] # BxD- return Hyperplane.from_vector(direction, origin)+ return Hyperplane.from_vector(Vector3(direction), Vector3(origin))diff --git a/kornia/geometry/vector.py b/kornia/geometry/vector.pyindex dba0bad9b..6b37c98d7 100644--- a/kornia/geometry/vector.py+++ b/kornia/geometry/vector.py@@ -1,79 +1,105 @@-from typing import List, Union+from typing import Optional, Tuple, Union, cast-from kornia.core import Module, Parameter, Tensor, normalize, rand-from kornia.geometry.linalg import batched_dot_product-from kornia.geometry.linalg import batched_squared_norm as _squared_norm-from kornia.testing import KORNIA_CHECK_SHAPE+from kornia.core import Tensor, as_tensor, normalize, rand, stack+from kornia.core.tensor_wrapper import TensorWrapper, wrap+from kornia.geometry.linalg import batched_dot_product, batched_squared_norm+from kornia.testing import KORNIA_CHECK-__all__ = ["UnitVector"]+__all__ = ["Vector3", "Scalar"]-# TODO: model _Scalar-class _ScalarType:- pass+# TODO: implement more functionality to validate+class Scalar(TensorWrapper):+ def __init__(self, data: Tensor) -> None:+ super().__init__(data)-# NOTE: not very clear if this is a module or custom Tensor-# tensor subclass doesn't like to override methods-class _VectorType(Module):+class Vector3(TensorWrapper):def __init__(self, vector: Tensor) -> None:- super().__init__()- # KORNIA_CHECK_SHAPE(vector, ["B", "N"]) # FIXME: resolve shape bugs. @edgarriba- self._vector = Parameter(vector)+ super().__init__(vector)+ KORNIA_CHECK(vector.shape[-1] == 3)@property- def data(self) -> Tensor:- return self._vector+ def x(self) -> Tensor:+ return self.data[..., 0]@property- def device(self):- return self.data.device+ def y(self) -> Tensor:+ return self.data[..., 1]@property- def dtype(self):- return self.data.dtype+ def z(self) -> Tensor:+ return self.data[..., 2]- @property- def shape(self):- return self.data.shape-- def __repr__(self) -> str:- return f"{self.data}"-- @classmethod- def random(cls, shape: List[int], device=None, dtype=None) -> "_VectorType":- return cls(rand(shape, device=device, dtype=dtype))-- def normalized(self) -> "_VectorType":- vec_norm = normalize(self._vector, p=2, dim=-1)- return _VectorType(vec_norm)+ def normalized(self) -> "Vector3":+ return Vector3(normalize(self.data, p=2, dim=-1))- def squared_norm(self) -> "_VectorType":- return _VectorType(_squared_norm(self.data))+ def dot(self, right: "Vector3") -> Scalar:+ return Scalar(batched_dot_product(self.data, right.data))- def dot(self, right: "_VectorType") -> "_VectorType":- if len(right.shape) == 1:- return _VectorType(self.data.dot(right.data))- return _VectorType(batched_dot_product(self.data, right.data))---class UnitVector(Module):- def __init__(self, vector: Union[Tensor, _VectorType]) -> None:- super().__init__()- KORNIA_CHECK_SHAPE(vector, ["B", "N"])- if isinstance(vector, Tensor):- self._vector = Parameter(vector)-- @property- def vector(self) -> Tensor:- return self._vector+ def squared_norm(self) -> Scalar:+ return Scalar(batched_squared_norm(self.data))@classmethod- def from_unit_vector(cls, v: Tensor) -> "UnitVector":- # TODO: add checks https://github.com/strasdat/Sophus/blob/23.04-beta/cpp/sophus/geometry/ray.h#L59- return UnitVector(_VectorType(v))+ def random(cls, shape: Optional[Tuple[int, ...]] = None, device=None, dtype=None) -> "Vector3":+ if shape is None:+ shape = ()+ return cls(rand(shape + (3,), device=device, dtype=dtype))++ # TODO: polish overload+ # @overload+ # @classmethod+ # def from_coords(+ # cls, x: Tensor, y: Tensor, z: Tensor, device=None, dtype=None+ # ) -> "Vector3":+ # KORNIA_CHECK(isinstance(x, Tensor))+ # KORNIA_CHECK(type(x) == type(y) == type(z))+ # return wrap(as_tensor((x, y, z), device=device, dtype=dtype), Vector3)++ # TODO: polish overload+ # @overload+ # @classmethod+ # def from_coords(+ # cls, x: float, y: float, z: float, device=None, dtype=None+ # ) -> "Vector3":+ # KORNIA_CHECK(isinstance(x, float))+ # KORNIA_CHECK(type(x) == type(y) == type(z))+ # return wrap(as_tensor((x, y, z), device=device, dtype=dtype), Vector3)@classmethod- def from_vector(cls, v: Tensor) -> "UnitVector":- """From a vector and normalize."""- return UnitVector(_VectorType(v).normalized())+ def from_coords(+ cls, x: Union[float, Tensor], y: Union[float, Tensor], z: Union[float, Tensor], device=None, dtype=None+ ) -> "Vector3":+ KORNIA_CHECK(type(x) == type(y) == type(z))+ KORNIA_CHECK(isinstance(x, (Tensor, float)))+ if isinstance(x, float):+ return wrap(as_tensor((x, y, z), device=device, dtype=dtype), Vector3)+ # TODO: this is totally insane ...+ tensors: Tuple[Tensor, ...] = (x, cast(Tensor, y), cast(Tensor, z))+ return wrap(stack(tensors, -1), Vector3)+++Vec3 = Vector3++# TODO: adapt to TensorWrapper++# class UnitVector(Module):+# def __init__(self, vector: Tensor) -> None:+# super().__init__()+# KORNIA_CHECK_SHAPE(vector, ["B", "N"])+# self._vector = Parameter(vector)+#+# @property+# def vector(self) -> Tensor:+# return self._vector+#+# @classmethod+# def from_unit_vector(cls, v: Tensor) -> "UnitVector":+# # TODO: add checks https://github.com/strasdat/Sophus/blob/23.04-beta/cpp/sophus/geometry/ray.h#L59+# return UnitVector(_VectorType(v))+#+# @classmethod+# def from_vector(cls, v: Tensor) -> "UnitVector":+# """From a vector and normalize."""+# return UnitVector(_VectorType(v).normalized())+#diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.pyindex 2d80b870d..988aa4880 100644--- a/kornia/losses/total_variation.py+++ b/kornia/losses/total_variation.py@@ -29,6 +29,10 @@ def total_variation(img: Tensor, reduction: str = "sum") -> Tensor:Reference:[1] https://en.wikipedia.org/wiki/Total_variation"""+ # TODO: here torchscript doesn't like KORNIA_CHECK_TYPE+ if not isinstance(img, Tensor):+ raise TypeError(f"Not a Tensor type. Got: {type(img)}")+KORNIA_CHECK_SHAPE(img, ["*", "H", "W"])KORNIA_CHECK(reduction in ("mean", "sum"), f"Expected reduction to be one of 'mean'/'sum', but got '{reduction}'.")diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.pyindex 44f65cad5..4092fe745 100644--- a/kornia/testing/__init__.py+++ b/kornia/testing/__init__.py@@ -283,8 +283,11 @@ def assert_close(# Logger api+# TODO: add somehow type check, or enforce to do it before+# TODO: get rid of torchscript test because prevents us to have type safe code-def KORNIA_CHECK_SHAPE(x, shape: List[str]) -> None:++def KORNIA_CHECK_SHAPE(x: Tensor, shape: List[str]) -> None:"""Check whether a tensor has a specified shape.The shape can be specified with a implicit or explicit list of strings.@@ -304,9 +307,6 @@ def KORNIA_CHECK_SHAPE(x, shape: List[str]) -> None:>>> x = torch.rand(2, 3, 4, 4)>>> KORNIA_CHECK_SHAPE(x, ["2","3", "H", "W"]) # explicit"""- # Desired shape here is list and not tuple, because torch.jit- # does not like variable-length tuples- KORNIA_CHECK_IS_TENSOR(x)if '*' == shape[0]:shape_to_check = shape[1:]diff --git a/kornia/utils/grid.py b/kornia/utils/grid.pyindex 199910661..b87d48aef 100644--- a/kornia/utils/grid.py+++ b/kornia/utils/grid.py@@ -60,6 +60,11 @@ def create_meshgrid(xs = (xs / (width - 1) - 0.5) * 2ys = (ys / (height - 1) - 0.5) * 2# generate grid by stacking coordinates+ # TODO: torchscript doesn't like `torch_version_ge`+ # if torch_version_ge(1, 13, 0):+ # x, y = torch_meshgrid([xs, ys], indexing="xy")+ # return stack([x, y], -1).unsqueeze(0) # 1xHxWx2+ # TODO: remove after we drop support of old versionsbase_grid: Tensor = stack(torch_meshgrid([xs, ys], indexing="ij"), dim=-1) # WxHx2return base_grid.permute(1, 0, 2).unsqueeze(0) # 1xHxWx2diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.pyindex e95d465b9..7b76ddd9c 100644--- a/kornia/utils/helpers.py+++ b/kornia/utils/helpers.py@@ -130,9 +130,9 @@ def _torch_svd_cast(input: Tensor) -> Tuple[Tensor, Tensor, Tensor]:NOTE: in torch 1.8.1 this function is recommended to use as torch.linalg.svd"""- if not isinstance(input, Tensor):- raise AssertionError(f"Input must be Tensor. Got: {type(input)}.")- dtype: torch.dtype = input.dtype+ # if not isinstance(input, torch.Tensor):+ # raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")+ dtype = input.dtypeif dtype not in (torch.float32, torch.float64):dtype = torch.float32diff --git a/setup_dev_env.sh b/setup_dev_env.shindex 324c11f50..fa4bcbe55 100755--- a/setup_dev_env.sh+++ b/setup_dev_env.sh@@ -34,9 +34,9 @@ if [ ! -e $conda_bin ]; thenfi# define a python version to initialise the conda environment.-# by default we assume python 3.7.-python_version=${PYTHON_VERSION:-"3.7"}-pytorch_version=${PYTORCH_VERSION:-"1.10.2"}+# by default we assume python 3.8+python_version=${PYTHON_VERSION:-"3.8"}+pytorch_version=${PYTORCH_VERSION:-"1.13.0"}pytorch_mode=${PYTORCH_MODE:-""} # use `cpuonly` for CPU or leave it in blank for GPUcuda_version=${CUDA_VERSION:-"10.2"}@@ -64,7 +64,7 @@ $conda_bin clean -yasource $conda_bin_dir/activate $dev_env_dir/envs/venv# install pytorch and torchvision-conda install pytorch=$pytorch_version torchvision $cuda_toolkit $pytorch_mode -c $pytorch_channel+conda install pytorch=$pytorch_version $cuda_toolkit $pytorch_mode -c $pytorch_channel# install testing dependenciespip install -e .[dev,x]diff --git a/test/core/test_tensor_wrapper.py b/test/core/test_tensor_wrapper.pynew file mode 100644index 000000000..9b1dfa55d--- /dev/null+++ b/test/core/test_tensor_wrapper.py@@ -0,0 +1,83 @@+import pytest+import torch++from kornia.core import Tensor+from kornia.core.tensor_wrapper import TensorWrapper, unwrap, wrap+from kornia.testing import BaseTester+++class TestTensorWrapper(BaseTester):+ def test_smoke(self, device, dtype):+ data = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)+ tensor = wrap(data, TensorWrapper)+ assert isinstance(tensor, TensorWrapper)+ assert isinstance(tensor.data, Tensor)+ assert tensor.shape == (1, 2, 3, 4)+ assert tensor.device == device+ assert tensor.dtype == dtype+ self.assert_close(data, tensor.data)+ self.assert_close(data, unwrap(tensor))++ def test_wrap_list(self, device, dtype):+ data_list = [torch.rand(2, device=device, dtype=dtype), torch.rand(3, device=device, dtype=dtype)]+ tensor_list = wrap(data_list, TensorWrapper)+ assert isinstance(tensor_list, list)+ assert len(tensor_list) == 2+ tensor_list_data = unwrap(tensor_list)+ assert len(tensor_list_data) == 2+ self.assert_close(tensor_list_data[0], data_list[0])+ self.assert_close(tensor_list_data[1], data_list[1])++ # TODO: implement me+ def test_accessors(self, device, dtype):+ data = torch.tensor([0.0, 1.0, 0.0], device=device, dtype=dtype)+ x = wrap(data, TensorWrapper)+ self.assert_close(x[1], torch.tensor(1.0, device=device, dtype=dtype))+ y = x[0]+ self.assert_close(y, torch.tensor(0.0, device=device, dtype=dtype))+ x[1] = 0.0+ self.assert_close(x, torch.zeros_like(x))++ def test_unary_ops(self, device, dtype):+ data = torch.rand(2, device=device, dtype=dtype)+ x = TensorWrapper(data)++ self.assert_close(x.add(x), x + x)+ self.assert_close(x.mul(x), x * x)+ self.assert_close(x.sub(x), x - x)+ self.assert_close(x.div(x), x / x)+ self.assert_close(x.true_divide(x), x / x)+ self.assert_close(x.floor_divide(x), x // x)+ self.assert_close(x.ge(x), x >= x)+ self.assert_close(x.gt(x), x > x)+ self.assert_close(x.lt(x), x < x)+ self.assert_close(x.le(x), x <= x)+ self.assert_close(x.eq(x), x == x)+ self.assert_close(x.ne(x), x != x)+ self.assert_close(-x, -data)++ def test_callable(self, device, dtype):+ data = torch.ones(2, device=device, dtype=dtype)+ x = TensorWrapper(data)+ y = (x * x).sum(-1, True)+ self.assert_close(y, torch.ones_like(y) * 2)++ @pytest.mark.skip(reason="not implemented yet")+ def test_cardinality(self, device, dtype):+ pass++ @pytest.mark.skip(reason="not implemented yet")+ def test_jit(self, device, dtype):+ pass++ @pytest.mark.skip(reason="not implemented yet")+ def test_exception(self, device, dtype):+ pass++ @pytest.mark.skip(reason="not implemented yet")+ def test_module(self, device, dtype):+ pass++ @pytest.mark.skip(reason="not implemented yet")+ def test_gradcheck(self, device):+ passdiff --git a/test/geometry/test_plane.py b/test/geometry/test_plane.pyindex 1285b0b46..f88a3fb8e 100644--- a/test/geometry/test_plane.py+++ b/test/geometry/test_plane.py@@ -2,28 +2,21 @@ import pytestimport torchfrom kornia.geometry.plane import Hyperplane, fit_plane-from kornia.geometry.vector import _VectorType+from kornia.geometry.vector import Vector3from kornia.testing import BaseTester# TODO: implement the rest of methodsclass TestFitPlane(BaseTester):- @pytest.mark.parametrize("B", (1, 2))- @pytest.mark.parametrize("D", (2, 3, 4))- def test_smoke(self, device, dtype, B, D):- N: int = 10 # num points- points = torch.ones(B, N, D, device=device, dtype=dtype)+ @pytest.mark.parametrize("N", (4, 10))+ @pytest.mark.parametrize("D", (3,))+ # @pytest.mark.parametrize("D", (2, 3, 4))+ def test_smoke(self, device, dtype, N, D):+ points = torch.ones(N, D, device=device, dtype=dtype)plane = fit_plane(points)assert isinstance(plane, Hyperplane)- assert plane.offset.shape == (B,)- assert plane.normal.shape == (B, D)-- assert (plane.normal == plane[0]).all()- assert (plane.offset == plane[1]).all()-- normal, offset = fit_plane(points)- assert (plane.normal == normal).all()- assert (plane.offset == offset).all()+ assert plane.offset.shape == ()+ assert plane.normal.shape == (D,)@pytest.mark.skip(reason="not implemented yet")def test_cardinality(self, device, dtype):@@ -48,56 +41,63 @@ class TestFitPlane(BaseTester):# TODO: implement the rest of methodsclass TestHyperplane(BaseTester):- @pytest.mark.parametrize("batch_size", [1, 2])- @pytest.mark.parametrize("dim", (2, 3))- def test_smoke(self, device, dtype, batch_size, dim):- p0 = _VectorType.random((batch_size, dim), device, dtype)- n0 = _VectorType.random((batch_size, dim), device, dtype).normalized()- pl0 = Hyperplane.from_vector(n0.data, p0.data)- # TODO: improve api so that we can accept Vector too- assert pl0.offset.shape == (batch_size,)- assert pl0.normal.shape == (batch_size, dim)-- def test_dot_unbatched(self, device, dtype):- p0 = _VectorType.random((3,), device, dtype)- n0 = _VectorType.random((3,), device, dtype).normalized()- assert p0.dot(n0).shape == ()-- @pytest.mark.parametrize("batch_size", [1, 2])- @pytest.mark.parametrize("dim", (2, 3))- def test_dot_batched(self, device, dtype, batch_size, dim):- p0 = _VectorType.random((batch_size, dim), device, dtype)- n0 = _VectorType.random((batch_size, dim), device, dtype).normalized()- assert p0.dot(n0).shape == (batch_size,)-- def test_sqn_unbatched(self, device, dtype):- p0 = _VectorType.random((3,), device, dtype).normalized()- assert p0.squared_norm().shape == ()-- @pytest.mark.parametrize("batch_size", [1, 2])- @pytest.mark.parametrize("dim", (2, 3))- def test_sqn_batched(self, device, dtype, batch_size, dim):- n0 = _VectorType.random((batch_size, dim), device, dtype).normalized()- assert n0.squared_norm().shape == (batch_size,)-- @pytest.mark.parametrize("batch_size", [1, 2])- def test_through_two(self, device, dtype, batch_size):- v0 = _VectorType.random((batch_size, 2), device, dtype)- v1 = _VectorType.random((batch_size, 2), device, dtype)- # TODO: improve api so that we can accept Vector too- p0 = Hyperplane.through(v0.data, v1.data)- assert p0.offset.shape == (batch_size,)- assert p0.normal.shape == (batch_size, 2)-- @pytest.mark.parametrize("batch_size", [1, 2])- def test_through_three(self, device, dtype, batch_size):- v0 = _VectorType.random((batch_size, 3), device, dtype)- v1 = _VectorType.random((batch_size, 3), device, dtype)- v2 = _VectorType.random((batch_size, 3), device, dtype)+ @pytest.mark.parametrize("shape", (None, (1,), (2, 1)))+ def test_smoke(self, device, dtype, shape):+ p0 = Vector3.random(shape, device, dtype)+ n0 = Vector3.random(shape, device, dtype).normalized()+ pl0 = Hyperplane.from_vector(n0, p0)+ assert pl0.normal.shape == shape or () + (3,)+ assert pl0.offset.shape == (shape + () if shape is not None else ())++ # TODO: implement `Vector2`+ # @pytest.mark.parametrize("batch_size", [1, 2])+ # def test_through_two(self, device, dtype, batch_size):+ # v0 = _VectorType.random((batch_size, 2), device, dtype)+ # v1 = _VectorType.random((batch_size, 2), device, dtype)+ # # TODO: improve api so that we can accept Vector too+ # p0 = Hyperplane.through(v0.data, v1.data)+ # assert p0.offset.shape == (batch_size,)+ # assert p0.normal.shape == (batch_size, 2)++ @pytest.mark.parametrize("shape", (None, (1,), (2, 1)))+ def test_through_three(self, device, dtype, shape):+ v0 = Vector3.random(shape, device, dtype)+ v1 = Vector3.random(shape, device, dtype)+ v2 = Vector3.random(shape, device, dtype)# TODO: improve api so that we can accept Vector too- p0 = Hyperplane.through(v0.data, v1.data, v2.data)- assert p0.offset.shape == (batch_size,)- assert p0.normal.shape == (batch_size, 3)+ p0 = Hyperplane.through(v0, v1, v2)+ assert p0.normal.shape == shape or () + (3,)+ assert p0.offset.shape == (shape + () if shape is not None else ())++ @pytest.mark.parametrize("shape", (None, (1,), (2, 1)))+ def test_abs_signed_distance(self, device, dtype, shape):+ p0 = Vector3.random(shape, device, dtype)+ p1 = Vector3.random(shape, device, dtype)++ n0 = Vector3.random(shape, device, dtype).normalized()+ n1 = Vector3.random(shape, device, dtype).normalized()++ s0 = torch.rand(shape or (), device=device, dtype=dtype)+ s1 = torch.rand(shape or (), device=device, dtype=dtype)++ pl0 = Hyperplane.from_vector(n0, p0)+ pl1 = Hyperplane.from_vector(n1, p1)++ expected = torch.ones(shape or (), device=device, dtype=dtype)+ self.assert_close(pl1.signed_distance(p1 + n1 * s0[..., None]), s0)+ assert (pl0.abs_distance(p0) < expected).all()+ assert (pl1.signed_distance(pl1.projection(p0)) < expected).all()+ assert (pl1.abs_distance(p1 + pl1.normal * s1) < expected).all()++ def test_projection(self, device, dtype):+ v0 = Vector3.from_coords(0.0, 0.0, 0.0, device=device, dtype=dtype)+ v1 = Vector3.from_coords(0.0, 1.0, 0.0, device=device, dtype=dtype)+ v2 = Vector3.from_coords(0.0, 0.0, 1.0, device=device, dtype=dtype)+ plane_in_world = Hyperplane.through(v0, v1, v2)+ p_in_world = Vector3.from_coords(0.0, 0.0, 1.0, device=device, dtype=dtype)+ p_in_plane = plane_in_world.projection(p_in_world)+ p_in_plane_expected = torch.tensor([0.0, 0.0, 1.0], device=device, dtype=dtype)+ self.assert_close(p_in_plane, p_in_plane_expected)@pytest.mark.skip(reason="not implemented yet")def test_cardinality(self, device, dtype):diff --git a/test/geometry/test_vector.py b/test/geometry/test_vector.pynew file mode 100644index 000000000..c041f2caa--- /dev/null+++ b/test/geometry/test_vector.py@@ -0,0 +1,69 @@+import pytest+import torch++from kornia.geometry.vector import Scalar, Vector3+from kornia.testing import BaseTester+++class TestVector3(BaseTester):+ def test_smoke(self, device, dtype):+ vec = Vector3.random(device=device, dtype=dtype)+ assert vec.shape == (3,)+ vec.x is not None+ vec.y is not None+ vec.z is not None++ @pytest.mark.parametrize("shape", ((), (1,), (2, 4)))+ def test_cardinality(self, device, dtype, shape):+ vec = Vector3.random(shape, device, dtype)+ assert vec.shape[:-1] == shape+ assert vec.x.shape == shape+ assert vec.y.shape == shape+ assert vec.z.shape == shape++ def test_from_coords(self):+ vec = Vector3.from_coords(0.0, 1.0, 0.0)+ assert vec.shape == (3,)+ assert vec.x == 0.0+ assert vec.y == 1.0+ assert vec.z == 0.0++ @pytest.mark.parametrize("shape", ((), (1,), (2, 4)))+ def test_from_coords_tensor(self, device, dtype, shape):+ xyz = torch.rand(shape + (3,), device=device, dtype=dtype)+ vec = Vector3.from_coords(xyz[..., 0], xyz[..., 1], xyz[..., 2])+ assert vec.shape[:-1] == shape+ assert vec.x.shape == shape+ assert vec.y.shape == shape+ assert vec.z.shape == shape++ @pytest.mark.parametrize("shape", (None, (1,), (2, 1)))+ def test_dot(self, device, dtype, shape):+ p0 = Vector3.random(shape, device, dtype)+ n0 = Vector3.random(shape, device, dtype).normalized()+ res: Scalar = p0.dot(n0)+ assert res.shape == () if shape is None else shape+ expected = torch.ones(shape or (), device=device, dtype=dtype)+ self.assert_close(n0.dot(n0), expected)++ @pytest.mark.parametrize("shape", (None, (1,), (2, 1)))+ def test_squared_norm(self, device, dtype, shape):+ p0 = Vector3.random(shape, device, dtype)+ res: Scalar = p0.squared_norm()+ assert res.shape == () if shape is None else shape++ @pytest.mark.skip(reason="not implemented yet")+ def test_jit(self, device, dtype):+ pass++ @pytest.mark.skip(reason="not implemented yet")+ def test_exception(self, device, dtype):+ pass++ @pytest.mark.skip(reason="not implemented yet")+ def test_module(self, device, dtype):+ pass++ @pytest.mark.skip(reason="not implemented yet")+ def test_gradcheck(self, device):+ pass