Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

solvers : Separating General Functionalities(polynomial solver) into `solvers` Submodule (#2465)

Anandhu875edb236743
diff --git a/kornia/geometry/__init__.py b/kornia/geometry/__init__.py
index c32a4e9aa..dadab871a 100644
--- a/kornia/geometry/__init__.py
+++ b/kornia/geometry/__init__.py
@@ -9,5 +9,6 @@ from .liegroup import *
from .linalg import *
from .line import *
from .ransac import *
+from .solvers import *
from .subpix import *
from .transform import *
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index 6f51602b5..01654c8ad 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -1,6 +1,5 @@
"""Module containing the functionalities for computing the Fundamental Matrix."""
-import math
from typing import Literal, Optional, Tuple
import torch
@@ -9,6 +8,7 @@ from kornia.core import Tensor, concatenate
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
from kornia.geometry.linalg import transform_points
+from kornia.geometry.solvers import solve_cubic
from kornia.utils.helpers import _torch_svd_cast
@@ -71,173 +71,6 @@ def normalize_transformation(M: Tensor, eps: float = 1e-8) -> Tensor:
return torch.where(norm_val.abs() > eps, M / (norm_val + eps), M)
-# Reference : https://github.com/opencv/opencv/blob/4.x/modules/calib3d/src/polynom_solver.cpp
-def solve_quadratic(coeffs: Tensor) -> Tensor:
- r"""Solve given quadratic equation.
-
- The function takes the coefficients of quadratic equation and returns the solutions.
-
- Args:
- coeffs : The coefficients of quadratic equation :`(B, 3)`
-
- Returns:
- A tensor of shape `(B, 2)` containing the solutions to the quadratic equation.
- """
-
- KORNIA_CHECK_SHAPE(coeffs, ['B', '3'])
-
- # Coefficients of quadratic equation
- a = coeffs[:, 0] # coefficient of x^2
- b = coeffs[:, 1] # coefficient of x
- c = coeffs[:, 2] # constant term
-
- # Calculate discriminant
- delta = b * b - 4 * a * c
-
- # Create masks for negative and zero discriminant
- mask_negative = delta < 0
- mask_zero = delta == 0
-
- # Calculate 1/(2*a) for efficient computation
- inv_2a = 0.5 / a
-
- # Initialize solution tensor
- solution = torch.zeros((coeffs.shape[0], 2), device=coeffs.device, dtype=coeffs.dtype)
-
- # Handle cases with negative discriminant
- # if torch.any(mask_negative):
- # solution[mask_negative, :] = torch.tensor(0, device=coeffs.device, dtype=coeffs.dtype)
-
- sqrt_delta = torch.sqrt(delta)
-
- # Handle cases with non-negative discriminant
- mask = torch.bitwise_and(~mask_negative, ~mask_zero)
- if torch.any(mask):
- solution[mask, 0] = (-b[mask] + sqrt_delta[mask]) * inv_2a[mask]
- solution[mask, 1] = (-b[mask] - sqrt_delta[mask]) * inv_2a[mask]
-
- return solution
-
-
-def solve_cubic(coeffs: Tensor) -> Tensor:
- r"""Solve given cubic equation.
-
- The function takes the coefficients of cubic equation and returns
- the solutions.
-
- Args:
- coeffs : The coefficients cubic equation : `(B, 4)`
-
- Returns:
- A tensor of shape `(B, 3)` containing the solutions to the cubic equation.
- """
- KORNIA_CHECK_SHAPE(coeffs, ['B', '4'])
-
- _PI = torch.tensor(math.pi, device=coeffs.device, dtype=coeffs.dtype)
-
- # Coefficients of cubic equation
- a = coeffs[:, 0] # coefficient of x^3
- b = coeffs[:, 1] # coefficient of x^2
- c = coeffs[:, 2] # coefficient of x
- d = coeffs[:, 3] # constant term
-
- torch.tensor(0, device=a.device, dtype=a.dtype)
- one_tensor = torch.tensor(1.0, device=a.device, dtype=a.dtype)
-
- solutions = torch.zeros((len(coeffs), 3), device=a.device, dtype=a.dtype)
-
- mask_a_zero = a == 0
- mask_b_zero = b == 0
- mask_c_zero = c == 0
-
- mask_a_zero & mask_b_zero & mask_c_zero
- mask_first_order = mask_a_zero & mask_b_zero & ~mask_c_zero
- mask_second_order = mask_a_zero & ~mask_b_zero & ~mask_c_zero
-
- if 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] = one_tensor
-
- # if torch.any(mask_zero_order):
- # solutions[mask_zero_order, 0] = zero_tensor
-
- # Normalized form x^3 + a2 * x^2 + a1 * x + a0 = 0
- inv_a = 1.0 / a[~mask_a_zero]
- b_a = inv_a * b[~mask_a_zero]
- b_a2 = b_a * b_a
-
- c_a = inv_a * c[~mask_a_zero]
- d_a = inv_a * d[~mask_a_zero]
-
- # Solve the cubic equation
- Q = (3 * c_a - b_a2) / 9
- R = (9 * b_a * c_a - 27 * d_a - 2 * b_a * b_a2) / 54
- Q3 = Q * Q * Q
- D = Q3 + R * R
- b_a_3 = (1.0 / 3.0) * b_a
-
- a_Q_zero = torch.ones_like(a)
- a_R_zero = torch.ones_like(a)
- a_D_zero = torch.ones_like(a)
-
- a_Q_zero[~mask_a_zero] = Q
- a_R_zero[~mask_a_zero] = R
- a_D_zero[~mask_a_zero] = D
-
- # Q == 0
- mask_Q_zero = (Q == 0) & (R != 0)
- mask_Q_zero_solutions = (a_Q_zero == 0) & (a_R_zero != 0)
-
- if torch.any(mask_Q_zero):
- x0_Q_zero = torch.pow(2 * R[mask_Q_zero], 1 / 3) - b_a_3[mask_Q_zero]
- solutions[mask_Q_zero_solutions, 0] = x0_Q_zero
-
- mask_QR_zero = (Q == 0) & (R == 0)
- mask_QR_zero_solutions = (a_Q_zero == 0) & (a_R_zero == 0)
-
- if torch.any(mask_QR_zero):
- solutions[mask_QR_zero_solutions] = torch.stack(
- [-b_a_3[mask_QR_zero], -b_a_3[mask_QR_zero], -b_a_3[mask_QR_zero]], dim=1
- )
-
- # D <= 0
- mask_D_zero = (D <= 0) & (Q != 0)
- mask_D_zero_solutions = (a_D_zero <= 0) & (a_Q_zero != 0)
-
- if torch.any(mask_D_zero):
- theta_D_zero = torch.acos(R[mask_D_zero] / torch.sqrt(-Q3[mask_D_zero]))
- sqrt_Q_D_zero = torch.sqrt(-Q[mask_D_zero])
- x0_D_zero = 2 * sqrt_Q_D_zero * torch.cos(theta_D_zero / 3.0) - b_a_3[mask_D_zero]
- x1_D_zero = 2 * sqrt_Q_D_zero * torch.cos((theta_D_zero + 2 * _PI) / 3.0) - b_a_3[mask_D_zero]
- x2_D_zero = 2 * sqrt_Q_D_zero * torch.cos((theta_D_zero + 4 * _PI) / 3.0) - b_a_3[mask_D_zero]
- solutions[mask_D_zero_solutions] = torch.stack([x0_D_zero, x1_D_zero, x2_D_zero], dim=1)
-
- a_D_positive = torch.zeros_like(a)
- a_D_positive[~mask_a_zero] = D
- # D > 0
- mask_D_positive_solution = (a_D_positive > 0) & (a_Q_zero != 0)
- mask_D_positive = (D > 0) & (Q != 0)
- if torch.any(mask_D_positive):
- AD = torch.zeros_like(R)
- BD = torch.zeros_like(R)
- R_abs = torch.abs(R)
- mask_R_positive = R_abs > 1e-16
- if torch.any(mask_R_positive):
- AD[mask_R_positive] = torch.pow(R_abs[mask_R_positive] + torch.sqrt(D[mask_R_positive]), 1 / 3)
- mask_R_positive_ = R < 0
-
- if torch.any(mask_R_positive_):
- AD[mask_R_positive_] = -AD[mask_R_positive_]
-
- BD[mask_R_positive] = -Q[mask_R_positive] / AD[mask_R_positive]
- x0_D_positive = AD[mask_D_positive] + BD[mask_D_positive] - b_a_3[mask_D_positive]
- solutions[mask_D_positive_solution, 0] = x0_D_positive
-
- return solutions
-
-
# Reference: Adapted from the 'run_7point' function in opencv
# https://github.com/opencv/opencv/blob/4.x/modules/calib3d/src/fundam.cpp
def run_7point(points1: Tensor, points2: Tensor) -> Tensor:
diff --git a/kornia/geometry/solvers/__init__.py b/kornia/geometry/solvers/__init__.py
new file mode 100644
index 000000000..ad2a5bbad
--- /dev/null
+++ b/kornia/geometry/solvers/__init__.py
@@ -0,0 +1,3 @@
+from .polynomial_solver import solve_cubic, solve_quadratic
+
+__all__ = ["solve_quadratic", "solve_cubic"]
diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.py
new file mode 100644
index 000000000..ca02709ac
--- /dev/null
+++ b/kornia/geometry/solvers/polynomial_solver.py
@@ -0,0 +1,178 @@
+"""Module containing the functionalities for computing the real roots of polynomial equation."""
+import math
+
+import torch
+
+from kornia.core import Tensor
+from kornia.core.check import KORNIA_CHECK_SHAPE
+
+
+# Reference : https://github.com/opencv/opencv/blob/4.x/modules/calib3d/src/polynom_solver.cpp
+def solve_quadratic(coeffs: Tensor) -> Tensor:
+ r"""Solve given quadratic equation.
+
+ The function takes the coefficients of quadratic equation and returns the solutions.
+
+ Args:
+ coeffs : The coefficients of quadratic equation :`(B, 3)`
+
+ Returns:
+ A tensor of shape `(B, 2)` containing the solutions to the quadratic equation.
+ """
+
+ KORNIA_CHECK_SHAPE(coeffs, ['B', '3'])
+
+ # Coefficients of quadratic equation
+ a = coeffs[:, 0] # coefficient of x^2
+ b = coeffs[:, 1] # coefficient of x
+ c = coeffs[:, 2] # constant term
+
+ # Calculate discriminant
+ delta = b * b - 4 * a * c
+
+ # Create masks for negative and zero discriminant
+ mask_negative = delta < 0
+ mask_zero = delta == 0
+
+ # Calculate 1/(2*a) for efficient computation
+ inv_2a = 0.5 / a
+
+ # Initialize solutions tensor
+ solutions = torch.zeros((coeffs.shape[0], 2), device=coeffs.device, dtype=coeffs.dtype)
+
+ # Handle cases with zero discriminant
+ if torch.any(mask_zero):
+ solutions[mask_zero, 0] = -b[mask_zero] * inv_2a[mask_zero]
+ solutions[mask_zero, 1] = solutions[mask_zero, 0]
+
+ # Negative discriminant cases are automatically handled since solutions is initialized with zeros.
+
+ sqrt_delta = torch.sqrt(delta)
+
+ # Handle cases with non-negative discriminant
+ mask = torch.bitwise_and(~mask_negative, ~mask_zero)
+ if torch.any(mask):
+ solutions[mask, 0] = (-b[mask] + sqrt_delta[mask]) * inv_2a[mask]
+ solutions[mask, 1] = (-b[mask] - sqrt_delta[mask]) * inv_2a[mask]
+
+ return solutions
+
+
+def solve_cubic(coeffs: Tensor) -> Tensor:
+ r"""Solve given cubic equation.
+
+ The function takes the coefficients of cubic equation and returns
+ the solutions.
+
+ Args:
+ coeffs : The coefficients cubic equation : `(B, 4)`
+
+ Returns:
+ A tensor of shape `(B, 3)` containing the solutions to the cubic equation.
+ """
+ KORNIA_CHECK_SHAPE(coeffs, ['B', '4'])
+
+ _PI = torch.tensor(math.pi, device=coeffs.device, dtype=coeffs.dtype)
+
+ # Coefficients of cubic equation
+ a = coeffs[:, 0] # coefficient of x^3
+ b = coeffs[:, 1] # coefficient of x^2
+ c = coeffs[:, 2] # coefficient of x
+ d = coeffs[:, 3] # constant term
+
+ solutions = torch.zeros((len(coeffs), 3), device=a.device, dtype=a.dtype)
+
+ mask_a_zero = a == 0
+ mask_b_zero = b == 0
+ mask_c_zero = c == 0
+
+ # Zero order cases are automatically handled since solutions is initialized with zeros.
+ # No need for explicit handling of mask_zero_order as solutions already contains 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
+
+ if 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)
+
+ # Normalized form x^3 + a2 * x^2 + a1 * x + a0 = 0
+ inv_a = 1.0 / a[~mask_a_zero]
+ b_a = inv_a * b[~mask_a_zero]
+ b_a2 = b_a * b_a
+
+ c_a = inv_a * c[~mask_a_zero]
+ d_a = inv_a * d[~mask_a_zero]
+
+ # Solve the cubic equation
+ Q = (3 * c_a - b_a2) / 9
+ R = (9 * b_a * c_a - 27 * d_a - 2 * b_a * b_a2) / 54
+ Q3 = Q * Q * Q
+ D = Q3 + R * R
+ b_a_3 = (1.0 / 3.0) * b_a
+
+ a_Q_zero = torch.ones_like(a)
+ a_R_zero = torch.ones_like(a)
+ a_D_zero = torch.ones_like(a)
+
+ a_Q_zero[~mask_a_zero] = Q
+ a_R_zero[~mask_a_zero] = R
+ a_D_zero[~mask_a_zero] = D
+
+ # Q == 0
+ mask_Q_zero = (Q == 0) & (R != 0)
+ mask_Q_zero_solutions = (a_Q_zero == 0) & (a_R_zero != 0)
+
+ if torch.any(mask_Q_zero):
+ x0_Q_zero = torch.pow(2 * R[mask_Q_zero], 1 / 3) - b_a_3[mask_Q_zero]
+ solutions[mask_Q_zero_solutions, 0] = x0_Q_zero
+
+ mask_QR_zero = (Q == 0) & (R == 0)
+ mask_QR_zero_solutions = (a_Q_zero == 0) & (a_R_zero == 0)
+
+ if torch.any(mask_QR_zero):
+ solutions[mask_QR_zero_solutions] = torch.stack(
+ [-b_a_3[mask_QR_zero], -b_a_3[mask_QR_zero], -b_a_3[mask_QR_zero]], dim=1
+ )
+
+ # D <= 0
+ mask_D_zero = (D <= 0) & (Q != 0)
+ mask_D_zero_solutions = (a_D_zero <= 0) & (a_Q_zero != 0)
+
+ if torch.any(mask_D_zero):
+ theta_D_zero = torch.acos(R[mask_D_zero] / torch.sqrt(-Q3[mask_D_zero]))
+ sqrt_Q_D_zero = torch.sqrt(-Q[mask_D_zero])
+ x0_D_zero = 2 * sqrt_Q_D_zero * torch.cos(theta_D_zero / 3.0) - b_a_3[mask_D_zero]
+ x1_D_zero = 2 * sqrt_Q_D_zero * torch.cos((theta_D_zero + 2 * _PI) / 3.0) - b_a_3[mask_D_zero]
+ x2_D_zero = 2 * sqrt_Q_D_zero * torch.cos((theta_D_zero + 4 * _PI) / 3.0) - b_a_3[mask_D_zero]
+ solutions[mask_D_zero_solutions] = torch.stack([x0_D_zero, x1_D_zero, x2_D_zero], dim=1)
+
+ a_D_positive = torch.zeros_like(a)
+ a_D_positive[~mask_a_zero] = D
+ # D > 0
+ mask_D_positive_solution = (a_D_positive > 0) & (a_Q_zero != 0)
+ mask_D_positive = (D > 0) & (Q != 0)
+ if torch.any(mask_D_positive):
+ AD = torch.zeros_like(R)
+ BD = torch.zeros_like(R)
+ R_abs = torch.abs(R)
+ mask_R_positive = R_abs > 1e-16
+ if torch.any(mask_R_positive):
+ AD[mask_R_positive] = torch.pow(R_abs[mask_R_positive] + torch.sqrt(D[mask_R_positive]), 1 / 3)
+ mask_R_positive_ = R < 0
+
+ if torch.any(mask_R_positive_):
+ AD[mask_R_positive_] = -AD[mask_R_positive_]
+
+ BD[mask_R_positive] = -Q[mask_R_positive] / AD[mask_R_positive]
+ x0_D_positive = AD[mask_D_positive] + BD[mask_D_positive] - b_a_3[mask_D_positive]
+ solutions[mask_D_positive_solution, 0] = x0_D_positive
+
+ return solutions
+
+
+# def solve_quartic(coeffs: Tensor) -> Tensor:
+# TODO: Quartic equation solver
+# return solutions
diff --git a/test/geometry/solvers/test_polynomial_solver.py b/test/geometry/solvers/test_polynomial_solver.py
new file mode 100644
index 000000000..8130f0a6e
--- /dev/null
+++ b/test/geometry/solvers/test_polynomial_solver.py
@@ -0,0 +1,68 @@
+import pytest
+import torch
+from torch.autograd import gradcheck
+
+import kornia.geometry.solvers as solver
+from kornia.testing import assert_close
+
+
+class TestQuadraticSolver:
+ def test_smoke(self, device, dtype):
+ coeffs = torch.rand(1, 3, device=device, dtype=dtype)
+ roots = solver.solve_quadratic(coeffs)
+ assert roots.shape == (1, 2)
+
+ @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, 3, device=device, dtype=dtype)
+ roots = solver.solve_quadratic(coeffs)
+ assert roots.shape == (B, 2)
+
+ @pytest.mark.parametrize(
+ "coeffs, expected_solutions",
+ [
+ (torch.tensor([[1.0, 4.0, 4.0]]), torch.tensor([[-2.0, -2.0]])), # zero discriminant
+ (torch.tensor([[1.0, -5.0, 6.0]]), torch.tensor([[3.0, 2.0]])),
+ (torch.tensor([[1.0, 2.0, 3.0]]), torch.tensor([[0.0, 0.0]])), # negative discriminant
+ ],
+ )
+ def test_solve_quadratic(self, coeffs, expected_solutions, device, dtype):
+ roots = solver.solve_quadratic(coeffs)
+ assert_close(roots[0], expected_solutions[0])
+
+ def gradcheck(self, device):
+ coeffs = torch.rand(1, 3, device=device, dtype=torch.float64, requires_grad=True)
+ assert gradcheck(solver.solve_quadratic, (coeffs), raise_exception=True, fast_mode=True)
+
+
+class TestCubicSolver:
+ def test_smoke(self, device, dtype):
+ coeffs = torch.rand(1, 4, device=device, dtype=dtype)
+ roots = solver.solve_cubic(coeffs)
+ assert roots.shape == (1, 3)
+
+ @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, 4, device=device, dtype=dtype)
+ roots = solver.solve_cubic(coeffs)
+ assert roots.shape == (B, 3)
+
+ @pytest.mark.parametrize(
+ "coeffs, expected_solutions",
+ [
+ (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, 3.0, -1.0]]), torch.tensor([[1.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
+ ],
+ )
+ def test_solve_quadratic(self, coeffs, expected_solutions, device, dtype):
+ roots = solver.solve_cubic(coeffs)
+ assert_close(roots[0], expected_solutions[0], rtol=1e-3, atol=1e-3)
+
+ def gradcheck(self, device):
+ coeffs = torch.rand(1, 4, device=device, dtype=torch.float64, requires_grad=True)
+ assert gradcheck(solver.solve_cubic, (coeffs), raise_exception=True, fast_mode=True)