Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): reject degenerate input in line and plane constructors (#5054)

niukanen1de8b7e91eec9
diff --git a/changelog.d/5054.breaking.md b/changelog.d/5054.breaking.md
new file mode 100644
index 000000000..9c03299ad
--- /dev/null
+++ b/changelog.d/5054.breaking.md
@@ -0,0 +1 @@
+`ParametrizedLine.through`, `fit_line`, `fit_plane` and `Hyperplane.through` now raise `ValueCheckError` for input that does not determine a line or a plane: two coincident points for `ParametrizedLine.through`; fewer than two points, identical points, or weights that do not sum to a positive value for `fit_line`; fewer than three points, identical points or collinear points for `fit_plane` and `Hyperplane.through`. They used to return an arbitrary valid-looking result: a zero direction, a fixed direction such as (0, 1) or (1, 0, 0), a NaN origin for all-zero weights, or one of the infinitely many planes that contain the line. A batch is rejected when any of its rows is degenerate. The collinearity tolerance is relative and scales with the machine epsilon of the input dtype. The checks are skipped under `torch.compile` and after `disable_checks()`, where the previous results come back.
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index 12855a185..215022385 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -23,8 +23,9 @@ import torch
import torch.nn.functional as F
from torch import nn
-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
-from kornia.core.utils import _torch_svd_cast, register_module_state
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE, are_checks_enabled
+from kornia.core.exceptions import ValueCheckError
+from kornia.core.utils import _torch_svd_cast, is_compiling, register_module_state
from kornia.geometry.linalg import batched_dot_product
from kornia.geometry.plane import Hyperplane
from kornia.geometry.vector import Scalar
@@ -94,13 +95,20 @@ class ParametrizedLine(nn.Module):
p0: tensor with first point :math:`(B, D)` where `D` is the point dimension.
p1: tensor with second point :math:`(B, D)` where `D` is the point dimension.
+ Raises:
+ ValueCheckError: if ``p0`` and ``p1`` coincide, so the line has no direction.
+
Example:
>>> p0 = torch.tensor([0.0, 0.0])
>>> p1 = torch.tensor([1.0, 1.0])
>>> l = ParametrizedLine.through(p0, p1)
"""
- return ParametrizedLine(p0, F.normalize((p1 - p0), p=2, dim=-1))
+ direction = p1 - p0
+ if not torch.jit.is_scripting() and are_checks_enabled() and not is_compiling():
+ if not bool((direction.abs().amax(dim=-1) > 0).all()):
+ raise ValueCheckError("ParametrizedLine.through requires two distinct points; p0 and p1 coincide.")
+ return ParametrizedLine(p0, F.normalize(direction, p=2, dim=-1))
def point_at(self, t: Union[float, torch.Tensor, Scalar]) -> torch.Tensor:
"""Get the point at :math:`t` along this line.
@@ -248,6 +256,32 @@ def _fit_line_weighted_ols_2d(points: torch.Tensor, weights: torch.Tensor) -> Pa
return ParametrizedLine(origin, direction)
+def _reject_degenerate_line(points: torch.Tensor, weights: Optional[torch.Tensor]) -> None:
+ """Raise ``ValueCheckError`` when the point set cannot determine a line.
+
+ A line needs at least two points that are not all identical. Comparing every point with
+ the first one is exact at any scale; comparing with the mean is not, because its rounding
+ leaves a nonzero residual for identical points such as three copies of (0.1, 0.7). With
+ weights, the weighted mean is undefined unless the weight sum of every row is positive.
+
+ The value checks are skipped under ``torch.compile``/export, where they would be a
+ data-dependent branch, and by ``disable_checks()``, like every kornia value check.
+ """
+ if torch.jit.is_scripting() or is_compiling() or not are_checks_enabled():
+ return
+ n = points.shape[-2]
+ if n < 2:
+ raise ValueCheckError(f"fit_line requires at least two points to determine a line; got a set of {n} point(s).")
+ if not bool((points != points[..., :1, :]).flatten(-2).any(-1).all()):
+ raise ValueCheckError("fit_line requires at least two distinct points; the given points are all identical.")
+ # Weights of the wrong type or shape are left to the type and shape checks in fit_line.
+ if isinstance(weights, torch.Tensor) and weights.shape == points.shape[:2]:
+ if not bool((weights.sum(-1) > 0).all()):
+ raise ValueCheckError(
+ "fit_line requires a positive sum of weights; the given weights do not sum to a positive value."
+ )
+
+
def fit_line(points: torch.Tensor, weights: Optional[torch.Tensor] = None) -> ParametrizedLine:
"""Fit a line from a set of points.
@@ -260,6 +294,10 @@ def fit_line(points: torch.Tensor, weights: Optional[torch.Tensor] = None) -> Pa
Return:
A tensor containing the direction of the fitted line of shape :math:`(B, D)`.
+ Raises:
+ ValueCheckError: if the points do not determine a line β€” fewer than two points,
+ all points identical, or (with weights) a zero weight sum.
+
Example:
>>> points = torch.rand(2, 10, 3)
>>> weights = torch.ones(2, 10)
@@ -272,6 +310,8 @@ def fit_line(points: torch.Tensor, weights: Optional[torch.Tensor] = None) -> Pa
_B, _N, D = points.shape
+ _reject_degenerate_line(points, weights)
+
# Fast path: use OLS for unweighted 2D case
if D == 2:
if weights is not None:
diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.py
index d3c72af0c..e94e8203b 100644
--- a/kornia/geometry/plane.py
+++ b/kornia/geometry/plane.py
@@ -23,10 +23,10 @@ from typing import Optional
import torch
from torch import nn
-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
-from kornia.core.exceptions import BaseError
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE, are_checks_enabled
+from kornia.core.exceptions import BaseError, ValueCheckError
from kornia.core.tensor_wrapper import _unwrap, _wrap
-from kornia.core.utils import _torch_svd_cast
+from kornia.core.utils import _torch_linalg_svdvals, _torch_svd_cast, is_compiling
from kornia.geometry.linalg import batched_dot_product
from kornia.geometry.vector import Scalar, Vector3
@@ -170,6 +170,8 @@ class Hyperplane(nn.Module):
Raises:
BaseError: if ``p2`` is omitted, or if the points are not ``(..., 3)`` tensors of the
same shape.
+ ValueCheckError: if the three points are collinear (or coincide), so they do not
+ determine a plane.
"""
if p2 is None:
# Raised directly rather than through KORNIA_CHECK, so it still fires with checks disabled.
@@ -199,6 +201,21 @@ class Hyperplane(nn.Module):
_, _, V = _torch_svd_cast(m) # kornia solution lies in the last row
return V[..., :, -1] # Bx3
+ # Collinear or coincident points do not determine a plane: raise instead of taking the SVD
+ # fallback, which returns an arbitrary valid-looking normal. The test is on the rank of
+ # (v0, v1), as in fit_plane, from singular values that ``_torch_linalg_svdvals`` computes in
+ # float32 or float64. It is relative and scaled by the input's machine epsilon, so a small
+ # or thin valid triangle keeps working (also one whose cross product underflows in
+ # float16), and it does not depend on the fallback threshold below.
+ # Skipped under torch.compile/export and by disable_checks(), like every kornia value check.
+ if not torch.jit.is_scripting() and not is_compiling() and are_checks_enabled():
+ sv = _torch_linalg_svdvals(torch.stack((_unwrap(v0), _unwrap(v1)), -2))
+ if bool((sv[..., 1] <= sv[..., 0] * _rank_tolerance(sv.dtype)).any()):
+ raise ValueCheckError(
+ "Hyperplane.through requires three points that are not collinear; "
+ "the given points do not determine a plane."
+ )
+
eps = torch.finfo(p0_data.dtype).eps if p0_data.is_floating_point() else 1e-6
normal_mask = norm <= v0_norm * v1_norm * eps
norm_safe = torch.where(normal_mask, torch.ones_like(norm), norm)
@@ -208,6 +225,12 @@ class Hyperplane(nn.Module):
return Hyperplane(_wrap(normal, Vector3), _wrap(offset, Scalar))
+def _rank_tolerance(dtype: torch.dtype) -> float:
+ # Relative tolerance on the ratio of singular values below which a point set counts as
+ # rank-deficient: a few units of rounding of the input dtype.
+ return 8.0 * torch.finfo(dtype).eps
+
+
# 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: Vector3) -> Hyperplane:
@@ -220,17 +243,44 @@ def fit_plane(points: Vector3) -> Hyperplane:
Return:
The computed hyperplane object.
+ Raises:
+ ValueCheckError: if fewer than three points are given, or the points are collinear,
+ so they do not determine a plane.
+
"""
# 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)")
+ # The value checks are skipped under torch.compile/export, where they would be a
+ # data-dependent branch, and by disable_checks(), like every kornia value check.
+ checks = not torch.jit.is_scripting() and not is_compiling() and are_checks_enabled()
+ if checks:
+ n = points.shape[-2]
+ if n < 3:
+ raise ValueCheckError(f"fit_plane requires at least three points to determine a plane; got {n} point(s).")
+ # Compare with the first point rather than the mean, whose rounding leaves a nonzero
+ # residual for identical points such as three copies of (0.1, 0.7, 0.3).
+ pts = _unwrap(points)
+ if not bool((pts != pts[..., :1, :]).flatten(-2).any(-1).all()):
+ raise ValueCheckError(
+ "fit_plane requires at least three points that are not identical; the given points are all identical."
+ )
+
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)
+ _, S, V = _torch_svd_cast(points_centered)
+
+ # The plane is determined when the centred points have rank 2: the second singular value
+ # must be nonzero relative to the first, a scale-invariant test that keeps a small or thin
+ # valid set working. ``_torch_svd_cast`` also covers float16 and bfloat16.
+ if checks and not bool((S[..., 1] > S[..., 0] * _rank_tolerance(S.dtype)).all()):
+ raise ValueCheckError(
+ "fit_plane requires points that are not collinear; the given points do not determine a plane."
+ )
# the first left eigenvector is the direction on the fited line
direction = V[..., :, -1] # BxD
diff --git a/tests/geometry/test_line.py b/tests/geometry/test_line.py
index 1614d0f7c..3a36455aa 100644
--- a/tests/geometry/test_line.py
+++ b/tests/geometry/test_line.py
@@ -18,6 +18,8 @@
import pytest
import torch
+from kornia.core.check import are_checks_enabled, disable_checks, enable_checks
+from kornia.core.exceptions import TypeCheckError, ValueCheckError
from kornia.geometry.line import ParametrizedLine, fit_line
from kornia.geometry.plane import Hyperplane
from kornia.geometry.vector import Scalar, Vector3
@@ -144,6 +146,12 @@ class TestParametrizedLine(BaseTester):
line.distance(p).backward()
assert torch.isfinite(p.grad).all()
+ def test_through_coincident_points_raises_5041(self, device, dtype):
+ # #5041: through(p, p) used to return a line with direction (0, 0).
+ p = torch.tensor([1.0, 2.0], device=device, dtype=dtype)
+ with pytest.raises(ValueCheckError, match="two distinct points"):
+ ParametrizedLine.through(p, p.clone())
+
def test_instersect_plane(self, device, dtype):
p0 = torch.tensor([0.0, 0.0, 0.0], device=device, dtype=dtype)
p1 = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype)
@@ -278,7 +286,9 @@ class TestFitLine(BaseTester):
@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)
+ # A line needs distinct points: ones() is a set of identical points, rejected since #5041.
+ t = torch.linspace(-1.0, 1.0, N, device=device, dtype=dtype)
+ points = torch.stack([t] + [t * (i + 1) for i in range(D - 1)], dim=-1)[None].expand(B, N, D)
line = fit_line(points)
assert isinstance(line, ParametrizedLine)
assert line.origin.shape == (B, D)
@@ -394,8 +404,18 @@ class TestFitLine(BaseTester):
batch = fit_line(torch.cat([points, points]), torch.cat([weights, 3.0 * weights]))
self.assert_close(batch.origin, expected.origin.expand(2, 3))
- # A row whose weights are all 0 keeps the unweighted mean and does not break the other rows.
- zero = fit_line(torch.cat([points, points]), torch.cat([weights, torch.zeros_like(weights)]))
+ # A row whose weights are all 0 is rejected (#5041). With checks disabled, as under torch.compile, it keeps
+ # the unweighted mean and does not break the other rows.
+ zero_weights = torch.cat([weights, torch.zeros_like(weights)])
+ with pytest.raises(ValueCheckError, match="positive sum of weights"):
+ fit_line(torch.cat([points, points]), zero_weights)
+ checks_were_enabled = are_checks_enabled()
+ disable_checks()
+ try:
+ zero = fit_line(torch.cat([points, points]), zero_weights)
+ finally:
+ if checks_were_enabled:
+ enable_checks()
self.assert_close(zero.origin, torch.cat([expected.origin, points.mean(-2)]))
def test_fit_line_vertical_dtype(self, device, dtype):
@@ -405,6 +425,71 @@ class TestFitLine(BaseTester):
assert line.direction.dtype == dtype
self.assert_close(line.direction, torch.tensor([[0.0, 1.0]], device=device, dtype=dtype))
+ def test_fit_line_degenerate_raises_5041(self, device, dtype):
+ # #5041: a single point, identical points, or all-zero weights used to return an
+ # arbitrary-looking line ((0, 1) / (1, 0, 0) directions, a NaN origin for zero weights).
+ one_point = torch.tensor([[[1.0, 2.0]]], device=device, dtype=dtype)
+ with pytest.raises(ValueCheckError, match="at least two points"):
+ fit_line(one_point)
+
+ identical = torch.tensor([[[1.0, 2.0, 3.0]] * 5], device=device, dtype=dtype)
+ with pytest.raises(ValueCheckError, match="two distinct points"):
+ fit_line(identical)
+
+ # Identical points whose mean rounds: three copies of 0.1 sum to 0.30000000000000004, so centring on the
+ # mean leaves a residual of about 1e-17 and a mean-based test would accept them.
+ identical_rounding = torch.tensor([[[0.1, 0.7]] * 3], device=device, dtype=dtype)
+ with pytest.raises(ValueCheckError, match="two distinct points"):
+ fit_line(identical_rounding)
+
+ # A batch is rejected as a whole when one of its rows is degenerate.
+ batch = torch.tensor([[[0.0, 0.0], [1.0, 3.0]], [[1.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
+ with pytest.raises(ValueCheckError, match="two distinct points"):
+ fit_line(batch)
+
+ # #5041: all-zero weights used to return an arbitrary line β€” a NaN origin and (1, 0) in 2-D,
+ # the unweighted mean and the first singular vector of a zero matrix in 3-D. The row is rejected
+ # like any other degenerate one, so a batch with one all-zero-weights row is rejected as a whole.
+ points_3d = torch.tensor([[[0.0, 0.0, 0.3], [1.0, 3.0, -0.2], [2.0, 5.0, 0.1]]], device=device, dtype=dtype)
+ zero_weights = torch.zeros(1, 3, device=device, dtype=dtype)
+ mixed = torch.cat([torch.ones_like(zero_weights), zero_weights])
+ for points in (points_3d[..., :2], points_3d):
+ with pytest.raises(ValueCheckError, match="positive sum of weights"):
+ fit_line(points, zero_weights)
+ with pytest.raises(ValueCheckError, match="positive sum of weights"):
+ fit_line(torch.cat([points, points]), mixed)
+
+ # Weights that are not a tensor still fail the type check, not the weight-sum check.
+ with pytest.raises(TypeCheckError, match="weights must be a tensor"):
+ fit_line(points_3d, [[1.0, 1.0, 1.0]])
+
+ def test_dynamo_skips_degenerate_checks(self, device, dtype, torch_optimizer):
+ # The degeneracy checks depend on tensor values, so they are skipped under torch.compile: a compiled call
+ # on identical points returns what an eager call returns with checks disabled.
+ p = torch.tensor([[[1.0, 2.0, 3.0]] * 4], device=device, dtype=dtype)
+
+ def op(points):
+ return ParametrizedLine.through(points[0, 0], points[0, 1]).direction, fit_line(points).direction
+
+ actual = torch_optimizer(op)(p)
+ checks_were_enabled = are_checks_enabled()
+ disable_checks()
+ try:
+ expected = op(p)
+ finally:
+ if checks_were_enabled:
+ enable_checks()
+ self.assert_close(actual[0], expected[0])
+ self.assert_close(actual[1], expected[1])
+
+ def test_fit_line_small_valid_set_still_fits(self, device, dtype):
+ # The degeneracy test is relative, not absolute: a small-but-distinct set still fits.
+ points = torch.tensor([[[1e-6, 2e-6], [3e-6, 7e-6]]], device=device, dtype=dtype)
+ line = fit_line(points)
+ assert line.direction.shape == (1, 2)
+ assert torch.isfinite(line.direction).all()
+ assert torch.isfinite(line.origin).all()
+
@pytest.mark.parametrize("dim", (2, 3))
def test_gradcheck(self, device, dim):
# Two point sets whose rows differ, each projected onto its own fitted line (#5013).
diff --git a/tests/geometry/test_plane.py b/tests/geometry/test_plane.py
index 021c6349d..874a23228 100644
--- a/tests/geometry/test_plane.py
+++ b/tests/geometry/test_plane.py
@@ -19,7 +19,7 @@ import pytest
import torch
from kornia.core.check import are_checks_enabled, disable_checks, enable_checks
-from kornia.core.exceptions import BaseError
+from kornia.core.exceptions import BaseError, ValueCheckError
from kornia.geometry.plane import Hyperplane, fit_plane
from kornia.geometry.vector import Vector3
@@ -32,7 +32,9 @@ class TestFitPlane(BaseTester):
@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)
+ # A plane needs non-collinear points: ones() is a set of identical points, rejected since #5041.
+ t = torch.linspace(-1.0, 1.0, N, device=device, dtype=dtype)
+ points = torch.stack([t, t**2, 1.0 - t], dim=-1).expand(N, D).contiguous()
plane = fit_plane(points)
assert isinstance(plane, Hyperplane)
assert plane.offset.shape == ()
@@ -58,6 +60,37 @@ class TestFitPlane(BaseTester):
def test_gradcheck(self, device):
pass
+ def test_fit_plane_degenerate_raises_5041(self, device, dtype):
+ # #5041: fewer than three points, collinear points or identical points used to
+ # return an arbitrary valid-looking plane normal.
+ a = torch.tensor([1.0, 1.0, 1.0], device=device, dtype=dtype)
+ b = torch.tensor([2.0, 3.0, 4.0], device=device, dtype=dtype)
+ c = 2 * b - a
+ with pytest.raises(ValueCheckError, match="at least three points"):
+ fit_plane(a[None])
+ with pytest.raises(ValueCheckError, match="at least three points"):
+ fit_plane(torch.stack([a, b]))
+ with pytest.raises(ValueCheckError, match="not collinear"):
+ fit_plane(torch.stack([a, b, c]))
+ with pytest.raises(ValueCheckError, match="not identical"):
+ fit_plane(torch.stack([a, a.clone(), a.clone()]))
+ # Collinear along an axis: the second singular value is exactly 0.
+ on_axis = torch.tensor([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0]], device=device, dtype=dtype)
+ with pytest.raises(ValueCheckError, match="not collinear"):
+ fit_plane(on_axis)
+ # Identical points whose mean rounds are still rejected as identical.
+ rounding = torch.tensor([0.1, 0.7, 0.3], device=device, dtype=dtype)
+ with pytest.raises(ValueCheckError, match="not identical"):
+ fit_plane(rounding.expand(3, 3))
+
+ def test_fit_plane_small_valid_set_still_fits(self, device, dtype):
+ # The collinearity test is relative, not absolute: a small non-degenerate set still fits.
+ s = 1e-6
+ points = torch.tensor([[0.0, 0.0, 0.0], [s, 0.0, 0.0], [0.0, s, 0.0]], device=device, dtype=dtype)
+ plane = fit_plane(points)
+ assert plane.normal.shape == (3,)
+ assert torch.isfinite(plane.normal.unwrap()).all()
+
# TODO: implement the rest of methods
class TestHyperplane(BaseTester):
@@ -100,6 +133,63 @@ class TestHyperplane(BaseTester):
assert p0.normal.shape == shape or (3,)
assert p0.offset.shape == ((*shape,) if shape is not None else ())
+ def test_through_collinear_points_raises_5041(self, device, dtype):
+ # #5041: collinear (or coincident) points used to take the SVD fallback and return an
+ # arbitrary plane containing the line instead of raising.
+ a = torch.tensor([1.0, 1.0, 1.0], device=device, dtype=dtype)
+ b = torch.tensor([2.0, 3.0, 4.0], device=device, dtype=dtype)
+ c = 2 * b - a
+ with pytest.raises(ValueCheckError, match="not collinear"):
+ Hyperplane.through(a, b, c)
+ with pytest.raises(ValueCheckError, match="not collinear"):
+ Hyperplane.through(a, a.clone(), a.clone())
+ # A batch is rejected as a whole when one of its rows is degenerate.
+ p0 = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype)
+ p1 = torch.tensor([0.0, 2.0, 0.0], device=device, dtype=dtype)
+ p2 = torch.tensor([0.0, 0.0, 3.0], device=device, dtype=dtype)
+ with pytest.raises(ValueCheckError, match="not collinear"):
+ Hyperplane.through(torch.stack([p0, a]), torch.stack([p1, b]), torch.stack([p2, c]))
+
+ @pytest.mark.parametrize("scale", (1.0, 1e-4))
+ def test_through_small_valid_triangle_still_fits(self, device, dtype, scale):
+ # A small triangle is not collinear. In float16 the cross product of the 1e-4 triangle underflows to 0
+ # (1e-8 is below the smallest subnormal), so it reaches the SVD fallback, which must not reject it.
+ p0 = torch.tensor([0.0, 0.0, 0.0], device=device, dtype=dtype)
+ p1 = torch.tensor([scale, 0.0, 0.0], device=device, dtype=dtype)
+ p2 = torch.tensor([0.0, scale, 0.0], device=device, dtype=dtype)
+ plane = Hyperplane.through(p0, p1, p2)
+ self.assert_close(plane.normal.unwrap().abs(), torch.tensor([0.0, 0.0, 1.0], device=device, dtype=dtype))
+
+ def test_dynamo_skips_degenerate_checks(self, device, dtype, torch_optimizer):
+ # The degeneracy checks depend on tensor values, so they are skipped under torch.compile: a compiled call
+ # on collinear points returns what an eager call returns with checks disabled.
+ a = torch.tensor([1.0, 1.0, 1.0], device=device, dtype=dtype)
+ b = torch.tensor([2.0, 3.0, 4.0], device=device, dtype=dtype)
+ c = 2 * b - a
+
+ def op(p0, p1, p2):
+ return Hyperplane.through(p0, p1, p2).normal.unwrap(), fit_plane(torch.stack([p0, p1, p2])).normal.unwrap()
+
+ actual = torch_optimizer(op)(a, b, c)
+ checks_were_enabled = are_checks_enabled()
+ disable_checks()
+ try:
+ expected = op(a, b, c)
+ finally:
+ if checks_were_enabled:
+ enable_checks()
+ self.assert_close(actual[0], expected[0])
+ self.assert_close(actual[1], expected[1])
+
+ def test_thin_valid_triangle_still_fits(self, device, dtype):
+ # The collinearity tolerance scales with the dtype: a sliver whose height is 64 machine epsilons of its
+ # base is a valid plane in every dtype (in float64 that is 1.4e-14, far below a fixed 1e-6 tolerance).
+ h = 64 * torch.finfo(dtype).eps
+ points = torch.tensor([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.5, h, 0.0]], device=device, dtype=dtype)
+ expected = torch.tensor([0.0, 0.0, 1.0], device=device, dtype=dtype)
+ self.assert_close(Hyperplane.through(points[0], points[1], points[2]).normal.unwrap().abs(), expected)
+ self.assert_close(fit_plane(points).normal.unwrap().abs(), expected)
+
@pytest.mark.parametrize("shape", (None, (1,), (2, 1)))
def test_abs_signed_distance(self, device, dtype, shape):
p0 = Vector3.random(shape, device, dtype)