Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

CyRoot Documentation

CYTHON ROOT FINDING · VERSION 2.0

Where Functions Meet Zero

Start with a Python function. Explore every iteration. Move the numerical hot path into native code when you need it.

A Small Function, A Native Engine

from cyroot import newton

answer = newton(lambda x: x*x - 2., None, 1.5)
assert answer.success
assert abs(answer.root - 2.**.5) < 1e-10

Pass an analytic derivative, or None for a native finite difference. Vector callbacks may return tuples, lists or NumPy arrays. With native callbacks the whole numerical loop runs without the GIL; Python callbacks take it for each call. NumPy and SciPy are required.

Version 2.0 is not backward compatible with 1.x; the migration guides map the old API to the new one. Stopping And Results explains how to tell a residual root from a narrow scalar bracket or a stationary point with a nonzero residual.

Explore The Manual

Getting Started

Scalar Solvers

Vector Solvers

Matrix-Free And Optimization

Derivatives

Callbacks And Native API

Stopping And Results

Migration From 1.x

The repository README includes the algorithm gallery and project links.

Quick Start

CyRoot solves \(f(x)=0\) and \(F(x)=0\) the same way: choose a method, supply the derivatives you have, and check why the solver stopped. Python callbacks are enough to start. Native callbacks are an optional next step when Python call overhead matters.

Install

For a published 2.x release:

python -m pip install 'cy-root>=2,<3'

To build from a source checkout instead:

git clone https://github.com/inspiros/cy-root.git
cd cy-root
python -m pip install -e .

The package supports CPython 3.11–3.14 and requires NumPy and SciPy. A source build also needs Cython 3.3.0, a C++17 compiler, and Python development headers. See Building And Testing for the full environment setup.

Solve A Scalar Equation

A bracket is a good starting point for a continuous scalar function whose values at the two endpoints have opposite signs. Newton suits a good starting estimate with a derivative; pass None to approximate the derivative numerically.

from cyroot import bisect, newton

f = lambda x: x*x - 2.
bracketed = bisect(f, 1., 2.)
analytic = newton(f, lambda x: 2*x, 1.5)
numerical = newton(f, None, 1.5)
assert bracketed.success and analytic.success and numerical.success
assert abs(analytic.root - 2.**.5) < 1e-10

Tolerances and other controls are keyword-only: newton(f, None, 1.5, etol=1e-12, max_iter=50). Cached values such as f_x0 and df_x0 are optional and must be the values at the starting point.

Solve A Nonlinear System

Vector callbacks receive a tuple and return a sequence of residuals. A Jacobian callback returns one row per residual and one column per unknown. Tall systems have more residuals than unknowns; wide systems have fewer.

from cyroot import generalized_newton, vector_lbfgs

f = lambda x: (x[0] - 1., x[1] - 2., x[0] + x[1] - 3.)
answer = generalized_newton(f, None, (0., 0.))
assert answer.success
assert max(abs(a-b) for a, b in zip(answer.root, (1., 2.))) < 1e-9

# Optimizer conveniences use the same function/Jacobian/point order.
optimized = vector_lbfgs(f, None, (0., 0.),
                         input_dimension=2, output_dimension=3)
assert optimized.success

Rectangular methods compute least-squares steps and still require the original residual to meet tolerance. Some quasi-Newton methods require a square system; see Choose A Method. For large matrix-free systems, see Newton–Krylov.

Inspect The Iterations

from cyroot import as_root_snapshot
from cyroot.native import DampedNewton

solver = DampedNewton(lambda x: x*x - 2., None, .1, history=32)
first = as_root_snapshot(solver.step())
final = as_root_snapshot(solver.run())
assert final.residual_converged
assert solver.history[-1].root == final.root
assert first.iters == 1

history=0, the default, records nothing. A positive history is the maximum number of copied snapshots; once it is full, later steps are not recorded and history_truncated is set. as_root_snapshot gives scalar and vector results the same fields and keeps the original record in diagnostics. Read Stopping And Results before interpreting success: a narrow scalar bracket and a small nonlinear residual are different outcomes.

Take The Next Step

Choose A Method

The right method depends on what you know about the function and on how expensive the residual is to evaluate. Higher derivative orders do not by themselves make a solve faster. Compare iteration histories and callback counts on your own problem.

Scalar Equations

What You HaveTryWhy
A continuous function and a sign-changing bracketbisect or brentKeeps a sign-changing bracket; bisection halves it every step.
One estimate and a derivativenewtonFull Newton steps with an analytic or numerical first derivative.
A Newton step that overshootsdamped_newtonArmijo backtracking accepts a smaller improving step.
First and second derivativeshalley or chebyshevUses curvature, at the cost of a second derivative.
Several derivative ordershouseholderAny order, through a native recurrence instead of symbolic formulas.
Two starting estimatessecantNeeds no derivative, but has no bracket to fall back on.
An interval enclosure callbackhybisectSplits the interval and can return several roots with a search status.

Scalar Migration lists every bracketing and interpolation method. Open methods can diverge or hit a zero denominator. Bracketing methods are only as reliable as their assumptions, such as continuity.

Vector Systems

MethodSquareTall Or WideMain Information
Generalized Newton / damped NewtonYesYesDense Jacobian or numerical plan.
Halley / Super-Halley / Chebyshev / tangent hyperbolasYesYesDense Jacobian and residual Hessian, supplied or numerical.
Newton–KrylovGMRESLSQRJacobian-vector products Jv; rectangular systems also need J^T w.
Broyden / Barnes / KlementYesNoA Jacobian approximation updated each step, initialized explicitly or numerically.
Robinson / Traub–SteffensenYesNoExtra residual evaluations that build a secant or difference matrix.
Wolfe–BittnerYesYesA pool of points and an affine least-squares step.
Levenberg–Marquardt / BFGS / L-BFGS / doglegYesYesResidual objective with a dense Jacobian or numerical plan.
VrahatisYesYes, subject to sign-polygon limitsA sign polygon, one vertex per residual sign pattern; a small polygon alone is not a root.

A Jacobian has shape (m, n) for m residuals and n unknowns. The dense Newton and higher-order methods take rank-aware least-squares steps on rectangular systems. Square systems use a direct factorization, and a singular square Jacobian is reported as a breakdown rather than silently replaced by a pseudoinverse. Each method’s page covers initialization, rank cutoffs and failure reasons.

Matrix Storage

A dense Jacobian needs m*n doubles, a residual Hessian m*n*n, and higher mixed partials m*n**order. Native code removes Python overhead from the numerical kernel; it does not reduce these storage or sampling costs.

Newton–Krylov never forms a dense Jacobian. It is fastest with supplied native products. Without them, rectangular systems recompute every Jacobian column for each product, so that Jv and J^T w come from the same matrix. Saving storage then does not mean saving time.

L-BFGS keeps a bounded number of correction pairs, but its least-squares objective still forms a dense Jacobian, so it is not a matrix-free alternative to Newton–Krylov.

Optimization And Root Success

The optimization family minimizes \(\frac12\|F(x)\|_2^2\). It can stop at a local minimum with a nonzero residual even when a root exists elsewhere, so these solvers check the original residual before reporting success. A stationary gradient, an accepted linear solve and a tiny step are reported separately; none of them is a root.

See Optimization for objective derivatives and external optimizers, and Stopping And Results for the shared tolerances. CyRoot does not choose a method for you, and no method is guaranteed to converge from an arbitrary starting point.

Building And Testing

CyRoot supports CPython 3.11–3.14. Building from source needs a C++17 compiler and the Python development headers, which Linux distributions often ship in a separate python3-dev (or version-specific) package.

Create an isolated environment, then build the package in editable mode:

python -m venv .venv
. .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install -e '.[dev]'
python tests/run_tests.py

On Windows, activate with .venv\Scripts\activate and use an MSVC toolchain with C++17 support. On macOS, install the Xcode command line tools.

The test runner uses up to four worker processes, or fewer on machines with fewer CPUs. It discovers test modules without importing them, then runs each module once in a fresh process of the current interpreter. External Cython consumer builds use their own temporary directories. --jobs 1 runs the modules one at a time, still in separate processes:

python tests/run_tests.py --jobs 1
python tests/run_tests.py --jobs 4 --pattern test_native_broyden.py
python tests/run_tests.py --self-check

By default the runner discovers tests in its own tests directory, so it also works when invoked by absolute path from outside the checkout. --start-directory and --pattern select a different set. Per-module logs and machine-readable results go to test-logs/ in the current directory, or to --log-directory; summary.json holds the totals and the test IDs run in each module. Test failures, import or discovery errors, unexpected successes and worker crashes give a nonzero exit status. --expected-tests N also checks the total count, and --require-no-skips fails on skips, for environments that provide every compiler and optional test dependency.

When adding tests, cover distinct behavior. Numerical identities, failure states and buffer safety belong in the native engine’s suite. Wrapper tests check argument forwarding, dispatch and the Python interface, without repeating the engine’s numerical cases for every alias. Keep regression tests for bugs found in practice, and compiled-consumer checks for the native API. For a local change, run the affected module first and the full suite before merging.

The runner passes CC, CXX and the rest of your environment through. Thread limits for OpenMP, OpenBLAS, MKL, Accelerate, NumExpr and BLIS that you have not set are set to one, so parallel workers do not multiply backend threads; limits you set yourself are kept.

NumPy and SciPy are runtime dependencies. SciPy provides the Cython LAPACK interface, so no separate system BLAS or LAPACK is needed. SciPy is limited to versions below 1.18, whose new Cython BLAS/LAPACK integer ABI has not yet been validated with CyRoot.

Source builds use Cython 3.3.0, as declared in pyproject.toml. Generated C++ goes to build/cython/. Source archives do not bundle generated C++, so installing from one needs Cython. Installed packages include the Cython declarations and native headers for compiled consumers.

Build distribution artifacts with:

python -m build

Test the wheel in a fresh environment, from outside the source directory, so the checkout cannot mask a missing installed module:

python -m venv /tmp/cyroot-wheel-test
/tmp/cyroot-wheel-test/bin/python -m pip install dist/*.whl Cython==3.3.0 setuptools
cd /tmp
/tmp/cyroot-wheel-test/bin/python /absolute/path/to/cy-root/tests/run_tests.py \
  --jobs 4 --installed-prefix /tmp/cyroot-wheel-test \
  --log-directory /tmp/cyroot-wheel-test-logs

Test the source archive the same way; installing it needs Cython, the Python development headers and a compiler. Only tests/ is searched for tests; examples/ holds demonstrations.

With --installed-prefix, each worker checks before and after its tests that cyroot and every loaded cyroot module come from that prefix, and fails the run otherwise. The runner adds the test directory to the path for its helper modules but never the checkout root, so testing the sources needs the editable installation above. To verify an installed wheel, run from outside the checkout and pass the fresh environment’s prefix.

The native callback tests compile a small external Cython extension against the installed package, so they need Cython and a compiler. The standalone native header check uses g++ when it is available. On Linux, run CYROOT_NATIVE_SANITIZERS=1 python tests/run_tests.py --pattern test_native_buffers.py --jobs 1 for AddressSanitizer and UndefinedBehaviorSanitizer checks. The dedicated CI job also enables leak detection; LeakSanitizer may not work in some sandboxed or traced local environments.

Native Newton

cyroot.native.Newton shares the scalar callback interface and the stepping, budget and history conventions of native bisection. The residual and an analytic derivative can each be a Python callable or a native ScalarCallback, in any combination. For a numerical derivative, pass None or a ScalarDerivativePlan.

from cyroot.native import Newton

solver = Newton(lambda x: x*x - 2., lambda x: 2*x, 1.5, history=16)
first = solver.step()
result = solver.run()
assert result.success
assert solver.history[-1].root == result.root

step() returns an immutable NewtonStep; run() and the result property return NewtonMethodsReturnType. cyroot.native.newton(function, derivative, x0, **options) runs a solver to completion. The public cyroot.newton(f, df, x0, f_x0=None, df_x0=None, *, h=None, ...) runs the same engine; h sets the step of the default numerical derivative.

Evaluation And Termination

Stopping And Results defines the tolerances. The residual scale is the initial absolute residual. The step is the actual difference between consecutive finite points, and the relative step tolerance uses the larger of their magnitudes. A small step without a small residual is reported as unsuccessful stagnation.

f_calls is the pair (residual_calls, derivative_calls) for this solve. With a numerical plan, stencil samples count as residual calls, and each approximation counts as one derivative call; samples do not add iterations. Supplying f_x0 or df_x0 skips that initial evaluation, so the cached value must be what the callback would return. Calls that raise or return a native failure code are counted. An iteration is one attempt to evaluate the residual at a finite candidate; nonfinite arithmetic before that call does not increase iters.

If the starting point already satisfies the residual tolerance, no derivative is evaluated or validated. After each finite new point and residual, the solver checks the residual, step and iteration budget before evaluating the next derivative. df_root is NaN when the derivative at the returned point was not evaluated, except that a supplied df_x0 is kept when the starting point is the root. A zero derivative stops with zero_derivative, a nonfinite one with nonfinite.

A failed or nonfinite residual trial keeps the previous finite point, residual, derivative and metrics, and updates only the call counts and the reason. If the derivative fails after a finite candidate was accepted, the new point and residual stand and df_root is NaN: a derivative from the previous point is never reported for the new one.

A Python exception propagates as the original instance, with the callback’s traceback. A nonzero native status raises NativeCallbackError, whose native_status, callback_stage ('function' or 'derivative') and copied result identify the failure. The solver also exposes the stage and code as callback_stage and callback_code, and the result reason is callback_failure. Numerical failures return ordinary unsuccessful results instead of raising.

History And Callback Lifetimes

history, history_every, history_bytes, history_truncated, done and iteration over the solver behave as in native bisection. Each record includes df_root, both evaluation counts and any callback failure stage and code. History storage is allocated before native work starts; it records the initial, sampled and terminal states and exports copied immutable tuples. A failure before any new residual attempt updates that iteration’s last record instead of adding a duplicate. Previously exported records never change.

The callback adapters are reserved together for setup, each step and a full run, including exception transfer and result construction. With a numerical plan, the residual adapter stays reserved throughout sampling. One adapter can serve as both residual and derivative. If the second adapter is already in use, the first is not left reserved. Reentrant or concurrent use of an active solver or adapter is rejected. Separate adapters that share native context memory still need synchronization by their owner. Context owners stay alive until every adapter and solver using them is released.

Native callbacks use the same versioned C/Cython descriptor as bisection. With a compiled residual and a compiled derivative, the whole numerical run happens outside the GIL; a Python callback takes the GIL for its call and conversion. The compiled example and its solve_newton() function show how to build against the installed package.

Plain Newton always takes the full step. For Armijo backtracking, use Damped Newton. Halley and Chebyshev accept analytic or numerical first and second derivatives, and Vector Newton handles square and rectangular systems. A running native solve cannot be cancelled.

Native Secant

cyroot.native.Secant finds a scalar root from two starting points. The residual can be a Python callable or the native ScalarCallback used by bisection and Newton. It needs no derivative and no sign-changing bracket.

from cyroot.native import Secant

solver = Secant(lambda x: x*x - 2., 1., 2., history=16)
first = solver.step()
result = solver.run()
assert result.success
assert solver.history[-1].root == result.root

step() returns an immutable SecantStep with the current and previous point/residual pairs. run() and the result property return RootReturnType. cyroot.native.secant(function, x0, x1, **options) runs a solver to completion; the public cyroot.secant(f, x0, x1, f_x0=None, f_x1=None, *, ...) runs the same engine.

Evaluations And Stopping

The common stopping rules apply. When neither start is a root, the residual scale is the larger initial absolute residual. The accepted state starts at x1; the distance between the two starting points never satisfies the step tolerance on its own. Later step metrics use consecutive accepted points. A candidate equal to the current point is still evaluated before the solver reports residual success or stagnation. Equal residuals stop with breakdown before another callback. Residuals are normalized before their difference is formed; any other unrepresentable step arithmetic stops with nonfinite before the trial call.

The starting points are checked in order. If x0 is already a root, x1 is neither evaluated nor validated, although every scalar argument is still converted before native execution starts.

f_calls counts this solve’s residual calls, including failed ones. f_x0 and f_x1 supply cached values and skip the corresponding starting calls. An iteration is one attempt to evaluate the residual at a finite candidate. Nonfinite arithmetic before that call, and a breakdown from equal residuals, use no iteration and no residual call. max_iter is shared by step() and run(); zero or None removes the limit. A failed or nonfinite trial keeps both previous pairs and their metrics and updates only the counts and the reason.

A Python exception propagates as the original instance, with the callback’s traceback. A nonzero native status raises NativeCallbackError with native_status, a copied result and callback_stage='function'; the solver exposes the same stage and code. Numerical failures return ordinary unsuccessful results.

Inspection And Ownership

history, history_every, history_bytes, history_truncated, done and iteration follow the native core conventions. History is bounded and allocated before native work starts. A terminal failure in the same iteration updates that iteration’s last record. Exported snapshots and results are copies, so later steps or destroying the solver cannot change them.

The residual adapter and its context stay alive and reserved through setup, execution, result conversion and exception transfer. Reentrant or concurrent use of an active solver or adapter is rejected. Separate adapters that share mutable native context still need synchronization by their owner. With a native residual, initialization and the whole numerical run happen outside the GIL; a Python callback takes the GIL for its call and result conversion. See the compiled callback example.

Secant has no bracket, damping or line search, and can fail or diverge from unsuitable starting points.

Native Halley Family

cyroot.native.Halley, Chebyshev, ModifiedHalley, SuperHalley and TangentHyperbolas share one scalar solver interface that uses first and second derivatives. The residual can be a Python callable or a compiled ScalarCallback. Each derivative can independently be an analytic callback, a native finite-difference plan, or None for a default central plan.

from cyroot.native import Halley, Chebyshev, ModifiedHalley, SuperHalley, TangentHyperbolas

def function(x):
    return x*x - 2.

for method in (Halley, Chebyshev, ModifiedHalley, SuperHalley, TangentHyperbolas):
    solver = method(function, lambda x: 2*x, lambda x: 2., 1.5, history=16)
    first = solver.step()
    result = solver.run()
    assert result.success
    assert solver.history[-1].root == result.root

# Approximate both derivatives from the residual:
result = Halley(function, None, None, 1.5).run()
assert result.success

# Select another member of the modified Halley family:
result = ModifiedHalley(function, None, None, 1.5, alpha=1.).run()
assert result.success

The convenience functions halley(function, derivative, second_derivative, x0, **options), chebyshev(...), super_halley(...), tangent_hyperbolas(...) and modified_halley(..., alpha=0.5, **options) run a solver to completion, and the top-level cyroot functions of the same names run the same engines. To configure a numerical first derivative, pass a ScalarDerivativePlan; for the second derivative, pass a ScalarSecondDerivativePlan. Each plan type serves only its own derivative order. Derivative arguments are positional, so pass None explicitly to select a default plan.

Steps And Numerical Failures

For residual \(f\), first derivative \(f'\) and second derivative \(f''\) at the current point, define

\[ t=\frac{f}{f'},\qquad q=\frac{t}{2}\frac{f''}{f'}. \]

The parameterized modified Halley family uses

\[ \Delta x=-t\left(1+\frac{q}{1-2\alpha q}\right). \]
ClassParameterImplemented update
Chebyshev\(\alpha=0\)\(-t(1+q)\)
Halley\(\alpha=1/2\)\(-t/(1-q)\)
SuperHalley\(\alpha=1\)\(-t(1+q/(1-2q))\)
ModifiedHalleyfinite real \(\alpha\), default \(1/2\)parameterized formula above
TangentHyperbolas\(\alpha=1/2\)Halley’s update

ModifiedHalley adds a keyword-only alpha to the common constructor options. Any finite real value is allowed, including negative values and values outside [0, 1]; text, sequences, booleans and nonfinite values are rejected. alpha is converted once, before any numerical work, even when the starting point is already a root. alpha=0 and alpha=0.5 reproduce the Chebyshev and Halley arithmetic exactly. SuperHalley fixes the parameter at one and has no alpha option.

For scalar equations, both classical tangent-hyperbolas formulas reduce to Halley’s update, so TangentHyperbolas reuses the Halley engine and has no formula selector. The public cyroot.tangent_hyperbolas still accepts formula=1 or formula=2, and both give the same result. The equivalence holds only for scalar equations.

The ratio form avoids squaring the derivative or multiplying the residual by the second derivative, either of which can overflow when the residual is rescaled. The ratios and all later arithmetic must still be finite: an unrepresentable intermediate reports nonfinite, even where a different algebraic arrangement might have succeeded.

With exact derivatives, these methods converge cubically near a smooth simple root under the usual nondegeneracy conditions. Numerical derivative errors can lower the rate and the attainable accuracy. There is no global convergence guarantee, bracket, damping or line search. A zero first derivative reports zero_derivative; a zero second derivative is fine. A zero Halley or modified Halley denominator reports an unsuccessful breakdown before another residual call; there is no automatic fallback to Newton. A candidate equal to the current point is still evaluated before success or stagnation is decided. In particular, a zero Super-Halley correction at q=1 evaluates that point and reports stagnation if its residual is not small enough. Super-Halley can converge faster on special functions such as quadratics, but in general it is third order at simple roots.

Tolerances and the iteration budget work as for native Newton and as described in Stopping And Results: the residual scale is the initial absolute residual, steps are actual finite differences between consecutive points, and max_iter is shared by step() and run(). Each attempt to evaluate the residual at a finite candidate is one iteration; an arithmetic failure before that call uses no iteration and no call.

Results, Caches And Lazy Derivatives

run() and result return NewtonMethodsReturnType. Its df_root is the tuple (first_derivative, second_derivative) at the returned point. f_calls is (residual_attempts, first_derivative_attempts, second_derivative_attempts) for this solve, counting failed calls too. Each numerical plan evaluation counts as one derivative attempt, and all of its residual samples count as residual attempts; sampling adds no iterations. Plans reuse the accepted residual but do not share samples with each other. step() and history return immutable HigherOrderStep records with separate scalar df_root and d2f_root fields, the counts, the metrics, the reason and any callback stage and code. Step records taken while running have termination_reason=None; the result of a running solver reports unspecified.

f_x0, df_x0 and d2f_x0 are optional cached starting values; each one skips the corresponding initial call, so it must match what the callback would return. If the starting point is already a root, unused derivatives are neither evaluated nor validated, and supplied derivatives are kept in the result. Cached values are still converted and callbacks still validated during setup.

When another step is needed, the first derivative is evaluated and checked before the second; a failed, nonfinite or zero first derivative skips the second derivative call. After a finite candidate residual, the new point and residual are accepted, both derivatives are reset to NaN, and convergence, stagnation and the budget are checked before any further derivative work.

A failed or nonfinite candidate residual keeps the previous finite point, residual, derivatives and metrics, and updates only the counts and the reason. If the first derivative fails at a newly accepted point, both derivatives are NaN. If only the second derivative fails, the new first derivative is kept and the second is NaN. A zero first derivative is reported as zero, with the unevaluated second derivative as NaN. A derivative from another point is never reported for the returned point.

Callbacks, History And Ownership

Native callbacks use the same scalar signature and lifetime rules as native Newton:

cdef int evaluate(double x, double* out, void* context) noexcept nogil:
    out[0] = ...
    return 0

A successful callback must write its output, which is set to NaN before each call. A nonzero native status raises NativeCallbackError with the exact native_status, a copied result and the callback_stage: 'function', 'derivative' or 'second_derivative'. A failed residual sample inside a numerical plan reports the stage of that plan. Python exceptions propagate as the original instance, with the callback’s traceback. The solver also exposes the stage and code; ordinary numerical failures return unsuccessful results. A callback failure is raised once, by the call that did the work. Later run() or step() calls on the finished solver return its failed state without calling back or raising again.

All supplied adapters are validated before any is reserved. They stay alive and reserved through setup, execution, result and history construction and exception transfer. One adapter can fill several roles; distinct adapters that share mutable native context still need synchronization by their owner. Reentrant or concurrent use of the solver or an active adapter is rejected. When every evaluated role has a compiled callback, initialization and the whole numerical run, including derivative sampling, happen outside the GIL; Python callbacks take the GIL for their calls and conversions. See the compiled example.

history, history_every, history_bytes, history_truncated, done and iteration follow the native scalar conventions. History storage is allocated and bounded in bytes before native work starts. Initial, sampled and terminal states are recorded until it is full; later entries are dropped and history_truncated is set. A terminal failure in the same iteration updates that iteration’s last record. Copied snapshots stay unchanged after the solver resumes or is destroyed. Iterations allocate no new history or workspace memory.

The callbacks use versioned native descriptors. Native solves cannot be cancelled and do not check for signals.

Native Householder

cyroot.native.Householder is the scalar Householder method for any derivative order chosen at run time, with Python or compiled callbacks, resumable execution and copied history. Given derivatives up to order \(d\), it converges with local order \(d+1\) near a smooth simple root. It uses a native reciprocal-series recurrence, so there is no symbolic formula generator and no upper limit on the order.

from cyroot.native import Householder

solver = Householder(
    lambda x: x*x*x - 1.,
    (lambda x: 3*x*x, lambda x: 6*x, lambda x: 6.),
    1.2, history=16,
)
first = solver.step()
result = solver.run()
assert result.success
assert solver.history[-1].root == result.root

The constructor is Householder(function, derivatives, x0, f_x0=None, dfs_x0=None, *, order=None, step=None, etol=1e-10, ertol=4*eps, ptol=1e-12, prtol=4*eps, max_iter=200, history=0, history_every=1, history_bytes=8*1024*1024, workspace_bytes=8*1024*1024, max_nodes=65). householder(function, derivatives, x0, **options) constructs a solver and runs it to completion. Callback ownership follows the native core contract.

Derivative Providers And Caches

derivatives is a non-empty list or tuple, starting with the first derivative. Each entry can be a Python function, a native ScalarCallback, None for a numerical approximation, or a ScalarFiniteDifferencePlan of the matching order; ScalarDerivativePlan and ScalarSecondDerivativePlan are also accepted for orders one and two. Order checks apply to plan subclasses too, and are made even when the starting point is already a root.

derivatives=None requires a positive integer order and uses numerical plans for every order. With an explicit sequence, order is optional and must match its length. step sets the step of the default numerical plans; the native class ignores it when there are none, while the public cyroot.householder rejects it. Explicit plans keep their own steps. The default is an automatic central stencil; see runtime-order derivatives for rounded nodes, resource limits and accuracy. Different derivative orders share no samples except the cached residual at the current point.

f_x0 caches the initial residual. dfs_x0 has exactly one entry per derivative, with None for one that has not been evaluated. Cached values must belong to the starting point and functions, and count as zero calls. All supplied values are converted during setup. If the starting point is already a root, unused derivatives are not checked for finiteness and the supplied caches are kept. Otherwise derivatives are evaluated in increasing order. A zero first derivative is valid for the general recurrence; a zero reciprocal-series denominator reports breakdown.

Native Execution And Budgets

The reciprocal recurrence costs \(O(d^2)\) arithmetic and \(O(d)\) workspace per step. Intermediate values are stored as binary64 mantissas with separately checked 64-bit binary exponents, which avoids many overflows but neither increases precision nor makes high-order derivatives stable. Analytic derivatives have no order limit. Numerical orders are limited by max_nodes, scratch memory and representable finite arithmetic; a larger budget does not make them more accurate.

Setup keeps every callback and plan owner alive, copies the native dispatch descriptors, and allocates workspace and history once. workspace_bytes covers values, counters, roles, cache flags, the recurrence and the largest numerical scratch. history_bytes separately covers the metadata, all derivatives and all counters of every requested record. Both limits are checked before native allocation; Python owners and exported result objects use additional memory.

The numerical loop creates no Python objects or memoryviews, does no NumPy operations and allocates nothing per step. With compiled noexcept nogil callbacks, it runs entirely in native code. Python callbacks take the GIL for their calls and scalar conversion, as do setup and result and history export. Adapters stay reserved through conversion, execution, result conversion and exception transfer. Separate adapters that share a native context need synchronization by the context’s owner. See the compiled example.

Results, History And Failure State

step() and run() share one iteration budget; max_iter=0 or None is unlimited. The shared stopping rules apply. A candidate equal to the current point is still evaluated before success or stagnation is decided. There is no fallback, damping or symbolic recovery.

result is a NewtonMethodsReturnType: df_root has \(d\) entries and f_calls has \(d+1\), residual first. Each plan evaluation counts as one attempt for its derivative order and adds every stencil sample to the residual count; failed attempts count too. Accepting a finite candidate clears the derivatives, and the stopping rules and iteration limit are checked before more derivatives are evaluated. Derivatives that are not available are NaN.

HouseholderStep is immutable and contains root, f_root, df_root, iters, f_calls, precision, error, termination_reason, callback_code, callback_stage and callback_order. history returns copied immutable steps, and history_truncated reports that the capacity ran out. Initial, sampled and terminal states follow the native history rules.

A failed trial residual keeps the previous finite point, derivatives and metrics, and updates only the counts and diagnostics. A failure in derivative order \(k\) keeps the lower-order derivatives and clears orders \(k\) to \(d\). A nonzero native status raises NativeCallbackError with the exact status, a copied result, the stage 'function' or 'derivative', and callback_order: zero for the residual, or \(k\) for a failure in derivative \(k\) or its stencil. Python exceptions propagate as the original instance, with its traceback. Once raised, an error is not raised again by later step() or run() calls on the finished solver.

Public Entry Point

cyroot.householder(f, dfs, x0, ...) runs this engine. Its dfs, d and h arguments correspond to derivatives, order and step. h=None selects an automatic step, and a supplied d must match the length of dfs. The 1.x c_code option, explicit reciprocal formulas, expression evaluator and symbolic factory are gone, and SymPy is no longer a dependency. Use cyroot.native.Householder for stepping and history.

Native Vector Newton

cyroot.native.VectorNewton solves nonempty real systems with an analytic Jacobian or a native finite-difference plan; pass None for a default central plan. It uses private native workspaces and SciPy’s Cython LAPACK interface. Neither its numerical loop nor its storage uses NumPy.

from cyroot.native import VectorNewton

def residual(x):
    return (x[0]**2 + x[1] - 3., x[0] + 2*x[1] - 3.)

def jacobian(x):
    return ((2*x[0], 1.), (1., 2.))

solver = VectorNewton(residual, jacobian, (1.2, .7), history=16)
first = solver.step()
result = solver.run()
assert result.success
assert solver.history[-1].root == result.root

The solution near this starting point is (1.5, .75). vector_newton(function, jacobian, x0, **options) runs a solver to completion, and the public cyroot.generalized_newton runs the same engine. The higher-order vector methods have their own migration guide. Traub–Steffensen reuses this state and the square LU solve, with residual-based divided differences in place of a Jacobian. Robinson also reuses it, with two starting points, fixed probe directions and secants built from the actual rounded points.

Public Entry Point: generalized_newton

The public signature is generalized_newton(F, J, x0, F_x0=None, J_x0=None, *, etol=1e-10, ertol=4*eps, ptol=1e-12, prtol=4*eps, max_iter=200, history=0, history_every=1, history_bytes=8*1024*1024, workspace_bytes=64*1024*1024), where eps is the binary64 machine epsilon. J is required: pass None for automatic central differences, a JacobianPlan (square) or RectangularJacobianPlan of matching shape for configured differences, or an analytic Python or native Jacobian callback.

from cyroot import generalized_newton
from cyroot.native import JacobianPlan

def residual(point):
    x, y = point
    return (x*x + y - 3., x + 2*y - 3.)

result = generalized_newton(residual, JacobianPlan(2, scheme='central'),
                            (1.2, .7))
assert result.success
assert max(abs(a-b) for a, b in zip(result.root, (1.5, .75))) < 1e-9

cyroot.vector_newton.generalized_newton and find_vector_root('generalized_newton', ...) are the same function. Options after J_x0 are keyword-only. The default max_iter is 200; zero or None is unlimited. There is no h option: set the step of a native plan instead. The 1.x derivative approximation classes are gone; see Finite Differences.

Python residual and Jacobian callbacks receive immutable tuples, not NumPy arrays. Replace array expressions such as point - 1. with indexed arithmetic, or convert explicitly inside the callback. Inputs, cache shapes and providers are validated even when the starting point is already a root. Square linear systems use LU, and a singular one returns an unsuccessful breakdown rather than falling back to a pseudoinverse. Rectangular systems take rank-aware least-squares steps.

For \(F:\mathbb R^n\to\mathbb R^m\), the Jacobian has \(m\) rows and \(n\) columns. Python functions need no dimension arguments: the point gives \(n\), and the cached or first residual gives \(m\). That first residual is reused, not evaluated twice. For example:

from cyroot import generalized_newton

def tall(point):
    x, y = point
    return (x-1., y-2., x+y-3.)

result = generalized_newton(tall, None, (0., 0.))
assert result.success
assert max(abs(a-b) for a, b in zip(result.root, (1., 2.))) < 1e-9

A nonfinite starting point calls no callbacks. Without a cached residual or explicit provider dimensions, the output shape cannot be discovered, so the unsuccessful result uses \(m=n\) placeholders. The same placeholders appear in the terminal state when the first callback fails before the shape is known. Explicit adapters and plans fix the shape even when the starting point is a root. Points and residuals must be vectors and Jacobians matrices; higher dimensional arrays are rejected.

The result is a NewtonMethodsReturnType, with tuple root and f_root and the Jacobian rows in df_root. The function returns only the final result; keep a VectorNewton to call step() and read intermediate history. Supplied F_x0 and J_x0 skip their initial evaluations and count as zero calls. Counts, terminal Jacobian placeholders and failures behave as described for the native engine below.

Python Boundary

Inputs and callback outputs can be sized, indexable sequences or buffers. x0 has length n and residuals length m; Jacobians have shape (m, n), given as a sequence of rows. NumPy arrays, array.array, memoryviews and DoubleBuffer work when their dimensions match. Native float64 buffers are read directly; other real dtypes, such as integers or float32, are converted element by element. Complex and boolean buffers, indirect buffers and empty systems are rejected. Read-only, negative-stride, zero-stride and unaligned buffers are copied by logical index. User data is never overwritten. Generators are not accepted in place of a sized sequence.

Each Python callback receives an immutable tuple copy of the current point, which it may keep. It returns a new or reused residual or Jacobian sequence or buffer, whose values are packed into private native storage at once. Python execution, conversion and buffer access hold the GIL; use the native callbacks below for a numerical run that never takes it.

run() and result return NewtonMethodsReturnType. Point and residual are immutable tuples, and df_root is a tuple of Jacobian rows. step() and history return immutable VectorNewtonStep records with the same numerical fields plus callback stage/code, LAPACK linear_status and linear_rank. The solver exposes input_dimension, output_dimension, linear_status and linear_rank. The rank is the effective rank of the last rectangular solve, or None for square LU and after a failed rectangular solve. It describes that linear step, not necessarily the Jacobian at the next accepted point.

Numerical Behavior

For square systems, each step solves J delta = -F with pivoted LU (dgesv) and then evaluates the candidate point. A singular factorization returns an unsuccessful breakdown, and the solver’s linear_status and terminal history keep LAPACK’s nonzero info. No residual is evaluated, no iteration is used, and the previous point, residual and Jacobian are kept. A negative info is also a backend failure; zero means success or that no factorization was needed. The solver also checks that every LU entry is finite, because elimination can overflow while LAPACK still reports success and then give a finite but wrong direction. Such factors report nonfinite before any trial.

For rectangular systems, the same iteration uses LAPACK dgelsy through the least-squares plan, with rcond=1e-12 and a conservative maximum dimension of 32767. It minimizes the linear residual and, when the linear solution is not unique, takes the correction of smallest Euclidean norm. Rank-deficient rectangular systems are allowed, but a singular square system never switches to this solver. A minimum-norm correction does not make the nonlinear root found the one of minimum norm. LAPACK info and the effective rank are reported separately, and a failed solve evaluates no candidate.

Only residual convergence counts as finding a root. An inconsistent overdetermined system can reach a least-squares stationary point with a nonzero residual; that ends in unsuccessful stagnation or the iteration limit, not a root. There is no damping, line search or regularization, and no global convergence guarantee.

Tolerances and the iteration budget work as for native scalar Newton and as described in Stopping And Results. Norms are maximum absolute components. The relative residual tolerance uses the initial residual norm, and the relative step tolerance the larger of two consecutive iterate norms. A small step without a small residual is unsuccessful stagnation. max_iter=0 is unlimited.

f_calls is (residual_calls, jacobian_calls) for this solve. With a numerical plan, stencil samples count as residual calls and each approximation as a Jacobian call. A central approximation samples 2*n residuals; forward and backward approximations sample n and reuse the current residual. An uncached initial residual adds one call. Supplying f_x0 or jac_x0 skips that initial callback, so the value must be what the callback would return. If the starting point is already a root, the Jacobian is neither evaluated nor checked for finiteness, though the shapes and formats of supplied caches are still validated. Each attempt to evaluate the residual at a finite candidate is one iteration; nonfinite arithmetic or a failed factorization before that call uses no iteration and no residual call.

A failed or nonfinite candidate residual keeps the previous finite point, residual, Jacobian and metrics, and updates only the counts. A finite candidate residual is accepted before convergence, stagnation and the budget are checked. The new Jacobian is evaluated only if another step is needed; otherwise df_root contains NaNs. If the Jacobian at a newly accepted point fails or is nonfinite, the point and residual stand and the Jacobian is entirely NaN; a partial or stale matrix is never reported.

Python exceptions, including output shape and conversion errors, propagate as the original instance with the callback’s traceback. A nonzero native status raises NativeCallbackError with native_status, a copied result and callback_stage ('function' or 'jacobian'). Numerical failures return ordinary unsuccessful results.

Native Callbacks

vector.pxd declares:

ctypedef int (*VectorFunction)(const double* x, size_t n,
                              double* out, void* context) noexcept nogil

This is the square callback ABI. Use make_vector_callback(function, dimension, context, keepalive, jacobian=False) for residuals and jacobian=True for Jacobians. Residuals write n doubles. Jacobians write n*n doubles in column-major order: element (row, column) is out[row + column*n]. A successful call writes every element and returns zero; outputs are filled with NaN beforehand to expose missed writes. A nonzero status stops the solve without using the partial output. Callbacks must not let Python or C++ exceptions cross the ABI, and must neither modify nor keep the borrowed input pointer. The producer must make sure its dimensions and their products are representable.

VectorCallback(function, dimension, jacobian=False) creates a Python adapter. Native capsules use cyroot.vector_callback.v1 and the cyroot_vector_descriptor in callbacks.h: version and size, dimension, kind (CYROOT_VECTOR_RESIDUAL or CYROOT_VECTOR_JACOBIAN), function and context. VectorCallback.from_capsule(capsule, keepalive=owner) validates and copies the descriptor; the producer remains responsible for the pointers and for keeping the context and code alive. For rectangular systems, use RectangularCallback, with its own factory and capsule and explicit n and m; its Jacobian layout is row + column*m. It also works for square systems. Compiled consumers built against 1.x must be rebuilt against the 2.0 declarations and versioned callback headers.

All explicit adapters are reserved together before setup converts any argument, including the point, caches, tolerances, budgets and history options. The reservation also covers result construction, history export, output conversion and exception transfer. Reusing an active adapter, or concurrent or reentrant use of the solver, is rejected. Each adapter’s kind and dimension must match its role: the residual needs a residual adapter and an analytic Jacobian a Jacobian adapter. A square VectorCallback declares m=n and cannot be used with a rectangular shape. Other native callback types and uninitialized or mismatched plans are rejected, even when the starting point is a root. Distinct adapters that share native state need synchronization by their owner. See the compiled example.

Workspace And History Limits

workspace_bytes defaults to 64 MiB. Before allocating, the solver checks the dimensions and their products, LAPACK’s C int limit and the workspace budget. With an analytic Jacobian, a square workspace holds five vectors, two square matrices and n C-int pivots: 8*(5*n + 2*n*n) + sizeof(int)*n bytes. LAPACK works on private packed copies. CyRoot allocates no native workspace or history during the loop; the LAPACK library manages its own internal memory and threads, which the budget does not include. Numerical plans add 3*n+2*m scratch doubles plus their explicit steps, as detailed in native Jacobians.

For rectangular systems, native storage holds 3*n+3*m+m*n doubles, the least-squares plan’s scratch (m*n + max(m,n) + lwork doubles) and n C-int pivots, plus any numerical-difference scratch and steps as above. lwork comes from a LAPACK workspace query, which allocates nothing, before the final budget check. A temporary n-double point buffer is freed before the persistent workspace is allocated. Copies at the Python boundary, allocations inside callbacks and Python object overhead are not counted. When the output shape has to be discovered, the first callback runs after preliminary bounds checks but before the full workspace and history checks.

history=0 disables recording. Otherwise history is allocated up front and bounded by history_bytes (default 8 MiB), counting the metrics and copies of the point, residual and whole Jacobian for every entry. history_every samples iterations; initial and terminal states are always eligible. A terminal failure in the same iteration updates its existing record. When storage is full, history_truncated is set and later entries are dropped. Exported tuples stay valid and unchanged after the solver resumes or is deleted.

Native solves cannot be cancelled and do not check for signals. With native callbacks, independent solves can run without the GIL; shared callback state needs synchronization by its owner.

Native Wolfe–Bittner accepts arbitrary nonempty point pools and rectangular residuals through rank-aware affine interpolation, and reports its best and active states separately.

Native Vrahatis Generalized Bisection

cyroot.vrahatis runs a native state machine. Its input is either a matrix of sign-polygon vertices or a single point, from which a bounded heuristic tries to build a polygon. Python callbacks receive a copied point tuple and return a residual vector. Setup accepts lists, tuples and compatible NumPy buffers; results and history are copied into immutable tuples.

from itertools import product
from cyroot import vrahatis
from cyroot.native import Vrahatis

vertices = tuple(product((0., 2.), repeat=2))
def residual(x):
    return (x[0]-.7, x[1]-.7)

answer = vrahatis(residual, vertices)
assert answer.success

solver = Vrahatis(residual, vertices, history=64)  # Keep the terminal sweep too.
first = solver.step()
answer = solver.run()
assert answer.success
assert solver.history[-1].root == answer.root

Sign And Stopping Contracts

For a residual with m components and points with n coordinates, a starting polygon has exactly 2**m vertices, one for each strict sign pattern of the residual. Every residual component at those vertices must be finite and nonzero, except that a supplied vertex that already meets the residual tolerance is returned before the sign condition is checked. All input and cached residual rows must have matching dimensions. Cached F_x0s values avoid new callback evaluations.

Vertices are ordered by the binary order of their signs, negative before positive. Each sweep visits pairs of sign cells that differ in one component, samples the midpoint of their current vertices, and replaces the vertex whose sign pattern the midpoint matches. A zero residual component matches either sign. A candidate that equals its vertex causes stagnation; a failed callback or nonfinite sample keeps the last accepted finite state.

precision is the largest coordinate span of the polygon, not the residual spread or the Euclidean diameter. The residual error is the infinity norm, and the relative residual tolerance uses the initial residual scale. The iteration budget counts sweeps; one sweep can sample several edges and stops early at a terminal condition. Function counts include setup and polygon-search samples, but not supplied cached values. For a constructed polygon, the residuals of its vertices set the residual scale. A sample found during construction that already meets the residual tolerance ends the solve at once, without completing the polygon.

For a single residual component, a sign-changing segment is an ordinary scalar bracket, which for a continuous function certifies a root, so a small coordinate width ends successfully. For several components, the vertex signs alone do not certify that a common root exists, so a small width is stagnation, not success; only the residual tolerance ends a multidimensional solve successfully. The method searches by signs and does not derive a degree or face certificate from its vertices.

Rectangular systems (n different from m) use the same recurrence. The polygon still needs 2**m sign patterns, and the extra input coordinates are ordinary coordinates of its geometry. Nothing here guarantees that a root of a rectangular system exists or is unique.

Python And Compiled Callbacks

Pass a Python callable, a residual VectorCallback for square systems, or a residual RectangularCallback when the input and output lengths differ. Native code creates them with make_vector_callback or make_rectangular_callback, the same callback ABI as the other vector solvers.

A native residual writes every output element and returns zero on success; a nonzero status raises NativeCallbackError. The producer must keep its context alive through the descriptor’s keepalive, must not let exceptions escape, and must synchronize any shared mutable native state. Reentrant or concurrent use of one adapter is rejected. Python exceptions propagate as the original instance.

Setup conversions and copied exports hold the GIL. With native callbacks, vertex initialization, polygon sampling and the whole numerical run() happen outside the GIL, with no NumPy calls and no per-sample arrays or views. Python callbacks take the GIL only for their own calls. See Compile Python Callbacks for typed Python-syntax and Cython examples.

Single-Point Polygon Discovery

from cyroot import vrahatis
from cyroot.vector_bracketing import compute_admissible_n_polygon

# A cube from (-1,-1) with side steps (2,2) already covers all four signs.
points, signs = compute_admissible_n_polygon(
    lambda x: (x[0]-.2, x[1]-.3), (-1.,-1.), h=(2.,2.))
answer = vrahatis(lambda x: (x[0]-.2, x[1]-.3), points)
assert answer.success

h is a scalar or one finite step per input coordinate. By default every coordinate uses max(1, norm_inf(x)), also at the origin. The search samples one axis-aligned cube of inputs, then refines the actual sign changes of each component along its edges to find the missing sign patterns. A complete polygon keeps one point per pattern with its evaluated residual. The search never invents signs, does not count zero components as extra patterns, and does not resample completed vertices before the iteration starts.

Edges are pairs of cube corners that differ in one input coordinate, in any dimension. Edges whose endpoints have the same sign in a component are skipped for that component instead of being bisected. The search is bounded and heuristic: failing to complete a polygon does not prove that no root or admissible polygon exists. When it fails, supply explicit vertices or change the starting point or steps.

polygon_eps controls the internal sign-change search; the standalone helper calls it eps. The search budgets max_evaluations, max_visits and max_bisections are separate from the solver’s max_iter. Resource limits and finite steps are checked before the native loops start. With 2**n cube corners and 2**m sign patterns, large dimensions are expensive even in native code.

The standalone helper compute_admissible_n_polygon requires a complete polygon even when its search happens to sample a root; the solver returns such a root directly.

cyroot.vector_bracketing also provides the helpers get_M, _get_1_simplexes and sorted_by_vertices, which return NumPy arrays. The solver and the native polygon builder do not use them, or any NumPy operation, internally.

Inspection And Resources

Vrahatis exposes step(), run(), result, done, iteration, history and history_truncated. A step is one edge sweep. History stores copies of the root, residual, polygon, residual polygon, counters and metrics. history=0 disables it; history, history_every and history_bytes bound what is kept. A full history does not stop the solve, and earlier snapshots stay valid after the solver resumes or is destroyed.

workspace_bytes bounds the native workspace and history_bytes the native history. Python conversion objects, exported tuples, allocator metadata and allocations made by callbacks come on top, so these are not limits on the process’s peak memory. Inputs are copied; caller arrays are never modified.

Migrating From 1.x

Callbacks receive tuples, so NumPy expressions such as lambda x: x-target need explicit elementwise arithmetic or a conversion of the input. Results contain tuples, and call counts and iteration paths can differ from 1.x. Compiled consumers must be rebuilt against the 2.0 declarations. The private vrahatis_kernel and the experimental Mishchenko and Ahmadi methods were removed. The Eiger–Sikorski–Stenger method, which needs degree and simplex search machinery, is not implemented.

Native Square Broyden

cyroot.native.BroydenGood and BroydenBad are resumable solvers for square systems that share one native state engine. Good Broyden starts from a Jacobian matrix, a native JacobianPlan, or None for an automatic central plan. The BroydenBad constructor instead takes an inverse Jacobian approximation and does not invert what you pass; to start from a Jacobian matrix, plan or None, use BroydenBad.from_jacobian(...), which builds the initial inverse. The public cyroot.broyden runs the same engine to completion. Its J_x0 is a Jacobian guess for both variants; for bad Broyden it goes through from_jacobian.

from cyroot.native import BroydenGood, BroydenBad

def residual(point):
    x, y = point
    return (x*x + y - 2., x + 2*y*y - 3.)

jacobian0 = ((2.8, 1.), (1., 2.8))
good = BroydenGood(residual, jacobian0, (1.4, .7), history=32)
first = good.step()
result = good.run()
assert result.success
assert max(abs(v-1.) for v in result.root) < 1e-9
assert good.history[-1].root == result.root

determinant = 2.8*2.8 - 1.
inverse0 = ((2.8/determinant, -1./determinant),
            (-1./determinant, 2.8/determinant))
bad = BroydenBad(residual, inverse0, (1.4, .7))
assert bad.run().success

Public Entry Point

The public signature is:

broyden(F, x0, F_x0=None, J_x0=None, *, algo=2,
        etol=1e-10, ertol=4*eps, ptol=1e-12, prtol=4*eps, max_iter=200,
        history=0, history_every=1, history_bytes=8*1024*1024,
        workspace_bytes=64*1024*1024)

Here eps is the binary64 machine epsilon. algo is the built-in integer 1 (good) or 2 (bad), or the string 'good' or 'bad'. Booleans, subclasses and other objects that merely compare equal or convert to integers are rejected. The default is bad Broyden.

from cyroot import broyden
from cyroot.native import JacobianPlan

result = broyden(residual, (1.4, .7), J_x0=jacobian0, algo='bad')
assert result.success
assert result.approximation_kind == 'inverse_jacobian'

planned_result = broyden(residual, (1.4, .7),
                         J_x0=JacobianPlan(2, step=1e-4), algo='good')
assert planned_result.success

J_x0 is a matrix, a native JacobianPlan of matching size, or None for an automatic central plan. Here it is never an inverse; to start from an inverse guess, use BroydenBad directly. A callable Jacobian is not accepted.

Compared with 1.x:

  • algo, the tolerances and the iteration and resource options are keyword-only after J_x0. The h option is gone; use JacobianPlan(..., step=...).
  • Python residuals receive immutable tuples instead of NumPy arrays. Replace expressions such as point - 1. with indexed arithmetic, or convert inside the callback (in Python, under the GIL).
  • Points, residuals and approximation matrices in the result are copied tuples. The result is a BroydenResult with the fields described below, so code that unpacked the old tuple or used ndarray methods needs updating. f_calls is an integer.
  • Only square, nonempty systems are accepted, even when a cached initial residual is already zero. Shape errors raise; a singular solve reports breakdown, with no pseudoinverse or least-squares fallback.
  • Native plans build the initial Jacobian. A central plan costs 2*n residual samples plus one evaluation at the starting point unless it is cached; forward and backward plans cost n plus that evaluation. F_x0 supplies it at no cost. The samples are skipped when the starting point is a root and are never repeated after setup.

cyroot.vector_quasi_newton.broyden and find_vector_root('broyden', ...) are the same function. It returns only the final result; although it accepts the history options, use a BroydenGood or BroydenBad.from_jacobian solver with step(), run() and .history to inspect intermediate records. Klement shares this state engine with its own row-weighted update, and Barnes shares the direct solve and initialization with a projected update over retained secants.

Distinct Updates

Write \(s=x_{k+1}-x_k\), using the actual rounded accepted points, and \(y=F(x_{k+1})-F(x_k)\). Direct good Broyden solves \(B_k d=-F(x_k)\), then updates

\[ B_{k+1}=B_k+\frac{(y-B_k s)s^T}{s^Ts},\qquad B_{k+1}s=y. \]

Inverse bad Broyden takes \(d=-H_kF(x_k)\), then updates

\[ H_{k+1}=H_k+\frac{(s-H_k y)y^T}{y^Ty},\qquad H_{k+1}y=s. \]

These are different minimum-change secant constraints. Neither matrix is an analytic derivative at the current point. The direct variant uses packed pivoted LU and checks factor finiteness even when LAPACK reports success. The inverse variant uses scaled native matrix-vector contraction.

The rank-one update scales binary exponents and uses compensated sums across the denominator, residual and final matrix addition. It avoids some premature product, denominator and correction overflow/underflow. It does not increase precision or certify a small secant error; cancellation, conditioning and final binary64 range still limit accuracy. In one dimension the update uses the secant quotient directly, avoiding subtraction of the previous approximation. There is no damping, line search, restart, pseudoinverse or rectangular fallback. Local convergence requires suitable smoothness, initial approximations and a nonsingular root Jacobian.

Interface And Boundaries

BroydenGood(function, jacobian0, x0, f_x0=None, *, etol=1e-10, ertol=4*eps, ptol=1e-12, prtol=4*eps, max_iter=200, history=0, history_every=1, history_bytes=8*1024*1024, workspace_bytes=64*1024*1024). BroydenBad has the same options, replacing jacobian0 with inverse0. broyden_good(function, jacobian0, x0, **options) and broyden_bad(function, inverse0, x0, **options) construct and run one solver. The default max_iter is 200; zero or None is unlimited. The total budget is shared by step() and run(). Iterating over a solver yields its remaining steps.

Points and residuals must have the same nonzero length \(n\), and initial matrices the shape \((n,n)\). Sized sequences and buffers, including strided NumPy arrays, are copied. Supplied matrix shapes and plan dimensions are checked even when the cached starting point is already a root. An unused nonfinite explicit matrix does not prevent residual convergence, but is reported as invalid. A callable initial Jacobian is not accepted; pass a matrix or a plan.

Python residual callbacks receive an immutable tuple and return a numeric sequence or a supported buffer. A residual VectorCallback created in Python, by the Cython factory or from a C capsule can run without the GIL, and its context is kept alive. All point, matrix, cache and option conversions happen while explicit adapters are reserved. Setup and result and history export hold the GIL.

Native Initial Jacobian And Inverse Setup

from cyroot.native import JacobianPlan

planned = BroydenGood(residual, JacobianPlan(2, step=.001), (1.4, .7))
assert planned.result.initialization_calls == 1
assert planned.result.approximation_valid
assert planned.run().success

inverse_planned = BroydenBad.from_jacobian(residual, None, (1.4, .7))
assert inverse_planned.run().success

None selects the default central plan; an explicit JacobianPlan sets the scheme and steps. The initial residual, including one passed as f_x0, is reused as the plan’s base point. initialization_calls counts attempts to build the initial Jacobian numerically (zero or one, failures included), and f_calls includes every residual sample. An explicit matrix counts no numerical attempt, even when bad Broyden has to invert it. Plans run only during setup; later steps use secant updates.

from_jacobian factors a private copy of the Jacobian once and solves for each unit vector in native scratch. Every status, factor and solution is checked, and no Python object or memoryview is created per column. Only a complete, finite inverse is published. If building or inverting fails, the initial point and residual are kept, the approximation is all NaN and approximation_valid is false; initialization_calls and phase show what was attempted. A failed native residual sample reports the callback stage 'initial_jacobian', and a Python exception propagates as the original instance.

If the starting point is already a root, no plan is sampled and nothing is inverted, so a generated matrix stays all NaN and invalid, with zero initialization attempts. A supplied finite approximation stays valid; an unused nonfinite one is marked invalid. Valid means that a complete, finite approximation is available, not that it is accurate or nonsingular. The initial inversion has no pseudoinverse fallback.

Results, History And Failures

BroydenResult is an immutable tuple with named fields: root, f_root, approximation, approximation_kind, approximation_iteration, iters, f_calls, precision, error, termination_reason, callback_code, callback_stage, linear_status, phase, approximation_valid, and initialization_calls. BroydenStep is the same type. success, converged and optimal are true only for residual convergence. Results taken while running have termination_reason=None. The integer f_calls counts residual attempts; a cached initial residual counts as zero.

approximation_kind is 'jacobian' or 'inverse_jacobian'. approximation_iteration starts at zero and gives the iteration of the last completed secant update. After a finite trial, the solver accepts the point and residual and checks the residual, step and budget before any update that would go unused. A final result’s approximation can therefore be older than the returned point; the metadata says so, rather than presenting it as the derivative there.

phase is None, 'linear', 'trial', 'update', 'initial_jacobian' or 'initial_inverse'. linear_status keeps the latest LAPACK status and is reset when a new linear phase starts. A singular direct solve reports breakdown; nonfinite factors, solutions, residuals, differences or updates report nonfinite. A zero denominator in a needed secant update reports breakdown. A trial equal to the current point with an unsatisfied residual reports unsuccessful stagnation first.

Each attempt to evaluate the residual at a finite trial point increments iters, even if the callback fails or returns nonfinite values; arithmetic or linear failures before the trial do not. A failed trial keeps the previously accepted point, residual, matrix and metrics. A failed update keeps the newly accepted point, residual and metrics with the previous complete matrix and approximation_iteration; a partially updated matrix is never visible. Callback errors keep the native status or the original Python exception, and a NativeCallbackError carries a copied result. Once an error has been raised, further calls on the finished solver only return its state.

history returns copied snapshots. history_every samples iterations, and the terminal snapshot is included if there is room. A failure later in the same iteration replaces that iteration’s earlier record. Once the capacity is full, later snapshots are dropped and history_truncated is true. Records already copied are unaffected by later steps or by destroying the solver.

Memory And Compiled Use

Good Broyden reserves \(6n+3n^2\) doubles and \(n\) C-int pivots; bad Broyden with an explicit inverse reserves \(6n+2n^2\) doubles and no pivots. from_jacobian needs another \(n^2\) doubles and \(n\) pivots for the initial inversion. A numerical initial plan adds \(5n\) scratch doubles plus storage for its explicit steps. History stores \(2n+n^2\) doubles and a metadata record per slot. Products, capacities and byte limits are all checked before allocation. These budgets cover CyRoot’s native storage; Python exports and memory used inside LAPACK come on top. The engine allocates no native storage per step.

The compiled example uses the installed .pxd declarations and headers with native callbacks, without NumPy C headers. broyden_ops.pxd exposes the low-level update helper from broyden.hpp. It takes non-overlapping packed column-major matrix and output spans plus direction and target vectors, and checks the dimensions before writing. A nonfinite or zero direction fills the whole output with NaN; invalid dimensions leave the spans untouched. The numerical kernel follows the native callback and storage contracts.

Native Barnes Method

cyroot.barnes runs the native direct quasi-Newton engine with a deterministic Barnes secant update. It shares initialization, the square LU solve, stopping rules, callback guards and copied history with good Broyden. Numerical work uses native buffers and SciPy’s Cython LAPACK interface. Native residual callbacks run without the GIL; Python callbacks and boundary conversions hold it.

from cyroot import barnes
from cyroot.native import Barnes, JacobianPlan

def residual(point):
    return (point[0]**2-2.,)

result = barnes(residual, (1.5,), J_x0=JacobianPlan(1, step=1e-4))
assert result.success
assert abs(result.root[0]-2.**.5) < 1e-9

solver = Barnes(residual, ((3.,),), (1.5,), history=16)
first = solver.step()
result = solver.run()
assert result.success
assert solver.history[-1].root == result.root
assert solver.secant_history_size == 0  # At most n-1 directions are retained.

The public signature is barnes(F, x0, F_x0=None, J_x0=None, *, etol=1e-10, ertol=4*eps, ptol=1e-12, prtol=4*eps, max_iter=200, history=0, history_every=1, history_bytes=8*1024*1024, workspace_bytes=64*1024*1024), also available as find_vector_root('barnes', ...). J_x0 is an initial Jacobian matrix, a JacobianPlan of matching size, or None for central differences. A cached F_x0 counts as zero calls and is reused by the plan. If the starting point is already a root, no derivative is computed and no update is made.

Compared with 1.x, options after J_x0 are keyword-only, and h and formula are gone. Use JacobianPlan(..., step=...) for the step. The update always uses the explicit secant residual described below (the former formula=2); the other formula used the new residual alone, which assumes an exact linear solve and ignores rounding of the accepted step. Python callbacks receive immutable tuples, so array operations on points need indexed arithmetic or an explicit conversion inside the callback. Results are BroydenResult tuples with an integer residual-call count; code that unpacked the old tuple or used ndarray methods needs updating.

cyroot.native.Barnes(function, jacobian0, x0, f_x0=None, **options) provides step(), run(), iteration and copied .history, and cyroot.native.barnes(function, jacobian0, x0, **options) runs one solver to completion. Constructor options and result fields are those of BroydenGood. solver.method is 'barnes', and solver.secant_history_size is the number of step directions currently retained for the update. That memory is separate from the optional exported history.

Deterministic Retained-Secant Update

Write \(s=x_{k+1}-x_k\), using actual rounded accepted points, and \(y=F(x_{k+1})-F(x_k)\). Retain the most recent \(n-1\) step directions from completed updates, in oldest-first order. Normalize each historical vector by its largest absolute entry and build a basis of its numerical span with two passes of modified Gram–Schmidt. Zero or numerically dependent history rows are skipped.

Project the max-scaled current step onto the orthogonal complement of that basis and normalize the result to a unit vector \(z\). The relative dependence threshold is \(64n\epsilon\), compared with the original max-scaled vector’s Euclidean norm, for both history rank and the current projection. A current projection at or below that threshold reports unsuccessful breakdown.

The matrix update is

\[ B^+=B+\frac{(y-Bs)z^T}{z^Ts}. \]

In exact arithmetic it satisfies \(B^+s=y\) and preserves the old matrix’s action on the retained numerical basis. History components omitted by the dependence threshold are preserved only approximately. Among unit vectors in that complement, the projected direction maximizes \(|z^Ts|\). This deterministic choice replaces the random direction of 1.x, so no random numbers are drawn. The first update has no history and reduces to good Broyden, and so does every update in one dimension, where the direction history has zero capacity.

After a complete, finite update, the accepted displacement is appended to the history, dropping the oldest entry when it is full. A failed update changes neither the matrix, its update iteration nor this history, but the newly accepted point and residual are kept. Convergence, stagnation and the iteration budget are checked before an update that would go unused, so a final result can carry the previous matrix and direction history, as approximation_iteration shows.

The projection uses scaled, compensated dot products, and the rank-one update keeps binary exponents and both compensated residual components through the final addition. This widens the intermediate range and reduces some cancellation, but does not raise binary64 precision or make the multisecant conditions hold exactly. Near-dependence and ill-conditioning can still limit accuracy. A dependent current direction does not trigger a restart or a fallback to Broyden. There is no damping, line search or global convergence guarantee.

Only nonempty square systems are accepted. A singular LU solve reports breakdown, with no least-squares fallback. Nonfinite factors, residual changes or updated entries report nonfinite. A small step with a nonzero residual is unsuccessful stagnation; only residual convergence counts as a root. Native callback codes, Python exceptions and the kept last accepted state behave as in the shared Broyden engine.

Memory And Native Use

Persistent native storage is \(6n+5n^2\) doubles and \(n\) C-int pivots. Compared with good Broyden, that adds \(n(n-1)\) stored directions, \(n(n-1)\) basis entries, an \(n\)-double scratch row and the \(n\)-double projected direction. Numerical initialization adds \(5n\) scratch doubles and copies of the plan’s explicit steps. Budgets are checked before allocation, and nothing is allocated during a step. Exported history has its own byte budget. Python boundary objects and memory used inside LAPACK are not counted.

barnes_ops.pxd exposes the allocation-free barnes_direction and barnes_update from barnes.hpp. Callers must pass valid, non-overlapping spans. The direction inputs are the oldest-first history[count*n] and step[n] with count<=n-1, the scratch is basis[n*(n-1)] and row[n], and the output is z[n]. The update inputs are the column-major matrix[n*n], step[n], target[n] and z[n], and the output is out[n*n]. Status zero is success, one a nonfinite input or result, two an invalid shape or count (nothing is written), and three a dependent or zero direction or a zero update denominator. Other failures fill the whole output with NaN. Callers are responsible for valid pointers and for keeping callback code and context alive.

The original reference is Barnes, An algorithm for solving non-linear equations based on the secant method.

Native Klement Method

cyroot.klement runs the native Broyden state engine with Klement’s row-weighted Jacobian update. Its numerical loop, initial derivative sampling and matrix operations use native buffers and SciPy’s Cython LAPACK interface. With a native residual callback the numerical work runs without the GIL; Python callbacks and input and result conversions hold it.

from cyroot import klement
from cyroot.native import JacobianPlan, Klement

def residual(point):
    x, y = point
    return (x*x+y-2., x+2*y*y-3.)

result = klement(residual, (1.4, .7),
                 J_x0=JacobianPlan(2, step=1e-4))
assert result.success
assert max(abs(value-1.) for value in result.root) < 1e-8

solver = Klement(residual, ((2.8, 1.), (1., 2.8)), (1.4, .7), history=32)
first = solver.step()
result = solver.run()
assert result.success
assert first.approximation_iteration == 1
assert solver.history[-1].root == result.root

The public signature is klement(F, x0, F_x0=None, J_x0=None, *, etol=1e-10, ertol=4*eps, ptol=1e-12, prtol=4*eps, max_iter=200, history=0, history_every=1, history_bytes=8*1024*1024, workspace_bytes=64*1024*1024), also available as find_vector_root('klement', ...).

J_x0 is an initial Jacobian matrix, a JacobianPlan of matching size, or None for automatic central differences; a callable Jacobian is not accepted. A cached F_x0 skips the initial residual call and is reused by the plan. Central initialization takes 2*n residual samples and forward or backward initialization n; nothing is sampled when the starting point is a root. After initialization, the matrix changes only through secant updates.

Compared with 1.x, options after J_x0 are keyword-only and h is gone; use JacobianPlan(..., step=...). The removed 1.x derivative providers are rejected. Python residuals receive immutable tuples and must return sized sequences or buffers, so array arithmetic on the point needs indexed arithmetic or an explicit conversion inside the callback.

The result is a BroydenResult, with tuple point, residual and matrix, an integer f_calls, the approximation’s validity and the iteration of its last update. The matrix is a secant approximation, not the derivative at the returned point. Code that unpacked the old tuple or used NumPy methods on the result needs updating. success, converged and optimal are true only for residual convergence.

cyroot.native.Klement(function, jacobian0, x0, f_x0=None, **options) provides step(), run(), iteration and copied .history, and cyroot.native.klement(function, jacobian0, x0, **options) runs one solver to completion. Constructor options and result and history fields are those of BroydenGood. solver.method is 'klement'.

Update And Failure Policy

Write \(s=x_{k+1}-x_k\) using the actual rounded accepted points and \(y=F(x_{k+1})-F(x_k)\). Each row of the old approximation \(B\) defines \(u_j=B_{ij}s_j\) and \(d_i=\sum_j u_j^2\). Klement updates

\[ B^+_{ij}=B_{ij}+\frac{\left(y_i-\sum_j u_j\right)u_jB_{ij}}{d_i}. \]

In exact arithmetic this enforces \(B^+s=y\). Unlike good Broyden’s shared \(s^Ts\) denominator, the weighting differs from row to row. Entries that start at zero stay zero, so the method cannot discover a sparsity pattern that the initial matrix lacks. A zero denominator in any row reports an unsuccessful breakdown when an update is needed; there is no fallback to Broyden, restart or random direction.

The update uses binary-exponent scaling and compensated sums to avoid some premature overflow and underflow in products, squares and corrections. It does not raise precision or make the secant error small under severe cancellation. In one dimension a nonzero row uses the secant quotient directly. Nonfinite inputs or updated entries report nonfinite.

Only nonempty square systems are supported. A singular linear solve reports breakdown, with no least-squares fallback. There is no damping, line search or global convergence guarantee, and a small step with a nonzero residual is unsuccessful stagnation. The engine accepts a finite trial before checking convergence, stagnation and the budget, and skips updates that would go unused. A failed update keeps the accepted point and residual and the previous complete matrix, with phase='update' and an unchanged approximation_iteration.

Memory budgets, history sampling, callback guards and error transfer are those of good Broyden: 6*n+3*n*n doubles and n C-int pivots, plus 5*n doubles and copied steps for numerical initialization. Native storage is allocated before the loop; Python objects and memory used inside LAPACK are not counted. For compiled calls, pass a residual VectorCallback.

broyden_ops.pxd also exposes the low-level klement_update from broyden.hpp. It takes non-overlapping column-major matrix[n*n], direction[n], target[n] and out[n*n] spans. Status zero is success, one a nonfinite input or result, two an invalid dimension (nothing is written), and three a zero row denominator. Other failures fill the whole output with NaN.

The original reference is On Using Quasi-Newton Algorithms of the Broyden Class for Model-to-Test Correlation.

Native Robinson Method

cyroot.robinson runs the shared native Newton state from two starting points, with a divided-difference matrix built from orthogonal probes. Native buffers, probe construction and SciPy’s Cython LAPACK routines let the numerical work run without the GIL when the residual is native; Python callbacks and boundary conversions hold it.

from cyroot import robinson
from cyroot.native import Robinson

def residual(point):
    return (point[0]**2-2.,)

result = robinson(residual, (1.,), (1.5,))
assert result.success
assert abs(result.root[0]-2.**.5) < 1e-9

solver = Robinson(residual, (1.,), (1.5,), history=16)
first = solver.step()
result = solver.run()
assert result.success
assert first.iters == 1
assert solver.history[-1].root == result.root

The public signature is robinson(F, x0, x1, F_x0=None, F_x1=None, *, orth='efficient', etol=1e-10, ertol=4*eps, ptol=1e-12, prtol=4*eps, max_iter=200, history=0, history_every=1, history_bytes=8*1024*1024, workspace_bytes=64*1024*1024), also available as find_vector_root('robinson', ...). Options after F_x1 are keyword-only.

cyroot.native.Robinson(function, x0, x1, f_x0=None, f_x1=None, **options) provides step(), run(), iteration and copied .history, and cyroot.native.robinson(function, x0, x1, **options) runs one solver to completion. The solver subclasses VectorNewton and reuses its iteration and stopping rules, without a Jacobian provider or Jacobian cache. Only nonempty square systems are accepted. The two starting points must have the same length and differ, even when a cached residual shows one is a root. A residual VectorCallback or a square RectangularCallback can wrap a compiled function.

Directions And Corrected Secant Equations

Let the previous point be \(p\), the active point \(x\), the actual separation \(s=x-p\) and radius \(r=\|s\|_2\). orth='identity' or the exact built-in integer 1 uses \(Q=I\). orth='efficient' (the default) or the exact built-in integer 2 uses a deterministic Householder reflection. With \(u=s/r\), set \(v=u+\sigma e_0\), where \(\sigma=-1\) when \(u_0<0\) and \(+1\) otherwise, and form

\[ Q=I-\frac{2vv^T}{v^Tv}. \]

This sign choice avoids cancellation in the reflection vector and handles steps with leading zero coordinates, which the 1.x construction treated as special cases. The radius is accumulated with hypot. The 1.x 'random'/3 option is gone, and no random numbers are drawn. Booleans, subclasses and objects that merely convert to these values are not accepted.

Each column defines the full probe point obtained by rounding \(x+rQ_{:,j}\). Write its actual displacement as \(S_{:,j}=\operatorname{probe}_j-x\), and \(D_{:,j}=F(\operatorname{probe}_j)-F(x)\). The divided-difference matrix satisfies

\[ JS=D. \]

The solver factors \(S^T\) once, solves for each row of \(J\), and then takes the ordinary Newton step \(J\delta=-F(x)\); no inverse is formed. Using the actual rounded displacements, rather than assuming an exactly orthogonal matrix, also fixes the row/column orientation error of 1.x. Both direction modes use the same reconstruction and the same square LU solve.

All starting coordinates and probe points are checked before sampling. A zero separation, a fully collapsed probe or a singular rounded displacement matrix reports an unsuccessful breakdown; overflowing coordinates, separations, factors, differences or results report nonfinite. There is no pseudoinverse, random retry, damping or line search, and no global convergence guarantee. Only residual convergence counts as a root.

Initial Pair, Counts And Snapshots

Both initial residuals are evaluated in order, x0 then x1, unless they are cached; cached values count as zero calls. Both points and residuals must be finite for initialization to proceed. A nonfinite starting point, or two identical points, fail validation before any callback.

The residual scale is the larger initial residual norm, the coordinate scale uses both points, and the initial precision is their separation in the infinity norm. If the starting pair already meets a residual or width tolerance, the point with the smaller residual is returned (x1 on a tie). Otherwise x1 becomes the active point, even if x0 has the smaller residual, and early failures report this active state’s point, residual and matrix. A separation that overflows is harmless at an initial root but reports nonfinite once probes are needed.

Python callbacks receive immutable tuples. Results are NewtonMethodsReturnType with copied tuple point, residual and matrix rows, and f_calls=(residual_calls, matrix_attempts). Building a matrix costs \(n\) residual probes, and the uncached starting pair adds two calls. A matrix attempt that fails its node or factor checks counts as an attempt without probes. Only trial residual calls count as iterations; probes and row solves do not. Each accepted trial makes the old active point the new previous point.

Convergence, stagnation and the iteration budget are checked before a matrix rebuild that would go unused, so a final df_root is then all NaN. A failed trial keeps the previous active state. A failed rebuild keeps the accepted point and residual and clears the whole matrix. Native errors in probe samples report the stage 'jacobian', and errors in the initial or trial residuals 'function'. Python exceptions propagate as the original instance; once one has been raised, further calls only return the solver’s state. If a starting callback fails, the result reports the x1 state with its cached residual, or NaN if it was not evaluated.

step() and .history return VectorNewtonStep records, including the linear status and rank (None for square LU). linear_status is the latest LAPACK status, including that of the probe-displacement factorization and row solves. Exported history is copied. Callback reservations cover setup conversions, probe sampling, and result, error and history construction.

Memory And Native Helper

The native workspace is \(8n+4n^2\) doubles and \(n\) C-int pivots: the square Newton workspace plus the previous point and residual, two probe and orientation matrices and a scratch row. No finite-difference plan is involved. Storage is checked and allocated before the iteration starts, and history has its own bounded allocation. Python boundary objects and memory used inside LAPACK are not counted.

robinson_ops.pxd exposes the allocation-free, noexcept robinson_nodes helper from robinson.hpp. Callers pass valid, non-overlapping previous[n], current[n], nodes[n*n], transpose[n*n] and scratch[n] spans. nodes holds the full probe points column by column, and transpose[j+n*i] the actual displacement in coordinate i for probe j. Status zero is success, one a nonfinite input or result, two an invalid dimension (nothing is written), and three a zero separation or a collapsed probe. Other failures fill both outputs with NaN. The solver validates the rounded orientation matrix before calling back.

The original reference is Robinson’s paper.

Native Traub–Steffensen

cyroot.traub_steffensen runs the shared native Newton state with divided differences whose steps come from the residual. The numerical loop, derivative samples and square LU solves use native buffers and SciPy’s Cython LAPACK interface. With native callbacks the numerical work runs without the GIL; Python callbacks and input and result conversions hold it.

from cyroot import traub_steffensen
from cyroot.native import TraubSteffensen

def residual(point):
    return (point[0]**2-2.,)

result = traub_steffensen(residual, (1.5,))
assert result.success
assert abs(result.root[0]-2.**.5) < 1e-9

solver = TraubSteffensen(residual, (1.5,), history=16)
first = solver.step()
result = solver.run()
assert result.success
assert first.iters == 1
assert solver.history[-1].root == result.root

The public signature is traub_steffensen(F, x0, F_x0=None, *, etol=1e-10, ertol=4*eps, ptol=1e-12, prtol=4*eps, max_iter=200, history=0, history_every=1, history_bytes=8*1024*1024, workspace_bytes=64*1024*1024), also available as find_vector_root('traub_steffensen', ...). Options after F_x0 are keyword-only.

cyroot.native.TraubSteffensen(function, x0, f_x0=None, **options) provides step(), run(), iteration and copied .history, and cyroot.native.traub_steffensen(function, x0, **options) runs one solver to completion. It subclasses VectorNewton and shares its stopping, resource and failure rules, without a Jacobian provider or Jacobian cache. Systems must be square and nonempty, with point and residual both of length \(n\). A RectangularCallback is accepted when its input and output dimensions are equal.

Residual-Based Differences

At an accepted point \(x\), take the signed coordinate step \(h_j=F_j(x)\). For each axis, evaluate \(F\) at the floating-point point obtained by adding \(h_j\) to coordinate \(j\). If its actual rounded displacement is \(a_j\), the matrix column is

\[ D_{ij}(x)=\frac{F_i(x+a_je_j)-F_i(x)}{a_j}. \]

The next point solves \(D(x)\delta=-F(x)\) and evaluates \(x+\delta\). The steps are recomputed from the residual at every accepted iterate; they are not the small automatic steps of JacobianPlan. In one dimension this is the usual Steffensen update. In several dimensions, pairing coordinate \(j\) with residual component \(j\) makes the method depend on the order and scaling of the equations.

The differences use the same native forward-difference stencil as JacobianPlan, dividing by the actual displacement rather than the requested residual component, which the 1.x formula got wrong when rounding changed the step. Every node is validated before any sample. A zero residual component away from a root, or a step that rounds back to the original coordinate, reports an unsuccessful breakdown; an overflowing node or displacement reports nonfinite. A zero component says nothing about the Jacobian column, and inverting a singular perturbation matrix would hide that missing information, so there is no automatic fallback. For such systems, generalized_newton(F, None, x0) uses independently sized steps. If the starting point is already a root, no differences are computed.

A singular linear system reports breakdown, as for the square LU solve of vector Newton. There is no pseudoinverse, rectangular variant, damping or line search, and no global convergence guarantee. Only residual convergence counts as a root; a small step with a nonzero residual is unsuccessful stagnation.

Results And Counts

Python callbacks receive immutable tuples, so NumPy arithmetic on the point needs indexed operations or an explicit conversion inside the callback. Inputs and outputs can be sized numeric sequences or buffers. Results are NewtonMethodsReturnType with copied tuple point, residual and Jacobian rows, and f_calls=(residual_calls, jacobian_attempts).

A complete divided-difference matrix costs \(n\) residual probes and reuses the residual at the current point. An uncached initial residual adds one call; a cached F_x0 adds none. jacobian_attempts counts every matrix attempt, including one that fails validation before sampling. Trial residuals count as iterations; probes do not. When an accepted trial ends the solve, no matrix is built for it and df_root contains NaNs. These rules match vector Newton.

step() and .history return VectorNewtonStep records with the matrix at the point, the counts, any callback stage and code, the linear status and the rank (None for square LU). A failed probe reports the native callback stage 'jacobian', a failed base or trial residual 'function'. Python exceptions propagate as the original instance. A failed trial keeps the previous accepted point, residual and matrix; a failed matrix rebuild keeps the newly accepted point and residual with an all-NaN matrix. Once an error has been raised, further calls only return the solver’s state.

The native workspace is that of numerical square Newton: \(10n+2n^2\) doubles and \(n\) C-int pivots, including the stencil’s \(5n\)-double scratch, with no persistent step vector or derivative plan. It is allocated before the iteration and reused. History is bounded separately. Python boundary copies and memory used inside LAPACK are not counted. Callback reservations cover setup, samples and result and history export.

The private _steffensen_jacobian declaration in derivatives.pxd takes non-overlapping x[n], base[n], out[n*n] and work[5*n] spans, a square native residual function and context, and call-count and status pointers. The caller must validate positive dimensions and their products and keep every buffer and callback alive. On failure the whole output is filled with NaN and the scratch point is restored.

Native Wolfe–Bittner Method

cyroot.wolfe_bittner uses native multipoint buffers and SciPy’s Cython LAPACK DGELSY solver. Its numerical loop does no NumPy operations and, with compiled residual callbacks, runs without the GIL. Python callbacks receive tuple points and take the GIL.

from cyroot import wolfe_bittner
from cyroot.native import WolfeBittner

def residual(point):
    return (point[0]**3 - 2*point[0] + 2.,)

solver = WolfeBittner(residual, ((0.,), (1.,)), max_iter=2,
                     etol=0., ertol=0., ptol=0., prtol=0., history=3)
first = solver.step()
assert first.root == (1.,)                 # best point so far
assert abs(first.active_root[0]-2.) < 1e-12
result = solver.run()
assert abs(result.root[0]-.8) < 1e-12
assert solver.history[-1].root == result.root

# Rectangular systems and pools of any size are supported.
answer = wolfe_bittner(lambda p: (p[0]-1., 2*(p[0]-1.)), ((0.,), (2.,)))
assert answer.success

The public signature is wolfe_bittner(F, x0s, F_x0s=None, *, rcond=1e-12, etol=1e-10, ertol=4*eps, ptol=1e-12, prtol=4*eps, max_iter=200, history=0, history_every=1, history_bytes=8*1024*1024, workspace_bytes=64*1024*1024), also available as find_vector_root('wolfe_bittner', ...). Options after the residual cache are keyword-only. cyroot.native.WolfeBittner(function, x0s, f_x0s=None, **options) provides step(), run(), iteration, a copied .result and a bounded, copied .history, and cyroot.native.wolfe_bittner(function, x0s, **options) runs one solver to completion.

Shapes And Initialization

Supply a nonempty matrix of \(k\) points of length \(n\), with residuals of length \(m\). A cache, if supplied, must have shape \((k,m)\). Neither \(m=n\) nor \(k=n+1\) is required; duplicate points and smaller or larger pools are accepted, and the affine consistency check below decides whether a useful step exists. A single point that is not a root has zero pool width and stops with an unsuccessful stagnation, even when all tolerances are zero. No warning is issued about the shape and no extra points are generated.

Python functions get the residual dimension from their first evaluation, which is reused. A residual VectorCallback declares a square shape and a RectangularCallback separate input and output dimensions; both can wrap compiled callbacks. LAPACK limits the sizes to \(1\le k\le32767\) and \(1\le m\le32766\), and the input dimension must fit a C int.

All starting coordinates and caches are packed and checked before any evaluation, and every initial residual must be finite before convergence can be reported. Uncached initial residuals are evaluated in input order and count once each; cached ones count as zero. On ties, the first point with the smallest residual norm wins. If an initial evaluation fails, the result reports the best finite point evaluated so far, or the first point with a NaN residual if there is none.

The residual scale is the largest initial residual infinity norm, and the coordinate scale includes every point. The pool width precision is the largest coordinate range, regardless of the residuals. Initial residual or width tolerances are checked before any linear solve. Otherwise the pool is ordered from largest to smallest initial residual, keeping input order on ties. After each accepted trial, the oldest point is dropped and the trial appended; the pool is not re-sorted.

Affine Step And Root Checks

For the current pool, form columns \(A_{:,j}=(1,F(x_j))\) and solve \(Ap=b\), with \(b=(1,0,\ldots,0)\), for the minimum-norm least-squares weights using DGELSY and rcond. Any rectangular affine system is supported, and rank deficiency alone does not reject a consistent solution. rcond must be finite and strictly between zero and one; it sets the numerical rank cutoff, not a root tolerance.

Before sampling the candidate \(x=\sum_jp_jx_j\), require

\[ \|Ap-b\|_\infty \le 32\epsilon\max(m+1,k)\left(\|A\|_\infty\|p\|_\infty+1\right). \]

An inconsistent affine system reports breakdown without a trial callback or iteration. Nonfinite coefficients, arithmetic, candidates or samples report nonfinite. Every point is checked, including those with zero weight, and an intermediate sum that overflows reports nonfinite even if later cancellation would have brought it back into range. The test checks backward consistency; it does not bound the error of the candidate or the root. A successful LAPACK call alone is not enough, and only nonlinear residual convergence counts as a root.

An iteration is counted when the trial residual is evaluated. A failed callback or nonfinite sample leaves the pool, the active state and the best point unchanged. A finite trial becomes the active state even if its residual is worse, and replaces the best point only if it is strictly better. The stopping checks use the best residual and the current pool width, then the iteration budget. The next affine solve happens only when another step is requested. There is no damping, random restart or line search, and no global convergence guarantee.

Results, History And Memory

Results are WolfeBittnerResult tuples, replacing the ndarray-based RootReturnType of 1.x. They contain the copied tuples root, f_root, active_root and active_f_root, plus iters, the integer f_calls, precision, error, termination_reason, callback_code, callback_stage, linear_status, linear_rank and affine_error. root, f_root and error always describe the best point; the active fields describe the latest accepted trial, which starts as the best initial point. success, converged and optimal all mean residual convergence.

WolfeBittnerStep is the same immutable type. The latest rank, LAPACK status and affine error can describe a failed step while the coordinates stay at the accepted states. Before the first solve, the rank is None and the affine error NaN. Native callback failures report the stage 'function' and the original integer code; Python exceptions propagate as the original instance, once. Inspecting a finished solver makes no further evaluations. Callback reservations cover conversions, evaluations and result, error and history creation.

The native workspace holds \(k(n+m)+3(n+m)+(m+1)k+(m+1)+k+w\) doubles and \(k\) C-int pivots, where \(w\) is the least-squares plan’s work_size. The temporary copy of the starting points is released before the persistent storage is allocated. History has its own checked storage for two point/residual pairs, diagnostics and the affine error per record. Python boundary copies and memory used inside LAPACK are not counted. All loop buffers are allocated before the iteration.

wolfe_bittner_ops.pxd exposes the allocation-free, noexcept wolfe_bittner_candidate from wolfe_bittner.hpp. Callers pass valid, non-overlapping column-major matrix[rows*k], weights[k], row-major points[k*n], candidate[n] and affine_error[1] spans. It returns two for invalid dimensions (nothing is written), one for nonfinite inputs or arithmetic and three for an inconsistent system. With valid dimensions, any failure fills the candidate with NaN. The affine error is kept when the full finite residual was computed, and is NaN otherwise.

Original reference: Wolfe–Bittner.

Native Vector Chebyshev

cyroot.native.VectorChebyshev solves square and rectangular real systems with analytic or numerical Jacobians and Hessians. This page describes square systems; the rectangular extension uses rank-aware least-squares corrections. The solver supports Python and compiled callbacks, resumable execution and bounded copied history. Its numerical loop uses native storage, SciPy’s Cython LAPACK interface and native tensor contraction, with no NumPy operations or per-step allocations.

from cyroot.native import VectorChebyshev

def residual(x):
    a, b = x
    return (a*a + a*b + b - 5., 2*a + b*b - 6.)

def jacobian(x):
    a, b = x
    return ((2*a + b, a + 1.), (2., 2*b))

def hessian(x):
    return (((2., 1.), (1., 0.)), ((0., 0.), (0., 2.)))

solver = VectorChebyshev(residual, jacobian, hessian, (1.1, 1.9), history=16)
first = solver.step()
result = solver.run()
assert result.success
assert solver.history[-1].root == result.root

Update And Linear Algebra

At an accepted point the solver computes

\[ Js=F,\qquad q=H[s,s],\qquad Jt=q,\qquad \Delta x=-s-\tfrac12t. \]

The Hessian contraction is \(q_o=\sum_{j,k}H_{o,j,k}s_js_k\). Every ordered pair of inputs contributes; analytic Hessians are neither checked for symmetry nor symmetrized. A zero component of \(s\) is fine. The solver copies \(J\), factors it once with LAPACK dgetrf and reuses the factors for both dgetrs solves; no inverse is formed. A nonzero LAPACK status reports breakdown, with the status in linear_status. Nonfinite factors or solutions report nonfinite even when LAPACK reports success, since that status alone does not guarantee finite factors.

With accurate derivatives, the method converges cubically near a smooth root with a nonsingular Jacobian. Matrix Halley and Super-Halley share this state engine with their own coupled updates, and the public higher-order vector functions run it; see the migration guide.

The contraction uses binary64 mantissas with explicit binary exponents and compensated summation. This avoids premature overflow and underflow in the individual triple products and lets some sums of individually unrepresentable terms come out finite; it extends the range, not the precision. Inaccurate derivatives, cancellation, ill-conditioned linear systems and overflow in the final values remain limitations, and LAPACK or the step arithmetic can still report a failure conservatively. There is no damping, line search or least-squares fallback for a singular square system.

Providers And Cached Values

The constructor is VectorChebyshev(function, jacobian, hessian, x0, f_x0=None, jac_x0=None, hess_x0=None, *, etol=1e-10, ertol=4*eps, ptol=1e-12, prtol=4*eps, max_iter=200, history=0, history_every=1, history_bytes=8*1024*1024, workspace_bytes=64*1024*1024). vector_chebyshev(function, jacobian, hessian, x0, **options) constructs a solver and runs it to completion. The default max_iter is 200; zero or None is unlimited. Native callbacks use versioned descriptors.

function is a Python residual or a residual VectorCallback. jacobian is a Python function, a Jacobian VectorCallback, a JacobianPlan of matching size, or None for a default central plan. hessian is a Python function, a HessianCallback, a HessianPlan of matching size, or None for a default central plan. Native dimensions, flags and kinds are validated, also for callable subclasses and when the cached starting point is a root.

Points and residuals have length \(n\), Jacobians shape \((n,n)\) and Hessians shape \((n,n,n)\), indexed [residual][input][input]. Jacobians can be nested sequences or two-dimensional buffers. Hessians from Python providers or caches are read by nested indexing, so NumPy arrays of the right shape work, including strided and read-only ones; they are always copied. Hessian entries must be real scalars. Python callbacks receive a copied point tuple, which they may keep, and may reuse their output containers.

f_x0, jac_x0 and hess_x0 are independent caches of the values at the starting point and count as zero evaluations. All of them are converted and their shapes checked during setup. If the starting point is already a root, unused derivatives are not checked for finiteness and the supplied caches are kept. Otherwise the Jacobian is evaluated before the Hessian. Numerical plans reuse the residual at the current point but sample the axes independently, since the plans can use different steps. See Jacobian plans and Hessian plans for rounded stencils, sample counts and accuracy limits.

State, Counts And Failures

step() and run() share one iteration budget and the shared stopping rules. An iteration is one attempt to evaluate the residual at a finite trial point, even if the callback fails. A candidate equal to the current point is still evaluated before success or stagnation is decided. Accepting a finite candidate clears the Jacobian and Hessian, and the stopping rules and budget are checked before more derivative work. A failed trial keeps the previous finite point, residual, derivatives and metrics and updates only the counts and diagnostics.

result is a NewtonMethodsReturnType. Its root and f_root are tuples, and df_root is (jacobian, hessian) as nested tuples. f_calls is (F, J, H): each plan evaluation counts once for its derivative, and all of its residual samples also count in \(F\); failed attempts count too. Derivatives that are not available are NaN. A Jacobian failure clears both derivatives; a Hessian failure keeps a valid Jacobian and clears the Hessian.

VectorChebyshevStep contains root, f_root, df_root, iters, f_calls, precision, error, termination_reason, callback_code, callback_stage, linear_status and linear_stage (None, 'jacobian' or 'secondary'). VectorHigherOrderStep is another name for the same class. Chebyshev uses only the Jacobian stage, and its read-only method property returns 'chebyshev'. Snapshots and history are immutable copies that survive later steps and the solver’s destruction; history follows the native recording rules. result, done, history, history_truncated, callback_code, callback_stage, linear_status and linear_stage read the state without advancing it.

A nonzero native callback status raises NativeCallbackError with the exact native_status, a copied result and the stage 'function', 'jacobian' or 'hessian', also for residual samples taken by numerical plans. Python exceptions propagate as the original instance, with their traceback. The solver is then finished: after the failing call raises, later step() or run() calls only return the failed state. Every callback output is set to NaN beforehand, so a value the callback did not write can never be accepted.

All explicit adapters are inspected before any is reserved. They stay reserved through the conversion of dimensions, options and caches, allocation, numerical execution, result conversion and exception transfer. Reentrant or concurrent use of an active solver or adapter raises an error. Independent callbacks can share immutable plans, each with its own workspace. Callers that share mutable native contexts must synchronize them.

Storage Budgets

For dimension \(n\), define \(w\) as the larger of \(5n\) for a numerical Jacobian and \(2n^2+10n\) for a numerical Hessian; omit a term when that role is analytic. The solver allocates \(8n+2n^2+n^3+w\) doubles and \(n\) C-int pivots up front. The workspace budget also counts both plans’ explicit steps, even when the plans are shared. History costs another \(2n+n^2+n^3\) doubles plus a metadata record per requested slot. Integer products and capacities are checked before allocation. Python owners and exports and memory used inside LAPACK are outside these budgets. Workspace and history are allocated once; nothing is allocated per step.

Compiled Hessian Callbacks

Installed tensor_callbacks.pxd exposes make_hessian_callback(function, dimension, context, keepalive) with signature int callback(const double* x, size_t n, double* out, void* context) noexcept nogil. Write all \(n^3\) entries in residual-first column-major order: out[o + n*(j + n*k)]. The input is borrowed only for the call; do not modify it or keep its pointer. Return zero on success and a nonzero status on failure, and never let Python or C++ exceptions cross this ABI. The adapter keeps the supplied keepalive object alive as long as it exists.

C and C++ code can instead put a cyroot_hessian_descriptor from callbacks.h in a capsule named cyroot.hessian_callback.v1 and call HessianCallback.from_capsule(capsule, keepalive=owner). The adapter checks the name, version, minimum size, dimension and that the function is not null, then copies the function and context and keeps the owners alive. The capsule name cannot prove that the pointers are valid. This tensor ABI is separate from the cyroot.vector_callback.v1 residual and Jacobian capsules.

When every evaluated role, including the residual sampled by numerical plans, has a native callback, execution stays outside the GIL. Python callbacks take it for each evaluation, as do setup and result and history export. The compiled example uses the installed headers and declarations without NumPy C headers. Rectangular corrections are described in the rectangular Chebyshev guide.

Native Matrix Halley And Super-Halley

cyroot.native.VectorHalley and VectorSuperHalley solve square and rectangular real systems with analytic or numerical Jacobians and Hessians. They share the callback, cache, history and stopping engine of vector Chebyshev, and their updates add a coupled solve with a secondary matrix.

from cyroot.native import VectorHalley, VectorSuperHalley

def residual(x):
    a, b = x
    return (a*a + a*b + b - 5., 2*a + b*b - 6.)

def jacobian(x):
    a, b = x
    return ((2*a + b, a + 1.), (2., 2*b))

def hessian(x):
    return (((2., 1.), (1., 0.)), ((0., 0.), (0., 2.)))

for method in (VectorHalley, VectorSuperHalley):
    solver = method(residual, jacobian, hessian, (1.25, 1.75), history=16)
    first = solver.step()
    result = solver.run()
    assert result.success
    assert solver.history[-1].root == result.root

Coupled Matrix Updates

The formulas and LU policy in this section describe square systems. For rectangular systems, see the least-squares extension.

At each accepted point, first solve \(Js=F\) and form the directional Hessian matrix \(A\), where

\[ A_{o,k}=\sum_j H_{o,j,k}s_j,\qquad Av=H[s,v]. \]

Halley solves

\[ (J-\tfrac12A)v=F,\qquad \Delta x=-v. \]

Super-Halley solves

\[ (J-A)v=F,\qquad \Delta x=-\tfrac12(s+v). \]

The Super-Halley mean avoids overflow from adding two large finite vectors and premature underflow from halving two subnormal components separately. Each method factors \(J\) to get \(s\), then factors its own secondary matrix to get \(v\), reusing the pivot storage. No inverse is formed, and a singular secondary system has no fallback.

These are matrix extensions of the scalar methods of the same names and, with accurate derivatives, converge cubically near a smooth root with a nonsingular Jacobian. They can be derived from the operator \(B=J^{-1}A\) and \((I-\alpha B)v=s\) with \(\alpha=1/2\) or \(1\), without assuming that \(J\) and \(A\) commute. Zero components of \(s\) are fine. The componentwise generalized_halley formula of 1.x behaved differently; the function now uses matrix Halley. The migration guide lists the numerical and interface changes.

The whole ordered Hessian contributes; analytic Hessians are neither checked for symmetry nor symmetrized. The directional contraction uses compensated, exponent-scaled arithmetic to extend the intermediate range, with the same accuracy limits as the Chebyshev contraction. Secondary entries are formed with fused multiply-add before they are checked for finiteness. Inaccurate derivatives, cancellation, ill-conditioned systems, final overflow and the binary64 range of the secondary matrix remain limitations. There is no damping, line search or automatic fallback.

Providers, Caches And Execution

Both constructors have the same signature as VectorChebyshev:

VectorHalley(function, jacobian, hessian, x0, f_x0=None, jac_x0=None, hess_x0=None, *, etol=1e-10, ertol=4*eps, ptol=1e-12, prtol=4*eps, max_iter=200, history=0, history_every=1, history_bytes=8*1024*1024, workspace_bytes=64*1024*1024).

VectorSuperHalley takes the same arguments, and vector_halley(...) and vector_super_halley(...) construct a solver and run it to completion. These fixed methods have no alpha argument; VectorModifiedHalley accepts any finite parameter and uses their exact arithmetic at the matching values. The read-only method property returns 'chebyshev', 'halley' or 'super_halley', and subclasses keep the update of the class they extend.

The provider shapes below are for square systems; rectangular callbacks and plans use the shapes in the rectangular manual.

Residuals are Python functions or residual VectorCallback adapters. Jacobians are Python functions, Jacobian VectorCallback adapters, JacobianPlans of matching size, or None for a default central plan. Hessians are Python functions, HessianCallback adapters, HessianPlans of matching size, or None for a default central plan. Points and residuals have length \(n\), Jacobians shape \((n,n)\) and Hessians shape \((n,n,n)\), indexed [residual][input][input]. Every supplied cache is converted and its shape checked while the callbacks are reserved, even when the starting point is a root. When the starting residual already converges, unused derivatives are neither evaluated nor checked. Numerical plans reuse the residual at the current point but have their own stencils and steps.

All the Chebyshev provider and cache rules apply, including context lifetimes, native field validation, copied Python callback inputs and the handling of derivative failures. Every numerical derivative evaluation counts one attempt for its derivative and adds all of its samples to the residual count. step() and run() share one iteration budget; the default max_iter is 200, and zero or None is unlimited.

Diagnostics And Retained State

result is a NewtonMethodsReturnType, with tuple root and residual, df_root=(jacobian, hessian) and f_calls=(F, J, H). Steps are immutable VectorChebyshevStep records (also named VectorHigherOrderStep), which include the linear_stage of the most recent linear operation.

linear_stage is None, 'jacobian' or 'secondary': the current or most recent linear phase, including the directional contraction and the formation of the secondary matrix. linear_status holds the latest LAPACK status in that phase, and is zero until a LAPACK call is made in it. Both are also copied into step and history records; the common result type does not include them.

A nonzero factorization or solve status reports breakdown with its code and stage. Nonfinite factors report nonfinite even if LAPACK reports success. The directional contraction, the secondary matrix and its solution are checked before any trial callback; a failure there keeps the previous accepted point, residual, derivatives and metrics and uses no iteration. Each attempt to evaluate the residual at a finite candidate counts one iteration, even if the callback fails. A failed trial keeps the previous accepted state; an accepted trial clears the derivatives, updates the metrics and checks the stopping rules and budget before any more derivative work. A candidate equal to the current point is still evaluated before success or stagnation is decided.

Callback failures report the stage 'function', 'jacobian' or 'hessian', with the exact native status or the original Python exception and traceback. After the failing call raises, later step() and run() calls only return the state. Immutable history follows the native recording rules and survives resuming or destroying the solver. Adapter reservations cover setup conversions, execution, exports and error transfer; reentering an active solver or adapter is rejected.

Workspace And Native Consumers

For square systems, the matrix methods add an \(n^2\)-double secondary matrix to the Chebyshev workspace, for a total of \(8n+3n^2+n^3+w\) doubles and \(n\) C-int pivots, plus the plans’ explicit steps, where \(w\) is the largest numerical-plan scratch. (Chebyshev needs \(8n+2n^2+n^3+w\) doubles.) For rectangular systems they add an \(mn\)-double secondary matrix to the rectangular Chebyshev workspace. Every method stores \(2n+n^2+n^3\) doubles plus a metadata record per history slot. Integer products, capacities and the separate workspace and history byte limits are checked before allocation, and nothing is allocated per step. Python owners and exports and memory used inside LAPACK are outside these budgets.

The compiled example uses native residual, Jacobian and Hessian callbacks with the installed .pxd files and headers, without NumPy C headers. vector_chebyshev.pxd declares the shared engine and both subclasses. tensor_ops.pxd exposes the native directional contraction and a helper for the finite negative mean of two scalars. The directional output is column-major, out[o+n*k], and the input Hessian is indexed H[o+n*(j+n*k)]. Callers own the spans and must pass valid, non-overlapping ones. Invalid dimensions fail before anything is written; any other contraction failure fills the whole directional matrix with NaN.

With native callbacks and numerical plans, execution happens outside the GIL; Python callbacks, setup and result and history export take it. The parameterized rectangular update uses the general correction, while the exact fixed values of alpha keep the fixed formulas. The public higher-order vector functions run this engine; see the migration guide.

Parameterized Native Matrix Modified Halley

cyroot.native.VectorModifiedHalley adds a finite real parameter alpha to the shared vector engine. It accepts the same analytic or numerical Jacobian and Hessian providers, cached values, stepping and bounded copied history as matrix Halley and Super-Halley.

from cyroot.native import VectorModifiedHalley

def residual(x):
    a, b = x
    return (a*a + a*b + b - 5., 2*a + b*b - 6.)

def jacobian(x):
    a, b = x
    return ((2*a + b, a + 1.), (2., 2*b))

def hessian(x):
    return (((2., 1.), (1., 0.)), ((0., 0.), (0., 2.)))

solver = VectorModifiedHalley(residual, jacobian, hessian, (1.25, 1.75),
                              alpha=.25, history=16)
first = solver.step()
result = solver.run()
assert result.success
assert solver.history[-1].root == result.root

Coupled Update And Exact Special Paths

For general parameter values, the method computes

\[ Js=F,\qquad A_{o,k}=\sum_j H_{o,j,k}s_j,\qquad (J-\alpha A)v=F,\qquad Jt=Av,\qquad \Delta x=-s-\tfrac12t. \]

The Jacobian’s LU factors and pivots are reused for the final correction solve, and the secondary matrix has its own pivots. The order of matrix products matters, since \(J\) and \(A\) need not commute. No inverse is formed, and \(t\) is never computed as \((v-s)/\alpha\), which would lose accuracy for small \(\alpha\). The general step uses fused multiply-add so that a subnormal half-correction is kept until the final addition is rounded.

alpha exactly zero (including negative zero) uses the Chebyshev path, exactly .5 matrix Halley and exactly 1 Super-Halley, with their arithmetic and workspace sizes. Other finite values use the general correction. The method property is 'modified_halley' for this class whichever path is used.

For square systems, the method converges cubically near a smooth root with a nonsingular Jacobian, given accurate derivatives. Some parameter values can make the secondary matrix singular, change the convergence behavior or amplify conditioning problems. There is no automatic parameter choice, damping or fallback. Every finite alpha also has a rectangular least-squares correction; because alpha=0, .5 and 1 select the fixed methods, rectangular steps can jump near .5 and 1, as that page explains. The public higher-order vector functions run this engine and the componentwise default of 1.x is gone; see the migration guide.

Configuration And Providers

The constructor is VectorModifiedHalley(function, jacobian, hessian, x0, f_x0=None, jac_x0=None, hess_x0=None, *, alpha=.5, etol=1e-10, ertol=4*eps, ptol=1e-12, prtol=4*eps, max_iter=200, history=0, history_every=1, history_bytes=8*1024*1024, workspace_bytes=64*1024*1024). vector_modified_halley(function, jacobian, hessian, x0, **options) constructs a solver and runs it to completion. The read-only alpha property returns the value as a binary64 float. Python subclasses keep the native parameterized method; overriding a property does not change what runs.

alpha is converted once, while the solver and all explicit callback adapters are reserved. Any object with a finite real conversion is accepted; text, sequences, booleans, complex values, NumPy boolean and complex scalars and nonfinite values are rejected, even when the cached starting point is a root. A failed conversion releases the reservations. The fixed Chebyshev, Halley and Super-Halley constructors reject an alpha argument.

The provider shapes and workspace formulas below are for square systems; for rectangular systems, see the rectangular manual.

Residuals are Python functions or residual VectorCallback adapters. Jacobians are Python functions, Jacobian VectorCallback adapters, JacobianPlans of matching size, or None for the default central plan. Hessians are Python functions, HessianCallback adapters, HessianPlans of matching size, or None. Points and residuals have length \(n\), Jacobians shape \((n,n)\) and Hessians shape \((n,n,n)\), indexed [residual][input][input]. Provider kinds, initialization and dimensions are checked, and so are the conversion and shape of every supplied cache; when the starting residual already converges, unused derivatives are not checked for finiteness.

All the shared provider and cache rules apply. Numerical Jacobian and Hessian plans each reuse the residual at the current point, but their steps can differ and they share no samples. f_calls=(F, J, H) counts each plan evaluation for its derivative and every residual sample in \(F\), failures included; cached values count as zero. Python callbacks receive copied tuples, and adapters keep native contexts alive.

Diagnostics, Failure State And Range

The result is a NewtonMethodsReturnType, with tuple root and residual, df_root=(jacobian, hessian), counts and termination reason. Snapshots are immutable VectorHigherOrderStep records (also named VectorChebyshevStep). Besides None, 'jacobian' and 'secondary', linear_stage can be 'correction' for the final matrix-vector product and the second Jacobian solve.

Each new phase resets linear_status to zero and then keeps the latest LAPACK status in that phase. A nonzero factorization or solve status reports breakdown, and nonfinite LU factors report nonfinite even with status zero. A nonfinite directional contraction, secondary matrix, solution or correction stops the solve before any trial callback, keeping the previous accepted point, residual, derivatives and metrics. Secondary entries use fused multiply-add.

The matrix-vector product uses scaled binary exponents and compensated summation, like the other native tensor helpers. This avoids premature overflow and underflow in products but does not increase precision. Ill-conditioned systems, derivative errors, cancellation, final overflow and the binary64 range of intermediates remain limitations. Finishing with finite values says nothing about derivative accuracy or convergence, and a failure is not retried with a different update.

The shared state rules apply: each attempt to evaluate the residual at a finite trial point is an iteration, a failed trial keeps the accepted state, and an accepted trial clears the derivatives and checks the stopping rules and budget before any more derivative work. A Jacobian failure clears both derivatives, while a Hessian failure keeps a valid Jacobian. Native callback errors keep their code and stage, and Python exceptions propagate as the original instance with its traceback. After an error is raised, later step() and run() calls only return the state. step() and run() share one budget; the default max_iter is 200, and zero or None is unlimited.

Workspace And Compiled Use

Let \(B=8n+2n^2+n^3+w\) doubles, where \(w\) is the largest selected numerical Jacobian/Hessian scratch requirement. alpha=0 needs \(B\) doubles and \(n\) C-int pivots. .5 and 1 need \(B+n^2\) doubles and \(n\) reused pivots. The general path needs \(B+2n^2\) doubles and \(2n\) pivots. Both plans’ explicit steps also count against workspace_bytes, even if the plans are shared. History takes \(2n+n^2+n^3\) doubles plus a metadata record per slot. Products, byte budgets and capacities are checked before allocation, and nothing is allocated per step. Python owners and exports and memory used inside LAPACK come on top.

The compiled example uses the installed Cython declarations and native callbacks, with contexts kept alive by their adapters and without NumPy C headers. vector_chebyshev.pxd declares the shared engine and the parameterized subclass. tensor_ops.pxd exposes matrix_vector for valid, non-overlapping packed column-major matrix, direction and output spans. Invalid dimensions fail before anything is written; any other contraction failure fills the whole output with NaN.

With native callbacks and plans, execution happens outside the GIL; Python callbacks, setup and result and history export take it. The callback and storage contracts are described in the native core guide.

Rectangular Chebyshev

VectorChebyshev and generalized_chebyshev accept \(F:\mathbb R^n\to\mathbb R^m\) with \(m<n\) or \(m>n\), using the same higher-order state engine as square systems: buffers, callbacks, derivative plans and linear algebra adapt to the shape, and there is no separate rectangular loop. Python callbacks receive tuples and take the GIL. Compiled callbacks and the numerical loop run without it, reusing the workspace between steps.

from cyroot import generalized_chebyshev
from cyroot.native import VectorChebyshev

def residual(x):
    value = x[0]**2 - 2.
    return (value, 2*value)

def jacobian(x):
    return ((2*x[0],), (4*x[0],))

def hessian(x):
    return (((2.,),), ((4.,),))

result = generalized_chebyshev(residual, jacobian, hessian, (1.5,))
assert result.success
assert abs(result.root[0]-2.**.5) < 1e-9

solver = VectorChebyshev(residual, None, None, (1.5,), history=8)
first = solver.step()
result = solver.run()
assert result.success
assert first.linear_rank == 1
assert solver.history[-1].root == result.root
assert (solver.input_dimension, solver.output_dimension) == (1, 2)

Equations And Rank Policy

With \(J\) of shape \((m,n)\) and \(H\) of shape \((m,n,n)\), the rectangular step is defined as

\[ s=J^+F,\qquad q=H[s,s],\qquad t=J^+q,\qquad \Delta x=-s-\tfrac12t. \]

Each solve takes the minimum-norm least-squares solution from the DGELSY LeastSquaresPlan, with its default rcond=1e-12. As for rectangular Newton, numerical rank deficiency is allowed. The two solves share native scratch and pivots, but each calls DGELSY; the factorization is not reused. Every ordered pair of Hessian inputs contributes, so analytic tensors need not be symmetric.

A rectangular linear solve can leave a nonzero least-squares residual. That alone neither rejects the correction nor makes the point a root; only nonlinear residual convergence counts as success. At an inconsistent stationary point the solve can stop with an unsuccessful stagnation, and a Jacobian of rank zero gives a zero correction with the same outcome. rcond is a numerical rank threshold, not a root tolerance. Cubic convergence is not claimed for rectangular or rank-deficient problems in general: the behavior depends on the rank, conditioning, derivative accuracy and the residual map. There is no damping, line search or automatic switch to another method.

Square systems still use LU, with one factorization and two triangular solves. A singular square system reports breakdown instead of falling back to least squares, and nonfinite intermediates report nonfinite.

VectorModifiedHalley(alpha=0) and generalized_halley(..., alpha=0) take this same Chebyshev path, rectangular systems included. Fixed Halley and Super-Halley, also reached with alpha=.5 and alpha=1, handle rectangular systems too. Other values of alpha use the general rectangular correction.

Shapes, Callbacks And Derivative Plans

The signatures are the same as for square systems:

  • generalized_chebyshev(F, J, H, x0, F_x0=None, J_x0=None, H_x0=None, **options).
  • VectorChebyshev(function, jacobian, hessian, x0, f_x0=None, jac_x0=None, hess_x0=None, **options) for step(), run(), iteration and copied history.

Options are keyword-only, as described in the square manual. The length of the point gives \(n\). Declared providers and the residual cache fix \(m\); if none of them does, one Python residual evaluation determines it and is reused as the first residual. Every provider must agree with the point and residual dimensions. Caches have shapes \((m)\), \((m,n)\) and \((m,n,n)\), and a residual cache sets the output length rather than implying a square system. Inputs are never reshaped silently.

Python callables can be passed directly. The native providers are RectangularCallback for residuals and Jacobians, RectangularHessianCallback for analytic Hessians, and RectangularJacobianPlan and RectangularHessianPlan for numerical derivatives; None selects automatic central plans. Square callback and plan types require \(m=n\), and rectangular adapters with a square shape also work. A Hessian provider passed as the residual or Jacobian is rejected before any input is converted. Callback reservations cover option, point and cache conversion, evaluation, snapshots and exception construction.

An invalid starting point calls no residual callback; if the output shape is unknown, the terminal state uses \(m=n\) placeholders. Exceptions from the first call, which discovers the shape, or from later callbacks propagate as the original instance. Construction records an inspectable terminal state before raising a callback error, and inspecting it afterwards makes no further evaluations. If the cached starting point is a root, no derivatives are evaluated and no linear solve is made.

Results, History And Storage

Results are NewtonMethodsReturnType with copied tuple point and residual and df_root=(Jacobian, Hessian). Call counts are (residual, Jacobian, Hessian), and numerical derivative samples count as residual calls. Native failures in the residual, Jacobian or Hessian report their own callback stage and code. A failed trial callback keeps the last accepted point and residual. An accepted finite trial clears the old derivatives before the stopping checks and recomputes them only if another iteration is needed.

The solver exposes input_dimension, output_dimension and linear_rank, and VectorChebyshevStep (or VectorHigherOrderStep) records include linear_rank. It is None for square LU and before the first rectangular solve, and otherwise the latest DGELSY rank. linear_status is the LAPACK status, and Chebyshev labels both solves linear_stage='jacobian'. Neither the rank nor a successful solve implies a root. Result and history shapes follow the two dimensions, and exported snapshots are immutable copies.

For rectangular systems, persistent storage holds \(5n+3m+mn+mn^2+w+d\) doubles and \(n\) C-int pivots, where \(w\) is the least-squares plan’s work_size and \(d\) the largest numerical Jacobian or Hessian scratch in use. The contraction vector doubles as the first solve’s right-hand side, and there is no LU buffer or secondary matrix. The plans’ explicit steps count against the workspace budget.

A temporary copy of the starting point is released before the persistent storage is allocated. History has its own checked budget: one record plus \(n+m+mn+mn^2\) doubles per snapshot. Python boundary copies and memory used inside LAPACK come on top, and the plans’ own budget checks can be conservative. Nothing is allocated per iteration. Numerical derivatives are configured through the derivative plans.

Rectangular Matrix Halley And Super-Halley

VectorHalley and VectorSuperHalley accept different input and residual lengths through the shared higher-order engine, with the same signatures as for square systems. Declared providers, the residual cache or the first Python residual, which is reused, determine the shapes, and None derivatives select numerical plans of the right shape. Compiled callbacks and the numerical loop run without the GIL; Python callbacks take it.

from cyroot import generalized_halley, generalized_super_halley
from cyroot.native import VectorHalley

def residual(x):
    value = x[0]**2 - 2.
    return (value, 2*value)

def jacobian(x):
    return ((2*x[0],), (4*x[0],))

def hessian(x):
    return (((2.,),), ((4.,),))

for method in (generalized_halley, generalized_super_halley):
    answer = method(residual, jacobian, hessian, (1.5,))
    assert answer.success
    assert abs(answer.root[0]-2.**.5) < 1e-9

solver = VectorHalley(residual, None, None, (1.5,), history=8)
first = solver.step()
answer = solver.run()
assert answer.success
assert first.linear_stage == 'secondary'
assert first.linear_rank == 1
assert solver.history[-1].root == answer.root

Rectangular Equations

For \(J\in\mathbb R^{m\times n}\) and \(H\) of shape \((m,n,n)\), first compute the minimum-norm least-squares correction and directional tensor matrix:

\[ s=J^+F,\qquad A_{o,k}=\sum_jH_{o,j,k}s_j. \]

Matrix Halley then uses

\[ B=J-\tfrac12A,\qquad v=B^+F,\qquad \Delta x=-v. \]

Super-Halley uses

\[ B=J-A,\qquad v=B^+F,\qquad \Delta x=-\tfrac12(s+v). \]

The pseudoinverse stands for the minimum-norm least-squares solution computed by the DGELSY plan; no inverse is formed. The rank threshold is fixed at rcond=1e-12, as for rectangular Chebyshev and Newton. Numerical rank deficiency is allowed in both the primary and the secondary system, and their ranks can differ. A secondary system of rank zero gives a zero solution, which can end in unsuccessful stagnation. There is no restart, damping or switch to another method.

These formulas extend the square updates to rectangular systems. They are not claimed to converge cubically on rectangular, rank-deficient or rank-changing problems in general, nor to match every possible generalized-inverse formulation. A least-squares residual alone neither rejects a step nor makes the point a root. Only nonlinear residual convergence counts as success, and an inconsistent stationary point can stagnate without one.

Every ordered pair of Hessian inputs contributes, so asymmetric analytic tensors are used as given. The shared contraction uses scaled, compensated arithmetic and forms secondary entries with fused multiply-add, and Super-Halley’s averaging handles very large and subnormal values as in the square case. None of this removes derivative noise, cancellation or conditioning limits.

Square systems still use LU. A singular square primary or secondary matrix reports breakdown, with no least-squares fallback.

Routes, Diagnostics And Storage

These entry points share the same state and equations:

Entry pointMethod
VectorHalley, vector_halley, generalized_halley(alpha=None)Halley
VectorSuperHalley, vector_super_halley, generalized_super_halleySuper-Halley
generalized_tangent_hyperbolasHalley
VectorModifiedHalley(alpha=.5), generalized_halley(alpha=.5)Halley
VectorModifiedHalley(alpha=1), generalized_halley(alpha=1)Super-Halley

alpha=0 gives rectangular Chebyshev. Other finite values of alpha use the general rectangular correction, so steps can jump near exactly .5 and 1. The method property of VectorModifiedHalley is 'modified_halley' even when a special path is taken.

Callbacks, cache shapes, copied result and history tuples, handling of the accepted state, counting and bounded storage work as for rectangular Chebyshev. linear_stage is 'jacobian' for the primary solve and 'secondary' while forming or solving the secondary system. linear_rank belongs to the latest DGELSY solve, so if the secondary contraction fails before its solve, it is still the primary rank. linear_status is the latest LAPACK status. Neither the rank nor a successful solve implies a root. For square LU the rank is None.

Each rectangular step makes two DGELSY solves with the same immutable plan, work array and pivots. The secondary right-hand side reuses the \(m\)-entry contraction buffer, and the solution has \(n\) entries. Nothing is allocated per step. Compared with rectangular Chebyshev, the workspace adds an \(mn\)-double secondary matrix. The plans’ steps and scratch count against the workspace budget, and copied history has its own checked budget.

Higher mixed partials are available as separate tensor plans; these second-order solvers use only Jacobian and Hessian providers.

Rectangular Parameterized Modified Halley

VectorModifiedHalley and generalized_halley(..., alpha=...) accept rectangular systems for every finite real alpha. Signatures, callback shapes and numerical plans are those of the shared rectangular higher-order engine. Native callbacks and the numerical loop run without the GIL; Python callbacks take it.

from cyroot import generalized_halley
from cyroot.native import VectorModifiedHalley

def residual(x):
    value = x[0]**2-2.
    return (value, 2*value)

def jacobian(x):
    return ((2*x[0],), (4*x[0],))

def hessian(x):
    return (((2.,),), ((4.,),))

answer = generalized_halley(residual, jacobian, hessian, (1.5,), alpha=.25)
assert answer.success
solver = VectorModifiedHalley(residual, None, None, (1.5,), alpha=.25, history=8)
first = solver.step()
assert first.linear_stage == 'correction'
assert first.linear_rank == 1
assert solver.run().success
assert solver.history[-1].root == solver.result.root

General Correction

For \(n\) inputs, \(m\) residuals and \(\alpha\notin\{0,1/2,1\}\), the rectangular update is

\[ s=J^+F,\qquad A_{o,k}=\sum_j H_{o,j,k}s_j,\qquad v=(J-\alpha A)^+F,\qquad t=J^+(Av),\qquad \Delta x=-s-\tfrac12t. \]

Each pseudoinverse is a minimum-norm least-squares solve with DGELSY, using the same fixed rcond=1e-12 as rectangular Newton and Chebyshev; no inverse is formed. Rank deficiency is allowed, and the Jacobian and the secondary matrix can have different numerical ranks. A solve of rank zero returns zero. Neither the rank nor the LAPACK status implies a root: only nonlinear residual convergence counts as success, and an inconsistent stationary point can stop unsuccessfully. There is no damping, restart or automatic fallback, and no convergence order is promised for rectangular or rank-changing systems.

Square systems still use LU factors for the correction solve, report breakdown on a singular matrix and have no least-squares fallback.

Exact Special Parameters

alpha exactly 0, .5 and 1 selects Chebyshev, Halley and Super-Halley, with their fixed update formulas and smaller workspace. This is a deliberate choice of method: the general pseudoinverse correction does not reduce to the fixed Halley or Super-Halley formula, so rectangular steps can jump as alpha approaches .5 or 1, even when both matrices have full rank.

For example, at \(x=0\), take \(F(x)=(1+x,1+x^2/2)\). Then \(J=(1,0)^T\), \(A=(0,1)^T\), and the general formula takes \(\Delta x=-1\). Exactly .5 selects Halley and takes \(-2/5\); exactly 1 selects Super-Halley and takes \(-1/2\). So do not treat alpha as interpolating continuously across these values. At alpha=0 the general formula does agree with Chebyshev, by linearity.

Diagnostics And Storage

The 'correction' linear stage covers the product \(Av\) and its Jacobian solve, for rectangular systems too. linear_rank always describes the latest solve, so a successful correction reports the Jacobian’s rank, which can differ from the secondary rank; a contraction failure before that solve leaves the secondary rank. linear_status is reset at the start of each phase and then keeps the LAPACK status. Callback errors, finiteness checks, the kept accepted state, iteration counts and copied history work as for the other higher-order methods.

The general rectangular path makes three solves with the same plan, scratch and \(n\) pivots. It adds an \(mn\)-double directional matrix to the fixed rectangular Halley workspace, to keep \(A\) while solving with the secondary matrix. With \(w\) the LAPACK scratch and \(d\) the largest numerical derivative scratch, native storage is \(5n+3m+3mn+mn^2+w+d\) doubles and \(n\) C-int pivots, plus the plans’ explicit steps. History has its own checked byte budget, and nothing is allocated per step.

Native Rank-Aware Least Squares

cyroot.native.LeastSquaresPlan solves a dense real linear system with between 1 and 32767 rows and columns. It minimizes ||A*x-b||₂ and returns the minimum-norm solution at the numerical rank chosen by LAPACK. The rectangular solvers use it for their steps; square solvers still use LU and report a singular system as a breakdown.

from cyroot.native import LeastSquaresPlan

plan = LeastSquaresPlan(3, 2, rcond=1e-12)
result = plan.solve(((1., 0.), (0., 1.), (1., 1.)), (1., 2., 4.))
assert result.status == 'ok'
assert result.rank == 2
# solution is approximately (4/3, 7/3); the residual is nonzero.

SciPy’s LAPACK provides DGELSY, which uses pivoted QR followed by a complete orthogonal factorization; it forms neither the normal equations nor a pseudoinverse. rcond must be finite and strictly between zero and one, and defaults to 1e-12. LAPACK chooses the rank from estimated condition numbers of triangular factors, not from a singular-value cutoff, so the rank can differ from that of SVD-based routines. See the Netlib DGELSY reference.

Python Interface And Results

LeastSquaresPlan(rows, columns, *, rcond=1e-12, workspace_bytes=64*1024*1024) is immutable. solve(matrix, rhs) accepts nested numeric sequences or buffers, including strided and unaligned ones, of exactly shape (rows, columns) and (rows,). Text and incompatible buffer formats are rejected. Each call packs the inputs and allocates private output and scratch in Python; only the numerical computation releases the GIL.

LeastSquaresResult contains solution (a copied tuple), rank, linear_status (LAPACK info), and status:

statusMeaning
okFinite factors and solution, with a valid selected rank.
nonfiniteNonfinite input or numerical output.
backend_failureLAPACK failure or invalid returned rank.
invalid_planUninitialized plan or invalid raw pointer arguments.

On numerical failure, rank is None and the solution is all NaN. Invalid shapes and constructor options raise exceptions before any computation. A finite rank-deficient solution can have status == 'ok'. The finiteness check on the factors is conservative: a representable solution can still be rejected if rescaling a factor overflows (for example two rows of 1.3e308 with the same right-hand side). A partial solution is never returned. Neither an ok status nor full rank guarantees accuracy, and the plan reports no residual; root solvers built on it check their own residual and stopping conditions.

Reusable Cython Workspaces

The declaration in cyroot.native.least_squares exposes:

cdef int compute(self, const double* A, const double* b, double* out,
                 double* scratch, int* pivots, int* rank, int* info) noexcept nogil

Construct a plan and allocate native storage once; compute then runs with no Python objects, allocations or workspace queries. The compiled example solves a tall and a wide system, reusing the workspace.

A is column-major with rows*columns doubles; b has rows doubles and out has columns. Allocate work_size scratch doubles and pivot_size (columns) C integers. Each call copies the inputs, which are left unchanged, pads the scratch right-hand side as needed and resets the pivots. All factors and solution entries are checked before the complete result is copied into out, so a failure leaves out unchanged. rank is -1 on failure, and info is zero unless LAPACK reports otherwise. The return code is 0 for ok, 1 for nonfinite, 2 for backend_failure and 3 for invalid_plan.

Every span, including the scalar outputs, must be valid, correctly sized and non-overlapping. Checking for null pointers cannot catch a wrong length, overlap or lifetime; those are the caller’s responsibility. A plan created through __new__ without initialization returns invalid_plan. An initialized plan is immutable and can be shared between concurrent calls, as long as each call has its own output and scratch and the inputs stay alive.

Memory Limits

rows, columns, rcond, lwork, work_size, pivot_size and memory_bytes are read-only properties. Construction validates positive dimensions and native capacities. Each dimension is capped at 32767, well below the C int limit, to leave headroom for LAPACK’s blocked workspace arithmetic. Construction queries the optimal workspace once and checks it against the LAPACK minimum.

The budget covers all the storage the plan manages for a solve: the packed matrix and right-hand side, the solution, a scratch matrix, the padded right-hand side, LAPACK’s work array and the pivots. For m rows and n columns this is (2*m*n + m + n + max(m,n) + lwork)*sizeof(double) + n*sizeof(int). Python result objects and memory used inside LAPACK are not counted. With the raw Cython interface the caller allocates the buffers, and the plan’s budget neither manages their lifetime nor limits concurrent calls.

Damped Newton

Damped Newton computes a Newton direction, then shortens it until the residual objective decreases enough. It can recover from an overly aggressive full step; it does not guarantee convergence from every starting point.

Scalar And Vector Interface

DampedNewton(function, derivative, x0, f_x0=None, df_x0=None, *,
             c1=1e-4, contraction=0.5, max_line_search=32, **options)
VectorDampedNewton(function, jacobian, x0, f_x0=None, jac_x0=None, *,
                   c1=1e-4, contraction=0.5, max_line_search=32, **options)

Both classes are exported from cyroot and cyroot.native. The functions damped_newton(function, derivative, x0, **options) and generalized_damped_newton(function, jacobian, x0, **options) run a solve to completion. Pass None for a native numerical derivative, or any Python or native provider accepted by Newton and Vector Newton.

import math
from cyroot import damped_newton, generalized_damped_newton
from cyroot.native import DampedNewton

f = lambda x: x*x - 2.
solver = DampedNewton(f, lambda x: 2*x, .1, history=32)
first = solver.step()
assert solver.step_scale == .125
assert solver.backtracks == 3
answer = solver.run()
assert answer.success
assert abs(answer.root - math.sqrt(2.)) < 1e-9
assert solver.history[-1].root == answer.root

answer = generalized_damped_newton(
    lambda x: (x[0] - 1., x[1] - 2., x[0] + x[1] - 3.),
    None, (0., 0.),
)
assert answer.success
assert max(abs(a-b) for a, b in zip(answer.root, (1., 2.))) < 1e-9

The vector shape comes from the point and residual, or from an adapter’s declaration. Square systems take an LU step and tall and wide systems a rank-aware least-squares step. A singular square factorization is a breakdown. The reported rank describes the linear step; it says nothing about whether a root exists or is unique.

Armijo Acceptance

For \(\phi(x)=\frac12\|F(x)\|_2^2\), a step \(p\) is accepted when

\[ \phi(x+\alpha p)-\phi(x) \leq c_1\alpha F(x)^\mathsf{T}J(x)p \]

and the objective strictly decreases. The search starts at \(\alpha=1\) and multiplies it by contraction after each rejected candidate. The test uses the actual slope \(F^\mathsf{T}Jp\), which matters for inexact rectangular steps. Scaled accumulation avoids needless intermediate overflow, but cannot fix an ill-conditioned problem or inaccurate derivatives.

c1 and contraction must be finite and strictly between zero and one. max_line_search is the positive maximum number of candidates per iteration. options passes the shared stopping controls and the base solver’s storage and history controls. All controls are keyword-only.

Results And Failures

step(), run(), result, iteration and copied bounded histories work as in the base Newton classes. The solver’s step_scale and backtracks properties describe its latest line search. Histories contain accepted states and terminal diagnostics, not rejected trial points; residual call counts include every evaluated trial.

Nonfinite trial points or residuals are rejected. A Python exception or a nonzero native callback status ends the solve at once, keeping the last accepted point and residual. When a derivative fails after an accepted step, that accepted point is kept. Python exceptions propagate as the original instance; native failures raise NativeCallbackError with their stage and status.

Only residual_tolerance counts as a root. A direction that does not descend, or a search that runs out of candidates, reports line_search_failure; a step that rounds to zero reports stagnation. The base solver’s reasons, such as zero_derivative, breakdown and nonfinite, can also occur. Calling a finished solver does not resume it.

Native Execution

With native residual and derivative callbacks, the numerical loop and the line search run without the GIL; Python callbacks take it for each call. Storage is allocated before stepping, and setup and the copied result and history export run in Python. The base classes’ callback reservation, ownership and concurrency rules apply; see Native Core.

Jacobian Products

A Jacobian need not be stored to apply it to a direction. For a residual \(F:\mathbb{R}^n\to\mathbb{R}^m\), a forward product maps \(v\in\mathbb{R}^n\) to \(J(x)v\in\mathbb{R}^m\). Its transpose product maps \(w\in\mathbb{R}^m\) to \(J(x)^\mathsf{T}w\in\mathbb{R}^n\). Newton–Krylov uses these operations instead of a dense Jacobian. A product that exploits sparsity or structure can avoid both the Jacobian’s storage and much of its computational cost.

Supplied Products

JacobianVectorCallback(function, input_dimension, output_dimension)
JacobianTransposeCallback(function, input_dimension, output_dimension)
callback.evaluate(point, direction, *, workspace_bytes=64*1024*1024)

Both adapters are exported from cyroot and cyroot.native. input_dimension=n and output_dimension=m describe the original residual in both classes, even though the transpose maps a direction of length m to a result of length n. Python callbacks receive copied tuples and may return numeric sequences or arrays; evaluate returns a tuple.

from cyroot import JacobianVectorCallback, JacobianTransposeCallback

# F(x) = (x0*x0 + x1, x0*x1, 2*x0 - x1)
jvp = JacobianVectorCallback(
    lambda x, v: (2*x[0]*v[0] + v[1], x[1]*v[0] + x[0]*v[1],
                  2*v[0] - v[1]), 2, 3,
)
vjp = JacobianTransposeCallback(
    lambda x, w: (2*x[0]*w[0] + x[1]*w[1] + 2*w[2],
                  w[0] + x[0]*w[1] - w[2]), 2, 3,
)
x, v, w = (1., 2.), (3., 4.), (5., 6., 7.)
assert jvp.evaluate(x, v) == (10., 10., 2.)
assert vjp.evaluate(x, w) == (36., 4.)
assert sum(a*b for a, b in zip(jvp.evaluate(x, v), w)) == sum(
    a*b for a, b in zip(v, vjp.evaluate(x, w))
)

Dimensions must be positive and fit native capacities, and inputs must be finite. Real numeric buffers are converted at the boundary; complex and boolean buffers are rejected. The output shape is checked. Called directly, an adapter returns nonfinite callback output as it is, for the caller to interpret; a solver treats it as a failure. Reentrant use of an active adapter is rejected.

Numerical Directional Products

JacobianVectorPlan(n, m, scheme='central', step=None, *,
                   memory_bytes=64*1024*1024)
plan.evaluate(function, x, direction, f_x=None)

The plan is immutable and holds neither a residual callback nor any mutable sampling workspace. evaluate returns an estimate with product, f_calls, status and callback_code, where the status is ok, nonfinite, breakdown or callback_failure. Python callback exceptions propagate; a nonzero native status raises NativeCallbackError with the estimate attached.

from cyroot import JacobianVectorPlan

f = lambda x: (x[0]*x[0] + x[1], x[0]*x[1], 2*x[0] - x[1])
plan = JacobianVectorPlan(2, 3)
estimate = plan.evaluate(f, (1., 2.), (3., 4.), f_x=f((1., 2.)))
assert estimate.status == 'ok'
assert estimate.f_calls == 2
assert max(abs(a-b) for a, b in zip(estimate.product, (10., 10., 2.))) < 1e-7
zero = plan.evaluate(f, (1., 2.), (0., 0.))
assert zero.product == (0., 0., 0.) and zero.f_calls == 0

A forward or backward product needs one shifted residual and a central product two, plus one call for the base residual unless f_x is given. A zero direction needs no samples. step is a positive absolute displacement along \(v/\|v\|_\infty\); automatic steps scale with the point’s magnitude and the binary64 precision. The weights use the actual rounded displacements. If a coordinate of the direction is lost to rounding or the sample geometry collapses, the result is breakdown before any sampling; numerical failures fill the product with NaN.

Scratch takes 2*n+3*m doubles, and a standalone native evaluation 4*n+5*m. workspace_bytes reports the scratch and memory_bytes the standalone allocation budget, neither counting Python objects or storage owned by callbacks.

There is no public numerical transpose plan. In rectangular Newton–Krylov, a numerical JVP plan comes with a matching internal transpose built from the same coordinate columns. Each product then costs O(n) residual samples, unlike a directional JVP, but keeps LSQR’s operator and its transpose consistent; see Newton–Krylov.

Cython And C/C++ Producers

cyroot.native.jvp declares JacobianVectorFunction and make_jacobian_vector_callback. cyroot.native.vjp declares JacobianTransposeFunction and make_jacobian_transpose_callback. Both native function signatures are:

cdef int product(const double* x, const double* direction,
                 size_t n, size_t m, double* out, void* context) noexcept nogil

The forward callback reads x[n] and direction[n] and writes all of out[m]; the transpose callback reads x[n] and direction[m] and writes all of out[n]. The inputs are borrowed, read-only and valid only during the call. Return zero only after writing every output, and a nonzero status on failure. No exception may cross the ABI; acquire the GIL explicitly before touching Python objects.

The C headers jvp_callbacks.h and vjp_callbacks.h define version-1 descriptors, with capsule names cyroot.jacobian_vector_callback.v1 and cyroot.jacobian_transpose_callback.v1; pass them to the matching adapter’s from_capsule(capsule, keepalive=None). The Cython factories take (function, n, m, context, keepalive=None) and keep that owner alive. Raw contexts stay owned by their producer, and separate adapters that share a mutable context need their own synchronization. Outputs are filled with NaN before each call, and a nonzero status makes the whole output NaN. The native ownership rules also apply to direct evaluate_raw callers.

Newton–Krylov

Newton–Krylov computes Newton steps from products with the Jacobian instead of the Jacobian itself. Since no dense matrix is stored, it suits problems with many unknowns and cheap directional products. Square systems use restarted GMRES and tall and wide systems LSQR. Every accepted nonlinear step passes an Armijo line search.

Interface

NewtonKrylov(function, jvp, x0, f_x0=None, *, vjp=None,
             restart=20, max_linear_iter=100, linear_rtol=1e-3,
             c1=1e-4, contraction=0.5, max_line_search=32,
             etol=1e-10, ertol=4*eps, ptol=1e-12, prtol=4*eps,
             max_iter=200, max_evaluations=10000,
             history=0, history_every=1, history_bytes=8*1024*1024,
             workspace_bytes=64*1024*1024)
newton_krylov(function, jvp, x0, f_x0=None, *, vjp=None, **options)

The class, result type, and function are exported from cyroot and cyroot.native. The dispatcher accepts find_vector_root('newton_krylov', function, jvp, x0, **options). Shared tolerances use binary64 eps; see Stopping And Results.

from cyroot import NewtonKrylov, newton_krylov

f = lambda x: (x[0]*x[0] - 2., x[1]*x[1] - 3.)
jvp = lambda x, v: (2*x[0]*v[0], 2*x[1]*v[1])
solver = NewtonKrylov(f, jvp, (.1, .2), history=32)
first = solver.step()
answer = solver.run()
assert answer.success and answer.error < 1e-9
assert solver.linear_solver == 'gmres'
assert solver.history[-1].root == answer.root

# None selects native numerical products.
numerical = newton_krylov(f, None, (1.5, 1.8))
assert numerical.success

jvp is a Python function of (x, v), a JacobianVectorCallback, a JacobianVectorPlan, or None. For a square problem, None selects a forward directional finite difference that reuses the current F(x). The residual is a Python callable, a VectorCallback or a RectangularCallback. The dimensions come from the adapter, from a cached f_x0, or from one Python residual evaluation, which is counted. Vector inputs are copied, and callbacks receive tuples.

Tall And Wide Systems

from cyroot import newton_krylov

f = lambda x: (x[0] - 1., x[1] - 2., x[0] + x[1] - 3.)
jvp = lambda x, v: (v[0], v[1], v[0] + v[1])
vjp = lambda x, w: (w[0] + w[2], w[1] + w[2])
answer = newton_krylov(f, jvp, (0., 0.), vjp=vjp)
assert answer.success
assert max(abs(a-b) for a, b in zip(answer.root, (1., 2.))) < 1e-9

# Underdetermined: a minimum-norm linear step from (0, 0).
wide = newton_krylov(lambda x: (x[0] + x[1] - 3.,), None, (0., 0.))
assert wide.success
assert max(abs(value - 1.5) for value in wide.root) < 1e-9

For an m-by-n rectangular Jacobian, LSQR needs both Jv and J^T w. Supply both products, or pass jvp=None and omit vjp. Without supplied products, each operation recomputes the same finite-difference columns, so the two stay consistent; a JacobianVectorPlan(n, m, ...) sets the scheme and step. Each product then costs n shifted samples for forward or backward differences and 2*n for central ones. No dense Jacobian is stored, but this can be expensive, so large problems should supply products that exploit their structure.

A supplied transpose cannot be combined with a numerical JVP in a rectangular solve. Supplied products must be linear in the direction and describe the same Jacobian and its transpose at the current point; the solver cannot verify this. Numerical products assume the residual is deterministic. A transpose supplied for a square problem is accepted but GMRES does not use it. See Jacobian Products for the adapters and native ABIs.

LSQR solves for a least-squares step without forming J^T J. Because the inner iteration starts from zero, the step has minimum norm in exact arithmetic. That does not make the nonlinear root found the one of minimum norm, and LSQR is no substitute for a dense rank-revealing solve on severely ill-conditioned systems.

Verification And Globalization

The inner system is \((J/s)p=-F/s\), where \(s=\|F\|_\infty\). GMRES uses twice-modified Gram–Schmidt and Givens rotations. LSQR uses Golub–Kahan bidiagonalization. The recurrences’ own estimates decide when convergence is worth checking, and freshly computed operator products decide whether the inner solution is actually acceptable. Every normal exit, including the linear iteration limit and breakdown, recomputes the reported diagnostics. Callback and nonfinite failures can stop earlier, without them.

Let \(A=J/s\), \(b=-F/s\), and \(r=b-Ap\). linear_residual is \(\|r\|_2/\|b\|_2\). For LSQR, linear_stationarity is \(\|A^\mathsf{T}r\|_2/\|A^\mathsf{T}b\|_2\); a zero denominator gives zero only when the normal residual is zero. Either verified quantity meeting linear_rtol is sufficient for an LSQR step. GMRES requires the verified linear residual criterion. linear_stationarity is infinity for GMRES.

An acceptable linear step must still decrease the nonlinear residual. The Armijo search uses the actual slope \(F^\mathsf{T}Jp\), starts with the full step and shrinks it by contraction. Nonfinite trials are rejected, and a callback exception or nonzero status ends the solve at once. Only accepted point/residual pairs replace the current state. There is no preconditioning, adaptive forcing or dense fallback.

Diagnostics And Termination

NewtonKrylovResult is a copied immutable record containing:

FieldsMeaning
root, f_root, error, precision, itersAccepted point/residual, infinity-norm residual and last accepted step, outer iterations.
f_calls(residual samples, Jv applications), including failed attempts and numerical samples.
vjp_callsTranspose applications.
linear_iterationsCumulative completed Arnoldi or LSQR updates.
linear_residual, linear_stationarity, linear_statusLatest verified inner diagnostics.
step_scale, backtracksLatest Armijo scale and rejection count.
callback_code, callback_stage, termination_reasonExplicit failure and stopping information.

linear_status is -1 before a solve, 0 converged, 1 iteration limit, 2 breakdown, 3 nonfinite arithmetic/output, or 4 operator failure. Only termination_reason='residual_tolerance' makes success, converged, and optimal true. LSQR stationarity with a nonzero nonlinear residual never establishes a root. Other reasons are stagnation, max_iterations, max_evaluations, line_search_failure, linear_failure, nonfinite, callback_failure, and derivative_breakdown.

max_linear_iter limits each inner solve. max_evaluations counts the initial residual, finite-difference samples and rejected line-search trials; running out keeps the accepted state and reports no callback error code. Callback stages are function, jacobian_vector_product and jacobian_transpose_product. Python exceptions propagate as the original instance, and nonzero native codes raise NativeCallbackError with a snapshot. Further step() or run() calls on a finished solver return its final state without raising again.

Storage And Native Execution

The solver exposes dimension, output_dimension, linear_solver, restart, and workspace_bytes. GMRES clamps restart to the smaller of the requested value, input dimension, and inner budget; LSQR reports restart=0. Analytic LSQR storage is 7*(n+m) doubles. Its numerical fallback adds 3*n+4*m doubles and m compensated accumulators. GMRES storage is O(n*restart + restart**2); none of these paths stores a dense Jacobian. Native budgets exclude Python objects and callback-owned allocations.

step(), run(), iteration, result and the bounded history share one engine. History stores the initial and accepted states and the terminal diagnostics, not inner Krylov vectors or rejected trial points, and exported tuples are independent copies. Setup, export and Python callbacks hold the GIL; with native callbacks the numerical loop runs without it and allocates no workspace while stepping. An active solver and its explicit adapters are protected against reentry, and independent solvers with independent contexts can run concurrently.

Root Finding Through Optimization

For a real residual function F: R^n -> R^m, define

\[ \phi(x)=\tfrac12\sum_{i=1}^m F_i(x)^2. \]

Every root of F is a global minimum of this nonnegative objective, with value zero, and every point where the objective is zero is a root. A positive local minimum or a small objective gradient is not a root. The construction works for square, overdetermined and underdetermined residuals alike.

Value, Gradient And Exact Hessian

from scipy.optimize import minimize
from cyroot.optimization import LeastSquaresObjective, root_via_optimizer

def F(x):
    return (x[0]**2 + x[1] - 2., x[0]*x[1] - .5)

def J(x):
    return ((2*x[0], 1.), (x[1], x[0]))

def H(x):
    return (((2., 0.), (0., 0.)), ((0., 1.), (1., 0.)))

objective = LeastSquaresObjective(F, 2, jacobian=J, hessian=H)
result = root_via_optimizer(
    objective, minimize, (1., .4),
    optimizer_options={'method': 'BFGS', 'jac': objective.gradient,
                       'options': {'gtol': 1e-12}},
)
assert result.success

LeastSquaresObjective(F, input_dimension, output_dimension=None, *, jacobian=None, hessian=None, workspace_bytes=64*1024*1024) is also available from cyroot.native. Without output_dimension, the residual is square. Python providers receive a copied tuple and return indexable real values of shape (m,), (m,n) and (m,n,n) respectively. Native VectorCallback, RectangularCallback, HessianCallback and RectangularHessianCallback providers of the right kind and dimensions are also accepted, and their context owners are kept alive as long as the adapter.

The methods value(x) (also objective(x)), residual(x), gradient(x) and hessian(x) return a float or copied immutable tuples. They compute

\[ \nabla\phi=J^T F,\qquad \nabla^2\phi=J^TJ+\sum_i F_i\nabla^2F_i. \]

The Hessian includes the residual-Hessian term. A Hessian provider requires a Jacobian provider, and a missing provider raises an error before any sampling. There is no implicit Gauss–Newton approximation or finite-difference fallback; for numerical derivatives, pass derivative callables that compute them. Every call samples afresh: value and residual call F once, gradient calls F and J once each, and hessian calls F, J and H once each. Nothing is cached between optimizer calls, and no optimizer options are forwarded behind your back.

The adapter checks dimensions and storage and allocates its native scratch once; memory_bytes reports that allocation, not counting Python boundary objects or allocations made by providers. Exponent-scaled compensated accumulation avoids needless intermediate overflow and underflow, but gives no extra accuracy under ill-conditioned cancellation. Unrepresentable results or nonfinite inputs raise FloatingPointError, and shape, kind and provider errors raise exceptions too. Python callback exceptions propagate as they are; nonzero native statuses raise NativeCallbackError with the callback stage and code. Partially written callback output is detected.

External Optimizers And Root Status

root_via_optimizer(objective, optimizer, x0, *, etol=1e-10, ertol=4*eps, optimizer_options=None) calls optimizer(objective, copied_x0, **options). The returned object must have an x attribute, which fits scipy.optimize.minimize; wrap other optimizers in a small function. Pass jac=objective.gradient, hess=objective.hessian, the method, bounds and tolerances through the optimizer’s own options. Derivatives you ask the optimizer to use must be backed by providers installed on the objective.

The result contains copied root, f_root, infinity-norm error, root success, and termination_reason, plus optimizer_success, optimizer_status and the original optimizer_result. Original optimizer exceptions propagate. Root success requires

\[ \|F(x)\|_\infty\le \text{etol}+\text{ertol}\,\|F(x_0)\|_\infty. \]

The scale uses the starting point. If the starting point is already a root, the optimizer is not called and the optimizer fields are None. Otherwise the residual at the returned point is evaluated and checked independently. If the optimizer reports success but the root tolerance is not met, the reason is optimizer_stopped_without_root. Conversely, a returned point that meets the root tolerance is a successful root even when the optimizer reports failure, whose status stays visible. An invalid or nonfinite returned point raises the objective’s exception. A result without a root says nothing about other points or whether a root exists at all.

For example, F(x,y)=(x^3-2*x+2,y) has a strict positive local minimum of phi at (sqrt(2/3),0), although a root exists at negative x. Convergence results for convex optimization do not apply, since squared nonlinear residuals are generally not convex. A stationary point is a root if the Jacobian there has full row rank; full column rank in an overdetermined system is not enough.

External Python optimizers run in Python under the GIL. Compiled code can call the objective’s numerical kernel without the GIL when the callbacks are native, but that does not make an external optimizer’s loop GIL-free. An objective and its native adapters are reserved during each operation, including input conversion, error transfer and result export; use separate objectives and adapters for concurrent evaluations.

Higher-Order Objective Derivatives

The product rule gives, for any positive order r,

\[ D^r\phi(x)[v_1,\ldots,v_r]=\frac12 \sum_{S\subseteq\{1,\ldots,r\}} \left\langle D^{|S|}F(x)[v_S], D^{r-|S|}F(x)[v_{S^c}]\right\rangle, \]

where D^0 F=F. Directions in a subset keep their original order. Complementary subsets have equal dot products, so the implementation uses one representative per pair. This includes all mixed terms; applying the scalar formula separately to residual coordinates would omit necessary contractions.

from cyroot.optimization import ObjectiveDerivativePlan

plan = ObjectiveDerivativePlan(1, 1, order=3)
third = plan.evaluate(
    lambda x: (x[0]**3,),
    [lambda x: ((3*x[0]**2,),),
     lambda x: (((6*x[0],),),),
     lambda x: ((((6.,),),),)],
    (2.,),
)
assert third == (((480.,),),)  # third derivative of x**6/2

ObjectiveDerivativePlan(n,m,r, *, max_terms=1_000_000, memory_bytes=64*1024*1024) is immutable. evaluate(F, derivatives, x) requires exactly r Python callables, for DF through D^rF. It calls each one once and packs its output before calling the next, so providers may reuse their own scratch arrays. These calls run in Python, under the GIL.

Alternatively transform([F_x, DF_x, ..., D^rF_x]) accepts already evaluated tensors. Order-k residual derivatives have shape (m,)+(n,)*k; the output has shape (n,)*r. No symmetry is imposed on the supplied tensors. Values are copied and finite-checked; bad shapes/nonfinite final entries raise ValueError, complex values raise TypeError. No numerical differentiation is performed.

The dense transform uses m*n**r*2**(r-1) products, plus subset bookkeeping. max_terms bounds this work before allocation. The byte limit covers retained native metadata, packed tensors and native output/scratch, excluding Python objects and provider allocations. Positive order must fit the native subset bit capacity. These limits make large requests explicit; native code does not remove the exponential cost of high derivative orders.

Compiled Interface

objective.pxd exposes the accumulator, value/gradient/Hessian kernels and LeastSquaresObjective.evaluate_raw. A caller pins the state, enters its reservation while holding the GIL, calls the raw method inside nogil, then leaves with the GIL. Raw orders are -1 residual, 0 value, 1 gradient and 2 exact Hessian. Output spans must be disjoint from the state and input; capacities are checked before sampling. Failure leaves caller output unchanged. Statuses: 0 success, 1 nonfinite, 2 invalid/missing provider, 3 callback failure. Inspect/transfer the original callback error before releasing its guard. See the compiled example.

objective_derivatives.pxd exposes ObjectiveDerivativePlan.compute and the allocation-free transform in objective_derivatives.hpp. Callers own packed D^kF spans, capacities, output and scratch. Derivative tensors are residual-first: D[k][o + m*(j0 + n*(j1 + ...))]; the objective output has its first input index fastest. State is immutable, so native callers can share a plan with disjoint caller-owned buffers. Status 1 denotes nonfinite input/final result; 2 denotes invalid counts/capacities/work bounds. Output is unchanged on failure. This entry point neither allocates nor calls Python and needs no new derivative-callback ABI.

Native Optimizer Families

Each of the four optimization methods has a scalar and a vector function, taking (function, derivative_or_jacobian, x0) positionally; pass None for a native numerical derivative. Vector dimensions are keyword-only. The input length can be inferred, but a rectangular Python residual needs output_dimension, unless you pass a native residual adapter that declares its shape.

from cyroot import (scalar_levenberg_marquardt, scalar_bfgs, scalar_lbfgs,
                    scalar_powell_dogleg, vector_lbfgs)
from cyroot.optimization import OptimizationSolver

for solve in (scalar_levenberg_marquardt, scalar_bfgs,
              scalar_lbfgs, scalar_powell_dogleg):
    answer = solve(lambda x: x*x - 2., lambda x: 2*x, 1.5)
    assert answer.success
    assert abs(answer.root - 2.**.5) < 1e-9

f = lambda x: (x[0]-1., x[1]-2., x[0]+x[1]-3.)
answer = vector_lbfgs(f, None, (0., 0.), input_dimension=2, output_dimension=3)
assert answer.success
solver = OptimizationSolver('lbfgs', lambda x: x*x-2., 1.5,
                            jacobian=lambda x: 2*x, scalar=True, history=32)
first = solver.step()
answer = solver.run()
assert answer.success
assert solver.history[-1].root == answer.root

OptimizationSolver is a resumable front end for these methods. result, history, step() and run() return OptimizationResult, with a scalar root in scalar mode and tuple coordinates in vector mode; its diagnostics keep the full native record. objective and native_state expose the underlying objective and method state. The LevenbergMarquardt, PowellDogleg, BFGS and LBFGS classes take (objective, x0, **options) directly.

MethodStep And AcceptanceDistinct Controls
Levenberg–MarquardtDamped Gauss–Newton with augmented least squares and a reduction ratio.damping=1e-3, max_trials=16, rcond=1e-12.
Powell doglegA scaled trust-region step between the Cauchy and Gauss–Newton directions.initial_radius=1, max_radius=1e6, min_radius=1e-15.
BFGSA dense inverse-Hessian approximation and bounded strong-Wolfe line search.c1=1e-4, c2=0.9, max_line_search=32.
L-BFGSBFGS-style line search with a bounded secant-pair ring.corrections=10, plus BFGS line-search controls.

These methods share the root stopping defaults, max_evaluations=10000 and gtol=1e-12. gtol bounds the stationarity measure \(\|J^\mathsf{T}F\|_\infty/(\|F\|_\infty\max_{ij}|J_{ij}|)\), which does not change when the residual is multiplied by a constant. Stationarity with an unsatisfied residual is an unsuccessful result. Where a scalar derivative vanishes, the solve can instead end with no_acceptable_step, line_search_failure or stagnation.

Only the residual tolerance makes these results successful; a tiny step, a successful linear solve or a stationary point is not enough. BFGS and L-BFGS have no bound constraints. L-BFGS limits its correction storage but still uses a dense residual Jacobian; for a truly matrix-free solve, use Newton–Krylov. Native callbacks remove Python calls from the numerical loop, and Python callbacks work as well.

Native Least-Squares Solver

Levenberg–Marquardt minimizes the residual objective with bounded, damped Gauss–Newton steps, using analytic or native numerical Jacobians, and keeps an inspectable history. It accepts the objective described above and checks root convergence separately from stationarity.

Levenberg–Marquardt Root Finding

LevenbergMarquardt minimizes the residual objective \(\phi(x)=\frac12\|F(x)\|_2^2\). Only meeting the residual tolerance counts as finding a root: a minimum of this objective can have a nonzero residual, as \(F(x)=x^2+1\) does at zero.

from cyroot.optimization import LeastSquaresObjective, LevenbergMarquardt

objective = LeastSquaresObjective(
    lambda x: (10*(x[1]-x[0]**2), 1-x[0]), 2,
    jacobian=lambda x: ((-20*x[0], 10.), (-1., 0.)),
)
solver = LevenbergMarquardt(objective, (-1.2, 1.), history=32)
first = solver.step()
result = solver.run()
assert result.success
assert result.error <= 1e-10
steps = solver.history

levenberg_marquardt(objective, x0, **options) returns the same result without keeping a solver to inspect. Both names are available from cyroot.optimization and cyroot.native. The solver takes a LeastSquaresObjective, which holds the callbacks; a scalar residual is a one-element vector. Square, overdetermined and underdetermined systems share the same interface. Callbacks return a residual vector of length m and, optionally, a Jacobian of shape (m,n). Without a Jacobian, the solver uses native central differences around the accepted residual. Residual Hessians are not used by this first-order model. (scalar_levenberg_marquardt and vector_levenberg_marquardt wrap all this in the usual (function, jacobian, x0) form; see Optimization.)

Algorithm

Let \(s=\|F\|_\infty\) and \(d_j=\max_i|J_{ij}|\), using one for a zero column. Set \(A_{ij}=J_{ij}/d_j\). Each trial solves the augmented least-squares problem

\[ \min_z\left\|\begin{bmatrix} A\\\sqrt{\lambda} I\end{bmatrix}z -\begin{bmatrix}-F/s\\0\end{bmatrix}\right\|_2, \qquad \Delta x_j=s z_j/d_j. \]

SciPy’s DGELSY gives a rank-aware solve without forming \(J^TJ\). Scaling the products and the objective reductions avoids several overflow and underflow cases, but the arithmetic is still binary64, and extreme conditioning or rounding can still prevent progress. Positive damping regularizes the augmented matrix, so the reported rank describes that matrix, not the undamped Jacobian.

A trial is accepted by comparing the actual reduction of the objective with the reduction predicted by the undamped linear model, using the displacement after rounding. It must decrease the objective with a reduction ratio of at least 1e-4. A rejected trial multiplies the damping by ten. An accepted trial multiplies it by .3 when the ratio is above .75 and by two when it is below .25, and otherwise leaves it unchanged. Damping stays within [1e-15,1e15]. Each outer iteration evaluates one Jacobian and tries at most max_trials solves. Rejected trials never replace the accepted state. A nonfinite trial is rejected; a callback exception or native callback error stops the solve at once and keeps the last accepted state.

Options And Diagnostics

Defaults:

LevenbergMarquardt(objective, x0, *,
    etol=1e-10, ertol=4*eps, ptol=1e-12, prtol=4*eps, gtol=1e-12,
    max_iter=200, max_evaluations=10000, max_trials=16,
    damping=1e-3, rcond=1e-12, history=0, history_every=1,
    workspace_bytes=64*1024*1024)

Root convergence means \(\|F\|_\infty\le\mathrm{etol}+ \mathrm{ertol}\|F(x_0)\|_\infty\), with a fixed initial relative scale. ertol must be less than one. An accepted step within the absolute and relative step tolerances stops with stagnation when the root tolerance is not met. gtol bounds the residual-relative stationarity \(\|J^TF\|_\infty/(\|F\|_\infty\max_{ij}|J_{ij}|)\), shared with BFGS and L-BFGS. It is invariant to residual scaling and stays of order one near simple and multiple roots, so it does not stop a solve near a root. A small value returns stationary_nonroot, an unsuccessful root result. A minimum where the whole Jacobian vanishes (for example a scalar \(f'(x)=0\)) keeps this ratio near one; such solves usually end as no_acceptable_step, line_search_failure or stagnation, which are also unsuccessful. The gradient field still reports the scaled model metric \(\|A^T(F/s)\|_\infty\).

result and history are properties returning copied immutable tuple snapshots. step() performs one outer iteration; run() finishes the solve. Both return LevenbergMarquardtResult, with root/residual, error, precision, iteration and callback counts, rejected-trial count, damping, model-gradient norm and statuses. gradient is the metric from the last linear model, which may precede the returned root. damping is the value prepared for the next trial. precision is the last accepted displacement infinity norm, initially infinity.

iters counts outer iterations whose Jacobian was successfully obtained, including a final stationary or unsuccessful iteration. f_calls includes the initial sample, finite-difference samples and evaluated trials. jac_calls counts attempted analytic or numerical Jacobian evaluations. max_evaluations bounds residual calls only; a numerical Jacobian requires room for its complete 2*n sample stencil. A finite residual evaluation budget and finite inner trial count ensure rejection cannot loop indefinitely. As for the root solvers, max_iter=0 or None removes the iteration limit; the positive evaluation budget remains.

termination_reason is None while running, then one of: residual_tolerance, stationary_nonroot, stagnation, max_iterations, max_evaluations, no_acceptable_step, linear_failure, nonfinite, callback_failure, derivative_breakdown. success is true only for residual_tolerance. linear_status is the native linear-plan status (0 success, 1 nonfinite, 2 backend failure, 3 invalid plan); linear_rank is None before a solve. Python callback exceptions retain their identity; native errors raise NativeCallbackError carrying the last accepted result.

history specifies a maximum snapshot count; zero disables recording. The initial point, every history_every outer iteration and termination are eligible for recording. Once full, history keeps its existing entries and sets history_truncated. workspace_bytes covers solver-owned native arrays, LAPACK scratch, pivots and requested history. It excludes the separately reusable objective adapter, Python snapshots and callback allocations. memory_bytes reports this native allocation. The augmented row count m+n is limited to 32767 by the least-squares plan. Nothing is implied about the Jacobian’s rank or the uniqueness of a root for rectangular or rank-deficient systems.

Compiled Use And The GIL

Native callbacks in the objective run without the GIL; Python callbacks take it for each call. Construction, result and history export and the Python side of step() and run() hold the GIL, and their numerical loops release it. No NumPy arrays or operations are used internally.

Compiled consumers can cimport LevenbergMarquardt from cyroot.native.levenberg_marquardt, enter _enter() while holding the GIL, call _step() or _run() in nogil, then transfer callback errors through _raise_callback_error() before _release() in a finally block with the GIL. The initialized state, objective and callback owners must remain alive and reserved through all execution and exports. These trusted methods allocate no native workspace. A state/objective/shared callback adapter cannot be used reentrantly or concurrently; independent states with independent adapters can run in parallel.

Numerical Derivatives

CyRoot provides fixed finite differences, adaptive Richardson refinement, and complex-step derivatives. These are explicit providers: pass one in the ordinary derivative or Jacobian position of a solver. They do not automatically differentiate arbitrary Python code.

Choose A Provider

ProviderDerivativesRequirement
Fixed finite-difference plansScalar runtime order, vector Jacobian/Hessian/higher mixed partialsReal residual samples and an appropriate step/stencil budget.
AdaptiveDerivative, AdaptiveSecondDerivativeScalar first/secondA smooth real function and a converged refinement sequence.
AdaptiveJacobian, AdaptiveHessianSquare/rectangular first/secondSmooth residual components; full mixed Hessian entries are included.
ComplexStepDerivative, ComplexStepJacobianScalar first / vector JacobianA holomorphic complex extension of the real residual.
JacobianVectorPlanDirectional firstA direction, without storing the full Jacobian.

Finite Differences lists all fixed plans and output shapes. Jacobian Products describes directional steps and their different sampling costs.

Adaptive Richardson Refinement

import math
from cyroot import AdaptiveDerivative, AdaptiveSecondDerivative, newton, halley

f = lambda x: x*x - 2.
first = AdaptiveDerivative(f)
second = AdaptiveSecondDerivative(f)
estimate = first.evaluate(1.5)
assert estimate.status == 'ok'
assert abs(estimate.derivative - 3.) < 1e-8
assert estimate.error is not None
assert newton(f, first, 1.5).success
assert halley(f, first, second, 1.5).success

Refinement compares central estimates at progressively smaller steps and uses Richardson extrapolation to reduce truncation error. step, atol, rtol, and max_steps bound the initial scale and refinement. Reported error values are estimates, not rigorous error bounds. Noise, discontinuities, cancellation, or rounding can prevent convergence. .evaluate(...) returns the diagnostic estimate; calling the provider as a derivative raises DifferentiationError when the estimate did not converge. Solvers therefore do not silently consume an unconverged estimate. last_estimate retains copied diagnostics.

from cyroot import AdaptiveJacobian, AdaptiveHessian, generalized_newton

f = lambda x: (x[0]*x[0] + x[1] - 3., 2*x[0] + x[1]*x[1] - 6.)
jacobian = AdaptiveJacobian(f, 2, 2)
hessian = AdaptiveHessian(f, 2, 2)
estimate = hessian.evaluate((1., 2.))
assert estimate.status == 'ok'
assert len(estimate.hessian) == 2
assert abs(estimate.hessian[0][0][0] - 2.) < 1e-6
assert generalized_newton(f, jacobian, (1.4, 1.7)).success

For n inputs and m residuals the Jacobian shape is (m,n) and the Hessian shape is (m,n,n). Hessian refinement includes mixed partials; diagonal entries alone would not supply the tensor expected by higher-order vector methods. Dense storage and sampling can be substantial. Vector providers take a checked memory_bytes budget; Python callback allocations are additional.

Complex-Step

import cmath
import math
from cyroot import ComplexStepDerivative, ComplexStepJacobian

derivative = ComplexStepDerivative(cmath.exp)
estimate = derivative.evaluate(.4)
assert estimate.status == 'ok'
assert abs(estimate.derivative - math.exp(.4)) < 1e-12
assert estimate.error is None

jacobian = ComplexStepJacobian(lambda x: (x[0]*x[0] + x[1],), 2, 1)
estimate = jacobian.evaluate((2., 3.))
assert estimate.status == 'ok'
assert max(abs(a-b) for a, b in zip(estimate.jacobian[0], (4., 1.))) < 1e-12

For an analytic real-valued function extended to complex arguments, \(f'(x)\approx\operatorname{Im}f(x+ih)/h\). This avoids subtracting nearby real values, but only when the function preserves the necessary complex information. abs, real-part extraction, comparisons, conjugation, and nonanalytic branches can invalidate it. Use cmath or complex-compatible operations. No error estimate is supplied, and a finite answer alone does not validate the holomorphic-extension assumption.

Native Callbacks

These providers accept their matching native residual adapters as well as ordinary Python functions. Numerical kernels run without the GIL when the residual callbacks are native; Python callbacks acquire it for every sample. Construction, input packing, and result export are Python boundaries. Sharing an immutable plan does not make an active callback adapter reentrant; keep independent mutable states and contexts for concurrent solves.

Finite Differences

Numerical derivatives are native plans. A plan fixes the shape, scheme and step once; evaluate(function, x, f_x=None) samples an ordinary Python callable or a native callback adapter and returns a copied estimate with its status and residual-call count. Solvers accept the same plans as derivative providers, and use them automatically when a derivative argument is None.

from cyroot.native import (ScalarFiniteDifferencePlan, RectangularJacobianPlan,
                           RectangularHessianPlan, TensorDifferencePlan)

first = ScalarFiniteDifferencePlan(1, 'central', .01).evaluate(lambda x: x*x, 2.)
assert abs(first.derivative - 4.) < 1e-9
jacobian = RectangularJacobianPlan(2, 1, 'central', .01).evaluate(
    lambda x: (x[0]*x[1],), (2., 3.))
assert max(abs(a-b) for a, b in zip(jacobian.jacobian[0], (3., 2.))) < 1e-9
hessian = RectangularHessianPlan(2, 1).evaluate(lambda x: (x[0]*x[0]*x[1],), (2., 3.))
third = TensorDifferencePlan(2, 1, 3).evaluate(lambda x: (x[0]*x[0]*x[1],), (2., 3.))
DerivativePlanResult shape
scalar, any orderScalarFiniteDifferencePlan(order, scheme, step)float
square JacobianJacobianPlan(n, scheme, step)(n, n)
rectangular JacobianRectangularJacobianPlan(n, m, scheme, step)(m, n)
square HessianHessianPlan(n, scheme, step)(n, n, n)
rectangular HessianRectangularHessianPlan(n, m, scheme, step)(m, n, n)
order three and aboveTensorDifferencePlan(n, m, order, ...)(m,) + (n,) * order
Jacobian-vector productJacobianVectorPlan(n, m, scheme, step)(m,)

The first tensor axis is the output component. Schemes are 'forward', 'backward' and 'central'. step=None chooses an automatic step relative to the point; an explicit step must be finite and nonzero, and strictly positive for JacobianVectorPlan, which normalizes its direction. Weights use the actual rounded sample points, so a step that collapses in floating point reports a breakdown rather than a silently wrong estimate. Plans check their scratch storage and stencil size before allocating.

For a derivative with an error estimate, use the adaptive Richardson providers AdaptiveDerivative, AdaptiveSecondDerivative, AdaptiveJacobian and AdaptiveHessian, or the complex-step ComplexStepDerivative and ComplexStepJacobian when the residual has a holomorphic complex extension.

Migrating From 1.x

The 1.x finite_difference, FiniteDifference, generalized_finite_difference and GeneralizedFiniteDifference wrappers, their DerivativeApproximation base classes, and the cyroot.fptr callback layer were removed in 2.0. Use the plan for the derivative’s order and shape from the table above. The removed kind=1/-1/0 selectors correspond to 'forward', 'backward' and 'central'.

Native Scalar Finite Differences

cyroot.native.ScalarDerivativePlan computes forward, backward or central first derivatives for native Newton. Pass a plan as the derivative argument, or None for a default central plan:

from cyroot.native import Newton, ScalarDerivativePlan

solver = Newton(lambda x: x*x - 2., ScalarDerivativePlan(), 1.5, history=16)
result = solver.run()
assert result.success
assert solver.history[-1].root == result.root

The residual can be a Python callable or a compiled ScalarCallback. With a compiled residual, sampling and the derivative arithmetic run outside the GIL; a Python residual takes it for each call and output conversion.

ScalarDerivativePlan(scheme='central', step=None) holds only immutable configuration, with the read-only properties scheme, step and sample_count. It owns no callback or sampling workspace, so independent solves can share it concurrently. The computation uses stack variables, so the solver needs no extra heap memory for finite differences. This plan has no standalone Python evaluator; use ScalarFiniteDifferencePlan for that.

Steps And Arithmetic

Schemes are the strings 'forward', 'backward' and 'central'; integer codes are rejected. An explicit step is a finite, nonzero absolute displacement; a negative step reverses the sampling direction. Text and sequences are rejected.

With step=None, the displacement is recomputed at each accepted point as \(h=\eta\max(1,|x|)\), where \(\eta=2^{-26}\) for one-sided schemes and \(\eta=\sqrt[3]{\epsilon}\) for central differences, with binary64 machine epsilon \(\epsilon\). These choices do not guarantee accuracy for noisy, nonsmooth or poorly scaled residuals.

The current residual is reused as the base value. Forward and backward schemes take one sample per derivative and use a first-order secant. The central scheme takes two samples and combines the secants through the base point with the actual rounded offsets, using the same weighted formula as native Jacobians. For smooth functions this gives a second-order truncation error, even when rounding makes the two offsets unequal.

All required points and displacements are checked before sampling. A step that collapses reports an unsuccessful breakdown; nonfinite points, samples or arithmetic report nonfinite. The stencil is never repaired, and steps or schemes are never changed on the fly. Overflow in the subtraction or division is a numerical failure, even where another arrangement might stay finite.

Counts And Failures

Newton’s f_calls is (residual_attempts, derivative_attempts). The residual count includes every base, trial and stencil call, failed ones too, and sampling adds no iterations. f_x0 supplies a cached base value, and df_x0 skips the initial approximation. No derivative is approximated when the starting point is a root, or after a step that ends the solve.

When an approximation fails, the accepted point and residual stand and df_root is NaN. Python exceptions propagate as the original instance with the callback’s traceback. Native failures raise NativeCallbackError with the exact code and callback_stage='derivative', and the solver exposes the same stage and code. The residual adapter stays reserved through sampling and exception transfer; sharing an immutable plan does not allow concurrent use of an active adapter.

The installed scalar_derivatives.pxd exposes the low-level compute, which takes a native scalar callback, an output pointer, a residual-call counter and a separate callback status; its pointer and no-throw requirements are documented there. The output is NaN on failure, and successful callbacks must write their output. See the compiled example.

This plan also supplies the first derivative of the Halley-family methods, whose second derivative takes a separate ScalarSecondDerivativePlan; the two plans sample independently. Runtime-order scalar plans have their own evaluator and native interface.

Native Scalar Second Derivatives

cyroot.native.ScalarSecondDerivativePlan(scheme='central', step=None) approximates a scalar residual’s second derivative for native Halley-family methods. Its immutable properties are scheme, step and sample_count. Pass it as the second derivative argument; pass None for the default central plan:

from cyroot.native import Halley, ScalarSecondDerivativePlan

solver = Halley(lambda x: x*x - 2., lambda x: 2*x,
                ScalarSecondDerivativePlan(), 1.5, history=16)
assert solver.run().success

# Both derivatives can be approximated using the same residual:
assert Halley(lambda x: x*x - 2., None, None, 1.5).run().success

The plan holds no callback, sample cache or mutable workspace. It computes with stack variables, so independent solves can share it concurrently. With a compiled residual, all sampling and arithmetic run without the GIL; Python callbacks take it. The plan always differentiates the residual twice, even when an analytic first derivative is supplied.

Stencil And Accuracy

All schemes use the cached residual at the current point and two additional samples, so sample_count is always two. Central samples at x+h, then x-h; forward at x+h, then x+2h; backward at x-h, then x-2h. An explicit step is a finite, nonzero absolute displacement; a negative step reverses the direction. Text and sequences are rejected.

Automatic steps are recomputed at each accepted point as \(h=\eta\max(1,|x|)\). Central uses \(\eta=\epsilon^{1/4}=2^{-13}\); one-sided schemes use \(\eta=\sqrt[3]{\epsilon}\), for binary64 machine epsilon \(\epsilon\). These choices balance truncation and rounding error for smooth functions and do not adapt to noisy, nonsmooth or badly scaled ones.

With actual rounded displacements \(a\) and \(b\), the plan computes the second derivative of the quadratic interpolating the three sampled points:

\[ f''(x)\approx\frac{2}{a-b} \left(\frac{f(x+a)-f(x)}{a}-\frac{f(x+b)-f(x)}{b}\right). \]

The formula stays exact for quadratics when rounding makes the spacings unequal. The central truncation error is second order for symmetric spacing, and the one-sided error first order. Smaller steps eventually amplify cancellation and rounding, and with these approximations neither exact derivatives nor cubic solver convergence are guaranteed.

Every coordinate, displacement and separation is checked before sampling. Collapsed or duplicate nodes report an unsuccessful breakdown, and nonfinite coordinates, samples or intermediate arithmetic report nonfinite. Steps and schemes are never changed on the fly. To keep accuracy under cancellation, the secants are normally subtracted before dividing; if that subtraction overflows, each secant is divided by the separation first. Any other unrepresentable intermediate is a failure, even if another arrangement might succeed.

Counts And Failures

Each plan evaluation adds one second-derivative attempt and up to two residual attempts to the solver’s (residual, first_derivative, second_derivative) counts, failed attempts included. d2f_x0 skips the initial evaluation, and f_x0 supplies the base residual. The first- and second-derivative plans sample independently and share no samples. Stencils add no iterations. No derivative work is done when the starting point is a root or after a step that ends the solve.

When the second derivative fails, the accepted point, residual and first derivative stand and the second derivative is NaN; when the first derivative fails, both are cleared. Errors in residual samples keep the exact native status or the original Python exception, with callback_stage='second_derivative' for this plan. The residual adapter stays reserved through sampling, export and error transfer. The plan can be shared, but an active adapter cannot be used concurrently.

The installed cyroot/native/scalar_derivatives.pxd exposes the low-level ScalarSecondDerivativePlan.compute(...) noexcept nogil, with the same pointer, callback and counter rules as the first-derivative plan. Callers pass a finite base residual and an initialized plan. The output is NaN on failure, and successful callbacks must write their output. The plan has no standalone Python evaluator. See the compiled example.

Runtime-order scalar derivative plans are separate, and Householder accepts them. Vector Hessian plans provide square and rectangular residual Hessians for the higher-order vector solvers. Samples within one evaluation are taken one after another.

Native Runtime-Order Scalar Derivatives

cyroot.native.ScalarFiniteDifferencePlan estimates a scalar derivative of any order chosen at run time, without symbolic algebra, NumPy or a table of formulas. It accepts Python residuals and compiled ScalarCallback adapters:

import math
from cyroot.native import ScalarFiniteDifferencePlan

plan = ScalarFiniteDifferencePlan(3)
estimate = plan.evaluate(math.exp, .4)
assert estimate.status == 'ok'
assert abs(estimate.derivative - math.exp(.4)) < 1e-4

# High orders work too; there is no table of formulas to run out of.
estimate = ScalarFiniteDifferencePlan(12, step=1.).evaluate(lambda x: x**12, 0.)
assert math.isclose(estimate.derivative, math.factorial(12), rel_tol=1e-10)

The immutable constructor is ScalarFiniteDifferencePlan(order, scheme='central', step=None, *, max_nodes=65, workspace_bytes=8*1024*1024). The order must be a positive integer. max_nodes and workspace_bytes are resource limits, and exceeding them raises an error during setup; any order within them works. A larger budget allows larger stencils but does not make them accurate. Text, sequences, booleans and complex steps are rejected; an explicit step must be a finite, nonzero real number, and a negative step reverses the sampling direction.

The properties order, scheme, step, stencil_size, sample_count, workspace_size and workspace_bytes are read-only; the last two give the scratch actually required, in doubles and in bytes, not the configured limit. Plans store no callback, mutable scratch or samples, so they can be shared concurrently by independent callbacks with their own workspaces.

Rounded Stencils And Accuracy

For order \(m\), forward/backward stencils include the base and \(m\) other points at signed integer multiples of the step. Central stencils include the base and pairs at \(\pm h,\ldots,\pm rh\), with \(r=\lceil m/2\rceil\). Samples visit the base first if needed, then forward/backward multiples, or central pairs in the order +h, -h, +2h, -2h, ....

The engine computes Fornberg interpolation weights from the actual rounded displacements, normalized by the largest one. All points, their distinctness and the weights are validated before any stencil callback. Collapsed or duplicate nodes report breakdown, and nonfinite coordinates, weights, samples or arithmetic report nonfinite; stencils are never repaired, retried or swapped. The base residual is subtracted before a compensated weighted sum, and the result is divided by the displacement scale repeatedly instead of forming h**order.

One-sided truncation error is first order. Central truncation error is second order for symmetric spacing, but for even orders rounding asymmetry can undo the cancellation that symmetry provides. Odd central orders use an extra node and keep second-order truncation error for moderately unequal spacing.

Automatic steps use \(h=\max(1,|x|)\epsilon^{1/(m+p)}\), with \(p=2\) for central and \(p=1\) for one-sided stencils. This is a rule of thumb that ignores constants depending on the function and the stencil, while high derivatives amplify cancellation, noise and residual offsets. An ok status means the computation finished with finite values, not that any accuracy was reached: high-order tests on polynomials can pass while a smooth non-polynomial function of the same order is inaccurate. Check estimates by varying the step.

Estimates, Counters And Native Callers

evaluate(function, x, f_x=None) returns immutable ScalarDerivativeEstimate(derivative, f_calls, status, callback_code). Status is 'ok', 'nonfinite' or 'breakdown' for returned estimates. f_calls counts every residual attempt, failures included, and includes the base unless f_x is supplied; sample_count excludes the base.

Python callback exceptions propagate as the original instance with its traceback. Nonzero native codes raise NativeCallbackError with the failed estimate, whose status is 'callback_failure', the exact code and the stage: 'function' for the base, 'derivative' for a stencil sample. Each output is set to NaN before the call, and a successful callback must write it. Numerical failures leave the derivative NaN.

The callback adapter stays reserved through conversion, allocation, sampling, result construction and exception transfer. Independent callbacks can share one plan, but an active adapter cannot be used concurrently or reentrantly. evaluate allocates private scratch before sampling.

The installed higher_derivatives.pxd exposes compute(...) noexcept nogil, which works in caller-owned scratch. Native callers pass the finite base residual, valid non-overlapping spans and the scratch capacity in doubles; too little capacity fails before anything is written, and the scratch contents are unspecified afterwards. The engine needs \(n(m+3)\) doubles, the Fornberg arithmetic costs \(O(n^2m)\), and it never allocates, calls Python or takes the GIL, so a native residual gives a fully native path. The Householder solver accepts these plans for any derivative order; Newton and the Halley family use the dedicated first- and second-derivative plans. See the compiled example.

Householder Without Symbolic Formulas

For derivatives through order \(d\), write \(a_k=f^{(k)}(x)/k!\). Reciprocal Taylor coefficients satisfy

\[ b_0=\frac1{a_0},\qquad b_n=-\frac1{a_0}\sum_{k=1}^n a_kb_{n-k}. \]

The Householder increment is

\[ \Delta x=d\frac{(1/f)^{(d-1)}}{(1/f)^{(d)}} =\frac{b_{d-1}}{b_d}. \]

The factorials cancel, so the recurrence works for any order chosen at run time, with no symbolic formulas. The installed householder.pxd exposes the allocation-free C++17 householder_step kernel, which takes the raw derivatives f, f', ..., f^(d) and 2*(d+1) caller-owned ScaledCoefficient scratch entries. Each coefficient carries a binary64 mantissa and a checked 64-bit base-two exponent, which avoids overflow in the factorials and in the reciprocal near a pole; only the final increment is converted to binary64. The recurrence costs \(O(d^2)\) arithmetic and \(O(d)\) workspace.

The status is zero for success, one for nonfinite input or arithmetic, and two for an invalid size or a zero reciprocal denominator. A residual that is already zero gives a zero increment without looking at the derivatives. The kernel does not need a nonzero first derivative. Scaled arithmetic extends the range, not the precision: cancellation, inaccurate derivatives and derivatives that already overflowed still limit the result. A final step can underflow to zero; the solver then decides between residual success and stagnation.

The resumable Householder solver combines this kernel with callback providers, caches, stopping rules, history and numerical derivatives, and cyroot.householder runs that solver. Python setup and result export still need the GIL even when the kernel and the callbacks do not.

Native Finite-Difference Jacobians

cyroot.native.JacobianPlan supplies numerical Jacobians to the square vector solvers. It evaluates the residual callback at perturbed points, using reusable native scratch storage. With a compiled residual, stencil generation, sampling, differencing and the Newton loop all run without the GIL; Python residuals go through the usual Python bridge.

from cyroot.native import JacobianPlan, VectorNewton

def residual(x):
    return (x[0]**2 + x[1] - 3., 2*x[0] + x[1]**2 - 6.)

plan = JacobianPlan(2, scheme='central')
solver = VectorNewton(residual, plan, (1.4, 1.7), history=16)
initial_jacobian = solver.result.df_root
result = solver.run()
assert result.success
assert abs(result.root[0] - 1.) < 1e-8
assert abs(result.root[1] - 2.) < 1e-8

VectorNewton(function, None, x0) creates a default central plan, and an analytic Jacobian callback takes the analytic path instead. A plan is immutable configuration: the dimension, the scheme and, optionally, copied steps. It holds no callback or mutable sampling workspace, so independent solvers can share it, also concurrently with separate callback adapters and contexts. The square plan only serves solvers; the rectangular plan below can also be evaluated directly from Python.

Schemes And Steps

JacobianPlan(dimension, scheme='central', step=None, workspace_bytes=64*1024*1024) accepts the scheme strings 'forward', 'backward' and 'central'; integer scheme codes are not accepted. The dimension must be a positive C int matching the square residual and solver.

An explicit step is a finite, nonzero number, used for every axis, or a vector of such numbers, one per axis. Step vectors can be sized sequences or buffers, including read-only, negative-stride, zero-stride and unaligned ones; the plan copies their values, so later changes to the input do not affect it. Steps are absolute displacements, not scaled further, and a negative step reverses the sampling direction.

With step=None, the requested displacement at each new point is

\[ h_j = \eta\max(1, |x_j|),\qquad \eta = \begin{cases} 2^{-26}, & \text{forward/backward},\\ \sqrt[3]{\epsilon}, & \text{central}, \end{cases} \]

where \(\epsilon\) is the binary64 machine epsilon. These steps scale with the point but do not adapt to the function; poor scaling, nonsmooth functions, noise or cancellation may call for explicit steps or an analytic Jacobian.

Forward and backward schemes take one residual sample per axis plus the cached base residual, with first-order truncation error for smooth functions. The central scheme takes two samples per axis plus the base, with second-order truncation error. The engine divides by the actual representable displacements. For central differences, the rounded offsets \(a=x_j^+-x_j\) and \(b=x_j^--x_j\) can differ in magnitude, so it uses weighted secants

\[ \frac{b}{b-a}\frac{F(x^+)-F(x)}{a} +\frac{a}{a-b}\frac{F(x^-)-F(x)}{b}. \]

The weights are computed from scaled offsets so that their difference cannot overflow. The formula stays exact for quadratics when rounding makes the stencil asymmetric.

Counts, Caches And Failures

f_calls is (residual_calls, jacobian_attempts). Residual calls include base and trial evaluations and every stencil sample, failed ones too; each numerical Jacobian adds one Jacobian attempt, and sampling adds no iterations. A forward or backward Jacobian costs n residual samples and a central one 2*n, reusing the current residual as the base.

f_x0 can supply the initial base residual, and jac_x0 skips the initial approximation. Nothing is sampled when the starting point is a root, or when a new point ends the solve. As for any Newton result or history, a Jacobian that was not evaluated contains NaNs.

All axes are validated before sampling. A step that rounds back to the original coordinate gives an unsuccessful breakdown with no sample calls, and nonfinite points, displacements, samples or arithmetic give nonfinite. Steps are never nudged, swapped for a one-sided scheme, retried or regularized. Overflow in a subtraction or division is a numerical failure, even if another arrangement might stay finite.

A failed sample keeps the accepted point and residual and clears the whole Jacobian, including columns already computed. Python exceptions propagate as the original instance with the callback’s traceback. Nonzero native codes raise NativeCallbackError with the original code and callback_stage='jacobian', which the solver also exposes, showing that the residual failed while building the Jacobian. Failed samples are counted, and adapters stay reserved through exception transfer. Native callbacks follow the same no-throw, borrowed-input and context-lifetime rules as analytic vector callbacks.

Storage And Limits

The plan’s properties are dimension, scheme, step (None or a copied tuple), storage_bytes and workspace_bytes. Automatic plans store no steps, and explicit plans store 8*n bytes of them; the constructor’s workspace_bytes argument limits that storage, while the property of the same name reports the separate scratch requirement of 5*n*8 bytes.

A Newton solve with a plan adds five vectors, for the perturbations, two samples and the prevalidated stencil coordinates. Its workspace budget is 8*(10*n + 2*n*n) + sizeof(int)*n + plan.storage_bytes, counting the plan’s storage even when the plan is shared, and history has its own byte budget. These limits cover CyRoot’s storage; LAPACK manages its own memory. Dimensions and their products are checked before any narrowing conversion or allocation.

derivatives.pxd exposes the low-level JacobianPlan.compute for compiled code. It takes non-overlapping caller-owned buffers, returns a DiffStatus, writes a column-major Jacobian, updates a residual-call counter and reports the native callback status separately. Its pointer, span and no-throw requirements are documented in the declaration. It allocates nothing and does no Python work. See the compiled example.

This square plan shares its stencil with the rectangular plan below. Traub–Steffensen reuses the forward stencil, with the residual components as steps. Hessian plans provide second derivatives, and higher mixed partials and adaptive error estimates are also available. Samples within one evaluation are taken one after another.

Rectangular Jacobians

A residual with n inputs and m outputs has a Jacobian of shape (m, n). RectangularJacobianPlan(n, m, scheme='central', step=None, *, memory_bytes=64*1024*1024) uses the same stencils and rounding rules. Its evaluate(function, x, f_x=None) method accepts a plain Python function, or a matching residual RectangularCallback, compiled or not. The explicit dimensions let native callers allocate buffers of the right size. Without an explicit plan, Vector Newton infers the dimensions from the starting point and residual.

from cyroot.native import RectangularJacobianPlan

def rectangular_residual(x):
    return (x[0]**2, x[1]**2, x[0]+x[1])

plan = RectangularJacobianPlan(2, 3, step=1e-3)
estimate = plan.evaluate(rectangular_residual, (1., 2.))
assert estimate.status == 'ok'
assert len(estimate.jacobian) == 3
assert all(len(row) == 2 for row in estimate.jacobian)

JacobianEstimate contains copied jacobian rows, integer f_calls, status (ok, nonfinite, breakdown or callback_failure) and callback_code. Forward and backward schemes take n samples and the central scheme 2*n, plus one call for the base unless f_x is given. A failed sample clears the whole Jacobian. Python exceptions propagate as the original instance; a nonzero native status raises NativeCallbackError with the estimate and the stage function or jacobian. The adapter stays reserved through conversion, sampling and exception transfer.

The read-only properties are input_dimension, output_dimension, scheme, step, storage_bytes, workspace_bytes and memory_bytes. The scratch takes 3*n+2*m doubles. The memory budget covers the copied input and base, the output, the scratch and the stored steps: (4*n+3*m+n*m+step_count)*sizeof(double), where step_count is zero for automatic steps and n otherwise. Python objects and allocations made by callbacks are not counted.

The compiled compute interface in derivatives.pxd takes non-overlapping, caller-owned x[n], base [m], output [m*n] and scratch [3*n+2*m] buffers, the rectangular native function and context, and the counters. The output is column-major, at row + column*m. A call allocates nothing and does no Python work, except that Python callbacks enter their own bridge. The caller reserves the callback and keeps the pointers valid. VectorNewton and generalized_newton accept this plan, and with J=None they infer the dimensions and create a central plan, so Python callers need no explicit dimensions. Least-squares stationarity alone never counts as root convergence.

Native Vector Hessians

cyroot.native.HessianPlan estimates the Hessian of a square residual \(F:\mathbb R^n\to\mathbb R^n\) using Python or compiled residual callbacks. For different input/output lengths, use RectangularHessianPlan, which shares its stencil. The numerical path uses native storage and arithmetic, with no NumPy operations, Python objects or allocations between samples. Python setup, callback bridges and result export hold the GIL.

from cyroot.native import HessianPlan

plan = HessianPlan(2, step=.125)
estimate = plan.evaluate(lambda x: (x[0]**2 + 3*x[0]*x[1],
                                    2*x[1]**2 - x[0]*x[1]), (1., 2.))
assert estimate.status == 'ok'
assert estimate.hessian[0] == ((2., 3.), (3., 0.))
assert estimate.hessian[1] == ((0., -1.), (-1., 4.))
assert estimate.f_calls == 9

Configuration And Memory

The immutable constructor is HessianPlan(dimension, scheme='central', step=None, *, memory_bytes=64*1024*1024). The dimension is a positive integer that fits the native vector callback ABI. Schemes are 'forward', 'backward' and 'central'. An explicit step is a finite, nonzero real number or a vector with one such value per axis, and different signs and sizes per axis are allowed. Steps are copied, also from read-only, negative-stride, zero-stride or unaligned buffers. Text, boolean, complex, nonfinite and malformed steps are rejected.

step=None chooses \(h_j=\max(1,|x_j|)\epsilon^{1/4}\) centrally, or \(h_j=\max(1,|x_j|)\epsilon^{1/3}\) one-sided, with binary64 machine epsilon. These are rules of thumb that ignore constants depending on the function. An explicit scalar applies to every axis, and a negative step reverses the sampling direction.

Properties dimension, scheme, step, shape, sample_count, storage_bytes, workspace_size, workspace_bytes, output_bytes, evaluation_bytes and memory_bytes are read-only. sample_count excludes the base residual, workspace_size is in doubles and the other sizes are in bytes. memory_bytes reports the native storage actually required, not the configured limit.

For dimension \(n\), the output has \(n^3\) doubles and the numerical scratch \(2n^2+10n\). An evaluation also copies the point and the base residual, another \(2n\) doubles. Explicit steps add \(n\) persistent doubles; automatic plans store none. Construction checks the total, including the storage one evaluation will need, against memory_bytes before allocating, and products and native capacities are checked however large the budget. Python owners, nested-tuple exports and allocator overhead come on top, and concurrent evaluations each allocate their own evaluation storage.

Rounded Stencils

The plan uses the actual floating-point shifted coordinates and displacements. Central samples along an axis are requested at \(x_j+h_j,x_j-h_j\), forward samples at \(x_j+h_j,x_j+2h_j\) and backward samples at \(x_j-h_j,x_j-2h_j\). Every coordinate, displacement, distinctness condition and interpolation coefficient is validated before any stencil callback, although the base residual may be evaluated before that check.

For actual displacements \(a,b\), the diagonal uses the three-point interpolant

\[ D_{jj}F=\frac{2}{a-b} \left(\frac{F(x+ae_j)-F(x)}a-\frac{F(x+be_j)-F(x)}b\right). \]

Central mixed partials use tensor products of the three-point first-derivative weights. Define \(\alpha_j(a)=b/(b-a)\) and \(\alpha_j(b)=a/(a-b)\). For axes \(j,k\), the plan sums four terms

\[ D_{jk}F=\sum_{p,q}\alpha_j(p)\alpha_k(q) \frac{[F(x+pe_j+qe_k)-F(x+pe_j)]-[F(x+qe_k)-F(x)]}{pq}. \]

The weights use the normalized actual displacements. Corner weights shared by several terms are applied after a compensated sum, so small contributions are not lost. The final scaling combines binary exponents before converting to binary64, which avoids premature overflow or underflow when axis scales are extreme. (The usual symmetric four-corner formula is biased when rounding makes opposite offsets unequal.) One-sided mixed partials use a single rectangle of first offsets. Compensated summation reduces accumulation error but does not remove cancellation or noise.

One-sided approximations are first order. Central mixed partials are second order even for moderately unequal spacing, but the central diagonal needs symmetric spacing to be second order, so severe rounding asymmetry can cost accuracy. An ok estimate means the computation finished, not that the derivative is accurate; check it by varying the step. Nonfinite intermediate arithmetic is a failure, even when another ordering could give a finite value.

Counts, Results And Failures

evaluate(function, x, f_x=None) accepts a Python function or a residual VectorCallback of matching dimension; Jacobian and uninitialized adapters are rejected. The point and the optional cached f_x, which must belong to the same point and function, are copied while the callback is reserved.

Samples along each axis are taken first (the first offset, then the second) and reused; then come the unordered pairs of axes. Central pairs visit the corners (+,+), (+,-), (-,+), (-,-), where the signs refer to the requested steps, explicit signs included. A supplied base costs nothing. Otherwise central sampling costs \(2n^2\) residual attempts and one-sided sampling \(n(n+3)/2\), every attempt counting, failed ones included.

The immutable result is HessianEstimate(hessian, f_calls, status, callback_code). Its nested-tuple shape is (residual, input, input). Only the two input axes are symmetric: the plan computes one triangle and copies it to the other exactly. Returned estimates have status 'ok', 'nonfinite' or 'breakdown'. Duplicate or collapsed nodes report breakdown, and nonfinite coordinates, coefficients, samples or arithmetic report nonfinite. A failure fills the whole Hessian with NaN, including entries finished before it. Every callback output is set to NaN beforehand, so values a callback did not write can never become derivatives.

Python callback exceptions propagate as the original instance with its traceback. A nonzero native code raises NativeCallbackError with the exact native_status, the failed estimate as result (with status 'callback_failure'), and the stage 'function' for the base or 'hessian' for a stencil sample. The reservation covers conversion, allocation, execution, result construction and exception transfer. An active adapter cannot be used concurrently or reentrantly, but the plan itself can serve independent callbacks concurrently or in nested evaluations, each with its own scratch and with native contexts synchronized where needed.

Native Consumers And Scope

The installed hessians.pxd exposes HessianConfig, a function to copy it, compute_hessian(...) noexcept nogil and the plan’s compute. The native output offset is residual + n*(input_j + n*input_k), extending the column-major Jacobian layout. Callers pass valid, non-overlapping input, base, output and scratch spans with their capacities, keep the configuration’s borrowed steps alive, and follow the residual callback ABI. An invalid configuration or too little output or scratch capacity returns breakdown before anything is written or called. Once the capacities pass, any failure fills the output with NaN and restores the scratch trial point to the original point. Nothing is allocated, and neither Python nor the GIL is involved, during the numerical work.

The compiled example uses the installed declarations and native callbacks without NumPy C headers. This square plan works with vector Chebyshev and the Halley family; rectangular Hessians and higher mixed partials cover different input and output dimensions and higher orders. Samples within one evaluation are taken one after another. See Finite Differences for every derivative plan.

Native Rectangular Numerical Hessians

RectangularHessianPlan estimates second derivatives of \(F:\mathbb R^n\to\mathbb R^m\), including \(m<n\), \(m>n\) and \(m=n\). The output shape is \((m,n,n)\): residual component first, then the two input axes, and only the input axes are symmetric. It uses the same stencil as the square HessianPlan.

from cyroot.native import RectangularHessianPlan

def residual(x):
    return (x[0]**2 + 3*x[0]*x[1],
            2*x[1]**2 - x[0]*x[1],
            4*x[0]**2 + x[1]**2)

plan = RectangularHessianPlan(2, 3, step=(.125, -.25))
estimate = plan.evaluate(residual, (1., 2.))
assert estimate.status == 'ok'
assert plan.shape == (3, 2, 2)
assert estimate.hessian == (((2., 3.), (3., 0.)),
                            ((0., -1.), (-1., 4.)),
                            ((8., 0.), (0., 2.)))
assert estimate.f_calls == 9
cached = plan.evaluate(residual, (1., 2.), f_x=residual((1., 2.)))
assert cached.hessian == estimate.hessian
assert cached.f_calls == 8

Construct with RectangularHessianPlan(input_dimension, output_dimension, scheme='central', step=None, *, memory_bytes=64*1024*1024). Both dimensions are positive integers that fit a C int. The read-only properties are input_dimension, output_dimension, shape, scheme, step, sample_count, storage_bytes, workspace_size, workspace_bytes, output_bytes, evaluation_bytes and memory_bytes; the reported memory is what is required, not the limit passed to the constructor.

evaluate(function, x, f_x=None) accepts a Python callable or a residual RectangularCallback of matching shape, or a residual VectorCallback when \(m=n\). The callback’s shape and kind are checked before any input is converted, and it stays reserved through the point and cache conversions, the evaluation and the creation of the result or exception. Plans can be shared concurrently by independent callbacks with their own storage. Python callbacks take the GIL; compiled callbacks and the stencil arithmetic run without it.

Sampling And Failures

Schemes, steps (scalar or per axis, signed), automatic steps, interpolation on the actual rounded nodes and range handling are those of the square Hessian plan. Central sampling costs \(2n^2\) residual attempts and forward or backward sampling \(n(n+3)/2\), depending only on the input dimension, plus one for the base unless it is cached. Each call evaluates all \(m\) components.

Results are HessianEstimate(hessian, f_calls, status, callback_code) with copied tuple tensors, and mirrored input-axis entries are exact copies. An 'ok' result means the computation finished, not that it is accurate; noise and cancellation still call for checks with varied steps. Collapsed nodes report 'breakdown', and nonfinite inputs, coefficients, samples or arithmetic 'nonfinite'. Every failure fills the whole tensor with NaN, including components already finished. Callback buffers start as NaN, so an incompletely written output fails explicitly.

Python exceptions propagate as the original instance with its traceback. Native callback failures raise NativeCallbackError with the exact integer code, a copied estimate and the stage 'function' for the base or 'hessian' for a stencil sample. Counts include failed attempts. The trial point is restored after every sample and failure. All nodes and interpolation coefficients are checked before any stencil callback, although an uncached base may be evaluated first.

Native Storage And Cython Interface

The output takes \(mn^2\) doubles. The scratch takes \(2nm+8n+2m\): a cache of axis samples, geometry vectors, a trial point, a corner residual and a compensation residual. An evaluation also copies the point and base, \(n+m\) doubles. Explicit steps add \(n\) persistent doubles; automatic plans store none. memory_bytes bounds the total before allocation; Python owners, tuple exports and allocator overhead come on top. Each concurrent evaluation allocates its own storage, and nothing is allocated between samples.

Cython callers can import RectangularHessianPlan, RectangularHessianConfig and compute_rectangular_hessian from cyroot.native.hessians. The config contains input_dimension, output_dimension, matrix_size \(=nm\), tensor_size \(=mn^2\), work, integer scheme and borrowed steps. Schemes zero, one and two mean forward, backward and central, as in the square plan. plan.copy_config(&config) lends out the plan’s immutable configuration, which stays valid while the plan is alive. The native tensor offset is o + m*(j + n*k).

plan.compute and compute_rectangular_hessian both take non-overlapping spans x[n], f0[m], out[m*n*n] and workspace[2*n*m+8*n+2*m], the output and work capacities, a RectangularFunction with its context, and non-null count and code pointers. The function signature is (const double* x, size_t n, size_t m, double* out, void* context) noexcept nogil. The caller reserves the callback and keeps it, the configuration, the context and the steps alive for the whole call. Input spans are read-only, and callbacks must fill their whole output on success.

The axis cache offset is (2*axis+side)*m+component, with side zero for an axis’s first sample and one for its second, and the trial point starts at 2*n*m+7*n. An invalid configuration or too little capacity returns DIFF_BREAKDOWN, resets callback_code to zero and leaves the outputs, scratch and call count untouched. With valid spans, every failure fills the tensor with NaN and restores the trial point. The square HessianConfig and compute_hessian go through a stack-only callback bridge to the same kernel.

These plans compute numerical derivatives; the analytic RectangularHessianCallback uses the same tensor layout. They serve the rectangular Chebyshev, Halley and Super-Halley and general modified Halley methods. If you used the removed 1.x derivative wrappers, choose a finite-difference plan and recheck old h values against that plan’s step and stencil conventions.

Native Higher Mixed Partial Derivatives

TensorDifferencePlan estimates dense derivatives of order three and above for functions with any input and output dimensions. It uses native C++ sampling, finite-difference weights on the rounded nodes and tensor arithmetic, with no NumPy or SymPy calls. Compiled callbacks run without the GIL; Python callbacks take it for each call, as do plan construction and result export.

A partial derivative differentiates with respect to one input. A mixed partial uses multiple inputs, and its order counts all differentiations. For example, \(\partial^3F/\partial x^2\partial y\) differentiates twice in \(x\) and once in \(y\). If \(F(x,y)=x^2y\), this derivative is \(2\). A third derivative tensor for a scalar-valued two-input function has eight entries, with four distinct symmetric components: xxx, xxy, xyy and yyy. Derivative order is separate from a root solver’s convergence order.

from cyroot.native import TensorDifferencePlan

def function(point):
    x, y = point
    return (x*x*y, x*y*y)

plan = TensorDifferencePlan(2, 2, 3, step=.125)
answer = plan.evaluate(function, (.5, 1.))
assert answer.status == 'ok'
assert plan.shape == (2, 2, 2, 2)
assert abs(answer.derivative[0][0][0][1]-2.) < 1e-10
assert abs(answer.derivative[1][0][1][1]-2.) < 1e-10
cached = plan.evaluate(function, (.5, 1.), f_x=function((.5, 1.)))
assert cached.f_calls == answer.f_calls-1
assert cached.derivative == answer.derivative

Shapes And Usage

The constructor is TensorDifferencePlan(input_dimension, output_dimension, order, scheme='central', step=None, *, max_nodes=65, max_terms=1_000_000, memory_bytes=64*1024*1024). Dimensions are positive C integers; order is at least three. Use JacobianPlan or RectangularJacobianPlan for order one, and HessianPlan or RectangularHessianPlan for order two; Finite Differences maps the removed 1.x derivative wrappers to these plans. Estimates are copied nested tuples.

For \(n\) inputs and \(m\) outputs, the copied nested tuple has shape \((m,n,\ldots,n)\), with order input axes. For instance, derivative[o][i][j][k] estimates the third partial of residual o with respect to input coordinates i, j, k; repeated indices mean repeated differentiation. Each distinct component is computed once and copied to all of its permutations, so symmetric entries are bit-identical. This assumes the smoothness under which mixed derivatives commute; the symmetry of the result says nothing about whether a nonsmooth function has such derivatives.

evaluate(function, point, f_x=None) accepts a Python function, a residual RectangularCallback of matching shape, or a square VectorCallback when the dimensions are equal. Python callbacks receive copied tuples. A cached base residual saves one call. Each distinct stencil point is sampled once per evaluation, even when several tensor entries use it, but nothing is reused between evaluations. Plans are immutable, and their native graph can be reused with separate caller-owned scratch.

The result is TensorDerivativeEstimate(derivative, f_calls, status, callback_code). f_calls counts attempted residual calls, including the base unless supplied. The status is ok, nonfinite, breakdown or callback_failure. Stencil points that collapse after rounding report breakdown, and nonfinite inputs, outputs or arithmetic nonfinite; any failure fills the whole tensor with NaN. Python callback exceptions are re-raised as they are; native callback failures raise NativeCallbackError with the estimate and the stage 'function' for the base or 'derivative' for a stencil sample. Adapters stay reserved through conversion, execution, error delivery and result construction.

Stencil And Numerical Limits

A component with multiplicity \(r\) on one axis uses r+1 nodes for forward or backward differences. Central differences use r+1+(r%2) nodes, including the base and requested offsets +1,-1,+2,-2,.... Tensor-product terms use these per-axis stencils. Setup enumerates only the distinct components and the points they need, rather than a full grid over every input axis.

step is None, a finite nonzero real number, or a vector of \(n\) such numbers, which is copied; negative steps are allowed. Automatic steps are \(\max(1,|x_j|)\epsilon^{1/(k+a)}\) per axis, where \(k\) is the total derivative order and \(a\) is 2 for central and 1 for one-sided differences. This is a rule of thumb, not an error estimate. On exactly symmetric nodes, central stencils have second-order and one-sided stencils first-order truncation error; rounding can break that symmetry and change the error.

The weights come from Fornberg’s recurrence on the normalized actual rounded displacements. The kernel subtracts the base residual before a compensated sum and rescales with binary exponents, so that products of step scales do not lose range prematurely. A result can still underflow to zero, while overflow and nonfinite intermediate arithmetic fail explicitly. Very high orders, noisy functions, cancellation and ill-conditioned stencils can give inaccurate finite results, and raising a resource limit does not improve precision.

Budgets And Native Consumers

Dense output contains \(mn^k\) doubles, so cost grows exponentially with order. max_nodes limits the largest per-axis stencil; the default allows order 64. max_terms bounds total tensor-product visits before enumeration, counting repeated visits to shared samples. The sample cache itself stores unique points. Requests exceeding shape, term or byte limits fail before residual sampling.

memory_bytes limits the native graph and steps plus one evaluation’s input, base, output, cache and scratch. The required graph sizes and a cap on cache entries are computed before the graph is enumerated, and each new entry is checked before it is inserted. Native vector capacity and allocator overhead, temporary Python planning objects, copied result tuples and callback internals come on top, so this budget does not bound the process’s peak memory.

The read-only properties are input_dimension, output_dimension, order, scheme, the copied step, shape, sample_count (distinct points other than the base), storage_bytes, workspace_size, workspace_bytes, output_bytes, evaluation_bytes and memory_bytes, which is the sum of storage_bytes and evaluation_bytes. The kernel never allocates or grows workspace.

Cython code cimports TensorDifferencePlan from cyroot.native.higher_mixed and TensorDifferenceConfig and compute_tensor_difference from cyroot.native.higher_mixed_ops. An initialized plan’s copy_config lends out its immutable graph and step pointers, so the plan must stay alive. compute and the free kernel take non-overlapping raw input, base, output and scratch spans and caller-owned attempt and status counters, with capacities in doubles. The output is packed as out[o+m*flat], with the first input index varying fastest. The caller is responsible for the graph contents and for keeping the callback’s pointers valid. An invalid configuration or too little capacity returns breakdown before anything is written, resetting only the callback code. With valid spans, any failure fills the output with NaN and restores the scratch trial point. The callback must not throw or modify the borrowed point.

Native Core

CyRoot separates Python setup and inspection from its native numerical engine. cyroot.native exposes resumable solver states, versioned callback adapters, owned storage, and derivative and linear-algebra plans, and the public cyroot functions run on the same engines. The native numerical loops make no Python-level NumPy calls.

Step, Inspect, Resume

from cyroot.native import Bisection

solver = Bisection(lambda x: x*x - 2., 0., 2., history=64)
first = solver.step()
answer = solver.run()
assert answer.success
assert solver.history[-1].root == answer.root
assert solver.done

step() advances one outer iteration, and run() finishes the solve through the same state machine. result returns a copy of the current result without advancing. The iteration budget includes earlier step() calls. A finished solver stays finished: further calls return its final result instead of starting again with a new budget. Iterating over a solver yields its remaining steps. Snapshots taken while running have termination_reason=None, and some public result types report unspecified until the solve ends; check done and the reason.

Histories are opt-in and bounded. history sets the maximum number of snapshots and history_every samples iterations. The initial and terminal states are recorded if there is room, and a terminal diagnostic in the same iteration can replace that iteration’s record. Once full, a history keeps its existing entries and sets history_truncated, so increase the capacity if you need the final iterate. Exported tuples are unaffected by later steps and by destroying the solver.

as_root_snapshot gives every single-root result the same fields and keeps the original record in diagnostics. Solver-specific counters, ranks, callback stages and failure states are described on the method pages, and hybisect also has a multi-root search and event interface. See Stopping And Results.

Python And Native Callbacks

A Python callback is wrapped in an adapter and takes the GIL for its call and result conversion. A compiled native callback has a raw status-and-output signature, which lets the solver run its numerical loop without the GIL. For a scalar residual the signature is:

cdef int residual(double x, double* out, void* context) noexcept nogil:
    out[0] = x*x - 2.
    return 0

Wrap that function with make_scalar_callback(function, context, keepalive) from cyroot.native.scalar. The adapter keeps keepalive alive, and keepalive must in turn keep the context and any code or data it refers to alive; the context itself stays owned by its producer. The compiled scalar example uses a Cython object that owns a parameter struct, and the pure Python syntax example uses Cython annotations and a native bridge in a .py module.

A native callback must write every required output before returning zero, and return a nonzero status on failure. Python and C++ exceptions must not cross the ABI, and any Python access needs the GIL acquired explicitly. A nogil declaration allows the function to run without the GIL; it neither releases the GIL nor makes the function thread-safe.

Different roles use different descriptors and layouts:

RoleGuide
Scalar residual or derivativeNewton
Square/rectangular residual and JacobianVector Newton, Rectangular Callbacks
Residual Hessian tensorsTensor Callbacks
Jacobian forward/transpose productsJacobian Products
Complex residualScalar Migration, Numerical Derivatives
Interval enclosure for a root searchScalar Migration

Capsule names include an ABI version. Adapters check descriptor sizes, versions, kinds, dimensions and that function pointers are not null; they cannot check where a pointer came from or how long it stays valid. Keep owners alive, and rebuild compiled consumers against the headers and declarations of the installed CyRoot.

Ownership And Reentry

Explicit callback adapters stay reserved while a solver converts arguments, runs native code, transfers errors and builds its outputs. Reentrant or concurrent use of an active solver or adapter is rejected. Separate adapters that point at the same mutable native context still need synchronization by the context’s owner. Construction and inspection run in Python, but independent solvers with independent callbacks can run their numerical loops concurrently. Samples are never evaluated in parallel automatically.

Derivative and linear-algebra plans are immutable: they hold configuration, not shared mutable scratch. Independent users can share a plan, each with its own buffers and properly synchronized contexts. Sharing a plan does not make an active callback safe to reuse.

A fully native run never checks for Python signals, so native callbacks should finish in bounded time and report failures through their status. Native solves cannot be cancelled, and there are no observer callbacks.

Callback Failures

Python exceptions propagate as the original instance, with their traceback. Nonzero native statuses raise NativeCallbackError with native_status, a copied result and the callback_stage; some methods also report a derivative order. Call counts include failed attempts. Native callback outputs are filled with NaN before each call, so a partial write can never expose stale scratch.

A failed trial generally keeps the previously accepted point and residual. A derivative that fails after an accepted step keeps that step and marks the missing derivative as unavailable. A failed quasi-Newton update keeps the accepted point and the last complete matrix. Each method page describes its failure state; an approximate matrix is never a fresh derivative.

Once the error has been raised, later step() and run() calls return the final state without sampling again or raising again, and the state can still be inspected. Numerical breakdown and nonfinite arithmetic return unsuccessful results as each method describes.

Storage And Borrowed Views

cyroot.native.DoubleBuffer accepts direct, native-format float64 buffers with one or two dimensions. It borrows the exporter’s memory, or with copy=True makes a private, writable, contiguous copy.

from array import array
from cyroot.native import DoubleBuffer

source = array('d', [1., 2., 3.])
borrowed = DoubleBuffer(source)
private = DoubleBuffer(source, copy=True)
private[0] = 7.
assert borrowed[0] == 1.
assert memoryview(borrowed).readonly

A borrowing guard keeps the exporter alive and copies its shape and strides. The data is read-only through the guard, but its owner can still change it, so synchronize such writes. Negative and zero strides, read-only exporters and unaligned data are supported. This low-level class rejects indirect buffers and other formats or dimensions; solver inputs, by contrast, convert real non-float64 buffers element by element and reject complex and boolean ones.

buffers.pxd exposes the C++17 OwnedDoubleBuffer, VectorView and MatrixView. Owners can be moved but not copied. Views borrow a pointer with signed byte strides; their raw constructors and span access do no checking of their own. Dimension checks cannot establish that a pointer is valid, long enough, non-overlapping or alive, so keep the owner or guard alive and never resize or reset the storage while native code is using it.

Resource Budgets

Native storage is allocated before stepping starts. Solvers check dimension products and have byte budgets for workspace and history, and plans also bound stencil nodes, tensor entries or terms wherever the work grows combinatorially. Budget names and what they cover vary by method, and they do not limit the process’s peak memory: Python snapshots, callback allocations, allocator overhead and memory used inside LAPACK come on top.

See Finite Differences to choose a derivative plan, Native Least Squares for DGELSY workspaces, and Newton–Krylov to avoid storing a dense Jacobian. Compiled kernels remove Python overhead, not conditioning limits or the inherent cost of dense high-order tensors.

Compile Python Callbacks With Cython

You can write typed numerical functions in an ordinary .py file, compile them with Cython’s pure Python mode, and pass them to CyRoot as native callbacks. The complete working example includes the source and the build command. It uses the standard callback interfaces and needs no JIT or extra runtime dependency.

The numerical part looks like Python with explicit C types:

import cython

@cython.ccall
@cython.nogil
@cython.exceptval(check=False)
def residual(x: cython.double) -> cython.double:
    return x*x - 2.0

Cython generates both a Python-callable wrapper and a C entry point. The example adds a small native bridge from that C entry point to CyRoot’s status-and-output callback signature, and exports callback() and derivative_callback():

from cyroot.native import Newton
import pure_python_callback as example  # the compiled extension

answer = Newton(example.callback(), example.derivative_callback(), 1.5).run()
assert answer.success

Passing example.residual itself also works, but as a Python callback: every call goes through Python’s call machinery and needs the GIL. The descriptor returned by example.callback() points at the native C entry point instead. nogil allows calls without the GIL, and the solver releases it around the numerical work. The example functions have no state, so their contexts are null and their function wrappers serve as owners; functions with parameters need a native context and an owner that keeps it alive.

How This Differs From Numba

The recommended Cython route is ahead of time: Cython translates the source to C or C++, and a compiler builds an importable extension. Type annotations mark the C arithmetic. Imported as ordinary Python, the same .py file does not become native code, and the example’s cython.cimports must be compiled before it can be imported at all. Neither the .py nor the .pyx suffix decides whether the GIL is needed.

Cython also has runtime compilation, such as cython.inline and @cython.compile. These need a build toolchain, come with constraints on the source, typing and Python state, and produce Python-callable functions. They do not export CyRoot’s callback ABI or guarantee GIL-free execution, so they are not a drop-in equivalent of numba.njit for a fully native solve. CyRoot has no runtime helper that automates this.

Native Restrictions

To run without the GIL, the body must use native types and operations only. Python objects, Python-level NumPy calls, dynamic closures and most Python library calls need the GIL. C math functions can replace many scalar math calls, and vector functions can write directly into the callback’s output span through typed pointers. Numerical derivatives can then sample the native residual without returning to Python.

exceptval(check=False) is safe only when no exception can escape. A bridge that can fail should check its own conditions and return a nonzero status, which CyRoot reports as NativeCallbackError. Shared mutable native context must support the concurrency you intend. Compiling a function does not make it thread-safe, accurate or fast.

For the raw scalar, rectangular vector and Hessian interfaces, see the native core guide, rectangular callbacks and tensor callbacks. The pure Python example needs neither NumPy arrays nor NumPy C headers.

Vector Functions And NumPy

The same pure-Python example includes a compiled vector residual, analytic Jacobian and native numerical Jacobian solve. It accepts two variables and writes three residuals directly into solver-owned output storage. No ndarray is created per sample.

Compiling an existing NumPy function generally does not remove its Python calls. For the native path, rewrite elementwise expressions as typed operations or loops, use C math functions, and call native BLAS or LAPACK for matrix operations. NumPy arrays remain useful for setup and for the results. Typed memoryviews can be acquired once, outside the callback, and then used without the GIL; with CyRoot’s raw pointer interface there is no need to create a view on every call. Other NumPy or SciPy routines need a native implementation of their own, or a Python callback.

Rectangular Callbacks

RectangularCallback adapts functions with n inputs and m outputs, separately from the square VectorCallback. Every solver that handles rectangular systems accepts it for residuals and Jacobians, including with native numerical differences, and Robinson and Traub–Steffensen accept it when n = m. Broyden, Klement and Barnes need a square VectorCallback. Plain Python callbacks need neither an adapter nor explicit dimensions; see Vector Newton.

from cyroot.native import RectangularCallback

residual = RectangularCallback(lambda x: (x[0], x[1], x[0]+x[1]), 2, 3)
assert residual.evaluate((2., 3.)) == (2., 3., 5.)
jacobian = RectangularCallback(lambda x: ((1., 0.), (0., 1.), (1., 1.)),
                               2, 3, jacobian=True)
assert jacobian.evaluate((2., 3.)) == ((1., 0.), (0., 1.), (1., 1.))

Python functions receive an immutable copy of the point as a tuple. Residuals return a vector of length m, and Jacobians m rows of length n. Sized sequences and buffers, including strided and read-only ones, are accepted if their shapes match. Returned tuples are independent copies. Nonfinite values are passed through for the solver to deal with.

evaluate(point, *, workspace_bytes=64*1024*1024) reserves the adapter before converting anything and keeps it reserved through output packing and exception transfer; reusing an active adapter raises RuntimeError. Python exceptions propagate as the original instance. The budget covers n + m doubles for a residual or n + m*n for a Jacobian, not counting Python objects or allocations made by the callback. The read-only properties are input_dimension, output_dimension, jacobian and native. Dimensions must be positive and fit both the C int ABI and native storage.

Compiled Functions

cyroot.native.rectangular declares the callback signature:

ctypedef int (*RectangularFunction)(const double* x, size_t n, size_t m,
                                  double* out, void* context) noexcept nogil

Use make_rectangular_callback(function, n, m, context, keepalive=None, jacobian=False). Residuals write m doubles; Jacobians write m*n doubles in column-major order, out[row + column*m]. A zero status means the callback finished; entries it did not write stay NaN. A nonzero status turns the whole output into NaN, and Python evaluate raises NativeCallbackError with the status and the stage function or jacobian. Native code must follow the signature, keep exceptions from crossing the ABI and acquire the GIL before touching Python.

In a native loop, reserve the adapter with _enter() while holding the GIL, call evaluate_raw(x, out) without the GIL, raise any saved Python _error, and release the adapter with _release() in a finally block. The caller keeps the adapter alive and passes valid, non-overlapping input and output spans of the declared sizes. This raw path allocates nothing; adapters around Python callbacks acquire the GIL inside their bridge. The producer is responsible for its context’s lifetime and for synchronizing distinct adapters that share native state.

RectangularCallback.from_capsule(capsule, keepalive=owner) accepts capsules named cyroot.rectangular_callback.v1. callbacks.h declares their cyroot_rectangular_descriptor, with size and version, input and output dimensions, kind (CYROOT_RECTANGULAR_RESIDUAL or CYROOT_RECTANGULAR_JACOBIAN), function and context. The descriptor is validated and copied, and the supplied owners are kept alive.

Analytic Rectangular Hessians And Native Contractions

RectangularHessianCallback adapts an analytic Hessian of \(F:\mathbb R^n\to\mathbb R^m\). It returns a copied tensor of shape \((m,n,n)\), like the rectangular numerical plan, and keeps every entry as given, without imposing symmetry.

from cyroot.native import RectangularHessianCallback

# This illustrative tensor is asymmetric: the adapter preserves every entry.
tensor = (((1., 2.), (3., 4.)),
          ((5., 6.), (7., 8.)),
          ((9., 10.), (11., 12.)))
callback = RectangularHessianCallback(lambda x: tensor, 2, 3)
result = callback.evaluate((1., 2.))
assert callback.shape == (3, 2, 2)
assert result == tensor
assert result[0][0][1] != result[0][1][0]
assert not callback.native

Construct with RectangularHessianCallback(function, input_dimension, output_dimension). Both dimensions must be positive integers fitting C int; the complete input and tensor storage must fit native capacities. The read-only properties are input_dimension, output_dimension, shape and native. The adapter serves only as a Hessian, never as a residual or Jacobian. The Chebyshev and fixed Halley and Super-Halley methods use it for rectangular systems, and the general modified Halley method uses it in its three-solve rectangular correction.

evaluate(point, *, workspace_bytes=64*1024*1024) copies the point, calls the callback and returns the tensor as nested tuples. Python callbacks receive a tuple of length \(n\) and return an indexable real tensor of shape \((m,n,n)\). Points can be negative-stride arrays or read-only float64 buffers. The result is independent of the tensor the callback returned. Complex entries, text and malformed shapes fail conversion. The adapter only evaluates the callback; it neither approximates nor checks anything numerically.

Evaluation needs \(n+mn^2\) native doubles, checked against workspace_bytes before allocation; Python owners, copied tuples and allocator overhead come on top. The callback is reserved through the budget and point conversions, the call, result export and exception creation. Reentry and reinitialization are rejected, and independent adapters can run concurrently. Python callbacks take the GIL; compiled callbacks run without it.

Native outputs start as NaN. A nonzero status makes the whole tensor NaN and raises NativeCallbackError with the original integer code, the stage 'hessian' and the all-NaN tensor as .result. Python exceptions propagate as the original instance with its traceback, and are cleared from the adapter once raised. A zero status is passed through even if entries are still NaN or are otherwise nonfinite: as with residual and Jacobian adapters, the consumer must check the whole tensor. The adapter never invents error codes for partial native output.

Compiled Callbacks And Capsules

Cython consumers import from cyroot.native.tensor_callbacks:

  • RectangularHessianCallback, RectangularHessianFunction and make_rectangular_hessian_callback(function, n, m, context, keepalive=None).
  • cyroot_rectangular_hessian_descriptor for capsules, or the equivalent C declaration in callbacks.h.

The callback signature is int function(const double* x, size_t n, size_t m, double* out, void* context) noexcept nogil. The input is borrowed and read-only. On success, write all \(mn^2\) entries, entry \((o,j,k)\) at offset o + m*(j + n*k). The producer owns the context and supplies an owner object to keep it alive. Callbacks must not throw, and must acquire the GIL before using Python.

The capsule name is cyroot.rectangular_hessian_callback.v1. The descriptor contains struct_size, abi_version, input_dimension, output_dimension, function and context, and the macros CYROOT_RECTANGULAR_HESSIAN_CALLBACK_ABI and CYROOT_RECTANGULAR_HESSIAN_CAPSULE_NAME in callbacks.h identify it. RectangularHessianCallback.from_capsule(capsule, keepalive=None) checks the name, descriptor size, version, dimensions and that the function is not null, and keeps both the capsule and the owner alive.

A Cython loop reserves the adapter with _enter(), keeps it alive, and calls evaluate_raw(x, out) on valid, non-overlapping x[n] and out[m*n*n] spans; it then raises any saved _error before calling _release() in a finally block. Reserving and raising need the GIL; evaluate_raw is noexcept nogil, allocates nothing and returns the native status, so a loop can reuse fixed buffers. The installed consumer test shows the complete reserve and error-transfer pattern.

Tensor Contractions

Allocation-free helpers in tensor_ops.hpp and tensor_ops.pxd take separate input/output dimensions:

HelperOperationOutput span/layout
contract_rectangular_hessian(H,s,n,m,out)\(\sum_{j,k}H_{o,j,k}s_js_k\)out[m]
contract_rectangular_hessian_direction(H,s,n,m,out)\(\sum_jH_{o,j,k}s_j\)out[m*n], o+m*k
rectangular_matrix_vector(A,s,n,m,out)\(\sum_jA_{o,j}s_j\)out[m]

Tensor spans are H[m*n*n], direction spans s[n], and matrices are column-major A[m*n]. All spans must be valid, non-overlapping and alive for the call, and the caller is responsible for storage and synchronization. Every ordered pair of inputs is used, with no symmetry assumed. The square helpers are thin wrappers with \(m=n\).

Status zero is success. One is a nonfinite input or result and makes the whole output NaN. Two is an invalid dimension or span-size overflow and leaves the spans untouched. Every tensor or matrix entry is validated, even where its direction weight is zero. Exponent-scaled compensated arithmetic extends the range, as for square systems, but not the precision, and does not protect against derivative noise or cancellation. The helpers never allocate, call Python or touch the GIL.

These helpers are building blocks. The solvers that use them are described in rectangular Chebyshev, rectangular Halley and Super-Halley and rectangular modified Halley.

Stopping Rules And Result Status

Every solver result has a termination_reason, a string-valued TerminationReason enum. success and converged are true when the residual or bracket tolerance is met, and optimal only when the residual tolerance is met. A small step with an unsatisfied residual is stagnation, not success.

from cyroot import newton, TerminationReason

result = newton(lambda x: x*x - 2, lambda x: 2*x, 1.)
assert result.termination_reason == TerminationReason.RESIDUAL_TOLERANCE
assert result.success

The tolerances are:

ArgumentMeaning
etolAbsolute residual tolerance.
ertolRelative residual tolerance against a fixed starting residual scale.
ptolAbsolute step or bracket-width tolerance.
prtolRelative step or bracket-width tolerance against the iterate scale.

Residual convergence uses

\[ \|F(x_k)\|_\infty \le \mathrm{etol} + \mathrm{ertol}\,s_F. \]

For one starting point, s_F is its residual norm; for several starting points or a scalar bracket, it is the largest starting residual norm. It stays fixed for the whole solve. A starting point that is an exact root is accepted even when both residual tolerances are zero.

Open methods test step size using

\[ \|x_k-x_{k-1}\|_\infty \le \mathrm{ptol} + \mathrm{prtol} \max(\|x_k\|_\infty,\|x_{k-1}\|_\infty). \]

Methods that keep several iterates use the diameter of that set. A scalar bracket uses its width and the larger endpoint magnitude. Complex methods use complex magnitudes and distances, not differences of magnitudes. The step or width and the residual norm are reported as precision and error.

A narrow valid bracket can meet the bracket criterion while the residual is still large. Whether it encloses a root depends on the method’s assumptions, such as continuity; sign changes observed numerically do not prove continuity. Vrahatis accepts width convergence when there is one output. With several outputs, its vertex signs do not certify a root, so stopping on width alone is unsuccessful stagnation and success requires residual convergence. Rectangular systems can take least-squares steps, but success still depends on the residual, not on least-squares stationarity.

All solver families share the defaults etol=1e-10, ertol=4*eps, ptol=1e-12, prtol=4*eps and max_iter=200 (with the binary64 eps), defined once in cyroot/defaults.hpp. root_via_optimizer uses the same residual defaults, while the external optimizer keeps its own iteration and convergence controls. Method-specific controls, such as the optimizers’ gtol or evaluation budgets, have their own defaults. All of these controls are keyword-only in every public function and native solver class; only the function, derivative providers, starting values and cached starting values are positional.

The relative residual term scales with the starting residual, not with the accuracy of the derivatives. For example, with a starting residual of 1e20, 4*eps adds about 8.9e4 to the threshold. Set ertol=0 when the application needs an absolute residual target. The relative step tolerance also scales with the size of the coordinates, so rescale badly balanced problems on purpose.

Tolerances must be finite and nonnegative, and relative tolerances less than one. max_iter is a nonnegative integer; zero or None removes the iteration limit. Disabling both the limit and every tolerance is rejected. Every method still stops on nonfinite arithmetic, breakdown or a collapsed step. Python callback exceptions propagate with their traceback.

Derivative methods evaluate only the derivatives needed for another step. They make no derivative calls when the starting point is already a root, or after a step that meets a stopping rule or uses up the iteration budget. When the derivative at the returned point was not evaluated, df_root holds NaN placeholders of the usual scalar or tensor shape, except that supplied initial derivatives are kept when the starting point is returned. Evaluation counts reflect the skipped calls. Quasi-Newton matrices are evolving approximations, not the derivatives at the returned point.

ReasonMeaning
residual_toleranceThe residual criterion is satisfied.
bracket_toleranceA valid bracket satisfies its width criterion.
stagnationSteps or retained iterates have collapsed without residual convergence.
max_iterationsThe iteration budget was exhausted.
zero_derivativeA required scalar derivative is zero.
breakdownA denominator, factorization or other numerical precondition failed.
nonfiniteA required point, value or arithmetic result is not finite.
callback_failureA callback raised a Python exception or returned a nonzero native status; the error is also raised.
line_search_failureNo acceptable descent step was found by the bounded line search.
linear_failureThe required inner linear solve did not meet its acceptance criterion.
max_evaluationsThe residual evaluation budget was exhausted.
derivative_breakdownA numerical derivative/product could not form a valid estimate.
stationary_nonrootThe optimizer’s stationarity test was met while the residual remained nonzero.
no_acceptable_stepA bounded optimizer trial search found no acceptable step.
optimizer_stopped_without_rootAn external optimizer returned a point that failed the root tolerance.

Interval-splitting results have termination_reasons, one per returned root, and a search_termination_reason for the whole search. A completed search can return no roots when the interval bounds exclude them. max_split_iterations means the search did not complete, even if some returned roots converged. success requires a completed search and successful returned roots.

A result constructed by hand without a reason reports unspecified; passing a known reason sets the matching success flags.

Scalar Solver Migration

In 2.0, all 26 scalar solvers run on native state machines, under the same names in cyroot and find_scalar_root as before. Python callables and native callback descriptors drive the same numerical methods. Python callbacks take the GIL for their calls, while native callbacks let the whole numerical run happen without it; validation, ownership setup and result and history export hold the GIL.

Supported Methods

FamilyMethodsNative inspection interface
BracketingbisectBisection
Bracketingregula_falsi, illinois, pegasus, anderson_bjorck, dekker, brent, chandrupatla, ridders, toms748, wu, itpBracketSolver(method=...)
Interval searchhybisectHybisect
Newtonnewton, homeierNewton, Homeier
Higher orderhalley, super_halley, chebyshev, tangent_hyperbolas, householderHalley, ModifiedHalley, SuperHalley, Chebyshev, TangentHyperbolas, Householder
Interpolationsecant, sidi, steffensen, inverse_quadratic_interp, hyperbolic_interp, mullerSecant, Sidi, Steffensen, InverseQuadraticInterpolation, HyperbolicInterpolation, Muller

The inspection classes live in cyroot.native. They expose step(), run(), result, done, iteration and bounded copied history. For example:

from cyroot import brent, find_scalar_root
from cyroot.native import BracketSolver

answer = brent(lambda x: x*x-2, 0, 2)
assert answer.success
assert find_scalar_root('brent', lambda x: x*x-2, 0, 2).success

solver = BracketSolver(lambda x: x*x-2, 0, 2, method='brent', history=32)
first = solver.step()
answer = solver.run()
assert answer.success
assert solver.history[-1].root == answer.root

step() advances one iteration of the algorithm. Ridders can sample twice per step and one TOMS748 iteration several times, and Steffensen needs an extra residual evaluation to form its candidate. Hybisect steps are search events, described below. Function counts include every callback attempt; supplied initial values are not counted. A failed trial keeps the last accepted finite state. To diagnose a failure, check termination_reason, f_calls, precision and error. A small step with a residual that is not small is stagnation, not success. Bracketing methods can also succeed by narrowing a sign-changing bracket enough, given the method’s continuity assumptions.

max_iter is one budget shared by step() and run(); zero or None removes the limit. History is opt-in: history=0 disables it, and history_every and history_bytes bound the copied snapshots. A full history does not stop the solve, and snapshots stay valid after the solver resumes or is destroyed. No observer callback is ever called.

ITP’s projection uses a fixed full-width tolerance derived from ptol and the initial prtol scale. With both disabled, it projects on an internal spacing scale instead, and the stopping tests are unchanged. The paper’s bound on bisection steps holds in exact arithmetic; with rounding, an extra iteration can be needed near a width threshold. The solver always respects max_iter and never relaxes the width tolerance to claim success. TOMS748 accepts k from 1 to 100.

Newton Derivatives And Breaking Changes

When no analytic derivative is given, the Newton-family functions use native derivative plans: h=None selects automatic steps, and an explicit h central differences with that step. A step h that no numerical derivative would use is rejected. ScalarDerivativePlan and ScalarSecondDerivativePlan set the scheme directly. The 1.x FiniteDifference API was removed; pass a native plan or a Python callable instead (see Finite Differences).

The alpha argument of halley selects native modified Halley; Super-Halley and Chebyshev correspond to alpha 1 and 0. The scalar tangent-hyperbolas formulas 1 and 2 are algebraically the same as Halley’s and use the same native update, but formula is still validated. Householder uses the native runtime-order reciprocal-series recurrence, without SymPy.

Compared with the 1.x kernels, iteration and evaluation counts, floating-point paths, failure states and numerical derivative steps can differ. Rebuild compiled consumers against the 2.0 declarations. The removed private kernel functions and NewtonPolynomial have no replacement.

Compiled Real And Complex Callbacks

Real methods accept a ScalarCallback, created from Python or by make_scalar_callback in cyroot.native.scalar. Typed .py and .pyx functions can both provide one; see Compile Python Callbacks.

Muller accepts Python complex callables or ComplexScalarCallback. It can leave the real axis even when all starting points are real:

from cyroot import muller

answer = muller(lambda z: z*z+1, 0, 1, 2)
assert answer.success
assert abs(answer.root*answer.root+1) < 1e-9

cyroot.native.complex_callbacks declares the native Cython factory make_complex_scalar_callback(function, context, keepalive=None). Its portable C signature passes components separately:

ctypedef int (*ComplexScalarFunction)(double real, double imag,
    double* out_real, double* out_imag, void* context) noexcept nogil

Write both outputs and return zero on success. A nonzero status stops the solve and raises NativeCallbackError; native exceptions must not escape this ABI. The header complex_callbacks.h defines cyroot_complex_scalar_descriptor (ABI version 1) and the capsule name cyroot.complex_scalar_callback.v1. ComplexScalarCallback.from_capsule(capsule, keepalive=owner) validates and copies the descriptor. The producer must keep its context alive and synchronize shared mutable state. Reentrant or concurrent use of one adapter is rejected.

Hybisect needs both a residual and an interval-enclosure callback. The latter is called as interval_function(a,b) and returns (lower,upper) containing all residual values on the interval. Producing a rigorous enclosure, including outward rounding where needed, is the caller’s responsibility.

from cyroot.native import Hybisect

def enclosure(a, b):
    # Exact for the simple representable endpoints used in this example.
    return (-1 if a <= 0 <= b else min(a*a, b*b)-1,
            max(a*a, b*b)-1)

solver = Hybisect(lambda x: x*x-1, enclosure, -2, 2, history=32)
answer = solver.run()
assert answer.success
assert answer.root == [-1, 1]

The search discards intervals whose enclosure excludes zero, splits intervals whose endpoints have the same sign (depth first), and bisects sign-changing intervals. Each sign-changing interval yields one root; neither a completed search nor the method guarantees that every root in the domain was isolated. Identical roots found at shared endpoints are reported once.

max_iter applies to each root bracket separately and max_split_iter to the total number of splits; zero removes either limit. The pending stack and the root records are allocated up front within workspace_bytes (8 MiB by default), with max_pending=4096 and max_roots=4096. Running out of capacity stops the search with breakdown and sets workspace_exhausted; the roots found so far remain available. A successful search has search_termination_reason='completed' and successful per-root reasons; a completed search can rightly return no roots.

step() performs one interval, split, bisection or root event. The copied events include the current bracket, the total bisection, split and callback counts, the roots found, the pending intervals and the search’s termination. roots_found and root events count recorded root candidates, failed brackets included, so check the per-root reason before treating a candidate as a root. The result keeps per-root iteration counts and (residual_calls, interval_calls) separately. Callbacks first run on step() or run(); constructing a search only validates arguments and allocates its state.

IntervalCallback uses cyroot.native.hybisect.make_interval_callback and the native signature:

ctypedef int (*IntervalFunction)(double a, double b,
    double* lower, double* upper, void* context) noexcept nogil

Write both bounds on success; nonfinite or reversed bounds stop the search. interval_callbacks.h defines the version-1 interval descriptor and the capsule name cyroot.interval_callback.v1. Context, keepalive and exception rules are those of the other callbacks. Both the residual and the enclosure must be native for the whole search to run without the GIL.

Removed Experimental Methods

The experimental Ahmadi and Mishchenko methods, which were never verified, were removed in 2.0.

Migrating Higher-Order Vector Methods

In 2.0, cyroot.generalized_halley, generalized_super_halley, generalized_chebyshev and generalized_tangent_hyperbolas run on a shared native engine, and Python callbacks receive tuples. Besides square systems, they handle rectangular ones: the Chebyshev path, including alpha=0, with rank-aware least-squares corrections, matrix Halley and Super-Halley likewise, and other values of alpha with a three-solve rectangular correction, so rectangular steps can jump at the exact values .5 and 1. Singular square systems use LU and never fall back to a pseudoinverse. generalized_newton also handles different point and residual lengths; see Vector Newton. The vector quasi-Newton methods run on native states too, each with its own shape rules. The 1.x derivative wrappers were removed; use the finite-difference plans instead.

Methods And Matrix Semantics

Entry pointNative method
generalized_halley(..., alpha=None) (default)VectorHalley
generalized_halley(..., alpha=value)VectorModifiedHalley
generalized_super_halley(...)VectorSuperHalley
generalized_chebyshev(...)VectorChebyshev
generalized_tangent_hyperbolas(...)VectorHalley

For a square residual map, let \(Js=F\) and \(A_{o,k}=\sum_j H_{o,j,k}s_j\). Matrix Halley solves \((J-A/2)v=F\), then takes \(\Delta x=-v\). The 1.x default divided componentwise after a different contraction. The two agree in one dimension but can give different steps for coupled systems.

For example, at \((0,0)\),

\[ F(x,y)=(1+x+xy,\;2+y+x^2) \]
has \(J=I\) and \(A=\begin{pmatrix}2&1\\2&0\end{pmatrix}\). The matrix Halley step is \((4,2)\), while the 1.x componentwise step was \((1,-4)\). This shows a numerical difference, not which converges. The componentwise implementation is gone. Vector tangent hyperbolas uses matrix Halley directly, and its redundant `formula` option is gone.

Modified Halley keeps the order of matrix products and reuses the Jacobian’s factors and pivots for its final correction. alpha exactly 0, .5 and 1 uses the Chebyshev, Halley and Super-Halley arithmetic, and other finite values the general correction. There is no automatic parameter choice, damping or alternative solve on failure.

Callback Inputs, Results And Derivatives

Python callbacks receive immutable tuples and can return numeric sequences or buffers, NumPy arrays included. Expressions that index the point work unchanged:

from cyroot import generalized_halley

def residual(point):
    x, y = point
    return (x*x + x*y + y - 5., 2*x + y*y - 6.)

def jacobian(point):
    x, y = point
    return ((2*x + y, x + 1.), (2., 2*y))

def hessian(point):
    return (((2., 1.), (1., 0.)), ((0., 0.), (0., 2.)))

result = generalized_halley(residual, jacobian, hessian, (1.25, 1.75))
assert result.success
assert max(abs(a-b) for a, b in zip(result.root, (1., 2.))) < 1e-9

Expressions such as point - 1. or scale * point need elementwise arithmetic or an explicit conversion inside the callback. Existing NumPy code can be wrapped, as in lambda point: old_residual(np.asarray(point)); the wrapper runs in Python under the GIL. The solver itself never creates a NumPy array around a callback.

J=None and H=None select independent automatic central-difference plans. To configure them, pass the native plan classes:

from cyroot.native import JacobianPlan, HessianPlan

result = generalized_halley(residual, JacobianPlan(2, step=1e-4),
                            HessianPlan(2, step=1e-3), (1.25, 1.75))
assert result.success

These four functions no longer take h; use JacobianPlan and HessianPlan for numerical derivatives, since the 1.x derivative approximation classes are gone. generalized_newton likewise takes None, an analytic provider or a native plan for its Jacobian.

NewtonMethodsReturnType holds tuple copies of the point, residual, Jacobian and Hessian. df_root=(jacobian, hessian) has NaNs for derivatives that were not evaluated at the returned point. f_calls=(F, J, H) counts each plan evaluation for its derivative and every sampled residual in F. Stopping, cached values and failures work as in the native engine.

Options, Shapes And Failure Policy

The shared signature is (F, J, H, x0, F_x0=None, J_x0=None, H_x0=None, *, etol=1e-10, ertol=4*eps, ptol=1e-12, prtol=4*eps, max_iter=200, history=0, history_every=1, history_bytes=8*1024*1024, workspace_bytes=64*1024*1024). generalized_halley also takes a keyword-only alpha=None. Everything after the three cache arguments is keyword-only. The default max_iter is 200; zero or None is unlimited. Removed options raise TypeError before any callback runs. Caches and options are passed unchanged to the native constructor.

With n inputs and m residuals, Jacobians have shape \((m,n)\) and Hessians \((m,n,n)\), indexed [residual][input][input]. The Python residual, native providers of matching shape or cached residuals determine m, and the default numerical plans follow. Inputs are never reshaped silently. Every finite alpha works for rectangular systems, as the rectangular pages specify. Only residual convergence counts as success. A singular square Jacobian or secondary system reports breakdown, with no least-squares fallback, while rectangular solves allow rank deficiency and take minimum-norm least-squares corrections. Nonfinite data or intermediates report nonfinite, and small steps with an unsatisfied residual report unsuccessful stagnation.

To inspect intermediate steps or the linear stage and status, use VectorHalley, VectorSuperHalley, VectorChebyshev or VectorModifiedHalley from cyroot.native. They provide step(), run() and bounded copied history, while the functions only return the final result. For example:

from cyroot.native import VectorHalley

solver = VectorHalley(residual, jacobian, hessian, (1.25, 1.75), history=16)
first = solver.step()
result = solver.run()
assert result.success
assert solver.history[-1].root == result.root

Native vector and Hessian callbacks can be passed straight to these functions. With native callbacks for every evaluated role, the numerical engine runs without the GIL; Python callbacks, setup and result and history export take it. Compiled consumers must be rebuilt against the 2.0 callback and solver declarations.