π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
feat(geometry): implement closed-form solve_quartic (#3536)
Zeel Darji4b3f21683223
diff --git a/kornia/geometry/solvers/__init__.py b/kornia/geometry/solvers/__init__.pyindex af4655acd..09ce29815 100644--- a/kornia/geometry/solvers/__init__.py+++ b/kornia/geometry/solvers/__init__.py@@ -26,6 +26,7 @@ from .polynomial_solver import (multiply_deg_two_one_poly,solve_cubic,solve_quadratic,+ solve_quartic,)__all__ = [@@ -34,4 +35,5 @@ __all__ = ["multiply_deg_two_one_poly","solve_cubic","solve_quadratic",+ "solve_quartic",]diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.pyindex ea781a39e..ef593d736 100644--- a/kornia/geometry/solvers/polynomial_solver.py+++ b/kornia/geometry/solvers/polynomial_solver.py@@ -213,9 +213,112 @@ def solve_cubic(coeffs: torch.Tensor) -> torch.Tensor:return solutions-# def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:-# TODO: Quartic equation solver-# return solutions+def solve_quartic(coeffs: torch.Tensor) -> torch.Tensor:+ r"""Solve given quartic equation.++ The function takes the coefficients of quartic equation and returns+ the real roots.++ .. math:: coeffs[0]x^4 + coeffs[1]x^3 + coeffs[2]x^2 + coeffs[3]x + coeffs[4] = 0++ Args:+ coeffs : The coefficients quartic equation : `(B, 5)`++ Returns:+ A torch.Tensor of shape `(B, 4)` containing the real roots to the quartic equation.++ Example:+ >>> coeffs = torch.tensor([[1., -10., 35., -50., 24.]])+ >>> roots = solve_quartic(coeffs)++ .. note::+ In cases where a quartic polynomial has fewer than four real roots, the remaining entries+ in the output are set to 0. Similarly, any non-real (complex) roots are represented as 0.+ This is done to maintain a consistent output shape for all cases.+ """+ KORNIA_CHECK_SHAPE(coeffs, ["B", "5"])++ # Coefficients+ a, b, c, d, e = coeffs.unbind(dim=-1)++ solutions = torch.zeros((len(coeffs), 4), device=coeffs.device, dtype=coeffs.dtype)++ # Numerical tolerances+ zero_tol = 1e-6 if coeffs.dtype == torch.float32 else 1e-12++ # Cubic fallback for a approx 0+ mask_a_zero = torch.abs(a) < zero_tol+ mask_quartic = ~mask_a_zero++ if torch.any(mask_a_zero):+ solutions[mask_a_zero, 0:3] = solve_cubic(coeffs[mask_a_zero, 1:])++ if not torch.any(mask_quartic):+ return solutions++ # Normalized coefficients: x^4 + A*x^3 + B*x^2 + C*x + D = 0+ a_q = a[mask_quartic]+ inv_a = 1.0 / a_q++ A = b[mask_quartic] * inv_a+ B = c[mask_quartic] * inv_a+ C = d[mask_quartic] * inv_a+ D = e[mask_quartic] * inv_a++ # Resolvent cubic coefficients+ rc_a = torch.ones_like(A)+ rc_b = -B+ rc_c = A * C - 4.0 * D+ rc_d = -1.0 * (A * A * D - 4.0 * B * D + C * C)++ cubic_coeffs = torch.stack([rc_a, rc_b, rc_c, rc_d], dim=1)++ # Solve cubic (Ferrari's method)+ y_roots = solve_cubic(cubic_coeffs)++ # Robust Root Selection: Pick y that maximizes R^2+ A_sq = A * A+ R_sq_candidates = 0.25 * A_sq.unsqueeze(-1) - B.unsqueeze(-1) + y_roots++ best_idx = torch.argmax(R_sq_candidates, dim=-1, keepdim=True)+ y = torch.gather(y_roots, -1, best_idx).squeeze(-1)+ R_sq = torch.gather(R_sq_candidates, -1, best_idx).squeeze(-1)++ R = torch.sqrt(torch.clamp(R_sq, min=0.0))++ # Compute E term+ mask_R_small = torch.abs(R) < zero_tol+ mask_R_large = ~mask_R_small+ E = torch.zeros_like(R)++ if torch.any(mask_R_large):+ numerator = A[mask_R_large] * y[mask_R_large] - 2.0 * C[mask_R_large]+ denominator = 4.0 * R[mask_R_large]+ E[mask_R_large] = numerator / denominator++ # Fallback for R approx 0+ if torch.any(mask_R_small):+ radicand = 0.25 * y[mask_R_small] * y[mask_R_small] - D[mask_R_small]+ E[mask_R_small] = torch.sqrt(torch.clamp(radicand, min=0.0))++ # Solve two resulting quadratic equations+ # Quad 1: x^2 + (A/2 - R)x + (y/2 - E) = 0+ q1_a = torch.ones_like(A)+ q1_b = 0.5 * A - R+ q1_c = 0.5 * y - E++ # Quad 2: x^2 + (A/2 + R)x + (y/2 + E) = 0+ q2_a = torch.ones_like(A)+ q2_b = 0.5 * A + R+ q2_c = 0.5 * y + E++ roots1 = solve_quadratic(torch.stack([q1_a, q1_b, q1_c], dim=1))+ roots2 = solve_quadratic(torch.stack([q2_a, q2_b, q2_c], dim=1))++ solutions[mask_quartic, 0:2] = roots1+ solutions[mask_quartic, 2:4] = roots2++ return solutions# Referencediff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.pyindex 1defdbfb5..899920fae 100644--- a/tests/geometry/solvers/test_polynomial_solver.py+++ b/tests/geometry/solvers/test_polynomial_solver.py@@ -246,3 +246,127 @@ class TestDeterminantToPolynomial(BaseTester):# Compare result with expected valuesself.assert_close(result, expected, rtol=1e-5, atol=1e-5)+++class TestQuarticSolver(BaseTester):+ def test_smoke(self, device, dtype):+ coeffs = torch.rand(1, 5, device=device, dtype=dtype)+ roots = solver.solve_quartic(coeffs)+ assert roots.shape == (1, 4)++ @pytest.mark.parametrize("batch_size", [1, 2, 4, 7])+ def test_shape(self, batch_size, device, dtype):+ B: int = batch_size+ coeffs = torch.rand(B, 5, device=device, dtype=dtype)+ roots = solver.solve_quartic(coeffs)+ assert roots.shape == (B, 4)++ @pytest.mark.parametrize(+ "coeffs, expected_solutions",+ [+ # Case 1: Distinct Real Roots+ # x^4 - 10x^3 + 35x^2 - 50x + 24 = 0 -> Roots: 1, 2, 3, 4+ (+ torch.tensor([[1.0, -10.0, 35.0, -50.0, 24.0]]),+ torch.tensor([[1.0, 2.0, 3.0, 4.0]]),+ ),+ # Case 2: Biquadratic (Symmetric)+ # x^4 - 5x^2 + 4 = 0 -> Roots: 1, -1, 2, -2+ (+ torch.tensor([[1.0, 0.0, -5.0, 0.0, 4.0]]),+ torch.tensor([[-2.0, -1.0, 1.0, 2.0]]),+ ),+ # Case 3: Double Roots+ # (x-2)^2 * (x-3) * (x+1) -> Roots: -1, 2, 2, 3+ (+ torch.tensor([[1.0, -6.0, 9.0, 4.0, -12.0]]),+ torch.tensor([[-1.0, 2.0, 2.0, 3.0]]),+ ),+ # Case 4: Cubic Fallback (a=0)+ # 0x^4 + x^3 - 6x^2 + 11x - 6 = 0 -> Roots: 1, 2, 3. Last col 0.+ (+ torch.tensor([[0.0, 1.0, -6.0, 11.0, -6.0]]),+ torch.tensor([[1.0, 2.0, 3.0, 0.0]]),+ ),+ # Case 5: Degenerate / All Zeros+ # x^4 = 0 -> Roots: 0, 0, 0, 0+ (+ torch.tensor([[1.0, 0.0, 0.0, 0.0, 0.0]]),+ torch.tensor([[0.0, 0.0, 0.0, 0.0]]),+ ),+ # Case 6: Complex Roots (Should be 0s per contract)+ # x^4 + 1 = 0 -> Roots: +/- sqrt(i) ... all complex -> 0, 0, 0, 0+ (+ torch.tensor([[1.0, 0.0, 0.0, 0.0, 1.0]]),+ torch.tensor([[0.0, 0.0, 0.0, 0.0]]),+ ),+ # Case 7: Mixed Real/Complex+ # x^4 - 1 = 0 -> Roots: 1, -1, i, -i -> Real: 1, -1. Others 0.+ (+ torch.tensor([[1.0, 0.0, 0.0, 0.0, -1.0]]),+ torch.tensor([[-1.0, 1.0, 0.0, 0.0]]),+ ),+ ],+ )+ def test_solve_quartic(self, coeffs, expected_solutions, device, dtype):+ coeffs = coeffs.to(device, dtype)+ expected_solutions = expected_solutions.to(device, dtype)++ roots = solver.solve_quartic(coeffs)++ # Sort roots to ensure order-invariant comparison+ # We sort both expected and actual to match this behavior.+ roots_sorted, _ = torch.sort(roots, dim=-1)+ expected_sorted, _ = torch.sort(expected_solutions, dim=-1)++ self.assert_close(roots_sorted, expected_sorted, rtol=1e-3, atol=1e-3)++ def test_random(self, device, dtype):+ # Generate random roots and construct coefficients to ensure valid solutions exist+ B = 10+ true_roots = torch.randn(B, 4, device=device, dtype=dtype)++ # Sort true roots for comparison later+ true_roots_sorted, _ = torch.sort(true_roots, dim=-1)++ r1, r2, r3, r4 = true_roots.unbind(-1)++ # Construct polynomial coefficients from roots+ # (x-r1)(x-r2)(x-r3)(x-r4) = 0+ a = torch.ones(B, device=device, dtype=dtype)+ b = -(r1 + r2 + r3 + r4)+ c = r1 * r2 + r1 * r3 + r1 * r4 + r2 * r3 + r2 * r4 + r3 * r4+ d = -(r1 * r2 * r3 + r1 * r2 * r4 + r1 * r3 * r4 + r2 * r3 * r4)+ e = r1 * r2 * r3 * r4++ coeffs = torch.stack([a, b, c, d, e], dim=-1)+ computed_roots = solver.solve_quartic(coeffs)++ computed_roots_sorted, _ = torch.sort(computed_roots, dim=-1)++ # 1. Check Residuals (Equation satisfaction)+ residuals = (+ coeffs[:, 0:1] * computed_roots**4+ + coeffs[:, 1:2] * computed_roots**3+ + coeffs[:, 2:3] * computed_roots**2+ + coeffs[:, 3:4] * computed_roots+ + coeffs[:, 4:5]+ )+ self.assert_close(residuals, torch.zeros_like(residuals), atol=1e-3, rtol=1e-3)++ # 2. Check Root Matching (Stronger Test)+ # Since we synthesized the coefficients from real roots, we expect+ # to recover exactly those roots (no complex outputs).+ self.assert_close(computed_roots_sorted, true_roots_sorted, atol=1e-3, rtol=1e-3)++ def test_gradcheck(self, device):+ # Use a specific polynomial with distinct roots to ensure gradient stability+ # x^4 - 10x^3 + 35x^2 - 50x + 24 = 0+ # Avoid double roots for gradcheck as gradients are undefined/infinite there.+ coeffs = torch.tensor(+ [[1.0, -10.0, 35.0, -50.0, 24.0]],+ device=device,+ dtype=torch.float64,+ requires_grad=True,+ )+ self.gradcheck(solver.solve_quartic, (coeffs,), raise_exception=True, fast_mode=True)