π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
feat(metrics): add pose error metrics and pose AUC (#3889)
Atikul Islam Munna384490ec85a8
diff --git a/docs/source/metrics.rst b/docs/source/metrics.rstindex 58b481cae..1271542e7 100644--- a/docs/source/metrics.rst+++ b/docs/source/metrics.rst@@ -48,6 +48,15 @@ Stereo.. autofunction:: root_mean_squared_disparity_error.. autofunction:: mean_bad_pixel_error+Pose+----++.. autofunction:: angle_error_mat+.. autofunction:: angle_error_vec+.. autofunction:: translation_ate+.. autofunction:: pose_errors+.. autofunction:: auc_from_errors+Monitoring----------diff --git a/kornia/metrics/__init__.py b/kornia/metrics/__init__.pyindex 212745796..ba285127f 100644--- a/kornia/metrics/__init__.py+++ b/kornia/metrics/__init__.py@@ -28,6 +28,7 @@ from .disparity import mean_absolute_disparity_error, mean_bad_pixel_error, rootfrom .endpoint_error import AEPE, aepe, average_endpoint_errorfrom .mean_average_precision import mean_average_precisionfrom .mean_iou import mean_iou, mean_iou_bbox+from .pose import angle_error_mat, angle_error_vec, auc_from_errors, pose_errors, translation_atefrom .psnr import psnrfrom .ssim import SSIM, ssimfrom .ssim3d import SSIM3D, ssim3d@@ -39,6 +40,9 @@ __all__ = ["AverageMeter","accuracy","aepe",+ "angle_error_mat",+ "angle_error_vec",+ "auc_from_errors","average_endpoint_error","confusion_matrix","mean_absolute_disparity_error",@@ -46,8 +50,10 @@ __all__ = ["mean_bad_pixel_error","mean_iou","mean_iou_bbox",+ "pose_errors","psnr","root_mean_squared_disparity_error","ssim","ssim3d",+ "translation_ate",]diff --git a/kornia/metrics/pose.py b/kornia/metrics/pose.pynew file mode 100644index 000000000..5cfbb5a68--- /dev/null+++ b/kornia/metrics/pose.py@@ -0,0 +1,252 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++"""Angular pose-error metrics and pose AUC.++The rotation error is the geodesic angle between two rotation matrices; the translation error is the+angle between two translation directions, optionally folded into ``[0, 90]`` degrees to absorb the+sign ambiguity of an essential-matrix translation. :func:`auc_from_errors` summarizes any error array+as the area under its cumulative curve.+"""++from __future__ import annotations++from collections.abc import Sequence++import torch+from torch import Tensor++from kornia.core.check import (+ KORNIA_CHECK,+ KORNIA_CHECK_IS_TENSOR,+ KORNIA_CHECK_SAME_SHAPE,+ KORNIA_CHECK_SHAPE,+)+++def angle_error_mat(R1: Tensor, R2: Tensor) -> Tensor:+ r"""Geodesic angle (in degrees) between two rotation matrices.++ The relative rotation :math:`R_1^\top R_2` has trace :math:`1 + 2\cos\theta`, so the geodesic+ angle is :math:`\theta = \arccos\!\big((\mathrm{tr}(R_1^\top R_2) - 1) / 2\big)`.++ Args:+ R1: a rotation matrix of shape :math:`(*, 3, 3)`.+ R2: a rotation matrix of shape :math:`(*, 3, 3)`.++ Return:+ the per-matrix angle in degrees, with shape :math:`(*,)`.++ .. note::+ The gradient is infinite/NaN exactly at :math:`0^\circ` and :math:`180^\circ` (identical or+ opposite rotations), because :math:`\frac{d}{dx}\arccos(x) \to \infty` at :math:`x = \pm 1`.+ This is inherent to every geodesic/angular metric; it only bites if you backpropagate through+ a perfect or exactly-opposite match.++ Example:+ >>> angle_error_mat(torch.eye(3), torch.eye(3))+ tensor(0.)+ """+ KORNIA_CHECK_IS_TENSOR(R1)+ KORNIA_CHECK_IS_TENSOR(R2)+ KORNIA_CHECK_SHAPE(R1, ["*", "3", "3"])+ KORNIA_CHECK_SHAPE(R2, ["*", "3", "3"])+ KORNIA_CHECK_SAME_SHAPE(R1, R2)++ relative = R1.transpose(-2, -1) @ R2+ trace = relative.diagonal(dim1=-2, dim2=-1).sum(-1)+ cos_theta = ((trace - 1.0) / 2.0).clamp(-1.0, 1.0)+ return torch.rad2deg(cos_theta.acos())+++def angle_error_vec(v1: Tensor, v2: Tensor) -> Tensor:+ r"""Angle (in degrees) between two vectors.++ The angle is :math:`\theta = \arccos\!\big((v_1 \cdot v_2) / (\lVert v_1 \rVert \lVert v_2 \rVert)\big)`.++ Args:+ v1: a vector of shape :math:`(*, 3)`.+ v2: a vector of shape :math:`(*, 3)`.++ Return:+ the per-vector angle in degrees, with shape :math:`(*,)`.++ .. note::+ The gradient is infinite/NaN exactly at :math:`0^\circ` and :math:`180^\circ` (identical or+ opposite vectors), because :math:`\frac{d}{dx}\arccos(x) \to \infty` at :math:`x = \pm 1`.+ This is inherent to every geodesic/angular metric; it only bites if you backpropagate through+ a perfect or exactly-opposite match.++ .. note::+ A zero-length vector gives ``NaN`` rather than raising, since the angle is undefined there.+ Mask those entries before reducing.++ Example:+ >>> v = torch.tensor([1.0, 0.0, 0.0])+ >>> angle_error_vec(v, v)+ tensor(0.)+ """+ KORNIA_CHECK_IS_TENSOR(v1)+ KORNIA_CHECK_IS_TENSOR(v2)+ KORNIA_CHECK_SHAPE(v1, ["*", "3"])+ KORNIA_CHECK_SHAPE(v2, ["*", "3"])+ KORNIA_CHECK_SAME_SHAPE(v1, v2)++ dot = (v1 * v2).sum(-1)+ norms = v1.norm(dim=-1) * v2.norm(dim=-1)+ cos_theta = (dot / norms).clamp(-1.0, 1.0)+ return torch.rad2deg(cos_theta.acos())+++def translation_ate(t: Tensor, t_gt: Tensor) -> Tensor:+ r"""Absolute translation error (ATE) between two translations.++ Computes the raw Euclidean distance :math:`\lVert t - t_{gt} \rVert_2`. Unlike+ :func:`angle_error_vec`, this keeps the magnitude and is therefore only meaningful when both+ translations share a common metric scale (it is **not** scale-invariant, so it is not suitable+ for raw essential-matrix translations).++ Args:+ t: an estimated translation of shape :math:`(*, 3)`.+ t_gt: a ground-truth translation of the same shape as ``t``.++ Return:+ the per-sample translation error, with shape :math:`(*,)`. An unbatched :math:`(3,)` input is+ treated as a single sample and returns shape :math:`(1,)`.++ .. note::+ Unlike the :func:`angle_error_vec` / :func:`angle_error_mat` angular metrics, this has no+ ``arccos`` singularity: the gradient stays finite even at zero distance, where ``norm``+ returns the subgradient ``0``.++ Example:+ >>> t = torch.tensor([0.0, 0.0, 0.0])+ >>> t_gt = torch.tensor([3.0, 4.0, 0.0])+ >>> translation_ate(t, t_gt)+ tensor([5.])+ """+ KORNIA_CHECK_IS_TENSOR(t)+ KORNIA_CHECK_IS_TENSOR(t_gt)+ KORNIA_CHECK_SHAPE(t, ["*", "3"])+ KORNIA_CHECK_SHAPE(t_gt, ["*", "3"])+ KORNIA_CHECK(t.shape == t_gt.shape, f"t and t_gt shapes must match. Got: {t.shape} and {t_gt.shape}")++ if t.dim() == 1:+ t, t_gt = t[None], t_gt[None]+ return (t - t_gt).norm(dim=-1)+++def pose_errors(P: Tensor, P_gt: Tensor, fold_translation: bool = True) -> dict[str, Tensor]:+ r"""Rotation and translation angular error (in degrees) between two relative poses.++ Args:+ P: an estimated relative pose ``[R | t]`` of shape :math:`(3, 4)`, :math:`(4, 4)`, or batched+ :math:`(B, 3, 4)` / :math:`(B, 4, 4)`.+ P_gt: a ground-truth relative pose of the same shape.+ fold_translation: if ``True`` (default), fold the translation error into :math:`[0, 90]` via+ :math:`\min(e, 180 - e)` to absorb the sign ambiguity of an essential-matrix translation.++ Return:+ a dict of per-pose errors of shape :math:`(B,)`: ``"R_err"`` (rotation), ``"t_err"``+ (translation) and ``"max_err"`` (element-wise max of the two).++ .. note::+ A pose with zero translation gives ``NaN`` for ``"t_err"`` and ``"max_err"``, and+ :func:`auc_from_errors` propagates that into the AUC. Mask those entries first.++ Example:+ >>> P = torch.eye(4)+ >>> P[0, 3] = 1.0+ >>> errs = pose_errors(P, P)+ >>> errs["R_err"], errs["t_err"]+ (tensor([0.]), tensor([0.]))+ """+ KORNIA_CHECK_IS_TENSOR(P)+ KORNIA_CHECK_IS_TENSOR(P_gt)+ KORNIA_CHECK(P.shape == P_gt.shape, f"P and P_gt shapes must match. Got: {P.shape} and {P_gt.shape}")+ KORNIA_CHECK(+ P.dim() in (2, 3) and P.shape[-2] in (3, 4) and P.shape[-1] == 4,+ f"P must be (3, 4)/(4, 4) or batched. Got: {P.shape}",+ )++ if P.dim() == 2:+ P, P_gt = P[None], P_gt[None]++ r_err = angle_error_mat(P[..., :3, :3], P_gt[..., :3, :3])+ t_err = angle_error_vec(P[..., :3, 3], P_gt[..., :3, 3])+ if fold_translation:+ t_err = torch.minimum(t_err, 180.0 - t_err)+ return {"R_err": r_err, "t_err": t_err, "max_err": torch.maximum(r_err, t_err)}+++def auc_from_errors(errors: Tensor, thresholds: float | Sequence[float] = (1, 3, 5, 10)) -> dict[float, float]:+ r"""Area under the cumulative error curve at one or more thresholds.++ The metric is generic: any non-negative error array works. Pose-error metrics (e.g. the+ ``"max_err"`` of :func:`pose_errors`) are one common source, but the thresholds simply need to be+ in the same units as ``errors``.++ Args:+ errors: per-sample error values of shape :math:`(B,)`. Must be non-negative. Integer and+ half-precision inputs are promoted to the default floating dtype before accumulating.+ thresholds: a single threshold or a sequence of thresholds, in the same units as ``errors``.+ Must be strictly positive. Defaults to ``(1, 3, 5, 10)``.++ Return:+ a dict mapping each threshold to its AUC in :math:`[0, 100]`, or ``NaN`` at every threshold+ if any error is ``NaN``.++ .. note::+ An error exactly equal to a threshold contributes no area there, so errors all equal to+ ``thr`` score ``0`` at ``thr``. This follows the reference implementations.++ Example:+ >>> auc_from_errors(torch.zeros(1), thresholds=5.0)+ {5.0: 100.0}+ """+ KORNIA_CHECK_IS_TENSOR(errors)+ if isinstance(thresholds, (int, float)):+ thresholds = [thresholds]+ thresholds = [float(thr) for thr in thresholds]+ KORNIA_CHECK(len(thresholds) > 0, "thresholds must not be empty.")+ KORNIA_CHECK(all(thr > 0 for thr in thresholds), f"thresholds must be positive. Got: {thresholds}")++ errors = errors.flatten()+ # An integer dtype would truncate the threshold, half precision loses exactness in arange.+ if errors.dtype not in (torch.float32, torch.float64):+ errors = errors.to(torch.get_default_dtype())+ # A negative error would sort ahead of the zero prepended below, leaving the array unsorted and+ # searchsorted free to return nonsense. NaN compares false here and is handled next.+ KORNIA_CHECK(not bool((errors < 0).any()), "errors must be non-negative.")+ if bool(torch.isnan(errors).any()):+ return dict.fromkeys(thresholds, float("nan"))+ errors = errors.sort().values+ n = errors.numel()+ recall = torch.arange(1, n + 1, device=errors.device, dtype=errors.dtype) / n+ errors = torch.cat([errors.new_zeros(1), errors])+ recall = torch.cat([recall.new_zeros(1), recall])++ aucs: dict[float, float] = {}+ for thr in thresholds:+ # First error at or past the threshold. A positive thr always lands past the prepended+ # zero, so last >= 1 and the curve can be closed off with a flat segment out to thr.+ last = int(torch.searchsorted(errors, errors.new_tensor(thr)).item())+ recall_below = torch.cat([recall[:last], recall[last - 1 : last]])+ errors_below = torch.cat([errors[:last], errors.new_tensor([thr])])+ area = torch.trapezoid(recall_below, x=errors_below)+ aucs[thr] = (area / thr).item() * 100.0+ return aucsdiff --git a/tests/metrics/test_pose.py b/tests/metrics/test_pose.pynew file mode 100644index 000000000..c57e91ea2--- /dev/null+++ b/tests/metrics/test_pose.py@@ -0,0 +1,259 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++from __future__ import annotations++import math++import pytest+import torch++import kornia++from testing.base import BaseTester++# 90-degree rotation about +z.+ROT_Z_90 = [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]+++class TestAngleErrorMat(BaseTester):+ def test_identity_is_zero(self, device, dtype):+ eye = torch.eye(3, device=device, dtype=dtype)+ expected = torch.tensor(0.0, device=device, dtype=dtype)+ self.assert_close(kornia.metrics.angle_error_mat(eye, eye), expected)++ def test_known_angle(self, device, dtype):+ eye = torch.eye(3, device=device, dtype=dtype)+ rot = torch.tensor(ROT_Z_90, device=device, dtype=dtype)+ expected = torch.tensor(90.0, device=device, dtype=dtype)+ self.assert_close(kornia.metrics.angle_error_mat(eye, rot), expected)++ def test_batched(self, device, dtype):+ eye = torch.eye(3, device=device, dtype=dtype)+ rot = torch.tensor(ROT_Z_90, device=device, dtype=dtype)+ batch1 = torch.stack([eye, eye])+ batch2 = torch.stack([eye, rot])+ expected = torch.tensor([0.0, 90.0], device=device, dtype=dtype)+ out = kornia.metrics.angle_error_mat(batch1, batch2)+ assert out.shape == (2,)+ self.assert_close(out, expected)++ def test_exception(self, device, dtype):+ from kornia.core.exceptions import ShapeError++ with pytest.raises(ShapeError):+ kornia.metrics.angle_error_mat(+ torch.eye(3, device=device, dtype=dtype), torch.ones(2, device=device, dtype=dtype)+ )++ def test_gradcheck(self, device):+ # 90 degrees apart, away from the arccos singularities at 0 and 180.+ R1 = torch.eye(3, device=device, dtype=torch.float64)+ R2 = torch.tensor(ROT_Z_90, device=device, dtype=torch.float64)+ self.gradcheck(kornia.metrics.angle_error_mat, (R1, R2), requires_grad=(True, False))++ def test_mismatched_batch_raises(self, device, dtype):+ # A batch of 1 against a batch of 4 used to broadcast instead of raising.+ R1 = torch.eye(3, device=device, dtype=dtype).expand(1, 3, 3)+ R2 = torch.eye(3, device=device, dtype=dtype).expand(4, 3, 3)+ with pytest.raises(Exception):+ kornia.metrics.angle_error_mat(R1, R2)+++class TestAngleErrorVec(BaseTester):+ def test_aligned_orthogonal_opposite(self, device, dtype):+ x = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype)+ y = torch.tensor([0.0, 1.0, 0.0], device=device, dtype=dtype)+ self.assert_close(kornia.metrics.angle_error_vec(x, x), torch.tensor(0.0, device=device, dtype=dtype))+ self.assert_close(kornia.metrics.angle_error_vec(x, y), torch.tensor(90.0, device=device, dtype=dtype))+ self.assert_close(kornia.metrics.angle_error_vec(x, -x), torch.tensor(180.0, device=device, dtype=dtype))++ def test_batched(self, device, dtype):+ a = torch.tensor([[1.0, 0.0, 0.0], [1.0, 0.0, 0.0]], device=device, dtype=dtype)+ b = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype)+ expected = torch.tensor([0.0, 90.0], device=device, dtype=dtype)+ out = kornia.metrics.angle_error_vec(a, b)+ assert out.shape == (2,)+ self.assert_close(out, expected)++ def test_zero_vector_is_nan(self, device, dtype):+ # Undefined angle, so NaN rather than an exception.+ zero = torch.zeros(3, device=device, dtype=dtype)+ unit = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype)+ assert torch.isnan(kornia.metrics.angle_error_vec(zero, unit))++ def test_mismatched_batch_raises(self, device, dtype):+ # A batch of 1 against a batch of 5 used to broadcast instead of raising.+ v1 = torch.tensor([[1.0, 0.0, 0.0]], device=device, dtype=dtype)+ v2 = torch.ones(5, 3, device=device, dtype=dtype)+ with pytest.raises(Exception):+ kornia.metrics.angle_error_vec(v1, v2)++ def test_gradcheck(self, device):+ v1 = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=torch.float64)+ v2 = torch.tensor([0.0, 1.0, 0.0], device=device, dtype=torch.float64)+ self.gradcheck(kornia.metrics.angle_error_vec, (v1, v2), requires_grad=(True, False))+++class TestTranslationAte(BaseTester):+ def test_single_returns_batch_shape(self, device, dtype):+ # ||[0,0,0] - [3,4,0]|| = 5 (3-4-5 triangle).+ t = torch.zeros(3, device=device, dtype=dtype)+ t_gt = torch.tensor([3.0, 4.0, 0.0], device=device, dtype=dtype)+ out = kornia.metrics.translation_ate(t, t_gt)+ assert out.shape == (1,)+ self.assert_close(out, torch.tensor([5.0], device=device, dtype=dtype))++ def test_batched(self, device, dtype):+ t = torch.tensor([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]], device=device, dtype=dtype)+ t_gt = torch.tensor([[3.0, 4.0, 0.0], [1.0, 1.0, 1.0]], device=device, dtype=dtype)+ out = kornia.metrics.translation_ate(t, t_gt)+ assert out.shape == (2,)+ self.assert_close(out, torch.tensor([5.0, 0.0], device=device, dtype=dtype))++ def test_mismatched_shapes_raise(self, device, dtype):+ # This used to broadcast to (1, B) instead of raising.+ t = torch.zeros(3, device=device, dtype=dtype)+ t_gt = torch.ones(4, 3, device=device, dtype=dtype)+ with pytest.raises(Exception):+ kornia.metrics.translation_ate(t, t_gt)++ def test_gradcheck(self, device):+ t = torch.zeros(3, device=device, dtype=torch.float64)+ t_gt = torch.tensor([3.0, 4.0, 0.0], device=device, dtype=torch.float64)+ self.gradcheck(kornia.metrics.translation_ate, (t, t_gt), requires_grad=(True, False))+++class TestPoseErrors(BaseTester):+ @staticmethod+ def _pose(t, device, dtype):+ eye = torch.eye(3, device=device, dtype=dtype)+ t = torch.tensor(t, device=device, dtype=dtype).reshape(3, 1)+ return torch.cat([eye, t], dim=1)++ def test_keys_and_values(self, device, dtype):+ # R=I both; t=[1,0,0] vs t_gt=[0,1,0] -> R_err=0, t_err=90, max=90.+ P = self._pose([1.0, 0.0, 0.0], device, dtype)+ P_gt = self._pose([0.0, 1.0, 0.0], device, dtype)+ out = kornia.metrics.pose_errors(P, P_gt)+ assert set(out) == {"R_err", "t_err", "max_err"}+ assert out["R_err"].shape == (1,)+ self.assert_close(out["R_err"], torch.tensor([0.0], device=device, dtype=dtype))+ self.assert_close(out["t_err"], torch.tensor([90.0], device=device, dtype=dtype))+ self.assert_close(out["max_err"], torch.tensor([90.0], device=device, dtype=dtype))++ def test_translation_sign_fold(self, device, dtype):+ # t=[1,0,0] vs t_gt=[-1,0,0]: 180 deg.+ P = self._pose([1.0, 0.0, 0.0], device, dtype)+ P_gt = self._pose([-1.0, 0.0, 0.0], device, dtype)+ # Folded (default) -> min(180, 0) = 0.+ out = kornia.metrics.pose_errors(P, P_gt)+ self.assert_close(out["t_err"], torch.tensor([0.0], device=device, dtype=dtype))+ # Unfolded -> the raw 180 deg.+ out = kornia.metrics.pose_errors(P, P_gt, fold_translation=False)+ self.assert_close(out["t_err"], torch.tensor([180.0], device=device, dtype=dtype))++ def test_exception(self, device, dtype):+ with pytest.raises(Exception):+ kornia.metrics.pose_errors(+ torch.eye(3, device=device, dtype=dtype), torch.eye(4, device=device, dtype=dtype)+ )++ @pytest.mark.parametrize("rows", [3, 4])+ def test_batched(self, device, dtype, rows):+ P = torch.eye(4, device=device, dtype=dtype)[:rows]+ batch = P.expand(2, rows, 4)+ out = kornia.metrics.pose_errors(batch, batch)+ assert out["R_err"].shape == (2,)+ assert out["max_err"].shape == (2,)++ @pytest.mark.parametrize("shape", [(2, 4), (2, 2, 3, 4)])+ def test_bad_dims_raise(self, device, dtype, shape):+ P = torch.zeros(shape, device=device, dtype=dtype)+ with pytest.raises(Exception):+ kornia.metrics.pose_errors(P, P)+++class TestAucFromErrors(BaseTester):+ def test_perfect_recall_is_100(self, device, dtype):+ # A single error of 0 sits below any threshold -> full area -> AUC 100.+ aucs = kornia.metrics.auc_from_errors(torch.zeros(1, device=device, dtype=dtype), thresholds=4.0)+ assert math.isclose(aucs[4.0], 100.0, abs_tol=1e-3)++ def test_known_value(self, device, dtype):+ # errors=[2], thr=4. Augmented errors=[0,2], recall=[0,1]; step up to thr=4:+ # trapezoid(recall=[0,1,1], x=[0,2,4]) = 1 (0..2) + 2 (2..4) = 3; 3/4*100 = 75.+ errors = torch.tensor([2.0], device=device, dtype=dtype)+ aucs = kornia.metrics.auc_from_errors(errors, thresholds=(2.0, 4.0))+ assert set(aucs) == {2.0, 4.0}+ # thr=2 sits exactly at the error -> no area below -> 0.+ assert math.isclose(aucs[2.0], 0.0, abs_tol=1e-3)+ assert math.isclose(aucs[4.0], 75.0, abs_tol=1e-3)++ def test_integer_errors_do_not_truncate_threshold(self, device):+ # On an integer tensor, thr=2.5 used to truncate to 2 and score 0 instead of 60.+ int_errors = torch.tensor([2], device=device, dtype=torch.int64)+ float_errors = torch.tensor([2.0], device=device)+ assert math.isclose(+ kornia.metrics.auc_from_errors(int_errors, thresholds=2.5)[2.5],+ kornia.metrics.auc_from_errors(float_errors, thresholds=2.5)[2.5],+ abs_tol=1e-3,+ )++ def test_errors_above_threshold_and_empty(self, device, dtype):+ above = torch.tensor([50.0, 60.0], device=device, dtype=dtype)+ assert math.isclose(kornia.metrics.auc_from_errors(above, thresholds=10.0)[10.0], 0.0, abs_tol=1e-3)+ empty = torch.empty(0, device=device, dtype=dtype)+ assert math.isclose(kornia.metrics.auc_from_errors(empty, thresholds=5.0)[5.0], 0.0, abs_tol=1e-3)++ @pytest.mark.parametrize("thr", [0.0, -3.0])+ def test_non_positive_threshold_raises(self, device, dtype, thr):+ # These used to fall off the front of the curve and return nan or -0.0.+ errors = torch.tensor([1.0], device=device, dtype=dtype)+ with pytest.raises(Exception):+ kornia.metrics.auc_from_errors(errors, thresholds=thr)++ def test_empty_thresholds_raise(self, device, dtype):+ errors = torch.tensor([1.0], device=device, dtype=dtype)+ with pytest.raises(Exception):+ kornia.metrics.auc_from_errors(errors, thresholds=[])++ def test_default_thresholds(self, device, dtype):+ errors = torch.tensor([2.0, 4.0, 6.0], device=device, dtype=dtype)+ assert set(kornia.metrics.auc_from_errors(errors)) == {1.0, 3.0, 5.0, 10.0}++ def test_nan_error_propagates(self, device, dtype):+ # pose_errors yields NaN for a zero translation, and it carries through to the AUC. This has+ # to hold at every threshold: NaN sorts last, so a low threshold used to cut it off and+ # return a finite number.+ errors = torch.tensor([1.0, 5.0, float("nan")], device=device, dtype=dtype)+ aucs = kornia.metrics.auc_from_errors(errors, thresholds=(2.0, 10.0))+ assert all(math.isnan(v) for v in aucs.values())++ def test_negative_errors_raise(self, device, dtype):+ # A negative sorts ahead of the prepended zero, so searchsorted returned an AUC above 100.+ errors = torch.tensor([-5.0, 1.0], device=device, dtype=dtype)+ with pytest.raises(Exception):+ kornia.metrics.auc_from_errors(errors, thresholds=2.0)++ def test_input_order_and_shape_do_not_matter(self, device, dtype):+ flat = torch.tensor([1.0, 2.0, 3.0, 4.0], device=device, dtype=dtype)+ shuffled = torch.tensor([3.0, 1.0, 4.0, 2.0], device=device, dtype=dtype)+ two_d = flat.reshape(2, 2)+ expected = kornia.metrics.auc_from_errors(flat, thresholds=5.0)[5.0]+ assert math.isclose(kornia.metrics.auc_from_errors(shuffled, thresholds=5.0)[5.0], expected, abs_tol=1e-3)+ assert math.isclose(kornia.metrics.auc_from_errors(two_d, thresholds=5.0)[5.0], expected, abs_tol=1e-3)