nlopt4m

    Pure MoonBit nonlinear optimization solvers

    optimization
    numerical
    nonlinear
    Download zip
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    2 hours ago
    Downloads
    7

    No dependencies

    #nlopt4m

    An early-stage, pure MoonBit nonlinear optimization library inspired by nlopt4r. It is an independent implementation, not a binding to NLopt.

    The nlopt4r book covers theory and usage (English edition).

    The solver packages have no native optimizer dependency and support MoonBit's Wasm, Wasm GC, JavaScript, and native targets. The file-summary command is native-only.

    #Current functionality

    FamilyImplemented methods
    Unbounded localSteepest descent, normalized gradient, Fletcher-Reeves, BFGS, L-BFGS, DFP, SR1, convex Broyden, Newton-CG, dense and matrix-free trust regions
    BoundedProjected gradient; value-only pattern search and Nelder-Mead
    Global searchSeeded differential evolution and particle swarm
    Least squaresLevenberg-Marquardt with QR-based steps
    ConstrainedConvex quadratic programming, augmented Lagrangian, equality-constrained Newton/SQP, and SQP with feasibility restoration
    ScalarGolden-section and safeguarded parabolic search
    Building blocksArmijo and strong-Wolfe line searches, Steihaug subproblem, checked dense solve, evaluation context, directional difference

    These are local or heuristic methods; they do not certify a global optimum. Convergence, stagnation and budget limits have distinct termination reasons.

    #Differences from nlopt4r and NLopt

    The comparison below is based on the nlopt4r source at revision e5a4de8. Matching method names do not guarantee identical iterations or results.

    • API and data types: nlopt4r uses Rust traits such as Evaluator, option structs, Bounds, and nalgebra vectors and matrices. nlopt4m instead uses MoonBit callbacks, labeled options, and arrays; it is not source-compatible. Its shared linear-algebra routines are internal, with solve_dense exposed for checked square systems.
    • Callbacks and reporting: gradient-based nlopt4m solvers generally request value and gradient together, including line-search trials. EvaluationContext separately supports value-only and optional-gradient calls. The result and work-count types differ from nlopt4r's Solution and EvaluationCounts.
    • Solver behavior: nlopt4m's projected gradient rejects an infeasible initial point by default and uses the feasible-direction gradient norm. Set project_initial=true and unit_step_mapping=true for the corresponding nlopt4r behaviors. nlopt4m provides SQP with restoration, but not nlopt4r's separate constrained::minimize(Method::Sqp) entry point without restoration. It also has no Constraints::from_nonpositive helper; pass inequalities using g(x) >= 0.
    • Error recovery: minimize(..., recover_errors=true) retains a completed local iterate after a successful initial evaluation, and EvaluationContext can retain a best point. Other solvers do not all return equivalent checkpoints. In particular, sqp_with_restoration returns successful restoration events on success, but does not expose nlopt4r's SqpError with failed restoration history and the last constrained multiplier state.
    • Benchmark tools: the 35-problem catalog and all seven benchmark algorithm choices are available, along with upstream-shaped record import and export. Six algorithms run by default; external-pattern is opt-in. The CLI writes to standard output instead of nlopt4r's --output file option, and existing records are summarized by a separate native command. The native NLopt comparison executable and a CLI for replaying a saved record are not included. Portable environment fields may be marked unavailable.
    • NLopt: this project does not expose the NLopt C API or implement its complete algorithm catalog. For example, COBYLA, BOBYQA, DIRECT, and MMA are not implemented. The available SQP and augmented-Lagrangian solvers should not be assumed to reproduce NLopt's corresponding implementations.

    #Next stage

    The planned next stage is to broaden NLopt algorithm coverage while keeping the solver core pure MoonBit:

    • Add COBYLA for derivative-free constrained optimization and BOBYQA for derivative-free, box-constrained local optimization.
    • Add DIRECT for bounded global optimization and MMA for gradient-based optimization with nonlinear inequalities.
    • Compare the existing SQP and augmented-Lagrangian methods with NLopt's counterparts, document behavioral differences, and improve compatibility where appropriate.
    • Add tests and benchmark comparisons for the new methods, including constraints, stopping conditions, and evaluation budgets.
    • Evaluate an optional NLopt C-compatible interface separately; it must not require a native NLopt optimizer dependency in the solver core.

    #Quick start

    ///|
    test {
    let result = @nlopt4m.minimize(
    x => {
    let a = x[0] - 3.0
    let b = x[1] + 2.0
    (0.5 * (a * a + b * b), [a, b])
    },
    [0.0, 0.0],
    algorithm=Bfgs,
    )
    assert_true(result.termination is GradientTolerance)
    assert_true((result.x[0] - 3.0).abs() < 1.0e-6)
    assert_true((result.x[1] + 2.0).abs() < 1.0e-6)
    }

    The callback supplies both value and analytic gradient, including for line-search trials. Steepest descent is the default. Callback errors normally propagate; minimize(..., recover_errors=true) can retain the last completed local iterate after a failure. Budget and iteration stops are not convergence. Dense quasi-Newton methods use quadratic space; L-BFGS uses linear space per stored update.

    The projected-gradient solver defaults to a feasible-direction gradient norm. unit_step_mapping=true and project_initial=true select the corresponding upstream behaviors. Equality-constrained Newton methods require a Lagrangian Hessian and reject inequalities. Population search supports observers and cancellation; EvaluationContext exposes checked evaluations and best-point recovery for custom algorithms. Optional step and value stagnation tests do not certify convergence.

    #Source layout and imports

    MoonBit compiles each directory with a moon.pkg as a package; the root package re-exports the solver functions and types for the quick-start API. Tests for each family live alongside its implementation.

    DirectoryContents
    local/Gradient, quasi-Newton, Newton-CG and trust-region solvers
    bounded/Projected gradient
    search/Value-only local searches, population searches and evaluation context
    constrained/Quadratic and nonlinear constrained solvers
    least_squares/, scalar/Residual-based and one-dimensional solvers
    line_search/, linear_algebra/Reusable line searches and dense solve
    common/, internal/Shared public types and internal numerical helpers
    benchmarks/, tests/api/Benchmark catalog/commands and facade integration tests

    Callers may import the root package or a family package such as qchen-fdii-cardc/nlopt4m/local. Re-exported enum variants work when their type is inferred or qualified, for example @nlopt4m.Algorithm::Lbfgs(10). After the package split, package-qualified variant shortcuts such as @nlopt4m.Lbfgs(10) and @nlopt4m.NewtonLagrange are not available; use the type-qualified form.

    #Benchmarks

    Run moon bench --target native --release for the current sphere microbenchmarks. A preliminary seeded benchmark runner with a 35-problem catalog and a six-problem smoke suite is available with moon run benchmarks/cmd --target native --release; it emits JSONL and -- --summary emits grouped evaluation and elapsed-time ERT instead. Use -- --catalog to run all 35 problems, optionally combined with --summary. By default each problem uses six algorithms and three seeds; selectors can change both. Add --shift and/or --rotate to create recorded affine instances using a fixed instance seed independent of solver seeds. Instance, noise, and benchmark global-solver streams follow the Rust benchmark's ChaCha8 protocol. Recorded transformation coefficients remain authoritative for exact replay. Timings use a monotonic clock. Add for example --noise gaussian --noise-level 0.01 --noise-seed 17 for independent observation noise; uniform and laplace are also supported. Target hits use noise-free values, and noisy recommendations are scored separately outside the solver budget. Select individual experiments with, for example, --problem sphere --algorithms lbfgs,de --seeds 0..3 --dimension 4--budget-per-dimension 1000. The smooth and global suites are also available via --suite. The optional external-pattern benchmark exercises EvaluationContext with a deterministic midpoint start; select it with --algorithms external-pattern. Use --csv to emit CSV rows with an embedded JSON record instead of JSONL. The embedded record remains nlopt4m's partial schema, not nlopt4r's schema. --upstream-records emits the nlopt4r record shape in JSONL, or in CSV when combined with --csv. Environment fields that cannot be collected portably are marked unavailable; rustc is marked not applicable. Combined with --summary, it emits upstream-shaped summaries as JSONL. Summaries keep different derivative modes and initialization streams separate; summarize_grouped also groups mixed run sets in first-seen order. The benchmark package can read and validate upstream JSONL or CSV with read_upstream_jsonl or read_upstream_csv, and group imported records by environment with summarize_imported. Imported counts must fit Int32, and dimensions are limited to 128. To summarize an existing file on the native target, run moon run benchmarks/summarize --target native -- records.jsonl (or .csv). Use --reference-start to match the initial-point stream of nlopt4r's native NLopt comparison harness instead of its regular benchmark runner. The upstream record schema cannot record this choice, so keep those runs separate from ordinary benchmark records when summarizing them in nlopt4r. Solver failures are included in run records and cause a nonzero exit after all selected runs finish. This runner does not bundle native NLopt.

    #Development and release

    To browse the local API documentation, run moon doc --serve and open http://127.0.0.1:3000/index.html#/qchen-fdii-cardc/nlopt4m/members.

    Run moon fmt, moon check --target all --deny-warn, and moon test --target all --deny-warn. moon test --target all --release also checks optimized builds. The package can be validated with moon publish --dry-run; actual publication is a separate action.

    #License

    Apache-2.0; see LICENSE.

    Algorithm

    Algorithm for unconstrained minimization.

    ArmijoStep

    A trial accepted by Armijo sufficient-decrease backtracking.

    ConstrainedEvaluation

    A checked objective, gradient, and constraints at the same point.

    ConstrainedSolution

    Nonlinear constrained result. Multipliers use L = f - mu'h - lambda'g.

    Constraints

    Values and row-oriented Jacobians for constraints h(x)=0 and g(x)>=0.

    EqualityNewtonMethod

    Equality-constrained exact-Hessian method.

    EvaluatedPoint

    A checked value-only point retained by an evaluation context.

    EvaluationContext

    Evaluation budget with best-so-far recovery and observation.

    EvaluationContextError

    A stopped context rejects further evaluations; a search failure can carry the original error and a best-point checkpoint.

    GlobalSolution

    Result of a seeded population search. Generations count fully completed generations; evaluations include initialization and partial generations. Diversity is the maximum normalized coordinate range of evaluated points in the current population.

    LineSearch

    Line-search strategy for local gradient-based minimization.

    LocalCheckpoint

    Last completed local iterate retained when a search fails.

    LocalSearchFailure

    An opt-in local-solver failure with its underlying error and checkpoint.

    NewtonCgSolution

    A matrix-free Newton-CG result, including the number of Hessian-vector products. Objective evaluation budgets do not include these products.

    OptimizeError

    Errors detected by the optimizer; errors raised by callbacks propagate.

    QuadraticSolution

    A quadratic-program result. Multipliers use the convention L = f - mu * (A x - b).

    RestorationEvent

    A successful feasibility-restoration attempt.

    ScalarMethod

    Scalar interval-search method.

    ScalarSolution

    Best evaluated point and remaining interval. When an original endpoint is best, the reported interval is extended to include it.

    ScalarTermination

    Termination of a bounded scalar minimization.

    SearchControl

    An observer's instruction after a successful objective evaluation.

    SearchEvent

    A checked value-only evaluation, after updating the best-so-far value.

    SearchSolution

    Best point evaluated by a value-only search. Iterations count completed polls or simplex iterations; evaluations include all attempted trials.

    SearchTermination

    A value-only search stops on a target, a limit, or mesh stagnation. Stagnation does not certify an optimum.

    Solution

    A completed optimization run. iterations counts algorithm iterations (accepted steps for line-search methods); evaluations counts every objective callback, including rejected trials. gradient_norm is projected for bounded projected-gradient runs and column-scaled for Levenberg-Marquardt.

    SqpSolution

    SQP result and successful restoration attempts.

    SteihaugStep

    Approximate trust-region step and model value.

    SteihaugTermination

    Why a Steihaug quadratic-model solve stopped.

    Termination

    Why an optimization run stopped. Stagnation and limit stops do not certify stationarity.

    Tolerance

    Mixed absolute and relative stagnation tolerance. At least one component must be positive; a stagnation stop is not a convergence certificate.

    TrustRegionCgSolution

    A matrix-free trust-region result and its Hessian-vector product count.

    TrustRegionSolution

    A dense trust-region result and its Hessian evaluation count.

    TrustRegionStep

    Solution of a dense trust-region quadratic model.

    WolfeStep

    A strong-Wolfe trial, including its already evaluated gradient.

    armijo

    fn armijo(value : Double, gradient : ArrayView[Double], direction : ArrayView[Double], objective : (Double) -> Double raise, initial_step? : Double, contraction? : Double, sufficient_decrease? : Double, max_evaluations? : Int) ->
    ArmijoStep
    raise

    Backtrack along a descent direction using a value-only trial callback. The caller supplies the origin value and gradient; they are not included in the returned evaluation count. Callback errors propagate.

    test {
    let step = @line_search.armijo(4.0, [-4.0], [1.0], a => (a - 2.0) * (a - 2.0))
    assert_true(step.value < 4.0)
    }

    augmented_lagrangian

    fn augmented_lagrangian(objective : (ArrayView[Double]) ->
    ConstrainedEvaluation
    raise, initial : ArrayView[Double], gradient_tolerance? : Double, feasibility_tolerance? : Double, max_iterations? : Int, max_evaluations? : Int, max_inner_iterations? : Int, initial_penalty? : Double, step_tolerance? :
    Tolerance
    , value_tolerance? :
    Tolerance
    ) ->
    ConstrainedSolution
    raise

    Minimize a smooth objective with Powell-Hestenes-Rockafellar augmented Lagrangian iterations and dense BFGS inner solves. The callback computes objective, gradient, constraints and Jacobians together on every evaluation. Equalities are zero and inequalities are nonnegative.

    Infeasible starts are allowed. KKT termination requires stationarity, feasibility and complementarity; it does not certify a global minimum. Inner evaluations share the strict outer budget. On budget exhaustion the returned point is the most recent completed outer checkpoint.

    test {
    let result = @constrained.augmented_lagrangian(
    x => {
    value: x[0] * x[0],
    gradient: [2.0 * x[0]],
    constraints: {
    equalities: [x[0] - 1.0],
    inequalities: [],
    equality_jacobian: [[1.0]],
    inequality_jacobian: [],
    },
    },
    [0.0],
    )
    assert_true(result.solution.termination is KktTolerance)
    }

    differential_evolution

    fn differential_evolution(objective : (ArrayView[Double]) -> Double raise, lower : ArrayView[Double], upper : ArrayView[Double], seed? : UInt64, population_size? : Int, max_generations? : Int, max_evaluations? : Int, weight? : Double, crossover? : Double, rust_compatible_rng? : Bool, initial_population? : Array[Array[Double]], target_value? : Double, observer? : (
    SearchEvent
    ) ->
    SearchControl
    raise) ->
    GlobalSolution
    raise

    Seeded synchronous DE/rand/1/bin on a finite box. The optional initial population must contain exactly population_size feasible points. Mutants outside the box are repaired halfway between the violated bound and the target. At least one crossover coordinate is forced.

    The returned best point includes partial initialization and generations; reaching a target does not certify a global optimum. The seed initializes MoonBit's ChaCha8 generator by default. Set rust_compatible_rng=true to use the Rust crate's seed expansion and sampling instead. The optional observer can stop after any successful evaluation; cancellation takes precedence over a target or budget reached at the same evaluation.

    test {
    let result = @search.differential_evolution(
    x => x[0] * x[0],
    [-1.0],
    [1.0],
    seed=42UL,
    max_evaluations=1000,
    target_value=1.0e-6,
    )
    assert_true(result.termination is TargetReached)
    }

    directional_difference

    fn directional_difference(context :
    EvaluationContext
    , x : ArrayView[Double], direction : ArrayView[Double], step : Double) -> Double raise

    Central directional difference using two value-only context evaluations. The direction is not normalized and trials are not projected onto bounds. A stop or error on the second probe leaves the first evaluation charged.

    test {
    let context = @search.EvaluationContext::new(x => x[0] * x[0], 1)
    let derivative = @search.directional_difference(context, [2.0], [1.0], 0.001)
    assert_true((derivative - 4.0).abs() < 1.0e-9)
    assert_eq(context.evaluations(), 2)
    }

    equality_constrained_quadratic

    fn equality_constrained_quadratic(hessian : ArrayView[Array[Double]], linear : ArrayView[Double], equalities : ArrayView[Array[Double]], equality_rhs : ArrayView[Double]) ->
    QuadraticSolution
    raise
    OptimizeError

    Solve a dense, convex equality-constrained quadratic program: minimize x' H x / 2 + c' x subject to A x = b.

    The symmetric positive-semidefinite Hessian and constraint rows must be finite and dimensionally consistent. Consistent redundant constraints and singular systems use a minimum-norm KKT solve. An inconsistent or numerically unsolvable KKT system raises an error.

    test {
    let result = @constrained.equality_constrained_quadratic(
    [[1.0, 0.0], [0.0, 1.0]],
    [-2.0, -4.0],
    [[1.0, 1.0]],
    [3.0],
    )
    assert_true(result.solution.termination is KktTolerance)
    assert_true(
    (result.solution.x[0] + result.solution.x[1] - 3.0).abs() < 1.0e-8,
    )
    }

    equality_newton

    fn equality_newton(objective : (ArrayView[Double]) ->
    ConstrainedEvaluation
    raise, lagrangian_hessian : (ArrayView[Double], ArrayView[Double]) -> Array[Array[Double]] raise, initial : ArrayView[Double], algorithm? :
    EqualityNewtonMethod
    , gradient_tolerance? : Double, feasibility_tolerance? : Double, max_iterations? : Int, max_evaluations? : Int, step_tolerance? :
    Tolerance
    , value_tolerance? :
    Tolerance
    ) ->
    ConstrainedSolution
    raise

    Solve equality-constrained problems using the exact Lagrangian Hessian. The Hessian callback receives the current point and equality multipliers, using L = f - mu'h. LagrangeSqp stabilizes the Hessian with A'A / 3.1. Inequality constraints are rejected. Objective callbacks, including rejected line-search trials, share the evaluation budget. KKT convergence does not certify that the stationary point is a minimum.

    test {
    let result = @constrained.equality_newton(
    x => {
    value: x[0] * x[0],
    gradient: [2.0 * x[0]],
    constraints: {
    equalities: [x[0] - 1.0],
    inequalities: [],
    equality_jacobian: [[1.0]],
    inequality_jacobian: [],
    },
    },
    (_, _) => [[2.0]],
    [0.0],
    )
    assert_true(result.solution.termination is KktTolerance)
    }

    levenberg_marquardt

    fn levenberg_marquardt(objective : (ArrayView[Double]) -> (Array[Double], Array[Array[Double]]) raise, initial : ArrayView[Double], gradient_tolerance? : Double, max_iterations? : Int, max_evaluations? : Int, initial_damping? : Double, minimum_damping? : Double, acceptance_ratio? : Double, max_damping_trials? : Int, step_tolerance? :
    Tolerance
    , value_tolerance? :
    Tolerance
    ) ->
    Solution
    raise

    Minimize half the squared residual norm with adaptive damped QR steps. The callback returns a nonempty residual vector and a row-major Jacobian with one row per residual and one column per variable. Both are evaluated together on every trial, including rejected trials.

    The reported gradient norm is column-scaled stationarity. Convergence does not imply zero residual or a global minimum. Callback errors propagate.

    test {
    let result = @least_squares.levenberg_marquardt(
    x => ([x[0] - 1.0, 2.0 * x[0] - 2.0], [[1.0], [2.0]]),
    [0.0],
    )
    assert_true(result.termination is GradientTolerance)
    assert_true((result.x[0] - 1.0).abs() < 1.0e-5)
    }

    minimize

    fn minimize(objective : (ArrayView[Double]) -> (Double, Array[Double]) raise, initial : ArrayView[Double], gradient_tolerance? : Double, max_iterations? : Int, max_evaluations? : Int, algorithm? :
    Algorithm
    , line_search? :
    LineSearch
    , step_tolerance? :
    Tolerance
    , value_tolerance? :
    Tolerance
    , recover_errors? : Bool) ->
    Solution
    raise

    Minimize a differentiable function using the selected local method and Armijo backtracking by default, optionally using strong Wolfe. The default algorithm is steepest descent. The callback returns the value and analytic gradient at x. Initial points and callback results must be finite, and the gradient must have the same dimension as initial. Callback errors are propagated.

    The returned point is a copy; initial is not modified. A budget exit is not convergence. The method is local and does not handle constraints. Optional step and objective tolerances report stagnation, not convergence. With recover_errors=true, errors after the first valid evaluation include the last completed iterate and the number of attempted objective evaluations.

    test {
    let solution = @local.minimize(
    x => (0.5 * (x[0] - 3.0) * (x[0] - 3.0), [x[0] - 3.0]),
    [0.0],
    )
    assert_true(solution.termination is GradientTolerance)
    assert_true((solution.x[0] - 3.0).abs() < 1.0e-6)
    }

    minimize_scalar

    fn minimize_scalar(objective : (Double) -> Double raise, lower : Double, upper : Double, absolute_tolerance? : Double, relative_tolerance? : Double, max_iterations? : Int, max_evaluations? : Int, algorithm? :
    ScalarMethod
    ) ->
    ScalarSolution
    raise

    Minimize a continuous unimodal scalar function on a closed finite interval by golden-section search or safeguarded parabolic interpolation. Both endpoints are candidates. IntervalTolerance describes the reduced interval before any extension to include the best endpoint, not an unconditional global-optimality proof. The interval test uses absolute_tolerance + relative_tolerance *max(abs(lower), abs(upper)), with the current reduced endpoints. All objective calls count against the strict evaluation limit.

    test {
    let result = @scalar.minimize_scalar(x => (x - 0.4) * (x - 0.4), -1.0, 2.0)
    assert_true(result.termination is IntervalTolerance)
    assert_true((result.x - 0.4).abs() < 1.0e-6)
    }

    nelder_mead

    fn nelder_mead(objective : (ArrayView[Double]) -> Double raise, initial : ArrayView[Double], lower : ArrayView[Double], upper : ArrayView[Double], initial_step? : Double, step_tolerance? : Double, max_iterations? : Int, max_evaluations? : Int, target_value? : Double) ->
    SearchSolution
    raise

    Minimize a value-only objective over a finite box using a projected Nelder-Mead simplex. Each free coordinate contributes one simplex vertex; fixed coordinates are allowed. The inputs are copied and never modified.

    The returned best point includes trials evaluated during an incomplete simplex initialization or iteration. Small or collapsed simplices report Stagnated, not convergence or global optimality.

    test {
    let result = @search.nelder_mead(
    x => (x[0] - 0.25) * (x[0] - 0.25),
    [0.0],
    [-1.0],
    [1.0],
    target_value=1.0e-8,
    )
    assert_true(result.termination is TargetReached)
    }

    newton_cg

    fn newton_cg(objective : (ArrayView[Double]) -> (Double, Array[Double]) raise, hessian_vector : (ArrayView[Double], ArrayView[Double]) -> Array[Double] raise, initial : ArrayView[Double], gradient_tolerance? : Double, max_iterations? : Int, max_evaluations? : Int, cg_tolerance? : Double, max_cg_iterations? : Int, line_search? :
    LineSearch
    , step_tolerance? :
    Tolerance
    , value_tolerance? :
    Tolerance
    ) ->
    NewtonCgSolution
    raise

    Minimize a smooth unbounded function using truncated matrix-free Newton-CG and Armijo backtracking by default, optionally using strong Wolfe. The second callback returns H(x) * direction and must represent a symmetric linear operator at each point. Nonpositive inner curvature truncates CG; the outer method still requires a descent step.

    Hessian-vector products do not consume the objective evaluation budget.

    test {
    let result = @local.newton_cg(
    x => (x[0] * x[0], [2.0 * x[0]]),
    (_, v) => [2.0 * v[0]],
    [3.0],
    )
    assert_true(result.solution.termination is GradientTolerance)
    }

    particle_swarm

    fn particle_swarm(objective : (ArrayView[Double]) -> Double raise, lower : ArrayView[Double], upper : ArrayView[Double], seed? : UInt64, population_size? : Int, max_generations? : Int, max_evaluations? : Int, inertia? : Double, cognitive? : Double, social? : Double, velocity_limit? : Double, rust_compatible_rng? : Bool, initial_population? : Array[Array[Double]], target_value? : Double, observer? : (
    SearchEvent
    ) ->
    SearchControl
    raise) ->
    GlobalSolution
    raise

    Seeded synchronous global-best particle swarm on a finite box. Velocities start at zero and are limited to velocity_limit times the coordinate's box width. A particle that crosses a bound is clamped and its velocity in that coordinate is reset. All particles in a generation use the same best point from the previous generation.

    The returned best point includes partial initialization and generations; reaching a target does not certify a global optimum. Set rust_compatible_rng=true for Rust-compatible random sampling. The optional observer can stop after any successful evaluation; cancellation takes precedence over a target or budget reached at the same evaluation.

    test {
    let result = @search.particle_swarm(
    x => x[0] * x[0],
    [-1.0],
    [1.0],
    seed=42UL,
    max_evaluations=1000,
    target_value=1.0e-6,
    )
    assert_true(result.termination is TargetReached)
    }
    fn pattern_search(objective : (ArrayView[Double]) -> Double raise, initial : ArrayView[Double], lower : ArrayView[Double], upper : ArrayView[Double], initial_step? : Double, step_tolerance? : Double, max_iterations? : Int, max_evaluations? : Int, target_value? : Double) ->
    SearchSolution
    raise

    Minimize a value-only objective over a finite box by coordinate polling. initial_step and step_tolerance are fractions of each box width. Fixed coordinates are allowed. The inputs are copied and never modified.

    The returned best point may be from an unfinished poll. A target value is not a global-optimality certificate, and a small mesh is not convergence. Callback errors propagate and non-finite objective values raise an error.

    test {
    let result = @search.pattern_search(
    x => (x[0] - 0.25) * (x[0] - 0.25),
    [0.0],
    [-1.0],
    [1.0],
    target_value=1.0e-8,
    )
    assert_true(result.termination is TargetReached)
    assert_true(result.value <= 1.0e-8)
    }

    projected_gradient

    fn projected_gradient(objective : (ArrayView[Double]) -> (Double, Array[Double]) raise, initial : ArrayView[Double], lower : ArrayView[Double], upper : ArrayView[Double], gradient_tolerance? : Double, max_iterations? : Int, max_evaluations? : Int, step_tolerance? :
    Tolerance
    , value_tolerance? :
    Tolerance
    , unit_step_mapping? : Bool, project_initial? : Bool) ->
    Solution
    raise

    Minimize a differentiable function on a finite box using projected gradient descent and Armijo backtracking. The callback provides both the value and gradient. Fixed coordinates are supported.

    gradient_norm is the norm of the gradient projected onto feasible coordinate directions; GradientTolerance means first-order stationarity, not necessarily a minimum. This method is not L-BFGS-B. Set unit_step_mapping=true to use the norm and direction of the unit-step gradient mapping instead. Set project_initial=true to project a finite initial point into the box before its first objective evaluation.

    test {
    let result = @bounded.projected_gradient(
    x => ((x[0] - 2.0) * (x[0] - 2.0), [2.0 * (x[0] - 2.0)]),
    [0.0],
    [-1.0],
    [1.0],
    )
    assert_eq(result.x, [1.0])
    assert_true(result.termination is GradientTolerance)
    }

    projected_gradient_norm

    fn projected_gradient_norm(x : ArrayView[Double], gradient : ArrayView[Double], lower : ArrayView[Double], upper : ArrayView[Double]) -> Double raise
    OptimizeError

    Euclidean norm of the unit-step gradient mapping x - project(x - gradient) for a feasible point in a finite box. Fixed coordinates contribute zero.

    test {
    let norm = @bounded.projected_gradient_norm([0.9], [-4.0], [0.0], [1.0])
    assert_true((norm - 0.1).abs() < 1.0e-12)
    }

    quadratic_minimize

    fn quadratic_minimize(hessian : ArrayView[Array[Double]], linear : ArrayView[Double], equalities : ArrayView[Array[Double]], equality_rhs : ArrayView[Double], inequalities : ArrayView[Array[Double]], inequality_rhs : ArrayView[Double], initial : ArrayView[Double], tolerance? : Double, max_iterations? : Int, max_evaluations? : Int) ->
    QuadraticSolution
    raise
    OptimizeError

    Solve a dense convex quadratic program with equalities Ae x = be and inequalities Ai x >= bi. The initial point may be infeasible; a phase-I active-set problem searches for feasibility. Multipliers use L = f - mu'(Ae x - be) - lambda'(Ai x - bi).

    The two phases each have an iteration allowance and share the evaluation budget. This is not a general unboundedness-certifying linear-programming solver; singular, inconsistent, or stalled subproblems raise errors.

    test {
    let result = @constrained.quadratic_minimize(
    [[1.0]],
    [-2.0],
    [],
    [],
    [[1.0], [-1.0]],
    [1.0, -1.5],
    [-3.0],
    )
    assert_true(result.solution.termination is KktTolerance)
    assert_true((result.solution.x[0] - 1.5).abs() < 1.0e-6)
    }

    solve_dense

    fn solve_dense(matrix : ArrayView[Array[Double]], rhs : ArrayView[Double]) -> Array[Double] raise
    OptimizeError

    Solve a finite square linear system using checked Householder QR. Inputs are not modified; singular, numerically rank-deficient or insufficiently accurate systems raise a numerical error.

    test {
    let x = @linear_algebra.solve_dense([[3.0, 1.0], [1.0, 2.0]], [9.0, 8.0])
    assert_true((x[0] - 2.0).abs() < 1.0e-12)
    assert_true((x[1] - 3.0).abs() < 1.0e-12)
    }

    sqp_with_restoration

    fn sqp_with_restoration(objective : (ArrayView[Double]) ->
    ConstrainedEvaluation
    raise, initial : ArrayView[Double], gradient_tolerance? : Double, feasibility_tolerance? : Double, max_iterations? : Int, max_evaluations? : Int, max_subproblem_iterations? : Int, max_subproblem_evaluations? : Int, max_restoration_iterations? : Int, restoration_damping? : Double, restoration_reduction? : Double, step_tolerance? :
    Tolerance
    , value_tolerance? :
    Tolerance
    ) ->
    SqpSolution
    raise

    Sequential quadratic programming with damped BFGS and feasibility restoration when the linearized constraints are inconsistent. Constraints use h(x)=0, g(x)>=0, and multipliers use L = f - mu'h - lambda'g. Callback evaluations, including restoration and rejected line-search trials, share the strict objective budget. Quadratic and restoration models share a synthetic evaluation budget, separate from the objective budget.

    test {
    let result = @constrained.sqp_with_restoration(
    x => {
    value: x[0] * x[0],
    gradient: [2.0 * x[0]],
    constraints: {
    equalities: [x[0] - 1.0],
    inequalities: [],
    equality_jacobian: [[1.0]],
    inequality_jacobian: [],
    },
    },
    [0.0],
    )
    assert_true(result.constrained.solution.termination is KktTolerance)
    }

    steihaug

    fn steihaug(gradient : ArrayView[Double], radius : Double, hessian_vector : (ArrayView[Double]) -> Array[Double] raise, relative_tolerance? : Double, max_iterations? : Int) ->
    SteihaugStep
    raise

    Approximately minimize g'p + p'Hp/2 within a Euclidean trust region. The callback applies a symmetric Hessian to a direction. The reported product count equals the number of inner iterations. A zero gradient returns zero without probing for negative curvature.

    test {
    let result = @local.steihaug([2.0], 1.0, v => [v[0]])
    assert_eq(result.step, [-1.0])
    assert_true(result.termination is Boundary)
    }

    strong_wolfe

    fn strong_wolfe(value : Double, gradient : ArrayView[Double], direction : ArrayView[Double], objective : (Double) -> (Double, Array[Double]) raise, sufficient_decrease? : Double, curvature? : Double, initial_step? : Double, maximum_step? : Double, max_evaluations? : Int) ->
    WolfeStep
    raise

    Find a positive step satisfying sufficient decrease and strong curvature. The callback receives the step length and returns the value and gradient at that trial. Its evaluations are counted separately from the supplied origin. Callback errors and exhausted or unrepresentable brackets are reported; an unchecked trial is never returned.

    test {
    let step = @line_search.strong_wolfe(4.0, [-4.0], [1.0], a => {
    ((a - 2.0) * (a - 2.0), [2.0 * (a - 2.0)])
    })
    assert_true(step.value < 4.0)
    }

    trust_region

    fn trust_region(objective : (ArrayView[Double]) -> (Double, Array[Double]) raise, hessian : (ArrayView[Double]) -> Array[Array[Double]] raise, initial : ArrayView[Double], gradient_tolerance? : Double, max_iterations? : Int, max_evaluations? : Int, initial_radius? : Double, max_radius? : Double, acceptance_ratio? : Double, step_tolerance? :
    Tolerance
    , value_tolerance? :
    Tolerance
    ) ->
    TrustRegionSolution
    raise

    Minimize a smooth unbounded function using dense spectral trust-region steps. The Hessian callback must return a finite symmetric matrix matching the initial dimension. Hessian evaluations do not consume the objective budget; rejected trial points do. Convergence is first-order stationarity, not a certificate of a local or global minimum.

    test {
    let result = @local.trust_region(
    x => (x[0] * x[0], [2.0 * x[0]]),
    _ => [[2.0]],
    [3.0],
    )
    assert_true(result.solution.termination is GradientTolerance)
    }

    trust_region_cg

    fn trust_region_cg(objective : (ArrayView[Double]) -> (Double, Array[Double]) raise, hessian_vector : (ArrayView[Double], ArrayView[Double]) -> Array[Double] raise, initial : ArrayView[Double], gradient_tolerance? : Double, max_iterations? : Int, max_evaluations? : Int, initial_radius? : Double, max_radius? : Double, acceptance_ratio? : Double, cg_tolerance? : Double, max_cg_iterations? : Int, step_tolerance? :
    Tolerance
    , value_tolerance? :
    Tolerance
    ) ->
    TrustRegionCgSolution
    raise

    Minimize a smooth unbounded function using a matrix-free Steihaug-CG trust region. The Hessian-vector callback must be a symmetric linear operator at each point. Rejected trials count as iterations and consume the objective budget.

    test {
    let result = @local.trust_region_cg(
    x => (x[0] * x[0], [2.0 * x[0]]),
    (_, v) => [2.0 * v[0]],
    [3.0],
    )
    assert_true(result.solution.termination is GradientTolerance)
    }

    trust_region_subproblem

    fn trust_region_subproblem(gradient : ArrayView[Double], hessian : ArrayView[Array[Double]], radius : Double) ->
    TrustRegionStep
    raise
    OptimizeError

    Globally minimize g'd + d'Bd/2 subject to ||d|| <= radius, using a dense symmetric eigensolve. Indefinite models and the hard case where the gradient is orthogonal to the minimum eigenspace are supported. The input Hessian must be finite and symmetric; no callback or budget is involved.

    test {
    let result = @local.trust_region_subproblem(
    [2.0, 0.0],
    [[1.0, 0.0], [0.0, 1.0]],
    1.0,
    )
    assert_true((result.step[0] + 1.0).abs() < 1.0e-8)
    }

    Source Files