Skip to content

ellphi.solver

The solver module dispatches tangency computations to the best available backend:

  • C++ / Eigen — compiled extension, used automatically when available (backend="auto").
  • Pure Python — SciPy-based fallback, always available.

The default method "brentq+newton" uses a short bracketing phase followed by Newton refinement, which is significantly faster than pure Brent's method for high-dimensional inputs.

from ellphi import tangency, pdist_tangency, build_info

print(build_info())         # shows cpp_backend_available, cpp_linalg_kind, etc.

result = tangency(p, q)
print(result.t, result.point, result.mu)

dists = pdist_tangency(cloud)   # condensed array

ellphi.solver

BuildInfo dataclass

Summary of solver backends and C++ build details.

Notes
  • backend_choices are the accepted values for the backend argument in solver functions ("auto", "python", "cpp").
  • cpp_linalg_kind reports the linear algebra implementation used by the C++ implementation ("eigen" or "internal").
Source code in src/ellphi/solver.py
@dataclass(frozen=True)
class BuildInfo:
    """Summary of solver backends and C++ build details.

    Notes:
        - ``backend_choices`` are the accepted values for the ``backend`` argument
          in solver functions ("auto", "python", "cpp").
        - ``cpp_linalg_kind`` reports the linear algebra implementation used by the
          C++ implementation ("eigen" or "internal").
    """

    version: str
    backend_choices: tuple[str, ...]
    backend_default: str
    cpp_backend_available: bool
    cpp_linalg_kind: str | None
    cpp_backend_version: str | None

build_info()

Return build information for solver selection and C++ backend details.

Source code in src/ellphi/solver.py
def build_info() -> BuildInfo:
    """Return build information for solver selection and C++ backend details."""
    return BuildInfo(
        version=__version__,
        backend_choices=_BACKEND_CHOICES,
        backend_default="auto",
        cpp_backend_available=has_cpp_backend(),
        cpp_linalg_kind=cpp_linalg_kind(),
        cpp_backend_version=_cpp.backend_version(),
    )

cpp_linalg_kind()

Return the C++ linear algebra build kind.

Returns:

Type Description
str | None

The linear algebra kind ("eigen" or "internal") if the C++ backend is

str | None

available, otherwise None.

Source code in src/ellphi/solver.py
def cpp_linalg_kind() -> str | None:
    """Return the C++ linear algebra build kind.

    Returns:
        The linear algebra kind ("eigen" or "internal") if the C++ backend is
        available, otherwise `None`.
    """
    return _cpp.linalg_kind()

has_cpp_backend()

Checks if the compiled C++ backend for tangency calculations is available.

Returns:

Type Description
bool

True if the C++ backend is available, False otherwise.

Source code in src/ellphi/solver.py
def has_cpp_backend() -> bool:
    """Checks if the compiled C++ backend for tangency calculations is available.

    Returns:
        `True` if the C++ backend is available, `False` otherwise.
    """
    return _cpp.is_available()

pdist_tangency(ellcloud, *, parallel=True, n_jobs=-1, backend='auto')

Computes pairwise tangency distances for a cloud of ellipses.

Parameters:

Name Type Description Default
ellcloud Iterable[FloatArray]

A collection of ellipse coefficient arrays or an EllipseCloud object.

required
parallel bool

If True, the computation is performed in parallel when using the Python backend.

True
n_jobs int | None

The number of jobs to run in parallel.

-1
backend str

The backend to use for the computation. Can be one of "auto", "python", or "cpp".

'auto'

Returns:

Type Description
FloatArray

A condensed distance matrix of tangency distances.

Source code in src/ellphi/solver.py
def pdist_tangency(
    ellcloud,
    *,
    parallel: bool = True,
    n_jobs: int | None = -1,
    backend: str = "auto",
) -> numpy.ndarray:
    """Computes pairwise tangency distances for a cloud of ellipses.

    Args:
        ellcloud: A collection of ellipse coefficient arrays or an
            `EllipseCloud` object.
        parallel: If `True`, the computation is performed in parallel when
            using the Python backend.
        n_jobs: The number of jobs to run in parallel.
        backend: The backend to use for the computation. Can be one of
            "auto", "python", or "cpp".

    Returns:
        A condensed distance matrix of tangency distances.
    """
    if backend not in _BACKEND_CHOICES:
        raise ValueError(
            "Unknown backend "
            f"'{backend}'. Expected one of {', '.join(_BACKEND_CHOICES)}"
        )

    if backend in {"cpp", "auto"}:
        coef = _extract_coef_array(ellcloud)
        if _should_use_cpp(backend):
            return _cpp.pdist_tangency(coef)

    if parallel:
        return _pdist_tangency_parallel(ellcloud, n_jobs=n_jobs)
    return _pdist_tangency_serial(ellcloud)

tangency(pcoef, qcoef, *, method='brentq+newton', bracket=(0.0, 1.0), x0=None, backend='auto', hybrid_bracket_maxiter=None, hybrid_newton_maxiter=None, failsafe=True)

Computes the tangency point between two ellipses.

This function returns the tangency time t, the tangent point point, and the pencil parameter μ at which the two ellipses are tangent.

Parameters:

Name Type Description Default
pcoef FloatArray

The coefficient vector for the first ellipse.

required
qcoef FloatArray

The coefficient vector for the second ellipse.

required
method MethodName | str

The root-finding method to use. Can be one of "brentq+newton", "brentq", "brenth", "bisect", or "newton".

'brentq+newton'
bracket Tuple[float, float]

The bracketing interval for bracket methods.

(0.0, 1.0)
x0 float | None

An optional initial guess for Newton's method. Required if method is "newton".

None
backend str

The backend to use for the computation. Can be one of "auto", "cpp", or "python".

'auto'
hybrid_bracket_maxiter int | None

An optional maximum number of iterations for the bracket phase in the hybrid method.

None
hybrid_newton_maxiter int | None

An optional maximum number of iterations for the Newton phase in the hybrid method.

None
failsafe bool

If True, a failsafe fallback is enabled. If Newton refinement fails to converge in the hybrid method, the function falls back to the high-precision Brent's method.

True

Returns:

Type Description
TangencyResult

A TangencyResult containing the tangency time, point, and pencil parameter.

Source code in src/ellphi/solver.py
def tangency(
    pcoef: numpy.ndarray,
    qcoef: numpy.ndarray,
    *,
    method: MethodName | str = "brentq+newton",
    bracket: Tuple[float, float] = (0.0, 1.0),
    x0: float | None = None,
    backend: str = "auto",
    hybrid_bracket_maxiter: int | None = None,
    hybrid_newton_maxiter: int | None = None,
    failsafe: bool = True,
) -> TangencyResult:
    """Computes the tangency point between two ellipses.

    This function returns the tangency time `t`, the tangent point `point`,
    and the pencil parameter `μ` at which the two ellipses are tangent.

    Args:
        pcoef: The coefficient vector for the first ellipse.
        qcoef: The coefficient vector for the second ellipse.
        method: The root-finding method to use. Can be one of "brentq+newton",
            "brentq", "brenth", "bisect", or "newton".
        bracket: The bracketing interval for bracket methods.
        x0: An optional initial guess for Newton's method. Required if
            `method` is "newton".
        backend: The backend to use for the computation. Can be one of "auto",
            "cpp", or "python".
        hybrid_bracket_maxiter: An optional maximum number of iterations for
            the bracket phase in the hybrid method.
        hybrid_newton_maxiter: An optional maximum number of iterations for
            the Newton phase in the hybrid method.
        failsafe: If `True`, a failsafe fallback is enabled. If Newton
            refinement fails to converge in the hybrid method, the function
            falls back to the high-precision Brent's method.

    Returns:
        A `TangencyResult` containing the tangency time, point, and pencil parameter.
    """
    method_literal = _normalize_method(method)
    pcoef_arr = numpy.asarray(pcoef, dtype=float).reshape(-1)
    qcoef_arr = numpy.asarray(qcoef, dtype=float).reshape(-1)
    if pcoef_arr.shape != qcoef_arr.shape:
        raise ValueError("Coefficient vectors must have the same length")
    coef_length = pcoef_arr.size
    infer_dim_from_coef_length(coef_length)

    dim = infer_dim_from_coef_length(coef_length)
    if method_literal == "brentq+newton":
        bracket_iter, newton_iter = _resolve_backend_hybrid_iterations(
            dim,
            hybrid_bracket_maxiter,
            hybrid_newton_maxiter,
        )
        if bracket_iter <= 0:
            raise ValueError("hybrid_bracket_maxiter must be positive")
        if newton_iter <= 0:
            raise ValueError("hybrid_newton_maxiter must be positive")
    else:
        default_bracket, default_newton = _py._hybrid_iteration_defaults(dim)
        bracket_iter = (
            default_bracket
            if hybrid_bracket_maxiter is None
            else hybrid_bracket_maxiter
        )
        newton_iter = (
            default_newton if hybrid_newton_maxiter is None else hybrid_newton_maxiter
        )

    if backend not in _BACKEND_CHOICES:
        raise ValueError(
            "Unknown backend "
            f"'{backend}'. Expected one of {', '.join(_BACKEND_CHOICES)}"
        )
    use_cpp = backend in {"cpp", "auto"} and _should_use_cpp(backend)

    if use_cpp:
        return _cpp.tangency(
            pcoef_arr,
            qcoef_arr,
            method=method_literal,
            bracket=bracket,
            x0=x0,
            hybrid_bracket_maxiter=bracket_iter,
            hybrid_newton_maxiter=newton_iter,
            failsafe=failsafe,
        )
    return tangency_python(
        pcoef_arr,
        qcoef_arr,
        method=method_literal,
        bracket=bracket,
        x0=x0,
        hybrid_bracket_maxiter=bracket_iter,
        hybrid_newton_maxiter=newton_iter,
        failsafe=failsafe,
    )