🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): solve polynomials with a zero leading coefficient (#4913)
Rızgar Ozane05b0eedf4c6
diff --git a/changelog.d/4913.fixed.md b/changelog.d/4913.fixed.mdnew file mode 100644index 000000000..babea277a--- /dev/null+++ b/changelog.d/4913.fixed.md@@ -0,0 +1 @@+`solve_quadratic`, `solve_cubic` and `solve_quartic` now solve a polynomial with a zero leading coefficient as the lower-degree polynomial it is. Before, `solve_quadratic` returned `nan`/`inf` for a linear equation, `solve_cubic` returned `1.0` for every linear equation and zeros for `bx² + d`, and `solve_quartic` inherited both. (#4873)diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex 8b45c41d2..acc2688f4 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -532,7 +532,7 @@ normalised camera coordinates, and :func:`~kornia.geometry.homography.find_homog* - polynomial roots- ``solve_quadratic``, ``solve_cubic`` and ``solve_quartic`` take coefficients highest degree first andreturn only the real roots, a missing root padded with ``0.0``; ``solve_quartic``'s order is unspecified;- a zero leading coefficient gives wrong roots (`#4873 <https://github.com/kornia/kornia/issues/4873>`_)+ a zero leading coefficient lowers the degree- ``numpy.roots`` takes the same coefficient order, returns the complex roots too and drops leading zerosPitfall checklistdiff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.pyindex a3ae2fad9..9365d83b9 100644--- a/kornia/geometry/solvers/polynomial_solver.py+++ b/kornia/geometry/solvers/polynomial_solver.py@@ -41,7 +41,8 @@ def solve_quadratic(coeffs: torch.Tensor) -> torch.Tensor:it matters.- For ``coeffs = [a, b, c]`` and ``D = b**2 - 4 * a * c``, ``solve_quadratic`` returns``[(-b + sqrt(D)) / (2 * a), (-b - sqrt(D)) / (2 * a)]``, so the order flips with the sign of ``a``.- - Known defects: ``a = 0`` returns non-finite values (`#4873 <https://github.com/kornia/kornia/issues/4873>`_).+ - A zero leading coefficient lowers the degree: with ``a = 0`` the root ``-c / b`` of the linear equation+ is in slot 0, as :func:`solve_cubic` and :func:`solve_quartic` do for their lower-degree rows.Args:coeffs : The coefficients of quadratic equation :`(B, 3)`@@ -68,8 +69,14 @@ def solve_quadratic(coeffs: torch.Tensor) -> torch.Tensor:mask_negative = delta < 0mask_zero = delta == 0+ # With a == 0 the equation is linear, bx + c = 0: its root goes to slot 0 and slot 1 is padded.+ # Dividing by a placeholder 1 there keeps the unused quadratic lanes (and their gradients) finite.+ one = torch.ones_like(a)+ mask_linear = a == 0+ mask_b_zero = b == 0+# Calculate 1/(2*a) for efficient computation- inv_2a = 0.5 / a+ inv_2a = 0.5 / torch.where(mask_linear, one, a)# Branch-free selection so the function traces under graph capture. The square root is only taken# where delta > 0: a zero discriminant yields the double root -b/(2a) with sqrt_delta = 0, and a@@ -82,9 +89,18 @@ def solve_quadratic(coeffs: torch.Tensor) -> torch.Tensor:root_plus = (-b + sqrt_delta) * inv_2aroot_minus = (-b - sqrt_delta) * inv_2a- return torch.stack(- [torch.where(mask_negative, zero, root_plus), torch.where(mask_negative, zero, root_minus)], dim=-1- )++ # The a * x^2 / b term is 0 in the forward pass, but it keeps the root's dependence on a in the+ # gradient (d root / da = -root^2 / b). With b == 0 as well there is no root to report. The lane+ # takes c only from the linear rows: torch.where differentiates the lane it discards too, and for an+ # ordinary row with a tiny b, (c / b)^2 overflows there and turns the row's gradient into nan.+ safe_b = torch.where(mask_b_zero, one, b)+ root_linear = -torch.where(mask_linear, c, zero) / safe_b+ root_linear = torch.where(mask_b_zero, zero, root_linear - a * root_linear * root_linear / safe_b)++ root_0 = torch.where(mask_linear, root_linear, torch.where(mask_negative, zero, root_plus))+ root_1 = torch.where(mask_linear | mask_negative, zero, root_minus)+ return torch.stack([root_0, root_1], dim=-1)def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:@@ -98,9 +114,7 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:Convention:- Coefficient layout and zero padding as :func:`solve_quadratic`. Three real roots are returned unsorted,and a single real root is in slot 0.- - Known defects: with a zero leading coefficient, a linear equation gets the root ``1.0`` and- ``bx^2 + d`` returns zeros- (`#4873 <https://github.com/kornia/kornia/issues/4873>`_).+ - A zero leading coefficient lowers the degree, and the roots of the remaining polynomial come first.Args:coeffs : The coefficients cubic equation : `(B, 4)`@@ -150,13 +164,18 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:# No need for explicit handling of mask_zero_order as solutions already contains torch.zeros by default.mask_first_order = mask_a_zero & mask_b_zero & ~mask_c_zero- mask_second_order = mask_a_zero & ~mask_b_zero & ~mask_c_zero+ mask_second_order = mask_a_zero & ~mask_b_zeroif torch.any(mask_second_order):solutions[mask_second_order, 0:2] = solve_quadratic(coeffs[mask_second_order, 1:])if torch.any(mask_first_order):- solutions[mask_first_order, 0] = torch.tensor(1.0, device=a.device, dtype=a.dtype)+ # cx + d = 0. The (a * x + b) * x^2 / c term is 0 in the forward pass, but it keeps the root's+ # dependence on a and b in the gradient, as solve_quadratic does for its linear case.+ c_first = c[mask_first_order]+ x0_first = -d[mask_first_order] / c_first+ a_first, b_first = a[mask_first_order], b[mask_first_order]+ solutions[mask_first_order, 0] = x0_first - (a_first * x0_first + b_first) * x0_first * x0_first / c_first# Normalized form x^3 + a2 * x^2 + a1 * x + a0 = 0inv_a = 1.0 / a[~mask_a_zero]@@ -302,8 +321,7 @@ def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:roots and return values that are not roots (`#4833 <https://github.com/kornia/kornia/issues/4833>`_);a leading coefficient below ``1e-6`` in magnitude (``1e-12`` in float64) counts as zero whatever theother coefficients are, so a small multiple of a quartic is solved as a cubic and loses its roots- (`#4905 <https://github.com/kornia/kornia/issues/4905>`_); and a row with a zero leading coefficient is- passed to :func:`solve_cubic`, with its defects (`#4873 <https://github.com/kornia/kornia/issues/4873>`_).+ (`#4905 <https://github.com/kornia/kornia/issues/4905>`_).Args:coeffs : The coefficients quartic equation : `(B, 5)`diff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.pyindex 6a65e7fd3..d08e72d49 100644--- a/tests/geometry/solvers/test_polynomial_solver.py+++ b/tests/geometry/solvers/test_polynomial_solver.py@@ -90,7 +90,7 @@ class TestCubicSolver(BaseTester):(torch.tensor([[2.0, 3.0, -11.0, -6.0]]), torch.tensor([[2.0, -3.0, -0.5]])),(torch.tensor([[1.0, 0.0, 4.0, 4.0]]), torch.tensor([[-0.847, 0.0, 0.0]])),(torch.tensor([[2.0, -6.0, 6.0, -2.0]]), torch.tensor([[1.0, 1.0, 1.0]])),- (torch.tensor([[0.0, 0.0, 1.0, -1.0]]), torch.tensor([[1.0, 0.0, 0.0]])), # handle first order+ (torch.tensor([[0.0, 0.0, 2.0, -6.0]]), torch.tensor([[3.0, 0.0, 0.0]])), # handle first order(torch.tensor([[0.0, 1.0, -5.0, 6.0]]), torch.tensor([[3.0, 2.0, 0.0]])), # handle second order],)@@ -1127,22 +1127,66 @@ class TestConventionPolynomialSolvers(BaseTester):@pytest.mark.parametrize("fn, coeffs, expected",[- (solver.solve_cubic, [0.0, 0.0, 2.0, -6.0], [1.0, 0.0, 0.0]), # 2x - 6: the root is 3- (solver.solve_cubic, [0.0, 1.0, 0.0, -4.0], [0.0, 0.0, 0.0]), # x^2 - 4: the roots +-2 are lost- (solver.solve_quartic, [0.0, 0.0, 0.0, 2.0, -6.0], [1.0, 0.0, 0.0, 0.0]), # through solve_cubic- (solver.solve_quadratic, [0.0, 2.0, -6.0], None), # 2x - 6: non-finite+ (solver.solve_cubic, [0.0, 0.0, 2.0, -6.0], [3.0, 0.0, 0.0]), # 2x - 6+ (solver.solve_cubic, [0.0, 0.0, 1.0, 5.0], [-5.0, 0.0, 0.0]), # x + 5+ (solver.solve_cubic, [0.0, 1.0, 0.0, -4.0], [2.0, -2.0, 0.0]), # x^2 - 4+ (solver.solve_cubic, [0.0, 0.0, 0.0, 3.0], [0.0, 0.0, 0.0]), # 3: no root+ (solver.solve_quartic, [0.0, 0.0, 0.0, 2.0, -6.0], [3.0, 0.0, 0.0, 0.0]), # through solve_cubic+ (solver.solve_quartic, [0.0, 0.0, 2.0, 0.0, -8.0], [2.0, -2.0, 0.0, 0.0]), # 2x^2 - 8+ (solver.solve_quadratic, [0.0, 2.0, -6.0], [3.0, 0.0]), # 2x - 6+ (solver.solve_quadratic, [0.0, -4.0, 2.0], [0.5, 0.0]), # -4x + 2+ (solver.solve_quadratic, [0.0, 0.0, 5.0], [0.0, 0.0]), # 5: no root+ ],+ ids=[+ "cubic_linear",+ "cubic_linear_negative_root",+ "cubic_bx2_plus_d",+ "cubic_constant",+ "quartic_linear",+ "quartic_bx2_plus_d",+ "quadratic_linear",+ "quadratic_linear_negative_b",+ "quadratic_constant",],- ids=["cubic_linear", "cubic_bx2_plus_d", "quartic_linear", "quadratic_linear"],)- def test_wart_solve_cubic_linear_returns_one_4873(self, fn, coeffs, expected, device, dtype):- # #4873: a zero leading coefficient is not handled. solve_cubic writes the constant 1.0 for any linear- # equation and drops the roots of bx^2 + d, solve_quartic inherits that, and solve_quadratic divides by- # zero. Once fixed, 2x - 6 gives the root 3 and x^2 - 4 gives +-2.+ def test_convention_zero_leading_coefficient_4873(self, fn, coeffs, expected, device, dtype):+ # #4873: a zero leading coefficient lowers the degree. The roots of the remaining polynomial are+ # returned with the usual 0.0 padding, as numpy.roots does after dropping leading zeros.out = fn(torch.tensor([coeffs], device=device, dtype=dtype))- if expected is None:- assert not bool(torch.isfinite(out).all())- else:- self.assert_close(out, torch.tensor([expected], device=device, dtype=dtype))+ self.assert_close(out, torch.tensor([expected], device=device, dtype=dtype))++ @pytest.mark.parametrize(+ "fn, coeffs",+ [(solver.solve_quadratic, [0.0, 2.0, -6.0]), (solver.solve_cubic, [0.0, 0.0, 2.0, -6.0])],+ ids=["quadratic_linear", "cubic_linear"],+ )+ def test_convention_zero_leading_coefficient_gradient_4873(self, fn, coeffs, device, dtype):+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("Gradient values are checked in float32 and float64.")+ # The root 3 of 2x - 6 keeps its dependence on the zero higher-order coefficients. By the implicit function+ # theorem d root / d coeffs[k] = -root^(n - k) / p'(root), with p'(root) = 2. gradcheck cannot stand in for+ # this: a negative leading coefficient adds real roots, and slot 0 can jump to one of them.+ x = torch.tensor([coeffs], device=device, dtype=dtype, requires_grad=True)+ (grad,) = torch.autograd.grad(fn(x)[0, 0], x)+ powers = [3.0 ** (len(coeffs) - 1 - k) for k in range(len(coeffs))]+ self.assert_close(grad, -torch.tensor([powers], device=device, dtype=dtype) / 2.0)++ @pytest.mark.parametrize(+ "fn, lead", [(solver.solve_quadratic, []), (solver.solve_cubic, [0.0])], ids=["quadratic", "cubic"]+ )+ def test_convention_zero_leading_coefficient_branch_keeps_ordinary_gradients_finite_4873(+ self, fn, lead, device, dtype+ ):+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("Gradient values are checked in float32 and float64.")+ # x^2 + b x - 1 with a tiny b is an ordinary quadratic with the roots +-1, but (c / b)^2 overflows.+ # torch.where still differentiates the linear lane it discards for this row, so that lane must not see c.+ b = 1e-20 if dtype == torch.float32 else 1e-160+ x = torch.tensor([[*lead, 1.0, b, -1.0]], device=device, dtype=dtype, requires_grad=True)+ (grad,) = torch.autograd.grad(fn(x).sum(), x)+ # The roots sum to -b / a.+ expected = torch.tensor([[*lead, b, -1.0, 0.0]], device=device, dtype=dtype)+ self.assert_close(grad, expected)def test_wart_solve_quartic_small_scale_4833(self, device, dtype):if dtype in (torch.float16, torch.bfloat16):