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

Introduction

This book documents the mathematics, interface usage and measured results of nlopt4r, a pure-Rust nonlinear optimization library. The crate version is 1.0.1, the minimum Rust version is 1.88, and the edition is 2024. Every solver takes dynamically sized f64 vectors; the runtime dependencies are the Rust crates nalgebra, rand and rand_chacha.

The book describes the published 1.0.1 API. Code excerpts, defaults and command examples were checked against the 1.0.1 source.

Publication and API documentation

The crate is published on crates.io:

[dependencies]
nlopt4r = "1.0.1"

The generated API documentation is at https://docs.rs/nlopt4r/1.0.1/nlopt4r/. The help chapters link to the corresponding item pages on docs.rs.

Book structure

The book has two parts and 22 chapters:

  • Part I: Theory (chapters 1–13) presents the mathematical models, update formulas, stopping criteria and reference baselines of each solver family.
  • Part II: Software Help (chapters 14–22) presents function signatures, option defaults, report fields, error categories and runnable examples.

Chapters correspond one-to-one across the two parts by solver family. Each theory chapter ends with a “Software interface” section that lists the family’s entry points and links to the matching help chapter; each help chapter opens with a “Theory background” section that links back.

Solver overview

Problem classEntry pointsRequired derivatives
Smooth unconstrained, small/mediumminimize + MethodGradient; Newton variants also a Hessian
Smooth unconstrained, largelocal::lbfgsGradient
Hessian-vector products availablelocal::newton_cg, local::trust_region_cgGradient and HVP
Small dense trust regiontrust_region::minimizeGradient and Hessian
Finite box, gradient availablebounded::projected_gradientGradient
Finite box, derivative-free local searchderivative_free::{pattern_search, nelder_mead}Objective values
Finite box, multimodal global searchglobal::{differential_evolution, particle_swarm}Objective values
Residuals and Jacobiansleast_squares::levenberg_marquardt_with_optionsJacobian
Convex quadratic programmingquadratic::minimizeModel data
Nonlinear constraintsconstrained::sqp_with_restoration, constrained::augmented_lagrangianGradient and constraint Jacobians

Chapters 16–19 contain the complete entry-point list, parameters and examples.

Notation

The book uses one notation set:

  • \(x\in\mathbb{R}^n\) is the decision variable, \(f(x)\) the objective, \(g=\nabla f(x)\) the gradient and \(H=\nabla^2 f(x)\) the Hessian.
  • The standard constraint form is \(h(x)=0\) (equalities) and \(g(x)\ge0\) (inequalities); each constraint occupies one Jacobian row.
  • The Lagrangian is \(L(x,\mu,\lambda)=f(x)-\mu^\top h(x)-\lambda^\top g(x)\) with \(\lambda\ge0\).
  • Least squares minimizes \(f(x)=\lVert r(x)\rVert^2/2\), with gradient \(g=J^\top r\) and Jacobian \(J\) of shape “residuals × variables”.
  • Quadratic programming minimizes \(x^\top Hx/2+c^\top x\) subject to \(A_e x=b_e\) and \(A_i x\ge b_i\).
  • EvaluationCounts records objective, gradient, Hessian, constraint, residual, Jacobian and subproblem-model calls in separate fields.

Site and language switching

The Chinese book occupies the site root and the English book occupies /en/. The English button on the right of the menu bar opens the current chapter in English; the 中文 button on an English page returns to the matching Chinese page. Chapter files correspond one-to-one, with identical filenames.

Local build and deployment

The site builds with mdBook 0.5.4:

cargo install mdbook --version 0.5.4 --locked
mdbook build books/zh && mdbook build books/en
python3 -m http.server 8000 -d book   # open http://localhost:8000/

Deployment uses a manual GitHub Actions run: Actions → Deploy nlopt4r book to GitHub Pages → Run workflow. The workflow builds both books and publishes book/. Chapter 22 documents the local wrkflw rehearsal of the build job.

Running the examples

The repository ships two runnable examples; run them from a repository checkout, because a downstream application that depends on the crates.io package does not provide cargo run --example. The measured benchmark tables in chapter 13 come from the separate nlopt4r-bench harness, not from these examples:

cargo run --example rosenbrock
cargo run --example global_search

rosenbrock minimizes the two-dimensional Rosenbrock function with BFGS; global_search compares DE and PSO on a three-dimensional sphere. Both examples check known solutions or target values and report a nonzero exit code when a check fails.

The published API reference is at https://docs.rs/nlopt4r/1.0.1/nlopt4r/; cargo doc -p nlopt4r --no-deps --open generates the same documentation locally.

1. Optimization Problems and Optimality Conditions

This chapter fixes the standard problem forms, first- and second-order optimality conditions, and the convergence quantities reported by each solver family in nlopt4r. Later chapters build the algorithms on these definitions.

1.1 Problem forms

Every entry point in nlopt4r minimizes. Maximization uses a negated objective and its derivatives.

Problem classStandard formMain entry points
Unconstrained\(\min f(x),\ x\in\mathbb R^n\)minimize, local::lbfgs, local::newton_cg
Box-constrained\(\min f(x),\ l\le x\le u\)bounded::projected_gradient, derivative_free::*
Nonlinear constraints\(\min f(x),\ h(x)=0,\ g(x)\ge 0\)constrained::{sqp_with_restoration, augmented_lagrangian}
Least squares\(\min \tfrac12|r(x)|^2\)least_squares::*
Quadratic programming\(\min \tfrac12 x^\top Hx+c^\top x,\ A_e x=b_e,\ A_i x\ge b_i\)quadratic::*

The book uses this notation throughout:

  • \(f:\mathbb R^n\to\mathbb R\) is the objective, \(g=\nabla f(x)\), \(H=\nabla^2 f(x)\);
  • \(h(x)\in\mathbb R^{m_e}\) holds the equalities and \(g(x)\in\mathbb R^{m_i}\) the inequalities;
  • constraint Jacobians have shape “constraints × variables”, one row per constraint;
  • the Lagrangian is \(L(x,\mu,\lambda)=f(x)-\mu^\top h(x)-\lambda^\top g(x)\) with \(\lambda\ge 0\).

1.2 Unconstrained first-order condition

A point \(x^\ast\) is stationary exactly when \(g(x^\ast)=0\). Gradient-based solvers in nlopt4r use

$$ \|g(x_k)\|_2 \le \tau_g $$

as the convergence test, where \(\tau_g\) comes from StopOptions::gradient_tolerance and defaults to \(10^{-6}\). The field Solution::gradient_norm carries this norm and termination_reason records the stopping criterion.

1.3 Box constraints and the gradient mapping

The feasible set of a box constraint is the closed box \(\mathcal B=\prod_i [l_i,u_i]\) with projection

$$ P(x)_i=\min\bigl(u_i,\max(l_i,x_i)\bigr). $$

First-order box stationarity is characterized by the unit-step gradient mapping

$$ G(x)=x-P\bigl(x-g(x)\bigr). $$

The equation \(G(x)=0\) is equivalent to the following coordinate conditions:

  • interior coordinates: \(g_i(x)=0\);
  • at the lower bound \(x_i=l_i\): \(g_i(x)\ge 0\);
  • at the upper bound \(x_i=u_i\): \(g_i(x)\le 0\);
  • fixed coordinates \(l_i=u_i\): the condition holds as stated.

bounded::projected_gradient reports \(|G(x)|_2\) in gradient_norm, and bounded::projected_gradient_norm computes this quantity separately. The mapping depends on variable units and box widths, which separates it from the unconstrained gradient norm.

1.4 Equality and inequality constraints

For the standard form \(\min f(x)\), \(h(x)=0\), \(g(x)\ge 0\), the Karush–Kuhn–Tucker (KKT) conditions read

$$ \nabla f(x)-\nabla h(x)^\top\mu-\nabla g(x)^\top\lambda=0, $$
$$ h(x)=0,\qquad g(x)\ge 0,\qquad \lambda\ge 0,\qquad \lambda_i g_i(x)=0\ \ (i=1,\dots,m_i). $$

nlopt4r reports three diagnostics separately:

  • Lagrangian stationarity \(|\nabla_x L|_2\) in ConstrainedSolution::solution.gradient_norm;
  • feasibility violation \(\max\bigl(\lVert h\rVert_\infty,\ \lVert(-g)_+\rVert_\infty\bigr)\) in constraint_violation;
  • complementarity \(\bigl(\sum_i \min(g_i,\lambda_i)^2\bigr)^{1/2}\) in complementarity.

Convergence requires all three within tolerance: stationarity uses gradient_tolerance; feasibility and complementarity use ConstrainedOptions::feasibility_tolerance with default \(10^{-6}\).

1.5 Least squares and quadratic programming

The least-squares objective \(f(x)=\tfrac12|r(x)|^2\) has gradient \(g(x)=J(x)^\top r(x)\), where \(J\) is the Jacobian of the residual vector. The stationarity condition \(J^\top r=0\) holds at nonzero residuals as well; the solver then reports convergence together with a positive residual norm.

The KKT system of a quadratic program uses the active inequality index set \(\mathcal A(x)={i: A_i x=b_i}\):

$$ Hx+c-A_e^\top\mu-A_i^\top\lambda=0,\qquad \lambda\ge 0,\qquad \lambda_i(A_i x-b_i)=0. $$

quadratic::QuadraticSolution reports equality multipliers, nonnegative inequality multipliers and the maximum constraint violation.

1.6 Second-order conditions

For the unconstrained case, a positive-definite \(H(x^\ast)\) at a stationary point is sufficient for a strict local minimum. With constraints, the sufficient condition tests the second-order term of the Lagrangian on the tangent space of the active constraints.

The two exact equality methods (NewtonLagrange, LagrangeSqp) read a caller-supplied Lagrangian Hessian:

$$ \nabla^2_{xx}L(x,\mu,\lambda)=\nabla^2 f(x)-\sum_j \mu_j\nabla^2 h_j(x)-\sum_i \lambda_i\nabla^2 g_i(x). $$

The dense Newton methods (DampedNewton, ModifiedNewton) and the dense trust region use the objective Hessian. The remaining methods read first derivatives.

1.7 Meaning of the convergence report

Solution::gradient_norm changes meaning by solver family:

Solver familyReported convergence quantity
Unconstrained gradient/quasi-Newton/trust region\(|g|_2\)
Box-constrained projected gradient\(|x-P(x-g)|_2\)
Nonlinear constraintsLagrangian stationarity \(|\nabla_x L|_2\)
Adaptive QR least squares\(|D^{-1}J^\top r|_2\), with \(D\) the diagonal of Jacobian column norms
Scalar-search error checkpointNaN (scalar search reads objective values)

The first-order test confirms a stationary point within the supplied tolerance; it does not certify global optimality. A global claim requires independent evidence, such as a complete exhaustive search over a finite candidate set, a mathematical lower bound, or an external certificate. Reaching a target value is a search outcome, not such a certificate. Chapter 9 documents the global-search report fields and chapter 13 the benchmark protocol.

Software interface

References

  • J. Nocedal, S. J. Wright, Numerical Optimization, 2nd ed., Springer, 2006, Chapters 2, 12, 16.
  • D. P. Bertsekas, Nonlinear Programming, 2nd ed., Athena Scientific, 1999, Chapter 3.

2. Line Search and Scalar Search

Line search chooses a step length for a one-dimensional subproblem. nlopt4r provides two searches: Armijo backtracking along a supplied descent direction (line_search::armijo) and a strong-Wolfe search (local::wolfe::strong_wolfe). Scalar search minimizes a univariate function on a finite closed interval. This chapter lists the conditions, implementation parameters and report fields.

2.1 Descent directions and the Armijo condition

For a smooth objective \(f\), a direction \(d\) is a descent direction when

$$ g^\top d\lt 0. $$

Armijo backtracking starts at \(\alpha_0=1\) and tries \(\alpha_k=\alpha_0\kappa^k\), accepting a step that satisfies

$$ \phi(\alpha)\le \phi(0)+c_1\,\alpha\,\phi'(0),\qquad \phi(\alpha)=f(x+\alpha d). $$

The defaults are \(c_1=0.2\), contraction \(\kappa=0.5\) and 60 trials.

Backtracking returns explicit errors in these cases:

  • the direction satisfies \(g^\top d\ge 0\): Error::InvalidInput;
  • the trial allowance runs out: Error::LineSearchFailed { evaluations, last_step }, with evaluations the number of trials and last_step the final step length;
  • a trial produces a non-finite value or the callback returns an error: that error propagates unchanged.

An accepted step returns Step { alpha, value, evaluations }, where value is the objective at the accepted point. armijo computes the origin gradient on entry; the caller supplies the direction and options.

Figure 2-1 Accepted interval of Armijo backtracking: \(\phi(\alpha)=1-3\alpha+3\alpha^2\), \(c_1=0.2\). The dashed line is the linear upper bound \(\phi(0)+c_1\alpha\phi^\prime(0)\) and the shaded band covers \(\alpha\in[0,0.8]\); the trial \(\alpha=0.5\) lies on the curve and the trial \(\alpha=1\) lies above the tangent. Section 2.2 of the textbook organizes inexact line search with the same inequality.

2.2 Strong Wolfe conditions

The strong-Wolfe search requires sufficient decrease and a curvature condition:

$$ \phi(\alpha)\le \phi(0)+c_1\alpha\phi'(0),\qquad |\phi'(\alpha)|\le c_2\,|\phi'(0)|, $$

with \(0<c_1<c_2<1\); the defaults are \(c_1=10^{-4}\) and \(c_2=0.9\).

The implementation has two stages:

  1. from the initial step 1, trial steps expand by doubling until a bracket holds an acceptable point;
  2. within a bracket, midpoints are strictly interior to the interval.

Both stages share the trial allowance (default 80, with the origin evaluation counted separately). Each trial computes the value and gradient together; the accepted pair is stored in StrongWolfeStep { alpha, value, gradient, evaluations } for reuse by the outer solver. A bracket that reaches midpoint precision returns LineSearchFailed.

The strong-Wolfe search supplies the outer step for L-BFGS and Newton-CG; the curvature condition supports positive-definite BFGS updates.

Scalar search minimizes a continuous unimodal function on a finite closed interval \([a,b]\) with two methods:

  • golden section (ScalarMethod::GoldenSection), contracting the interval by \(\rho=(3-\sqrt5)/2\approx0.382\);
  • parabolic/Brent interpolation (ScalarMethod::Parabolic), with safeguarded interpolation combined with golden-section protection.

Figure 2-2 Golden-section interval contraction: trial points sit at \(a+0.382(b-a)\) and \(a+0.618(b-a)\). Case (1) keeps \([a,q]\) and case (2) keeps \([p,b]\); both keep one trial point for the next round and multiply the interval length by \(t\approx0.618\). Section 2.1.1 of the textbook derives \(t\) from \(t^2=1-t\) (equation (2.6)) and gives the complete algorithm.

The stopping test uses the mixed interval tolerance

$$ b-a\le \tau_{\text{abs}}+\tau_{\text{rel}}\max(|x|,1), $$

with defaults \(\tau_{\text{abs}}=10^{-8}\) and \(\tau_{\text{rel}}=\sqrt{\varepsilon_{\text{machine}}}\). ScalarOptions::interval_tolerance stores both parameters, and StopOptions provides iteration and objective-evaluation allowances.

minimize_scalar is the convenience entry with an absolute tolerance, an iteration cap and a method; minimize_scalar_with_options takes full ScalarOptions and supports a strict objective budget.

The mathematical assumption is continuity and unimodality on the interval. The interval test and global multimodal optimality are distinct conclusions.

2.4 Report fields

TypeFieldMeaning
StepalphaAccepted step length
StepvalueObjective at the accepted point
StepevaluationsNumber of trials
StrongWolfeStepalpha, value, gradientAccepted step, objective, analytic gradient
StrongWolfeStepevaluationsCombined value/gradient callbacks (origin counted separately)
ScalarSolutionx, value, bracketBest point, objective, remaining interval
ScalarSolutionstatus, termination_reasonInterval convergence or a budget/iteration stop
ScalarSolutionevaluationsObjective calls, including endpoint evaluations

2.5 Parameter defaults

Option typeFieldDefaultValid range
ArmijoOptionsinitial_step1Positive finite
ArmijoOptionscontraction0.5\((0,1)\)
ArmijoOptionssufficient_decrease0.2\((0,1)\)
ArmijoOptionsmax_iterations60Positive integer
StrongWolfeOptionssufficient_decrease\(10^{-4}\)\(0<c_1<c_2\)
StrongWolfeOptionscurvature0.9\(c_1<c_2<1\)
StrongWolfeOptionsinitial_step / maximum_step1 / \(10^{20}\)Positive finite, initial at most maximum
StrongWolfeOptionsmax_evaluations80Positive integer
ScalarOptionsinterval_tolerance\(10^{-8}+\sqrt{\varepsilon},\vert x\vert\)Nonnegative, at least one term positive

Software interface

  • line_search::{armijo, minimize_scalar, minimize_scalar_with_options}: see chapter 16.
  • Step, StrongWolfeStep and recovery from failures: see chapter 20.
  • API reference (docs.rs): line_search.

References

  • 马昌凤, 最优化方法及其 Matlab 程序设计 (in Chinese), 2010, chapter 2.
  • J. Nocedal, S. J. Wright, Numerical Optimization, 2nd ed., 2006, Chapter 3.
  • R. P. Brent, Algorithms for Minimization without Derivatives, Prentice-Hall, 1973.

3. Gradient Methods and Conjugate Gradients

This chapter describes the three first-order unconstrained methods in nlopt4r: steepest descent, normalized gradient and Fletcher–Reeves nonlinear conjugate gradients. All three use vector-sized workspace with \(O(n)\) resident storage.

3.1 Steepest descent and normalized gradient

Steepest descent takes

$$ d_k=-g_k. $$

Normalized gradient takes the unit-length direction

$$ d_k=-\frac{g_k}{\|g_k\|_2}. $$

Both directions satisfy the descent condition \(g_k^\top d_k<0\). Armijo backtracking supplies the step. Under the book-wide assumptions of smoothness and a bounded sublevel set, backtracked steepest descent produces iterates whose gradients converge to a stationary point.

Figure 3-1 Exact line-search steepest descent on \(f(x)=\tfrac12(x_1^2+10x_2^2)\): consecutive search directions satisfy \(g_{k+1}^\top g_k=0\), and the polyline alternates near the two coordinate axes; the dashed line is the Newton step from \(x_0\), which reaches \(x^*\) in one step on a quadratic. Table 3.1 in section 3.1 of the textbook records iteration counts for the same quadratic from several starting points.

3.2 Fletcher–Reeves conjugate gradients

The Fletcher–Reeves direction is

$$ d_k=-g_k+\beta_k d_{k-1},\qquad \beta_k=\frac{\|g_k\|_2^2}{\|g_{k-1}\|_2^2}. $$

Implementation details:

  • a restart occurs every \(n+1\) iterations with restart direction \(-g_k\);
  • a shared descent safeguard tests \(g_k^\top d_k\ge -10^{-12}|g_k||d_k|\) and replaces the direction by \(-g_k\).

The restart period \(n+1\) gives finite termination on quadratic objectives; on general smooth objectives the restart controls the drift of accumulated conjugacy.

3.3 Convergence rate and problem size

MethodMain work per stepStorageTypical rate
Steepest descent1 gradient + line search\(O(n)\)Linear; slow on ill-conditioned problems
Normalized gradient1 gradient + line search\(O(n)\)Linear
Fletcher–Reeves1 gradient + line search\(O(n)\)Linear in general; finite on quadratics

All three read analytic gradients. Method::{SteepestDescent, NormalizedGradient, FletcherReeves} in minimize selects them; the gradient-tolerance test appears in chapter 1.

3.4 Callbacks and counts

Each outer iteration requests one combined value/gradient evaluation, and each line-search trial requests one objective value. EvaluationCounts::objective records all objective calls, while gradient records combined calls. The budget StopOptions::max_evaluations limits objective calls only and charges rejected trials.

Software interface

References

  • 马昌凤, 最优化方法及其 Matlab 程序设计 (in Chinese), 2010, chapter 3.
  • R. Fletcher, C. M. Reeves, “Function minimization by conjugate gradients,” Computer Journal 7 (1964), 149–154.
  • J. Nocedal, S. J. Wright, Numerical Optimization, 2nd ed., 2006, Chapter 5.

4. Newton and Quasi-Newton Methods

Newton methods use a second-order model to choose the search direction; quasi-Newton methods build curvature information from gradient differences. The dense implementations live in the Method enum of minimize, with \(O(n^2)\) resident storage and \(O(n^3)\) factorizations or inversions.

4.1 Newton equations and damping

At \(x_k\), the Newton direction solves the linear system

$$ H_k d_k=-g_k. $$

Method::DampedNewton solves this system and then runs Armijo backtracking. The callback supplies the Hessian with shape \(n\times n\); the entry point checks symmetry.

Method::ModifiedNewton handles indefinite or singular Hessians by shifting:

$$ H_k+\sigma I,\qquad \sigma\leftarrow 2\sigma, $$

starting from \(\sigma=|g_k|\) and doubling until a Cholesky factorization succeeds, then solving

$$ (H_k+\sigma I)d_k=-g_k. $$

The shift scales with the gradient norm, so regularization weakens as the iterate approaches a stationary point.

4.2 Secant condition and inverse-Hessian updates

Write \(s_k=x_{k+1}-x_k\) and \(y_k=g_{k+1}-g_k\). The inverse-Hessian approximation \(B_k\approx H_k^{-1}\) satisfies the secant condition

$$ B_{k+1}y_k=s_k. $$

nlopt4r implements four dense updates:

BFGS (\(\phi=1\)):

$$ B_{k+1}=\bigl(I-\rho_k s_k y_k^\top\bigr)B_k\bigl(I-\rho_k y_k s_k^\top\bigr)+\rho_k s_k s_k^\top,\qquad \rho_k=\frac{1}{s_k^\top y_k}. $$

DFP (\(\phi=0\)):

$$ B_{k+1}=B_k+\frac{s_k s_k^\top}{s_k^\top y_k}-\frac{B_k y_k y_k^\top B_k}{y_k^\top B_k y_k}. $$

SR1:

$$ B_{k+1}=B_k+\frac{(s_k-B_k y_k)(s_k-B_k y_k)^\top}{(s_k-B_k y_k)^\top y_k}. $$

Broyden convex family (\(0\le\phi\le 1\)), interpolating between DFP and inverse BFGS:

$$ B_{k+1}=B_k+\frac{s s^\top}{s^\top y}-\frac{Byy^\top B}{y^\top By}+\phi\,(y^\top By)\,v v^\top,\qquad v=\frac{s}{s^\top y}-\frac{By}{y^\top By}. $$

Method::Broyden { phi } gives DFP at \(0\) and inverse BFGS at \(1\).

4.3 Safeguards

The four updates share these rules:

  • the initial inverse Hessian is the identity;
  • BFGS/DFP/Broyden updates require \(s^\top y>10^{-12}|s||y|\) and \(y^\top B y>0\); a passing pair is applied and symmetrized as \(B\leftarrow (B+B^\top)/2\);
  • the SR1 update requires \(|(s-By)^\top y|>10^{-8}|s-By||y|\);
  • each iteration checks descent: if \(g^\top d\ge -10^{-12}|g||d|\), the direction becomes \(-g\) and the inverse Hessian resets to the identity.

A failing curvature or definiteness test skips the update and keeps the current inverse model. This is independent of the descent safeguard: when the computed direction fails its descent test, the direction becomes \(-g\) and the inverse model resets to the identity.

4.4 Cost and problem size

MethodWork per stepStorageDerivatives
DampedNewton1 Hessian + \(O(n^3)\) solve + line search\(O(n^2)\)Gradient and Hessian
ModifiedNewtonCholesky attempts + linear solves\(O(n^2)\)Gradient and Hessian
Bfgs / Dfp / Sr1 / Broydenrank-one/two update \(O(n^2)\) + line search\(O(n^2)\)Gradient

Chapter 6 covers limited-memory and matrix-free alternatives for large problems.

Software interface

References

  • 马昌凤, 最优化方法及其 Matlab 程序设计 (in Chinese), 2010, chapters 3 and 5.
  • C. G. Broyden, “The convergence of a class of double-rank minimization algorithms,” J. Inst. Math. Appl. 6 (1970), 76–90.
  • J. Nocedal, S. J. Wright, Numerical Optimization, 2nd ed., 2006, Chapter 6.

5. Trust-Region Methods

Trust-region methods minimize a quadratic model in a spherical neighborhood of the current point and adjust the radius using the ratio of actual to predicted decrease. nlopt4r provides a dense spectral method (trust_region::minimize) and a matrix-free Steihaug truncated-CG method (local::trust_region_cg).

5.1 Quadratic model and subproblem

At \(x_k\) the quadratic model is

$$ q_k(d)=g_k^\top d+\tfrac12 d^\top H_k d, $$

and the subproblem reads

$$ \min_{d}\ q_k(d)\quad \text{s.t.}\quad \|d\|_2\le \Delta_k. $$

A global minimizer \(d^\ast\) satisfies

$$ (H_k+\lambda I)d^\ast=-g_k,\qquad H_k+\lambda I\succeq 0,\qquad \lambda\ge 0,\qquad \lambda(\|d^\ast\|-\Delta_k)=0. $$

When \(H_k\) is indefinite and \(g_k\) is orthogonal to the minimal-eigenvalue subspace, the solution lies on the boundary: the hard case. The dense implementation covers this case with a symmetric eigendecomposition and a multiplier search.

Figure 5-1 Subproblem with \(g=(3,2.4)\), \(H=\operatorname{diag}(1,4)\), \(\Delta=1.5\): the unconstrained minimizer of \(q\) (hollow dot) lies outside the circle, the solution \(d^*\) lies on the boundary with multiplier \(\lambda\approx1.106\), the thin lines are \(q\) contours, and the dashed line is the boundary tangent. Sections 6.1 and 6.3 of the textbook discuss interior solutions, boundary solutions and the multiplier of the same subproblem.

5.2 Dense spectral solver

trust_region::subproblem(g, H, radius) solves the subproblem directly:

  • symmetric eigendecomposition \(H=Q\Lambda Q^\top\);
  • construction of a displacement and multiplier in eigencoordinates that satisfy the optimality conditions;
  • a search over \(\lambda\ge 0\) covering positive-definite, semidefinite and indefinite matrices;
  • return TrustRegionStep { step, value, multiplier }, with value the model change \(q(d)\) and multiplier the \(\lambda\).

The function is independent of the objective and budget system, with \(O(n^2)\) storage and \(O(n^3)\) eigenanalysis.

5.3 Dense outer iteration

The outer rules of trust_region::minimize:

  1. compute \(g_k\) and test the gradient tolerance;
  2. solve the subproblem for a step \(d_k\) and predicted decrease \(q_k(d_k)\);
  3. compute the ratio
$$ \rho_k=\frac{f(x_k)-f(x_k+d_k)}{-q_k(d_k)}; $$
  1. accept when \(\rho_k>\tau_a\), default \(\tau_a=0.15\);
  2. update the radius: for \(\rho_k\le\tau_a\), \(\Delta\leftarrow\Delta/2\); for \(\rho_k\ge0.75\) with \(|d_k|\ge0.99\Delta\), \(\Delta\leftarrow\min(2\Delta,\Delta_{\max})\);
  3. a rejected trial leaves the current iterate in place.

Defaults: initial radius 1, maximum radius 2, acceptance threshold 0.15.

5.4 Steihaug truncated conjugate gradients

local::steihaug approximately minimizes \(q(p)\) subject to \(|p|\le\Delta\):

  • stop when the residual norm drops to a configured fraction of its initial value (ResidualTolerance);
  • on a positive-curvature direction reaching the boundary, truncate at the positive root of \(|p+\tau d|=\Delta\) (Boundary);
  • on nonpositive curvature, compare the two boundary endpoints and keep the lower model value (NegativeCurvature);
  • at the inner iteration cap, return the current approximate step (MaxIterations).

SteihaugStep reports the step, model change, inner iterations, Hessian products and termination type. Defaults: inner tolerance 0.1, inner iteration cap 100, with the effective cap \(\min(100,n)\).

5.5 Matrix-free outer iteration

The outer rules of local::trust_region_cg match the dense version with these radius parameters:

  • acceptance threshold \(\tau_a=0.1\);
  • for \(\rho_k<0.25\), \(\Delta\leftarrow\Delta/4\);
  • for \(\rho_k>0.75\) with a step ending at the boundary or on a negative-curvature direction, \(\Delta\leftarrow\min(2\Delta,\Delta_{\max})\), default \(\Delta_{\max}=100\).

The method reads gradients and Hessian-vector products with \(O(n)\) workspace. A zero-gradient start terminates at first-order stationarity; the dense spectral method identifies hidden negative curvature.

5.6 Budget and counts

Each outer iteration requests one combined value/gradient evaluation; rejected trials consume objective budget. EvaluationCounts::subproblem records subproblem solves, and hessian records Hessian-vector products in the matrix-free version. Hessian products and subproblem iterations form separate count categories.

Software interface

  • trust_region::{minimize, subproblem, TrustRegionOptions}: see chapter 16.
  • local::{trust_region_cg, steihaug, SteihaugOptions, TrustRegionCgOptions} and the HessianVector trait: see chapter 16.
  • Option defaults: see chapter 20.
  • API reference (docs.rs): trust_region.

References

  • 马昌凤, 最优化方法及其 Matlab 程序设计 (in Chinese), 2010, chapter 6.
  • J. Nocedal, S. J. Wright, Numerical Optimization, 2nd ed., 2006, Chapter 4.
  • T. Steihaug, “The conjugate gradient method and trust regions in large scale optimization,” SIAM J. Numer. Anal. 20 (1983), 626–637.

6. Large-Scale Local Methods

This chapter describes three smooth unconstrained methods for large problems: limited-memory BFGS (local::lbfgs), truncated Newton-CG (local::newton_cg) and matrix-free trust regions (local::trust_region_cg). All three read gradients; the latter two read Hessian-vector products.

6.1 Limited-memory BFGS

For steps \(s_i=x_{i+1}-x_i\) and gradient differences \(y_i=g_{i+1}-g_i\), L-BFGS stores the most recent \(m\) correction pairs and computes the inverse-Hessian product with two loops:

q = g
newest to oldest: a[i] = rho[i] * s[i]'q; q -= a[i] * y[i]
r = gamma * q
oldest to newest: b = rho[i] * y[i]'r; r += (a[i] - b) * s[i]
d = -r,            rho[i] = 1 / (s[i]'y[i])

with the initial scaling

$$ \gamma=\frac{s^\top y}{y^\top y}. $$

A correction pair is admitted when

$$ s^\top y>\tau_c\,\|s\|\,\|y\|, $$

default \(\tau_c=10^{-10}\); the reciprocal and initial scaling must be finite and positive. An admitted pair is stored, and the oldest pair is dropped once the history exceeds \(m\). A failing pair is skipped while the existing history remains.

Direction check: a computed direction \(d\) is used when \(g^\top d<0\) with finite entries; otherwise the history clears and \(d=-g\).

Storage is \(O(mn)\) and each step costs \(O(mn)\). The default is \(m=10\).

6.2 Truncated Newton-CG

local::newton_cg approximately solves the Newton equation in each outer iteration:

$$ H_k p_k=-g_k. $$

The inner conjugate-gradient loop:

  • targets a residual \(|r_j|\le\tau_{\text{cg}}|g_k|\), default \(\tau_{\text{cg}}=0.1\);
  • caps inner iterations at \(\min(\text{max_cg_iterations}, n)\), default 100;
  • on nonpositive curvature \(d^\top H d\le 0\), returns the accumulated direction \(p\); a first-iteration occurrence returns \(-g_k\);
  • after inner convergence, checks the outer direction for descent and runs a strong-Wolfe line search.

Storage is \(O(n)\), and EvaluationCounts::hessian records Hessian products. The outer search uses StrongWolfeOptions.

6.3 Matrix-free trust region

local::trust_region_cg embeds the Steihaug truncated-CG solver in a trust-region outer loop:

  • subproblem options SteihaugOptions { max_iterations, relative_tolerance } with defaults 100 and 0.1;
  • radius updates as in section 5.5;
  • each outer iteration requests one value/gradient evaluation and several Hessian products;
  • rejected trials consume objective budget.

6.4 Hessian-vector operator

Alongside the three matrix-free entry points, the local::HessianVector trait defines the operator interface:

fn hessian_vector(&self, x: &[f64], v: &[f64], product: &mut [f64]) -> Result<(), Error>;

Conventions:

  • at a fixed \(x\), the product is linear in \(v\) and the operator is symmetric;
  • the callback writes every buffer entry; the buffer starts as NaN, and the solver detects and reports missing entries;
  • each product, including a failed callback, counts in EvaluationCounts::hessian;
  • product calls are independent of the objective budget.

6.5 Counts and stopping

All three entry points return Solution and use StopOptions:

  • max_evaluations covers objective calls, including the start evaluation, rejected trials and failed callbacks;
  • gradient_tolerance tests \(|g|\);
  • optional value_tolerance and step_tolerance report stagnation;
  • evaluations.subproblem records inner CG solves.

Software interface

  • local::{lbfgs, newton_cg, trust_region_cg} and their option types: see chapter 16.
  • A complete HessianVector example: see chapter 16.
  • Counts and error recovery: see chapter 20.
  • API reference (docs.rs): local.

References

  • J. Nocedal, “Updating quasi-Newton matrices with limited storage,” Math. Comp. 35 (1980), 773–782.
  • J. Nocedal, S. J. Wright, Numerical Optimization, 2nd ed., 2006, Algorithms 7.1–7.2.
  • T. Steihaug, “The conjugate gradient method and trust regions in large scale optimization,” SIAM J. Numer. Anal. 20 (1983), 626–637.

7. Nonlinear Least Squares

A least-squares problem minimizes half the squared residual norm:

$$ f(x)=\tfrac12\|r(x)\|_2^2,\qquad r:\mathbb R^n\to\mathbb R^m. $$

Each row of the Jacobian \(J(x)\in\mathbb R^{m\times n}\) corresponds to one residual. nlopt4r provides two Levenberg–Marquardt implementations: the legacy normal-equation method (levenberg_marquardt) and the adaptive QR method (levenberg_marquardt_with_options).

7.1 Gauss–Newton and LM damping

The Gauss–Newton step solves the normal equations

$$ J^\top J\,d=-J^\top r. $$

Levenberg–Marquardt adds damping:

$$ \bigl(J^\top J+\mu I\bigr)d=-J^\top r. $$

Figure 7-1 Three directions from \(x_0=(2,1)\) on \(f(x)=\tfrac12(x_1^2+4x_2^2)\): the GN step reaches the unconstrained minimizer directly, while the LM steps for \(\mu=0.5\) and \(\mu=2\) shorten and rotate toward the negative gradient. Section 7.2 of the textbook tunes step length and direction with the damping parameter, and section 7.3 lists the lmm.m program.

The legacy implementation takes

$$ \mu=\max(\|r\|_2,10^{-12}), $$

solves the linear system with a dense factorization, and runs Armijo backtracking. This method targets medium-sized residual systems with moderate conditioning.

7.2 Adaptive column-scaled QR method

The adaptive method solves an augmented rectangular system in scaled coordinates. With \(D\) the diagonal of Jacobian column norms (unit entries for zero-norm columns) and \(z=Dd\), each step solves

$$ \min_z\left\| \begin{bmatrix}JD^{-1}\\ \sqrt{\mu}\,I\end{bmatrix}z- \begin{bmatrix}-r\\ 0\end{bmatrix} \right\|_2, \qquad d=D^{-1}z. $$

Properties:

  • Householder QR and triangular back-substitution solve the augmented matrix \(((m+n)\times n)\) directly;
  • positive damping gives the augmented system full column rank, which yields steps for underdetermined and rank-deficient residual systems;
  • each step computes \(D\) from all nonzero column norms, with unit entries for zero columns.

Damping follows Nielsen’s cubic rule. With \(\rho\) the ratio of actual to predicted decrease, an accepted step updates

$$ \mu\leftarrow \mu\cdot\max\!\left(\tfrac13,\ 1-(2\rho-1)^3\right), $$

bounded below by minimum_damping. A rejected step grows damping by \(2,4,8,\dots\), with at most max_damping_trials attempts per accepted point (default 40). Acceptance requires \(\rho>\tau_a\) together with a trial objective below the current value, default \(\tau_a=10^{-4}\).

7.3 Convergence test

The adaptive method reports the column-scaled stationarity quantity

$$ \|D^{-1}J^\top r\|_2 $$

in Solution::gradient_norm, with the test

$$ \|D^{-1}J^\top r\|_2\le\tau_g. $$

This quantity is invariant under independent rescaling of variable units. A converged residual system satisfies \(J^\top r=0\); with a positive residual norm the objective equals the corresponding constant, and the fit rests at the smallest residual level.

7.4 Counts and recovery

  • each residual call, including rejected trials and failed callbacks, counts in evaluations.objective and evaluations.residuals;
  • each Jacobian call counts in evaluations.jacobian and evaluations.gradient;
  • the objective budget max_evaluations covers residual calls;
  • the accepted residual is cached and reused in the convergence test.

7.5 NIST certified data

tests/nist.rs uses the 14 observations of NIST StRD Misra1a with the model

$$ y=b_1\bigl(1-e^{-b_2 x}\bigr). $$

The published reference parameters are \(b_1=238.94212918\) and \(b_2=0.00055015643181\), with certified residual sum of squares \(0.12455138894\). The solver objective is half the residual sum of squares. The test uses two published starts \((500,0.0001)\) and \((250,0.0005)\); all data ship with the repository.

Software interface

References

  • 马昌凤, 最优化方法及其 Matlab 程序设计 (in Chinese), 2010, chapter 7.
  • K. Levenberg, “A method for the solution of certain non-linear problems in least squares,” Quart. Appl. Math. 2 (1944), 164–168.
  • D. W. Marquardt, “An algorithm for least-squares estimation of nonlinear parameters,” SIAM J. Appl. Math. 11 (1963), 431–441.
  • K. Madsen, H. B. Nielsen, O. Tingleff, Methods for Non-Linear Least Squares Problems, 2nd ed., DTU, 2004.

8. Bounded and Derivative-Free Local Search

This chapter covers three local methods on finite boxes: projected gradient (reads gradients), coordinate pattern search and Nelder–Mead simplex (read objective values). All three keep every trial point feasible.

8.1 Boxes and projection

The constraints are

$$ l_i\le x_i\le u_i,\qquad i=1,\dots,n, $$

with finite ordered endpoints; \(l_i=u_i\) denotes a fixed coordinate. Section 1.3 defines the projection and gradient mapping.

Bounds construction checks:

  • a nonempty dimension with matching endpoint lengths;
  • finite endpoints, each lower bound at most its upper bound, and finite widths;
  • normalized coordinates \(u_i=(x_i-l_i)/(u_i-l_i)\) for random sampling, with fixed coordinates normalized to 0.

8.2 Projected gradient

The iteration of bounded::projected_gradient:

  1. project the initial point into the box;
  2. compute the gradient \(g_k\);
  3. take the negative projected mapping \(d_k=P(x_k-g_k)-x_k\);
  4. run Armijo backtracking along the feasible segment \(x_k+\alpha d_k\), projecting each trial;
  5. stop when \(|G(x_k)|\le\tau_g\).

For step lengths \(\alpha\le1\), box convexity and the projection inequality give

$$ g_k^\top d_k\le-\|d_k\|^2, $$

so backtracking on the segment provides sufficient decrease. Fixed coordinates have zero mapping component and retain their value.

Defaults follow Options: Armijo initial step 1, contraction 0.5, \(c_1=0.2\), 60 trials; gradient tolerance \(10^{-6}\).

derivative_free::pattern_search polls coordinate directions with a normalized step \(h\):

  1. for each free coordinate \(i\), evaluate \(x\pm h,(u_i-l_i)\) with trials projected into the box;
  2. after a poll, take the best point among all evaluated points;
  3. halve the step, \(h\leftarrow h/2\), when the poll produces no improvement;
  4. stop when \(h\le\tau_{\text{step}}\) or every coordinate is fixed, reporting Stagnated.

Defaults: initial_step=0.1, step_tolerance=1e-8, max_iterations=2000, objective budget 10000. Working vectors use \(O(n)\).

The mesh-contraction report records where the step sequence stopped; gradient methods supply the stationary-point test.

8.4 Nelder–Mead simplex

derivative_free::nelder_mead maintains a simplex with \(n+1\) vertices:

  • vertices sorted by objective value;
  • reflection coefficient 1, expansion 2, contraction 1/2, shrink 1/2;
  • every new vertex is projected into the box; fixed coordinates leave the simplex construction;
  • stop when the normalized diameter drops below step_tolerance, reporting Stagnated;
  • if the budget runs out during initialization or shrink, return the best valid point.

Simplex storage is \(O(n^2)\). Boundary projection can flatten the simplex at a boundary, and the diameter test then yields a stagnation report.

8.5 Reports and budget

Both derivative-free methods return derivative_free::Solution:

FieldMeaning
x, valueBest evaluated point and its objective
iterationsCompleted poll/simplex iterations
evaluationsObjective calls (gradient counts remain zero)
termination_reasonTargetReached, MaxEvaluations, MaxIterations, Stagnated or Cancelled

BudgetOptions::target_value supplies the target stop: reaching it returns TargetReached early.

Software interface

References

  • D. P. Bertsekas, Nonlinear Programming, 2nd ed., 1999, Chapter 2 (gradient projection).
  • J. A. Nelder, R. Mead, “A simplex method for function minimization,” Computer Journal 7 (1965), 308–313.
  • R. P. Brent, Algorithms for Minimization without Derivatives, 1973.

9. Global Search: DE and PSO

Global search in nlopt4r runs on finite boxes, reads objective values and uses explicitly seeded random streams. The two population algorithms are synchronous differential evolution (DE/rand/1/bin) and inertia-weight global-best particle swarm optimization (PSO).

9.1 Differential evolution

The per-generation flow of global::differential_evolution:

  1. initialization: sample population_size points uniformly in the box, or validate a caller-supplied population;
  2. for each target \(i\), draw three distinct donors \(a,b,c\) with \(i\) excluded from the donor set;
  3. mutation vector
$$ v=x_a+F\,(x_b-x_c); $$
  1. binomial crossover: each coordinate takes the mutant component with probability \(CR\), with at least one coordinate forced to the mutant component, including at \(CR=0\);
  2. bound repair: a mutant component below its lower bound becomes
$$ \text{repaired}=l_j+\tfrac12\,(x_{i,j}-l_j), $$

and one above its upper bound becomes

$$ \text{repaired}=u_j+\tfrac12\,(x_{i,j}-u_j); $$
  1. selection: replace the target when the trial objective is at most the current value.

All donors read the preceding generation, giving synchronous updates. Defaults and valid ranges:

FieldDefaultValid range
population_size40\(\ge 4\)
max_generations1000Nonnegative integer
weight (\(F\))0.8\(0<F\le2\)
crossover (\(CR\))0.9\(0\le CR\le1\)
seed0Any 64-bit unsigned integer
budget.max_evaluations10000Positive integer
budget.target_valueNoneFinite value

9.2 Particle swarm

The velocity and position updates of global::particle_swarm:

$$ v_i\leftarrow w\,v_i+c_1 r_1\odot(p_i-x_i)+c_2 r_2\odot(g-x_i), $$
$$ x_i\leftarrow x_i+v_i, $$

where \(p_i\) is the personal best, \(g\) the global-best snapshot taken at the start of the generation, and \(r_1,r_2\) independent uniform draws per coordinate.

Implementation details:

  • initial velocities are zero;
  • velocity components clip to \(\pm v_{\max,j}\) with \(v_{\max,j}=c_v,(u_j-l_j)\), where velocity_limit supplies \(c_v\);
  • positions project into the box; a projected coordinate resets its velocity to zero;
  • personal bests update on a strict objective decrease; ties keep the earlier best;
  • the global best updates by generation, and all particles in a generation read one snapshot.

Defaults and valid ranges:

FieldDefaultValid range
population_size40\(\ge 2\)
max_generations1000Nonnegative integer
inertia (\(w\))0.7\(0\le w<1\)
cognitive (\(c_1\))1.5Finite nonnegative
social (\(c_2\))1.5Finite nonnegative
velocity_limit0.2\(0<v\le1\)
seed0Any 64-bit unsigned integer

9.3 Randomness and reproduction

Both entry points use the ChaCha8 stream of rand_chacha 0.9, seeded by the seed field. Initialization samples normalized coordinates:

$$ x_i=l_i+s_i\,(u_i-l_i),\qquad s_i\sim U[0,1]. $$

Reproduction conditions: identical seed, dependency versions and floating-point platform. The same seed reproduces the same sequence on the same build and platform.

9.4 Report and diversity

GlobalSolution fields:

FieldMeaning
x, valueBest evaluated point and its objective
generationsCompleted generations (initialization and an unfinished generation excluded)
evaluationsCallback counts, including initialization
termination_reasonTargetReached, MaxEvaluations, MaxIterations, Stagnated or Cancelled
seedSeed of this run
diversityMaximum over coordinates of the population spread divided by the box width

target_reached() tests for TargetReached, which corresponds to the objective reaching the caller’s target_value.

9.5 Budget and cancellation

  • the objective budget is a strict cap: exhaustion during initialization or a partial generation returns the best evaluated point;
  • _with_observer variants call the observer after each valid evaluation; Control::Stop cancels after the current evaluation; an observer error propagates with the best point retained;
  • cancellation, budget and generation caps are ordinary reports, with termination_reason recording the specific cause.

Software interface

  • DeOptions, PsoOptions, differential_evolution, particle_swarm: see chapter 17.
  • Observers and EvaluationContext: see chapter 21.
  • Benchmark protocol and measured results: see chapter 13.
  • API reference (docs.rs): global.

References

  • R. Storn, K. Price, “Differential Evolution—A Simple and Efficient Heuristic for Global Optimization over Continuous Spaces,” J. Global Optim. 11 (1997), 341–359.
  • J. Kennedy, R. Eberhart, “Particle swarm optimization,” Proc. IEEE ICNN 4 (1995), 1942–1948.
  • Y. Shi, R. Eberhart, “A modified particle swarm optimizer,” Proc. IEEE ICEC (1998), 69–73.

10. Quadratic Programming

Quadratic programming solves a convex quadratic objective under linear constraints. The quadratic module of nlopt4r provides an active-set method, a phase-I feasible-point search and a direct KKT solve for equality-constrained models.

10.1 Model

The model form is

$$ \min_x\ \tfrac12 x^\top Hx+c^\top x \quad\text{s.t.}\quad A_e x=b_e,\quad A_i x\ge b_i, $$

with \(H\) symmetric positive semidefinite, checked against the threshold

$$ \lambda_{\min}(H)\ge-10^{-10}\,(1+\|H\|). $$

The solve entry validates finiteness and shapes of all arrays; an absent constraint matrix has shape \(0\times n\).

10.2 KKT system and active set

Given the active set \(\mathcal A\) (equality rows and active inequality rows), the KKT system is

$$ \begin{bmatrix} H & -A_{\mathcal A}^\top\\ A_{\mathcal A} & 0 \end{bmatrix} \begin{bmatrix} d\\ \nu \end{bmatrix} = \begin{bmatrix} -c-Hx\\ b_{\mathcal A}-A_{\mathcal A}x \end{bmatrix}. $$

The active-set iteration:

  1. solve the KKT system for the step \(d\) and multipliers \(\nu\);
  2. check inequality rows along \(d\): a blocking row (\(A_i(x+\alpha d)=b_i\) reached first) joins the active set;
  3. with no blocking row, update \(x\); check inequality multiplier signs and drop rows with negative multipliers;
  4. terminate when the working set is stable and all conditions hold, judged by the KKT tolerance.

Equality multipliers and inequality multipliers are reported separately; inequality rows outside the active set carry zero multiplier.

Figure 10-1 Feasible set \(x_1\ge0\), \(x_2\ge0\), \(x_1+x_2\le3\) with objective \(\tfrac12\lVert x-(3.4,1.2)\rVert^2\): the step from \(x^0\) meets the blocking constraint \(x_1+x_2=3\) at the blocking point, which joins the active set, and the iterate then moves along the constraint to \(x^*=(3,0.8)\); thin lines are objective contours. Section 11.2 of the textbook gives the step formula and algorithm of the active-set method.

10.3 Phase I

When the initial point is infeasible, phase I solves the auxiliary problem with a scalar \(t\):

$$ \min\ t \quad\text{s.t.}\quad A_e x=b_e,\quad A_i x+t\ge b_i,\quad t\ge0, $$

starting from \(t=\text{violation}(x_0)+1\). After the auxiliary problem converges, \(t\le\tau_g\) marks the original problem as feasible, and the first \(n\) components of the phase-I solution start the main solve. Exhausted auxiliary iterations or \(t\) above tolerance return Infeasible or the corresponding error.

Each phase uses StopOptions::max_iterations and the phases share the strict objective budget max_evaluations. Reported iteration counts cover the main solve.

10.4 Singular and redundant systems

Linear systems are solved in this order:

  1. square systems try full-pivot LU; a residual within \(10^{-10}(1+|b|)\) accepts that solution;
  2. remaining cases use the SVD minimum-norm solution with truncation threshold \(10^{-12}\max(|A|,1)\);
  3. a solution residual above \(10^{-7}(1+|b|)\) returns SingularSystem.

This order covers redundant consistent constraints, rank-deficient KKT matrices and inconsistent systems; unbounded flat directions and general linear programs surface explicitly as SingularSystem or Infeasible.

10.5 Direct equality-constrained solve

quadratic::equality_constrained(h, c, a, b) assembles one KKT system for an equality-constrained model and solves it:

  • returns QuadraticSolution with an iteration count of 1;
  • reported multipliers satisfy \(Hx+c-A^\top\mu=0\);
  • inconsistent constraints or a numerically unsolvable system return an error.

This entry performs a single KKT solve and records 1 objective evaluation.

Software interface

  • QuadraticProgram, minimize, equality_constrained: see chapter 18.
  • QuadraticSolution fields and KKT diagnostics: see chapter 20.
  • Sign conventions for constraint multipliers: see chapter 1.
  • API reference (docs.rs): quadratic.

References

  • 马昌凤, 最优化方法及其 Matlab 程序设计 (in Chinese), 2010, chapter 11.
  • J. Nocedal, S. J. Wright, Numerical Optimization, 2nd ed., 2006, Chapter 16.
  • P. E. Gill, W. Murray, M. H. Wright, Practical Optimization, Academic Press, 1981.

11. Nonlinear Constrained Optimization

The nonlinear constraint solvers work on the standard form

$$ \min f(x)\quad\text{s.t.}\quad h(x)=0,\quad g(x)\ge 0 $$

with the Lagrangian and KKT conditions of section 1.4. nlopt4r provides four entry families: SQP with restoration, the legacy SQP, the exact equality methods (Newton–Lagrange and Lagrange SQP), and PHR augmented Lagrangian.

11.1 SQP model and active-set subproblem

At iterate \(x_k\), SQP builds a subproblem from a quadratic model and linearized constraints:

$$ \min_d\ \tfrac12 d^\top B_k d+g_k^\top d \quad\text{s.t.}\quad h(x_k)+J_h d=0,\quad g(x_k)+J_g d\ge0. $$

quadratic::minimize solves the subproblem, and the active-set method returns the step \(d_k\) with multiplier estimates. The subproblem requires a consistent linearization; when the linearization is infeasible, the legacy SQP returns Infeasible and the restoration entry starts its restoration phase.

The Hessian model \(B_k\) uses the Powell damped BFGS update. With

$$ \theta=\begin{cases} 1, & s^\top y\ge0.2\,s^\top B s,\\ \dfrac{0.8\,s^\top B s}{s^\top B s-s^\top y}, & \text{otherwise}, \end{cases} $$

the update is

$$ B_{k+1}=B_k+\frac{zz^\top}{s^\top z}-\frac{(B_k s)(B_k s)^\top}{s^\top B_k s}, \qquad z=\theta y+(1-\theta)B_k s. $$

Multipliers interpolate along the step:

$$ \mu_{k+1}=(1-\alpha_k)\mu_k+\alpha_k\mu_k^{\text{QP}},\qquad \lambda_{k+1}=(1-\alpha_k)\lambda_k+\alpha_k\lambda_k^{\text{QP}}. $$

The line search uses the \(l_1\) exact penalty function

$$ \phi_\pi(x)=f(x)+\pi\,\ell_1(x),\qquad \ell_1(x)=\sum_j|h_j(x)|+\sum_i\max(0,-g_i(x)), $$

with penalty parameter \(\pi\ge\max(\lVert\mu\rVert_\infty,\lVert\lambda\rVert_\infty)+1\); each iteration sets it to the larger of its current value and the current multiplier bound plus one.

11.2 Feasibility restoration

constrained::sqp_with_restoration runs a constraint-specific restoration phase when the subproblem is infeasible. The restoration objective is

$$ \theta(x)=\tfrac12\Bigl(\|h(x)\|^2+\|\min(g(x),0)\|^2\Bigr). $$

The restoration iteration:

  1. assemble residuals and Jacobian rows from the equality rows and the currently violated inequality rows;
  2. solve a damped augmented QR system for the direction;
  3. backtrack on the actual nonlinear objective \(\theta\);
  4. end restoration when the objective decrease reaches the configured ratio restoration_reduction (default 0.1) or feasibility reaches tolerance.

Restoration resets the Hessian model and multipliers, and the same SQP continues. Each restoration records a RestorationEvent: triggering subproblem error, outer iteration number, violation before and after restoration, restoration iteration count and failure information. max_subproblem_evaluations and max_subproblem_iterations bound the subproblem budget; max_restoration_iterations bounds restoration iterations.

11.3 Exact equality methods

Method::NewtonLagrange and Method::LagrangeSqp of constrained::minimize handle the equality-constrained subset. Both methods solve Newton steps on the KKT system

$$ \nabla_x L(x,\mu)=0,\qquad h(x)=0 $$

with the Lagrangian Hessian supplied by the caller. LagrangeSqp adds the stabilization term

$$ \nabla^2_{xx}L+\tfrac{1}{3.1}\,J_h^\top J_h. $$

The line-search merit function is

$$ \psi(x,\mu)=\|\nabla_x L(x,\mu)\|^2+\|h(x)\|^2, $$

and multipliers interpolate along the direction. Inequality constraints are rejected explicitly by these two methods (InvalidInput).

11.4 PHR augmented Lagrangian

constrained::augmented_lagrangian uses the Powell–Hestenes–Rockafellar multiplier method. The augmented objective is

$$ \Phi_\rho(x,\mu,\lambda)=f(x)-\mu^\top h(x)+\frac{\rho}{2}\|h(x)\|^2 +\frac{\bigl\|\max(0,\lambda-\rho g(x))\bigr\|^2-\|\lambda\|^2}{2\rho}. $$

Figure 11-1 Quadratic-penalty minimizer path for the equality constraint \(x_1^2+x_2^2=1\) and objective \((x_1-2)^2+(x_2-1)^2\): with \(\rho=0.25,0.5,1,4,16\), \(x(\rho)\) approaches \(x^*=(0.894,0.447)\) along the feasible curve; with no multiplier update the augmented objective reduces to this penalty. Sections 9.1 and 9.3 of the textbook derive the exterior penalty and multiplier methods, and section 9.4 lists the multphr.m program.

The outer flow:

  1. inner BFGS minimization of \(\Phi_\rho\) with inner tolerance \(0.1,\tau_g\) (lower bound \(10^{-12}\)) and iteration cap max_inner_iterations (default 1000);
  2. multiplier updates
$$ \mu\leftarrow\mu-\rho\,h(x),\qquad \lambda\leftarrow\max(0,\lambda-\rho\,g(x)); $$
  1. residual \(r=\max(\text{violation},\text{complementarity})\) triggers a penalty doubling when \(k\ge2\) and \(r>0.8,r_{\text{prev}}\);
  2. convergence when three KKT diagnostics meet their tolerances simultaneously.

Inner objective calls share the strict outer budget. initial_penalty supplies the initial penalty parameter (default 2).

11.5 Report and restoration state

The four entry families report a ConstrainedSolution: objective and iteration status, equality and inequality multipliers, constraint violation, complementarity and inner iteration count. sqp_with_restoration additionally returns the list of restoration events; on failure, SqpError carries the complete last_constrained checkpoint, including multipliers.

The convergence test checks stationarity, feasibility and complementarity together; solution.converged() is true when all three meet their thresholds.

Software interface

References

  • 马昌凤, 最优化方法及其 Matlab 程序设计 (in Chinese), 2010, chapters 9 and 12.
  • M. J. D. Powell, “A method for nonlinear constraints in minimization problems,” in Optimization, Academic Press, 1969.
  • M. R. Hestenes, “Multiplier and gradient methods,” J. Optim. Theory Appl. 4 (1969), 303–320.
  • J. Nocedal, S. J. Wright, Numerical Optimization, 2nd ed., 2006, Chapters 15, 18.

12. Stopping, Budgets and Error Recovery

This chapter collects the stopping controls, counters and error classes shared by all solvers. Local solvers use StopOptions; value search uses BudgetOptions, and the two control families are defined separately.

12.1 Stopping options

StopOptions fields and defaults:

FieldDefaultMeaning
max_iterations5000Outer iteration cap; 0 still evaluates the initial point and checks convergence
max_evaluationsNoneStrict objective-call cap; None leaves iterations as the sole limit
gradient_tolerance\(10^{-6}\)Stationarity (gradient/KKT/interval) tolerance
value_toleranceNoneOptional objective-stagnation tolerance
step_toleranceNoneOptional accepted-step stagnation tolerance

Mixed tolerances meet the condition

$$ \text{difference}\le \tau_{\text{abs}}+\tau_{\text{rel}}\,\text{scale}, $$

where scale is the larger norm of adjacent iterates or the larger absolute objective value. Both stagnation tolerances start disabled; once enabled they report ObjectiveStagnation or StepStagnation.

12.2 Decision order

The outer decision order at each step:

  1. on a satisfied convergence criterion, return convergence (GradientTolerance, KktTolerance or IntervalTolerance);
  2. on reaching the objective-call budget, return MaxEvaluations;
  3. on reaching the iteration cap, return MaxIterations;
  4. on a satisfied enabled stagnation criterion at an accepted step, return a Stagnated reason.

Convergence takes priority: when the last allowed iterate meets the convergence condition, the result counts as converged. When the budget runs out mid-trial, the solver returns the most recent fully evaluated accepted point, labeled MaxEvaluations.

12.3 Evaluation counts

The seven fields of EvaluationCounts:

FieldCounted object
objectiveObjective or residual calls, including rejected trials and failed callbacks
gradientGradient requests; least-squares Jacobian requests count here
hessianDense Hessian or Hessian-vector product requests
constraintsNonlinear constraint value or model-state evaluations
residualsResidual vector requests
jacobianResidual or constraint Jacobian requests
subproblemSynthesized subproblem model evaluations, separate from the outer objective budget

A combined value/gradient call counts once in each category. max_evaluations consumes only the objective field.

12.4 Status and termination reasons

The five Status values:

ValueMeaning
ConvergedA solver convergence criterion holds
MaxIterationsIteration cap exhausted
MaxEvaluationsObjective budget exhausted
StagnatedAn enabled stagnation criterion holds
FailedState of an error-recovery checkpoint

TerminationReason records the criterion precisely: GradientTolerance, KktTolerance, IntervalTolerance, MaxIterations, MaxEvaluations, ObjectiveStagnation, StepStagnation, Failed.

Value search uses SearchTermination: TargetReached, MaxEvaluations, MaxIterations, Stagnated, Cancelled.

12.5 Error classes

The Error enum variants:

VariantTrigger
InvalidInputAn option, domain, direction or precondition fails
DimensionMismatchVector or matrix shape mismatch, with expected and actual shapes
NonFiniteA non-finite value in inputs, callback outputs or intermediate arithmetic
MissingHessianA dense Newton method requests a Hessian the problem leaves absent
SingularSystemA linear system that is singular, inconsistent or numerically unsolvable
InfeasibleA constraint system or linearized subproblem infeasible
LineSearchFailedLine-search trials exhausted, with trial count and final step
IterationLimitA nested solver exhausts its iterations, with solver name and count
SubproblemStoppedA synthesized subproblem stops, with solver name, reason and count
EvaluationBudgetExceededInternal objective-budget signal
SearchStoppedAn extra evaluation request on a stopped context
SearchFailureValue-search failure, with best point and counts
EvaluationAn application callback fails, with operation class and message
SolverFailureA local solve fails, with outer name, source error and checkpoint

12.6 Checkpoints and recovery

Error wrappers retain valid state:

  • Error::root_cause() unwraps SolverFailure/SearchFailure and returns the underlying class;
  • Error::last_solution() returns the local solver’s full evaluation checkpoint with status Failed;
  • Error::last_point() returns the best evaluated point of a value search;
  • Error::source() chains follow the standard std::error::Error convention.

A checkpoint is a fully evaluated accepted state with current counts. A failure in the initial evaluation leaves the checkpoint absent. The recovery point serves as a restart seed, and its objective can exceed the smallest value seen during the search.

12.7 Budget boundaries

  • a zero objective budget fails at entry validation; a zero iteration cap is legal, returning after the initial evaluation under the convergence criterion;
  • budget exhaustion during initialization, a generation or a trial keeps the most recent fully evaluated point;
  • nested subproblems (the SQP QP model, the PHR inner loop) return IterationLimit or SubproblemStopped when their iterations run out;
  • callback panics propagate under the Rust unwinding rules.

Software interface

References

  • J. Nocedal, S. J. Wright, Numerical Optimization, 2nd ed., 2006, Section 3.2 (termination) and Chapter 18 (SQP subproblems).

13. Benchmark Evaluation and Reproducibility

tools/bench (crate name nlopt4r-bench) is the in-repo benchmark driver, and tools/nlopt-reference provides comparison runs against the crates.io nlopt wrapper. This chapter records the protocol, metric definitions and published measurements.

13.1 Run protocol

  • suites: smoke (sphere, Rosenbrock, Booth, Rastrigin, linear fit, coupled QP), smooth (analytic, non-global, unconstrained catalog entries) and global (multimodal and nonsmooth groups);
  • dimension: 1–128, bounded by each formula’s minimum dimension; fixed-dimension problems keep their declared dimension;
  • budget: budget_per_dimension × actual dimension objective calls;
  • starting points: generated by a run-local SplitMix64 stream; population algorithms receive explicit seeds;
  • target value: reference value + \(10^{-6}(1+|\text{reference}|)\); a hit requires box feasibility and constraint violation \(\le10^{-8}\);
  • local solvers use exact chain-rule gradients for analytic entries and central differences for the rest, with each probe counted in the same budget;
  • recorded fields: seed, dimension, budget, derivative mode, termination or error, best point and value, improvement history and platform metadata.

13.2 Metrics

The expected running time (ERT) to first hit is

$$ \text{ERT}=\frac{\sum_{\text{success}}(\text{calls to first hit})+\sum_{\text{failure}}(\text{calls actually consumed})}{\text{success count}}. $$
  • failed runs enter the numerator with their actual consumption;
  • with zero successes the ERT is infinite (summary output null);
  • time ERT uses the corresponding hit times and full run times;
  • summaries group by budget, target, transform and noise configuration, and metadata is emitted with each group.

13.3 Affine-transform instances

Optional switches --shift, --rotate and --instance-seed generate paired comparison instances:

$$ z=r+Q\,\bigl(x-(r+s)\bigr),\qquad F(x)=f(z),\qquad \nabla F(x)=Q^\top\nabla f(z). $$
  • the shift \(s\) samples uniformly in the central 60% of each coordinate’s original interval;
  • the rotation \(Q\) comes from a Gaussian QR factorization with a sign correction and determinant +1;
  • reference and target values stay the same;
  • the JSON record carries generator version, seed, switches, shift vector and rotation matrix; with the switches off these fields record null.

The outer box and solver starting points stay in place; the transform acts on the objective landscape.

13.4 Observation noise

The main driver supports independent identically distributed additive noise

$$ Y(x)=F(x)+\sigma Z, $$

with a Gaussian (Box–Muller), Uniform (\(U[-\sqrt3,\sqrt3]\)) or Laplace (scale \(1/\sqrt2\)) distribution. Noise applies after the transform; reference values, constraints and targets stay the same.

Records separate three metric classes:

  • best_* and first-hit: noise-free feasible best visits;
  • observed_best: the smallest noisy observation and its true value;
  • recommendation: true-value score of the point the solver actually returns (or of the error-recovery point).

Noisy runs disable objective-value stopping, and the remaining stopping rules stay in force.

13.5 Measured baseline

The data below are historical measurements at the source revisions recorded in docs/BENCHMARK_RESULTS.md: seeds 0–29, Rust 1.99.1, Linux/x86_64, Intel Core i7-12700H, default algorithm parameters. Cell format is “hits/30; ERT (objective calls)”. They are not portable wall-time or current-revision claims.

smoke suite, dimension 2, budget 4000:

ProblemBFGSL-BFGSDEPSO
Sphere30/30; 3.0030/30; 3.0030/30; 1420.6730/30; 1343.23
Rosenbrock30/30; 62.8730/30; 39.3030/30; 2232.7324/30; 3879.67
Booth30/30; 13.0730/30; 10.5330/30; 1744.5330/30; 1773.03
Rastrigin0/300/3029/30; 3534.1030/30; 2513.23
Linear fit30/30; 9.0030/30; 10.2030/30; 1517.3730/30; 1448.27
Coupled QP30/30; 11.7030/30; 7.2730/30; 1320.6030/30; 1173.60

global suite, requested dimension 4 (fixed-dimension problems keep dimension 2):

ProblemDimension/budgetDEPSO
Ackley4 / 80002/3030/30; 5067.03
Alpine4 / 80000/3030/30; 4891.83
Easom2 / 400030/30; 1722.6030/30; 1499.43
Griewank4 / 80000/300/30
Himmelblau2 / 400030/30; 2977.2030/30; 1942.23
Levy4 / 800030/30; 4402.5730/30; 2351.37
Qing4 / 80000/3030/30; 3096.20
Rastrigin4 / 80000/307/30; 31449.29
Schwefel-2224 / 80001/3030/30; 5193.03

Native L-BFGS comparison (same ChaCha8 starting points, unbounded domain, history 10):

ProblemDimension/budgetNative NLoptnlopt4r
Sphere2 / 400030/30; 3.0030/30; 3.00
Rosenbrock2 / 400030/30; 37.8330/30; 43.30
Sphere20 / 4000030/30; 3.0030/30; 3.00
Rosenbrock20 / 4000025/30; 166.5225/30; 195.80

Five of the 20-dimensional Rosenbrock Rust runs report explicit errors from strong-Wolfe search exhaustion at seeds 1, 5, 9, 15 and 16; all records stay in the ERT.

The shift/rotate pairing experiment (instance seed 42, dimension 2, budget 4000, 2160 records) shows: the external pattern search on shifted sphere, coupled QP and Rastrigin moves from a single hit to 96, 85–93 calls or a miss; Rastrigin’s DE/PSO hit counts vary with orientation; sphere keeps its results under rotation. These records describe one instance seed’s observations.

The noise pairing experiment (instance seed 42, noise seed 17, 2520 records) shows: at \(\sigma=10^{-6}\), visit hits and recommendation hits stay close; at \(\sigma=0.01\), Gaussian gives 118 visit hits and 0 recommendation hits over 360 runs, Uniform gives 208 visit hits and 5 recommendation hits, and Laplace gives 80 visit hits and 0 recommendation hits.

13.6 Coverage and validation

Historical baseline at the recorded benchmark revision:

  • 118 workspace tests passed: 90 solver integration tests, 3 unit tests, 1 doctest, 10 native comparisons and 14 tool tests;
  • line coverage 90.05% (3331/3699), function coverage 93.91% (262/279), region coverage 88.34%;
  • 13 Criterion kernel smoke checks passed;
  • an allocation regression checks workspace scale at dimensions 512 and 2048.

Current 1.0.1 counts are 90 solver integration tests, 3 unit tests, 16 doctests, 10 native comparisons and 28 benchmark-tool tests; the extension example has no tests. Coverage figures come from cargo llvm-cov. Branch coverage was not instrumented, so no branch-coverage percentage is claimed.

Software interface

  • benchmark commands, options and summaries: see chapter 22.
  • transform and noise field definitions: see docs/BENCHMARKS.md in the repository.
  • full record files: tools/bench/results/*.jsonl.gz.
  • published API reference for the benchmarked entries: https://docs.rs/nlopt4r/1.0.1/nlopt4r/.

References

  • N. Hansen, A. Auger, R. Ros, O. Mersmann, T. Tušar, D. Brockhoff, “COCO: A Platform for Comparing Continuous Optimizers in a Black-Box Setting,” Optimization Methods and Software 36 (2021).
  • R. Storn, K. Price (1997); J. Kennedy, R. Eberhart (1995), see chapter 9.

14. Installation and First Solve

This chapter covers the build environment, the dependency declaration, a first runnable program and how to read results.

14.1 Environment

  • Rust toolchain 1.88 or newer, edition 2024;
  • Cargo with cargo test available;
  • the build fetches nalgebra, rand and rand_chacha from crates.io.

Check the toolchain versions:

rustc --version
cargo --version

14.2 Dependency declaration

Add nlopt4r to the application’s Cargo.toml from crates.io:

[dependencies]
nlopt4r = "1.0.1"

The crate page is https://crates.io/crates/nlopt4r, and the generated API reference for 1.0.1 is https://docs.rs/nlopt4r/1.0.1/nlopt4r/.

For a local checkout, use a path dependency instead (adjust the path):

[dependencies]
nlopt4r = { path = "../optimization/nlopt" }

The nlopt4r package version is 1.0.1 with rust-version = "1.88". The repository workspace contains four members: the solver, the benchmark tool, the native comparison tool and the extension example; applications depend on the solver package alone.

14.3 First program

The following program minimizes the quadratic

$$ f(x,y)=\tfrac12\bigl((x-3)^2+(y+2)^2\bigr), $$

whose optimum is \((3,-2)\) with value 0:

use nlopt4r::{minimize, Method, Options, Vector};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let target = Vector::from_vec(vec![3.0, -2.0]);
    let objective = (
        |x: &Vector| 0.5 * (x - &target).norm_squared(),
        |x: &Vector| x - &target,
    );
    let result = minimize(
        &objective, &Vector::zeros(2), Method::Bfgs, &Options::default(),
    )?;
    if !result.converged() {
        return Err("optimization exhausted its iteration budget".into());
    }
    println!("x = {}, f = {}", result.x, result.value);
    Ok(())
}

Key points:

  • the objective and analytic gradient enter as a closure tuple (value, gradient); Vector is an alias of nalgebra::DVector<f64>;
  • Options::default() supplies a 5000-iteration cap, gradient tolerance \(10^{-6}\) and Armijo parameters;
  • result.converged() checks the convergence status; read this field before using the returned point.

14.4 Running the repository examples

Run these commands from a repository checkout; a downstream application that depends on the crates.io package does not include the examples.

cargo run --example rosenbrock     # BFGS on the two-dimensional Rosenbrock function
cargo run --example global_search  # DE/PSO comparison on a three-dimensional sphere

rosenbrock starts from \((-1.2,1)\) and checks an objective \(\le10^{-12}\) together with the coordinate error; global_search compares DE and PSO on \([-4,4]^3\) with a budget of 15000 calls, seed 7 for both and target \(10^{-8}\). Both examples return an error with a nonzero exit code when a check fails.

14.5 Reading results

Key Solution fields:

FieldMeaning
x, valueReturned point and objective value
gradient_normStationarity norm of the solver family (section 1.7)
iterationsOuter iteration count
statusConverged, MaxIterations, MaxEvaluations, Stagnated or Failed
termination_reasonThe specific criterion
evaluationsPer-class objective/gradient/Hessian counts

Standard reading flow: read status; with Converged, use x and value; with another status, read termination_reason and adjust budget or tolerances.

14.6 API documentation: docs.rs and local

The published 1.0.1 API reference is at https://docs.rs/nlopt4r/1.0.1/nlopt4r/. To generate the same documentation from a checkout:

cargo doc -p nlopt4r --no-deps --open

The documentation carries each module’s mathematical conventions, input shapes, defaults, diagnostic fields and runnable examples. Strict checks:

RUSTDOCFLAGS="-D warnings -D missing_docs" cargo doc -p nlopt4r --no-deps
cargo test -p nlopt4r --doc

Theory background

15. Objectives and Callback Interfaces

The nlopt4r solvers read objective values, gradients, Hessians, residuals and constraints through one callback interface family. This chapter lists the three interfaces, their adapters and the output validation rules.

API reference (docs.rs): Objective, Evaluator, Function, ValueOnly, value_only, EvaluationError, Vector, Matrix.

15.1 Type aliases

pub type Vector<T = f64> = nalgebra::DVector<T>;
pub type Matrix<T = f64> = nalgebra::DMatrix<T>;

Solver entries use Vector<f64> and Matrix<f64>. Dimensions are determined at runtime, and every solver accepts any nonempty dimension.

15.2 Infallible objective: Objective

pub trait Objective {
    fn value(&self, x: &Vector<f64>) -> f64;
    fn gradient(&self, x: &Vector<f64>) -> Vector<f64>;
    fn hessian(&self, x: &Vector<f64>) -> Option<Matrix<f64>> { None }
}
  • implement the trait for an application type, or pass a closure tuple at the call site;
  • a (value, gradient) tuple implements the trait;
  • a (value, gradient, hessian) tuple implements the trait with the Hessian returning Some.

Example (application type implementation):

#![allow(unused)]
fn main() {
use nlopt4r::{Objective, Vector};

struct Bowl;

impl Objective for Bowl {
    fn value(&self, x: &Vector<f64>) -> f64 {
        (x[0] - 1.0).powi(2) + (x[1] + 2.0).powi(2)
    }
    fn gradient(&self, x: &Vector<f64>) -> Vector<f64> {
        Vector::from_vec(vec![2.0 * (x[0] - 1.0), 2.0 * (x[1] + 2.0)])
    }
}
}

Objective comes with an automatic Evaluator adapter that builds the gradient vector on each call.

15.3 Buffered, fallible callbacks: Evaluator and Function

pub trait Evaluator {
    fn evaluate(&self, x: &[f64], gradient: Option<&mut [f64]>) -> Result<f64, Error>;
    fn evaluate_hessian(&self, x: &[f64]) -> Result<Option<Matrix<f64>>, Error> {
        Ok(None)
    }
}

Function is the closure adapter:

#![allow(unused)]
fn main() {
use nlopt4r::{EvaluationError, Function};

let problem = Function::new(|x: &[f64], gradient: Option<&mut [f64]>| {
    if let Some(g) = gradient {
        for (out, &value) in g.iter_mut().zip(x) {
            *out = 2.0 * value;
        }
    }
    Ok::<_, EvaluationError>(x.iter().map(|v| v * v).sum::<f64>())
});
}

The Hessian variant:

#![allow(unused)]
fn main() {
use nlopt4r::{EvaluationError, Function, Matrix};

let problem = Function::new(|x: &[f64], gradient: Option<&mut [f64]>| {
    if let Some(g) = gradient {
        g.copy_from_slice(x);
    }
    Ok::<_, EvaluationError>(0.5 * x.iter().map(|v| v * v).sum::<f64>())
})
.with_hessian(|_: &[f64]| Ok::<_, EvaluationError>(Matrix::from_element(2, 2, 1.0)));
}

Conventions:

  • gradient: None requests the objective value alone;
  • on a gradient request, the callback writes every element of the buffer;
  • on non-finite outputs, unwritten buffer elements or shape mismatches, the solver returns an explicit error;
  • buffers are filled with NaN before the call, which makes missed writes detectable.

15.4 Value-only objectives: value_only

#![allow(unused)]
fn main() {
use nlopt4r::{EvaluationError, value_only};

let problem = value_only(|x: &[f64]| {
    Ok::<_, EvaluationError>(x.iter().map(|v| v * v).sum())
});
}

The ValueOnly adapter produced by value_only returns an explicit error on a gradient request. This interface serves global, derivative_free and core::EvaluationContext.

15.5 Application errors

EvaluationError carries a display message:

#![allow(unused)]
fn main() {
use nlopt4r::EvaluationError;

let error: EvaluationError = "mesh solver diverged".into();
let error = EvaluationError::new(std::io::Error::other("model failed"));
}

When a callback returns EvaluationError, the solver reports Error::Evaluation { operation, source } in the error chain, with operation values such as "objective", "Hessian", "residuals", "Jacobian", "constraints" or "observer".

15.6 Least-squares and constraint interfaces

Least squares uses a (residuals, jacobian) tuple or the least_squares::LeastSquares trait; nonlinear constraints use the constrained::ConstrainedProblem trait returning Constraints. Chapters 18 and 19 cover the two interfaces.

15.7 Interface selection

NeedInterface
Analytic objective returning values directlyObjective or a closure tuple
Buffered writes, shared value/gradient computationFunction or Evaluator
Application errors reported upwardFunction, Evaluator or try_* hooks
Objective values alonevalue_only
Hessian-vector productslocal::HessianVector (chapter 16)

A type picks one interface implementation. Objective provides the Evaluator adapter, so an application type implementing Objective works with every solver.

Theory background

16. Local Solver Reference

This chapter lists the entries, option defaults and report fields of the local smooth solvers. The theory is in chapters 3–7.

16.1 Legacy dense methods: minimize and Method

pub fn minimize<P: Evaluator + ?Sized>(
    problem: &P,
    x0: &Vector<f64>,
    method: Method,
    options: &Options,
) -> Result<Solution, Error>

API pages (docs.rs): minimize, Method, Options, Solution.

Method values:

VariantDirection/modelMemory
SteepestDescent\(d=-g\)\(O(n)\)
NormalizedGradient\(d=-g/\lVert g\rVert\)\(O(n)\)
FletcherReevesConjugate gradient, restart every \(n+1\) steps\(O(n)\)
DampedNewtonDense Newton system + Armijo\(O(n^2)\)
ModifiedNewtonPositive-definite shifted Hessian\(O(n^2)\)
BfgsDense inverse BFGS\(O(n^2)\)
DfpDense inverse DFP\(O(n^2)\)
Sr1Symmetric rank-one inverse update\(O(n^2)\)
Broyden { phi }Broyden convex family, 0 for DFP and 1 for BFGS\(O(n^2)\)

Options combines two settings:

pub struct Options {
    pub stopping: StopOptions,          // defaults in chapter 12
    pub line_search: ArmijoOptions,     // defaults in chapter 3
}

All legacy methods use Armijo backtracking; the dense Newton variants read evaluate_hessian and return an explicit error on None.

Call example (BFGS):

#![allow(unused)]
fn main() {
use nlopt4r::{minimize, Method, Options, Vector};

let problem = (
    |x: &Vector| (x[0] - 1.0).powi(2) + (x[1] + 1.0).powi(2),
    |x: &Vector| Vector::from_vec(vec![2.0 * (x[0] - 1.0), 2.0 * (x[1] + 1.0)]),
);
let result = minimize(&problem, &Vector::zeros(2), Method::Bfgs, &Options::default())?;
assert!(result.converged());
assert!(result.gradient_norm <= 1e-6);
Ok::<(), nlopt4r::Error>(())
}

16.2 Calling Armijo backtracking directly

pub fn armijo<P: Evaluator + ?Sized>(
    problem: &P,
    x: &Vector<f64>,
    direction: &Vector<f64>,
    options: &ArmijoOptions,
) -> Result<Step, Error>

API pages (docs.rs): armijo, ArmijoOptions, Step.

  • one value/gradient request at the starting point, then value-only requests at trial points;
  • Step fields: alpha (accepted step), value (trial value), evaluations (trial count, with the starting call counted separately);
  • the direction satisfies \(g^\top d<0\); exhausted backtracking returns Error::LineSearchFailed { evaluations, last_step }.

ArmijoOptions defaults:

FieldDefault
initial_step1
contraction0.5
sufficient_decrease0.2
max_iterations60

16.3 Bounded projected gradient

pub fn projected_gradient<P: Evaluator + ?Sized>(
    problem: &P,
    x0: &Vector,
    bounds: &Bounds,
    options: &Options,
) -> Result<Solution, Error>

API pages (docs.rs): projected_gradient, projected_gradient_norm, Bounds.

Properties:

  • the initial point projects into the box, and every callback point is feasible;
  • the direction is \(d=P(x-g)-x\), and backtracking tests \(x+\alpha d\) with every trial projected into the box;
  • Solution::gradient_norm is the gradient-mapping norm \(\lVert x-P(x-g)\rVert\), zero at active boundary points;
  • uses the gradient tolerance of Options::stopping and the Armijo parameters of Options::line_search.

Computing the mapping norm separately:

pub fn projected_gradient_norm(
    x: &Vector,
    gradient: &Vector,
    bounds: &Bounds,
) -> Result<f64, Error>

Example:

#![allow(unused)]
fn main() {
use nlopt4r::{Bounds, Options, Vector, bounded::projected_gradient};

let problem = (
    |x: &Vector| (x[0] - 3.0).powi(2),
    |x: &Vector| Vector::from_vec(vec![2.0 * (x[0] - 3.0)]),
);
let bounds = Bounds::uniform(1, -1.0, 1.0)?;
let result = projected_gradient(&problem, &Vector::zeros(1), &bounds, &Options::default())?;
assert!(result.converged());
assert!((result.x[0] - 1.0).abs() < 1e-6);
Ok::<(), nlopt4r::Error>(())
}

16.4 L-BFGS

pub fn lbfgs<P: Evaluator + ?Sized>(
    problem: &P,
    x0: &Vector,
    options: &LbfgsOptions,
) -> Result<Solution, Error>

API pages (docs.rs): lbfgs, LbfgsOptions.

  • stores history_size correction pairs with \(O(m n)\) memory;
  • outer steps use the strong Wolfe conditions, and the accepted point’s value/gradient is reused directly;
  • correction pairs with curvature below \(s^\top y>10^{-10}\lVert s\rVert\lVert y\rVert\) are skipped;
  • an anomalous direction resets the history and falls back to steepest descent.

LbfgsOptions defaults:

FieldDefault
stoppingStopOptions::default()
line_searchStrongWolfeOptions::default()
history_size10
curvature_tolerance1e-10

Example (two-dimensional Rosenbrock):

#![allow(unused)]
fn main() {
use nlopt4r::{local::{lbfgs, LbfgsOptions}, Vector};

let rosenbrock = (
    |x: &Vector| (1.0 - x[0]).powi(2) + 100.0 * (x[1] - x[0] * x[0]).powi(2),
    |x: &Vector| Vector::from_vec(vec![
        -2.0 * (1.0 - x[0]) - 400.0 * x[0] * (x[1] - x[0] * x[0]),
        200.0 * (x[1] - x[0] * x[0]),
    ]),
);
let result = lbfgs(
    &rosenbrock,
    &Vector::from_vec(vec![-1.2, 1.0]),
    &LbfgsOptions::default(),
)?;
assert!(result.converged());
Ok::<(), nlopt4r::Error>(())
}

evaluations.objective and evaluations.gradient record the actual callback counts; a budget interruption returns a non-converged report.

16.5 Newton-CG (matrix-free)

pub trait HessianVector: Evaluator {
    fn hessian_vector(&self, x: &[f64], v: &[f64], product: &mut [f64]) -> Result<(), Error>;
}
pub fn newton_cg<P: HessianVector + ?Sized>(
    problem: &P,
    x0: &Vector,
    options: &NewtonCgOptions,
) -> Result<Solution, Error>

API pages (docs.rs): HessianVector, newton_cg, NewtonCgOptions.

  • the inner truncated CG caps iterations at min(max_cg_iterations, n);
  • the inner termination condition is \(\lVert r\rVert\le\texttt{cg_tolerance}\cdot\lVert g\rVert\);
  • a direction of curvature at or below zero ends the inner loop, and the outer loop runs a strong Wolfe search along the resulting direction;
  • each Hessian-vector product counts in evaluations.hessian.

NewtonCgOptions defaults:

FieldDefault
stoppingStopOptions::default()
line_searchStrongWolfeOptions::default()
max_cg_iterations100
cg_tolerance0.1

Example:

#![allow(unused)]
fn main() {
use nlopt4r::{Error, Evaluator, Vector, local::{HessianVector, NewtonCgOptions, newton_cg}};

struct Sphere;
impl Evaluator for Sphere {
    fn evaluate(&self, x: &[f64], gradient: Option<&mut [f64]>) -> Result<f64, Error> {
        if let Some(g) = gradient {
            for (out, &v) in g.iter_mut().zip(x) {
                *out = 2.0 * v;
            }
        }
        Ok(x.iter().map(|v| v * v).sum())
    }
}
impl HessianVector for Sphere {
    fn hessian_vector(&self, _: &[f64], v: &[f64], out: &mut [f64]) -> Result<(), Error> {
        for (out, &v) in out.iter_mut().zip(v) {
            *out = 2.0 * v;
        }
        Ok(())
    }
}
let result = newton_cg(&Sphere, &Vector::from_element(10, 1.0), &NewtonCgOptions::default())?;
assert!(result.converged());
Ok::<(), Error>(())
}

16.6 Dense trust region

pub fn minimize<P: Evaluator + ?Sized>(
    problem: &P,
    x0: &Vector,
    options: &TrustRegionOptions,
) -> Result<Solution, Error>

API pages (docs.rs): trust_region::minimize, subproblem, TrustRegionOptions, TrustRegionStep.

  • each step solves the quadratic subproblem \(\min g^\top d+\tfrac12 d^\top B d\), \(\lVert d\rVert\le\Delta\), globally via eigendecomposition;
  • the ratio \(\rho=\text{actual decrease}/\text{model decrease}\) above acceptance_threshold accepts the step;
  • a subproblem solution on the radius boundary with ratio at least 0.75 doubles the radius, and a low ratio halves it.

TrustRegionOptions defaults:

FieldDefault
stoppingStopOptions::default()
initial_radius1
maximum_radius2
acceptance_threshold0.15

The subproblem is also callable on its own:

#![allow(unused)]
fn main() {
use nlopt4r::{Matrix, Vector, trust_region::subproblem};

let g = Vector::from_vec(vec![2.0, 0.0]);
let step = subproblem(&g, &Matrix::identity(2, 2), 1.0)?;
assert!((step.step.norm() - 1.0).abs() < 1e-8);
Ok::<(), nlopt4r::Error>(())
}

TrustRegionStep fields: step (displacement), value (model change \(g^\top d+\tfrac12d^\top Bd\)), multiplier (multiplier \(\lambda\ge0\) satisfying \((B+\lambda I)d=-g\)).

16.7 Steihaug matrix-free trust region

pub fn steihaug<F>(
    g: &Vector,
    radius: f64,
    options: &SteihaugOptions,
    multiply: F,
) -> Result<SteihaugStep, Error>
where
    F: FnMut(&Vector) -> Result<Vector, Error>

pub fn trust_region_cg<P: HessianVector + ?Sized>(
    problem: &P,
    x0: &Vector,
    options: &TrustRegionCgOptions,
) -> Result<Solution, Error>

API pages (docs.rs): steihaug, trust_region_cg, SteihaugOptions, TrustRegionCgOptions, SteihaugStep, SteihaugTermination.

SteihaugStep fields: step, value, iterations, hessian_products, termination: SteihaugTermination. Inner termination reasons:

VariantCondition
ResidualToleranceResidual norm reaches relative_tolerance times the starting norm
BoundaryPositive-curvature CG reaches the trust-region boundary
NegativeCurvatureA direction of nonpositive curvature continues to the better point on the boundary
MaxIterationsInner iteration cap

SteihaugOptions defaults: max_iterations = 100, relative_tolerance = 0.1. TrustRegionCgOptions defaults: initial radius 1, maximum radius 100, acceptance threshold 0.1, subproblem from SteihaugOptions::default().

16.8 Strong Wolfe utility

pub fn strong_wolfe<F>(
    value: f64,
    gradient: &Vector,
    direction: &Vector,
    options: &StrongWolfeOptions,
    evaluate: F,
) -> Result<StrongWolfeStep, Error>
where
    F: FnMut(f64) -> Result<(f64, Vector), Error>

API pages (docs.rs): strong_wolfe, StrongWolfeOptions, StrongWolfeStep.

The callback returns trial value and gradient for a step length; the accepted state StrongWolfeStep carries alpha, value and gradient for direct reuse. StrongWolfeOptions defaults: sufficient_decrease = 1e-4, curvature = 0.9, initial_step = 1, maximum_step = 1e20, max_evaluations = 80.

pub fn minimize_scalar<F: Fn(f64) -> f64>(
    f: F,
    bounds: (f64, f64),
    tolerance: f64,
    max_iterations: usize,
    method: ScalarMethod,
) -> Result<ScalarSolution, Error>

pub fn minimize_scalar_with_options<F: Fn(f64) -> f64>(
    f: F,
    bounds: (f64, f64),
    method: ScalarMethod,
    options: &ScalarOptions,
) -> Result<ScalarSolution, Error>

API pages (docs.rs): minimize_scalar, minimize_scalar_with_options, ScalarMethod, ScalarOptions, ScalarSolution.

  • minimize_scalar is the convenience entry: one absolute interval tolerance and an iteration cap, with the relative tolerance fixed at \(\sqrt{\varepsilon_{\text{mach}}}\);
  • minimize_scalar_with_options takes the full ScalarOptions and a strict objective budget;
  • ScalarMethod::GoldenSection and ScalarMethod::Parabolic (Brent-protected interpolation);
  • interval defaults: absolute \(10^{-8}\), relative \(\sqrt{\varepsilon_{\text{mach}}}\);
  • ScalarSolution fields: x, value, bracket, iterations, status, termination_reason, evaluations.
#![allow(unused)]
fn main() {
use nlopt4r::line_search::{minimize_scalar_with_options, ScalarMethod, ScalarOptions};

let result = minimize_scalar_with_options(
    |x| (x - 0.4).powi(2),
    (-1.0, 2.0),
    ScalarMethod::Parabolic,
    &ScalarOptions::default(),
)?;
assert!((result.x - 0.4).abs() < 1e-6);
Ok::<(), nlopt4r::Error>(())
}

16.10 Selection guide

ScenarioEntry
Small scale with analytic HessianMethod::DampedNewton, Method::ModifiedNewton
Small scale, gradient onlyMethod::Bfgs, Method::Dfp, Method::Sr1
Medium to large scale, gradient onlylocal::lbfgs
Large scale with computable Hessian-vector productslocal::newton_cg, local::trust_region_cg
Variables with lower and upper boundsbounded::projected_gradient
One-dimensional continuous unimodalline_search::minimize_scalar*
Few variables, nonsmooth objectivederivative_free (chapter 17)

Theory background

17. Global and Derivative-Free Solver Reference

This chapter covers three interface groups: differential evolution and particle swarm on bounded boxes, bounded derivative-free local search, and the shared budget and observer machinery. The theory is in chapters 8 and 9.

17.1 Shared inputs: Bounds and value_only

All three method families require finite box constraints:

API pages (docs.rs): Bounds, value_only.

#![allow(unused)]
fn main() {
use nlopt4r::Bounds;

let bounds = Bounds::uniform(3, -4.0, 4.0)?;          // same lower and upper bound
let bounds = Bounds::new(
    vec![-4.0, -1.0], vec![4.0, 1.0],
)?;                                                   // per-coordinate bounds
Ok::<(), nlopt4r::Error>(())
}

The objective enters through value_only:

#![allow(unused)]
fn main() {
use nlopt4r::{EvaluationError, value_only};

let sphere = value_only(|x: &[f64]| {
    Ok::<_, EvaluationError>(x.iter().map(|v| v * v).sum())
});
}

value_only returns an explicit error on a gradient request; the three modules request objective values alone.

17.2 Differential evolution

pub fn differential_evolution<P: Evaluator + ?Sized>(
    p: &P,
    bounds: &Bounds,
    options: &DeOptions,
) -> Result<GlobalSolution, Error>

API pages (docs.rs): differential_evolution, DeOptions.

Algorithm state:

  • a population of \(N\) candidates updates synchronously: every donor vector reads the preceding generation;
  • mutation \(v_i=x_{r_0}+F(x_{r_1}-x_{r_2})\), with three distinct donor indices excluding the target index;
  • binomial crossover keeps at least one donor coordinate;
  • selection accepts candidates that are at least as good (ties accept the trial);
  • out-of-bound coordinates repair toward the midpoint between the target point and the coordinate boundary.

DeOptions defaults:

FieldDefaultNotes
budgetBudgetOptions::default()10000 objective calls, no target value
seed0ChaCha8 seed
population_size40At least 4
max_generations1000Generation zero still runs initialization
weight0.8\(F\in(0,2]\)
crossover0.9\(CR\in[0,1]\)
initial_populationNoneOptional initial population of exact size, finite and feasible
#![allow(unused)]
fn main() {
use nlopt4r::{Bounds, Vector, value_only, global::{differential_evolution, DeOptions}};

let problem = value_only(|x: &[f64]| {
    Ok::<_, nlopt4r::EvaluationError>((x[0] - 0.3).powi(2) + (x[1] + 0.2).powi(2))
});
let mut options = DeOptions::default();
options.seed = 7;
options.budget.target_value = Some(1e-10);
let result = differential_evolution(&problem, &Bounds::uniform(2, -1.0, 1.0)?, &options)?;
assert!(result.target_reached());
Ok::<(), nlopt4r::Error>(())
}

17.3 Particle swarm

pub fn particle_swarm<P: Evaluator + ?Sized>(
    p: &P,
    bounds: &Bounds,
    options: &PsoOptions,
) -> Result<GlobalSolution, Error>

API pages (docs.rs): particle_swarm, PsoOptions.

Update rules:

$$ v_i \leftarrow \omega v_i + c_1 r_1 \odot (p_i-x_i) + c_2 r_2 \odot (g-x_i), \qquad x_i \leftarrow P(x_i+v_i), $$

where \(p_i\) is the personal best, \(g\) the previous generation’s global-best snapshot, and \(r_1,r_2\) independent uniform draws per coordinate.

  • velocity components clip to \(\pm c_v,(u_j-l_j)\);
  • positions project into the box; a projected coordinate resets its velocity to zero;
  • personal bests update on strict improvement;
  • initial velocities are zero.

PsoOptions defaults:

FieldDefaultNotes
budgetBudgetOptions::default()10000 objective calls
seed0ChaCha8 seed
population_size40At least 2
max_generations1000Initialization counted separately
inertia0.7\(\omega\in[0,1)\)
cognitive1.5\(c_1\ge0\)
social1.5\(c_2\ge0\)
velocity_limit0.2\(c_v\in(0,1]\)
initial_populationNoneFeasible initial positions of exact size

17.4 Observers and cancellation

Both algorithms have *_with_observer variants (differential_evolution_with_observer and particle_swarm_with_observer); the observer runs after each valid evaluation and returns Control::Continue or Control::Stop:

API pages (docs.rs): differential_evolution_with_observer, particle_swarm_with_observer, EvaluationEvent, Control, SearchTermination.

#![allow(unused)]
fn main() {
use nlopt4r::{Bounds, value_only, core::{Control, EvaluationEvent, SearchTermination},
    global::{DeOptions, differential_evolution_with_observer}};

let problem = value_only(|x: &[f64]| Ok::<_, nlopt4r::EvaluationError>(x[0] * x[0]));
let mut observer = |event: &EvaluationEvent<'_>| {
    Ok(if event.evaluations.objective >= 5 { Control::Stop } else { Control::Continue })
};
let result = differential_evolution_with_observer(
    &problem,
    &Bounds::uniform(1, -1.0, 1.0)?,
    &DeOptions::default(),
    Some(&mut observer),
)?;
assert_eq!(result.termination_reason, SearchTermination::Cancelled);
assert_eq!(result.evaluations.objective, 5);
Ok::<(), nlopt4r::Error>(())
}

An observer error reports the search with the best valid point as its checkpoint.

17.5 Reading global results

API page (docs.rs): GlobalSolution.

GlobalSolution fields:

FieldMeaning
x, valueBest point and value over all valid evaluations
generationsComplete generations, with initialization and an unfinished generation excluded
evaluationsAttempted-call counts
termination_reasonTargetReached, MaxEvaluations, MaxIterations, Stagnated or Cancelled
seedSeed of this run
diversityMaximum over coordinates of the population spread divided by the domain width

target_reached() corresponds to the TargetReached status alone. The returned point is the best evaluated point; it is not a certified global optimum. The measured tables of chapter 13 give empirical hit rates and ERT per problem class.

pub fn pattern_search<P: Evaluator + ?Sized>(
    p: &P,
    x0: &Vector,
    bounds: &Bounds,
    options: &Options,
) -> Result<Solution, Error>

pub fn nelder_mead<P: Evaluator + ?Sized>(
    p: &P,
    x0: &Vector,
    bounds: &Bounds,
    options: &Options,
) -> Result<Solution, Error>

API pages (docs.rs): pattern_search, nelder_mead, derivative_free::Options, derivative_free::Solution.

  • pattern_search: positive and negative coordinate trials around the current best point, halving the step after a failed poll; zero-width coordinates are skipped, and points left unchanged by projection are skipped;
  • nelder_mead: the initial simplex has one vertex per free coordinate, with reflection 1, expansion 2, contraction 1/2 and shrink 1/2; projection can compress the simplex;
  • the initial point x0 must be finite, of the correct dimension and feasible.

derivative_free::Options defaults:

FieldDefault
budget10000 objective calls
max_iterations2000
initial_step0.1 (fraction of the coordinate width, in \((0,1]\))
step_tolerance1e-8 (normalized step/simplex diameter)
#![allow(unused)]
fn main() {
use nlopt4r::{Bounds, Vector, value_only, derivative_free::{nelder_mead, Options}};

let problem = value_only(|x: &[f64]| Ok::<_, nlopt4r::EvaluationError>((x[0] - 0.25).powi(2)));
let mut options = Options::default();
options.budget.target_value = Some(1e-8);
let result = nelder_mead(&problem, &Vector::zeros(1), &Bounds::uniform(1, -1.0, 1.0)?, &options)?;
assert!(result.value <= 1e-8);
Ok::<(), nlopt4r::Error>(())
}

Solution fields: x, value, iterations, evaluations, termination_reason. A step or diameter below the threshold reports Stagnated, a state recording that the step/diameter fell below the threshold; the optimality certificate comes from separate criteria.

17.7 Budget and stopping semantics

API pages (docs.rs): BudgetOptions, SearchTermination.

  • BudgetOptions.max_evaluations is a strict cap, and the count includes initialization and failed callbacks;
  • with target_value present, any valid point reaching \(f(x)\le\) target stops the search;
  • max_generations = 0 still runs the initial population evaluation;
  • observer cancellation takes effect before the next objective call;
  • every stop reports as a SearchTermination; gradient convergence status stays with gradient criteria.

Theory background

  • Differential evolution and particle swarm: see chapter 9.
  • Pattern search and Nelder-Mead: see chapter 8.
  • Budgets, target values and cancellation: see chapter 12.
  • Benchmark protocol and measured hit rates: see chapter 13.

18. Least-Squares and QP Reference

The two solvers in this chapter take model data directly: a residual vector and Jacobian, or a quadratic objective with linear constraints. The theory is in chapters 7 and 10.

18.1 Residual model

Least squares solves

$$ \min_x f(x)=\tfrac12\lVert r(x)\rVert^2,\qquad r:\mathbb{R}^n\to\mathbb{R}^m, $$

with Jacobian \(J(x)=\partial r/\partial x\) of size \(m\times n\).

Interface:

pub trait LeastSquares {
    fn residuals(&self, x: &Vector) -> Vector;
    fn jacobian(&self, x: &Vector) -> Matrix;
    fn try_residuals(&self, x: &Vector) -> Result<Vector, EvaluationError> { ... }
    fn try_jacobian(&self, x: &Vector) -> Result<Matrix, EvaluationError> { ... }
}

API page (docs.rs): LeastSquares.

A (residuals, jacobian) closure tuple implements the trait automatically. The residual count \(m\) stays fixed and positive during a solve, and all outputs are finite.

18.2 The two LM entries

EntryStep computationDampingUse
levenberg_marquardtNormal equations \((J^\top J+\mu I)d=-J^\top r\), \(\mu=\max(\lVert r\rVert,10^{-12})\), Armijo backtrackingFixed ruleWell-conditioned problems with small residuals
levenberg_marquardt_with_optionsColumn-scaled augmented QR, adaptive \(\mu\)Nielsen updateIll-conditioned, rank-deficient and rectangular problems

Signatures:

pub fn levenberg_marquardt<P: LeastSquares + ?Sized>(
    problem: &P, x0: &Vector, options: &Options,
) -> Result<Solution, Error>

pub fn levenberg_marquardt_with_options<P: LeastSquares + ?Sized>(
    problem: &P, x0: &Vector, options: &LmOptions,
) -> Result<Solution, Error>

API pages (docs.rs): levenberg_marquardt, levenberg_marquardt_with_options, LmOptions.

LmOptions defaults:

FieldDefaultNotes
stoppingStopOptions::default()Gradient tolerance applies to the column-scaled stationarity quantity
initial_damping1e-3At or above the damping lower bound
minimum_damping1e-15Damping lower bound
acceptance_ratio1e-4Actual/predicted decrease ratio threshold, in \([0,1)\)
max_damping_trials40Damping trials per accepted iterate

Convergence quantity of the adaptive variant:

$$ \lVert D^{-1}J^\top r\rVert,\qquad D=\operatorname{diag}(\lVert J_{:,j}\rVert), $$

with a unit value for zero column norms. This quantity fills Solution::gradient_norm.

Example (linear residuals with exact solution \(x=1\)):

#![allow(unused)]
fn main() {
use nlopt4r::{Matrix, Vector, least_squares::{LmOptions, levenberg_marquardt_with_options}};

let problem = (
    |x: &Vector| Vector::from_vec(vec![x[0] - 1.0, 2.0 * x[0] - 2.0]),
    |_: &Vector| Matrix::from_column_slice(2, 1, &[1.0, 2.0]),
);
let result = levenberg_marquardt_with_options(
    &problem, &Vector::zeros(1), &LmOptions::default(),
)?;
assert!(result.converged());
assert!((result.x[0] - 1.0).abs() < 1e-6);
Ok::<(), nlopt4r::Error>(())
}

Counting convention: each residual call (rejected trials and failed callbacks included) counts in evaluations.objective and evaluations.residuals; Jacobian calls additionally count in evaluations.gradient and evaluations.jacobian.

18.3 Quadratic program model

pub struct QuadraticProgram {
    pub hessian: Matrix,          // H, symmetric positive semidefinite, n x n
    pub linear: Vector,           // c, length n
    pub equalities: Matrix,       // Ae, rows = equality_rhs.len()
    pub equality_rhs: Vector,     // be
    pub inequalities: Matrix,     // Ai, rows = inequality_rhs.len()
    pub inequality_rhs: Vector,   // bi
}

API page (docs.rs): QuadraticProgram.

Objective and constraints:

$$ \min_x \tfrac12 x^\top H x + c^\top x \quad\text{s.t.}\quad A_e x=b_e,\quad A_i x\ge b_i. $$
  • the inequality direction is \(A_i x\ge b_i\);
  • with zero constraint rows the matrices have shape \(0\times n\); QuadraticProgram::unconstrained builds empty constraints from linear.len();
  • convexity check threshold: \(\lambda_{\min}(H)\ge-10^{-10}(1+\lVert H\rVert)\).

Solve entries:

pub fn minimize(
    qp: &QuadraticProgram, x0: &Vector, options: &StopOptions,
) -> Result<QuadraticSolution, Error>

pub fn equality_constrained(
    hessian: &Matrix, linear: &Vector, a: &Matrix, b: &Vector,
) -> Result<QuadraticSolution, Error>

API pages (docs.rs): minimize, equality_constrained.

  • minimize: active-set iteration; a feasible initial point enters the main loop directly, and an infeasible one first runs phase I,
$$ \min t\quad\text{s.t.}\quad A_e x=b_e,\ A_i x+t\mathbf 1\ge b_i,\ t\ge0, $$
from \\(t=\text{violation}(x_0)+1\\); - each phase receives the `max_iterations` allowance and both share the strict `max_evaluations`; - `equality_constrained` solves the KKT system directly, including consistent rank-deficient cases; an LU failure switches to the SVD minimum-norm solution.

API page (docs.rs): QuadraticSolution.

QuadraticSolution fields:

FieldMeaning
solutionIteration/objective/stationarity report; check solution.converged() first
equality_multipliersEquality multipliers \(\mu\) satisfying \(Hx+c-A_e^\top\mu-A_i^\top\lambda=0\)
inequality_multipliersActive inequality multipliers, nonnegative; zero outside the active set
constraint_violationMaximum of equality residuals and the negative part of inequality residuals

Example:

#![allow(unused)]
fn main() {
use nlopt4r::{Matrix, StopOptions, Vector, quadratic::{QuadraticProgram, minimize}};

let mut qp = QuadraticProgram::unconstrained(
    Matrix::identity(2, 2),
    Vector::from_vec(vec![-2.0, -4.0]),
);
qp.equalities = Matrix::from_row_slice(1, 2, &[1.0, 1.0]);
qp.equality_rhs = Vector::from_vec(vec![3.0]);
let result = minimize(&qp, &Vector::zeros(2), &StopOptions::default())?;
assert!(result.solution.converged());
assert!((result.solution.x.sum() - 3.0).abs() < 1e-6);
Ok::<(), nlopt4r::Error>(())
}

18.4 QP stopping criteria

The gradient tolerance of StopOptions serves both the stationarity norm and the constraint violation:

  • an initial point already meeting \(\lVert\nabla f\rVert\le\tau\) and constraint_violation \(\le\tau\) converges with KktTolerance;
  • each main-loop step solves the active-set equality subproblem, checks multiplier signs and releases the constraint of the most negative multiplier;
  • budget exhaustion returns a non-converged checkpoint of the same dimension as the original problem;
  • an unsolvable phase I or KKT subproblem returns an explicit error (Infeasible, SingularSystem and related variants).

Counting convention: QP evaluations describe model states, with objective/gradient/constraints each counted once per step; external callbacks are absent.

18.5 Model suite and validation

The repository ships NIST nonlinear least-squares data for adaptive LM validation:

cargo test -p nlopt4r --test nist

The tests check certified parameters and residuals and cover ill-conditioned and rank-deficient models. QP tests cover phase I, redundant constraints, active-set transitions and KKT multiplier signs.

Theory background

  • Gauss–Newton and LM derivations, Nielsen damping: see chapter 7.
  • Active sets, phase I and KKT multipliers: see chapter 10.
  • Stopping criteria and counts: see chapter 12.

19. Nonlinear Constraint Reference

This chapter gives the constrained-problem interface, the four entries and the multiplier conventions. The theory is in chapter 11.

19.1 Constraint conventions

Problem form:

$$ \min_x f(x)\quad\text{s.t.}\quad h(x)=0,\quad g(x)\ge0, $$

with Lagrangian

$$ L(x,\mu,\lambda)=f(x)-\mu^\top h(x)-\lambda^\top g(x),\qquad \lambda\ge0. $$

Constraints carries constraint values and row-wise Jacobians at one point:

pub struct Constraints {
    pub equalities: Vector,             // h(x)
    pub inequalities: Vector,           // g(x)
    pub equality_jacobian: Matrix,      // m_e x n
    pub inequality_jacobian: Matrix,    // m_i x n
}

API page (docs.rs): Constraints.

Constructors:

ConstructorUse
Constraints::empty(n)Unconstrained, with \(0\times n\) Jacobians
Constraints::equalities_only(values, jacobian)Equalities alone
Constraints::inequalities_only(values, jacobian)\(g(x)\ge0\) alone
Constraints::linear(x, ae, be, ai, bi)Linear constraints \(A_ex=b_e\), \(A_ix\ge b_i\)
Constraints::from_nonpositive(...)Translates \(c(x)\le0\) into \(g=-c\ge0\)

Constraint counts stay fixed within one solve.

19.2 Problem interface

pub trait ConstrainedProblem: Evaluator {
    fn constraints(&self, x: &Vector) -> Constraints;
    fn lagrangian_hessian(&self, x: &Vector, mu: &Vector, lambda: &Vector)
        -> Option<Matrix> { None }
    fn try_constraints(&self, x: &Vector) -> Result<Constraints, EvaluationError> { ... }
    fn try_lagrangian_hessian(&self, x: &Vector, mu: &Vector, lambda: &Vector)
        -> Result<Option<Matrix>, EvaluationError> { ... }
}

API page (docs.rs): ConstrainedProblem.

  • objective values and gradients come from Evaluator or the Objective adapter;
  • lagrangian_hessian returns the Hessian of \(L\), and both exact-Hessian methods require it;
  • a failing constraint callback reports as Error::Evaluation { operation: "constraints" } through try_constraints.

19.3 Entries and options

API pages (docs.rs): Method, minimize, augmented_lagrangian, ConstrainedOptions, ConstrainedSolution.

EntryAlgorithmConstraint types
minimize(..., Method::Sqp, ...)Powell damped BFGS + \(l_1\) exact penaltyEqualities and inequalities
minimize(..., Method::NewtonLagrange, ...)Newton on the KKT equationsEqualities alone
minimize(..., Method::LagrangeSqp, ...)SQP with a stabilized Lagrange HessianEqualities alone
sqp_with_restorationSQP + feasibility restoration phaseEqualities and inequalities
augmented_lagrangianPHR multiplier/penalty iteration + BFGS inner loopEqualities and inequalities

ConstrainedOptions defaults:

FieldDefaultNotes
solverOptions::default()Outer stopping and Armijo parameters
feasibility_tolerance1e-6Feasibility and complementarity threshold
max_inner_iterations1000PHR inner budget; other entries ignore it
initial_penalty2PHR initial penalty parameter

Solve signatures:

pub fn minimize<P: ConstrainedProblem + ?Sized>(
    p: &P, x0: &Vector, method: Method, options: &ConstrainedOptions,
) -> Result<ConstrainedSolution, Error>

pub fn augmented_lagrangian<P: ConstrainedProblem + ?Sized>(
    p: &P, x0: &Vector, options: &ConstrainedOptions,
) -> Result<ConstrainedSolution, Error>

The SQP \(l_1\) penalty parameter is the larger of its current value and the largest multiplier magnitude plus one. SQP multipliers interpolate along the accepted step:

$$ \mu^+=(1-\alpha)\mu+\alpha\mu^{\text{QP}},\qquad \lambda^+=(1-\alpha)\lambda+\alpha\lambda^{\text{QP}}. $$

PHR instead updates multipliers by \(\mu\leftarrow\mu-\rho h\) and \(\lambda\leftarrow\max(0,\lambda-\rho g)\). Its inner objective is

$$ \Phi(x)=f(x)-\mu^\top h(x)+\frac{\rho}{2}\lVert h(x)\rVert^2 +\sum_j\frac{1}{2\rho}\Bigl[\max(0,\lambda_j-\rho g_j)^2-\lambda_j^2\Bigr], $$

and the penalty parameter doubles when consecutive outer iterations reach \(k\ge2\) with the residual above 0.8 times the previous value.

19.4 SQP with restoration

pub fn sqp_with_restoration<P: ConstrainedProblem + ?Sized>(
    p: &P, x0: &Vector, options: &SqpOptions,
) -> Result<SqpSolution, SqpError>

API pages (docs.rs): sqp_with_restoration, SqpOptions, SqpSolution, SqpError, RestorationEvent.

An infeasible linearized QP starts a constraint-only restoration phase:

  • restoration objective \(\theta(x)=\tfrac12(\lVert h\rVert^2+\lVert\min(g,0)\rVert^2)\);
  • restoration direction from a damped least-squares QR solve;
  • acceptance when the violation drops by at least the restoration_reduction ratio;
  • one RestorationEvent per attempt.

SqpOptions defaults:

FieldDefault
solverConstrainedOptions::default()
max_subproblem_iterations1000 (per QP phase)
max_subproblem_evaluations10000 (whole run)
max_restoration_iterations100 (per attempt)
restoration_reduction0.1
restoration_damping1e-3

Return structure:

pub struct SqpSolution {
    pub constrained: ConstrainedSolution,   // nested convergence flag
    pub restoration: Vec<RestorationEvent>, // in execution order
}

RestorationEvent fields: iteration, trigger (the triggering error), initial_violation, final_violation, iterations, failure.

Failures return SqpError:

FieldMeaning
sourceSolver error with its source chain
restorationRestoration attempts so far
last_constrainedComplete outer checkpoint (with multipliers), None before a valid state appears

19.5 Reading results

API page (docs.rs): ConstrainedSolution.

ConstrainedSolution fields:

FieldMeaning
solutionObjective, Lagrangian stationarity norm, iterations and status
equality_multipliers\(\mu\)
inequality_multipliers\(\lambda\ge0\), zero for inactive constraints
constraint_violationMaximum of equality residuals and the negative part of inequality residuals
complementarity\(\lVert\min(g,\lambda)\rVert\) (component-wise)
inner_iterationsTotal PHR inner iterations, zero for other entries

The convergence conditions hold simultaneously:

$$ \lVert\nabla_xL\rVert\le\tau,\qquad \texttt{constraint\_violation}\le\min(\tau,\ \texttt{feasibility\_tolerance}),\qquad \texttt{complementarity}\le\min(\tau,\ \texttt{feasibility\_tolerance}), $$

where \(\tau\) is solver.stopping.gradient_tolerance.

19.6 Example

An equality-constrained quadratic with analytic solution \((0,1)\):

#![allow(unused)]
fn main() {
use nlopt4r::{Matrix, Objective, Vector};
use nlopt4r::constrained::{ConstrainedProblem, Constraints, SqpOptions, sqp_with_restoration};

struct Model;
impl Objective for Model {
    fn value(&self, x: &Vector) -> f64 {
        (x[0] - 1.0).powi(2) + (x[1] - 2.0).powi(2)
    }
    fn gradient(&self, x: &Vector) -> Vector {
        Vector::from_vec(vec![2.0 * (x[0] - 1.0), 2.0 * (x[1] - 2.0)])
    }
}
impl ConstrainedProblem for Model {
    fn constraints(&self, x: &Vector) -> Constraints {
        Constraints {
            equalities: Vector::from_vec(vec![x[0] + x[1] - 1.0]),
            equality_jacobian: Matrix::from_row_slice(1, 2, &[1.0, 1.0]),
            inequalities: Vector::zeros(0),
            inequality_jacobian: Matrix::zeros(0, 2),
        }
    }
}
let mut options = SqpOptions::default();
options.solver.solver.stopping.max_evaluations = Some(500);
let result = sqp_with_restoration(&Model, &Vector::zeros(2), &options)?;
assert!(result.constrained.solution.converged());
assert!(result.constrained.constraint_violation < 1e-6);
Ok::<(), Box<dyn std::error::Error>>(())
}

For inequality problems, write the constraints as \(g(x)\ge0\) or translate \(c(x)\le0\) with Constraints::from_nonpositive.

19.7 Counts and budgets

  • each outer state evaluation counts once each in evaluations.objective, gradient, constraints and jacobian;
  • constraint Jacobians and objective gradients count separately;
  • PHR inner objective calls share the strict outer budget;
  • SQP subproblem states count in evaluations.subproblem, separate from the external callback budget;
  • budget interruption returns a non-converged report, and callback or subproblem failures keep the checkpoint.

Theory background

  • Full derivations of SQP, restoration and PHR: see chapter 11.
  • KKT conditions and multiplier signs: see chapter 1.
  • Stopping criteria and error checkpoints: see chapter 12.

20. Options, Reports and Errors Reference

This chapter collects the defaults of every public option and the report fields into lookup tables. Chapters 14–19 cover entry usage, and the corresponding Part I chapters give the mathematical definitions. The published API reference is https://docs.rs/nlopt4r/1.0.1/nlopt4r/.

20.1 Module map

ModuleContents
rootVector, Matrix, Objective, Evaluator, Function, ValueOnly, value_only, Bounds, EvaluationCounts, StopOptions, TerminationReason, Tolerance, EvaluationError, Solution, Status, Error, minimize, Method, Options
line_searcharmijo, minimize_scalar, minimize_scalar_with_options, ScalarMethod, ScalarOptions, ScalarSolution
locallbfgs, newton_cg, trust_region_cg, steihaug, strong_wolfe, HessianVector, SteihaugTermination
boundedprojected_gradient, projected_gradient_norm
trust_regionDense Newton trust region minimize, subproblem, plus Steihaug-family re-exports
problemBounds (construction, projection, unit-box mapping, sampling)
derivative_freepattern_search, nelder_mead
globaldifferential_evolution, particle_swarm and observer variants
least_squaresLeastSquares, the two LM entries
quadraticQuadraticProgram, minimize, equality_constrained
constrainedConstrainedProblem, Constraints, SQP/PHR entries
coreEvaluationContext, BudgetOptions, EvaluatedPoint, Control, EvaluationEvent, Observer, SearchTermination
utilsvalidate_slice, solve_dense, directional_difference, RNG re-exports

Each module page lists its functions, structs, traits and enums.

20.2 Stopping and tolerances

StopOptions:

FieldDefaultConstraint
max_iterations5000Zero allowed, still running the initial evaluation and convergence check
max_evaluationsNoneSome(0) invalid
gradient_tolerance1e-6Positive finite
value_toleranceNoneTolerance
step_toleranceNoneTolerance

Tolerance: absolute and relative finite and nonnegative with at least one positive; criterion difference <= absolute + relative * scale.

BudgetOptions (value-search): max_evaluations default 10000, target_value default None.

StopOptions, Tolerance and BudgetOptions expose a public validate(): entry points call it before the first callback and reject nonpositive budgets, non-finite targets, negative tolerances and all-zero tolerances with Error::InvalidInput.

ArmijoOptions: 1, 0.5, 0.2, 60 (initial step, contraction factor, sufficient-decrease coefficient, trial cap).

StrongWolfeOptions: sufficient_decrease = 1e-4, curvature = 0.9, initial_step = 1, maximum_step = 1e20, max_evaluations = 80.

ScalarOptions: interval_tolerance = {absolute: 1e-8, relative: sqrt(ε)}.

API pages (docs.rs): StopOptions, Tolerance, BudgetOptions, ArmijoOptions, StrongWolfeOptions, ScalarOptions.

20.3 Per-solver options

Option typeDefaults
LbfgsOptionshistory_size = 10, curvature_tolerance = 1e-10, remaining fields from the stopping/strong-Wolfe defaults
NewtonCgOptionsmax_cg_iterations = 100, cg_tolerance = 0.1
SteihaugOptionsmax_iterations = 100, relative_tolerance = 0.1
TrustRegionCgOptionsradius 1→100, acceptance threshold 0.1, subproblem SteihaugOptions::default()
TrustRegionOptionsinitial_radius = 1, maximum_radius = 2, acceptance_threshold = 0.15
LmOptionsinitial_damping = 1e-3, minimum_damping = 1e-15, acceptance_ratio = 1e-4, max_damping_trials = 40
derivative_free::Optionsbudget 10000, max_iterations = 2000, initial_step = 0.1, step_tolerance = 1e-8
DeOptionspopulation 40, generations 1000, weight = 0.8, crossover = 0.9, seed 0, budget 10000
PsoOptionspopulation 40, generations 1000, inertia = 0.7, cognitive = 1.5, social = 1.5, velocity_limit = 0.2, seed 0, budget 10000
ConstrainedOptionsfeasibility_tolerance = 1e-6, max_inner_iterations = 1000, initial_penalty = 2, outer Options::default()
SqpOptionssubproblem iterations 1000, subproblem evaluations 10000, restoration iterations 100, restoration reduction 0.1, restoration damping 1e-3

Valid domains:

QuantityAllowed range
StrongWolfeOptions\(0<c_1<c_2<1\), initial_step ≤ maximum_step
NewtonCgOptions::cg_tolerance\((0,1)\)
SteihaugOptions::relative_tolerance\((0,1)\)
TrustRegionOptions::acceptance_threshold\([0,0.75)\)
TrustRegionCgOptions::acceptance_threshold\([0,0.25)\)
LmOptions::acceptance_ratio\([0,1)\)
DeOptions::weight\((0,2]\)
DeOptions::crossover\([0,1]\)
PsoOptions::inertia\([0,1)\)
PsoOptions::velocity_limit\((0,1]\)
derivative_free::Options::initial_step\((0,1]\)
Broyden { phi }\([0,1]\)

The solver option types expose validate(): LbfgsOptions, NewtonCgOptions, StrongWolfeOptions, SteihaugOptions, TrustRegionCgOptions, derivative_free::Options. Entry points call this check before the first callback, covering budgets, out-of-range parameters and tolerances.

API pages (docs.rs): LbfgsOptions, NewtonCgOptions, SteihaugOptions, TrustRegionCgOptions, TrustRegionOptions, LmOptions, derivative_free::Options, DeOptions, PsoOptions, ConstrainedOptions, SqpOptions.

20.4 Report types

TypeKey fields
Solutionx, value, gradient_norm, iterations, status, termination_reason, evaluations
GlobalSolutionthe point/value/counts above + generations, seed, diversity, termination_reason: SearchTermination
derivative_free::Solutionx, value, iterations, evaluations, termination_reason
ScalarSolutionx, value, bracket, iterations, status, termination_reason, evaluations
QuadraticSolutionsolution, equality_multipliers, inequality_multipliers, constraint_violation
ConstrainedSolutionsolution, multipliers, constraint_violation, complementarity, inner_iterations
SqpSolutionconstrained, restoration

gradient_norm by solver family:

Solver familygradient_norm
Unconstrained and trust region\(\lVert\nabla f\rVert\)
Bounded projected gradientGradient mapping \(\lVert x-P(x-g)\rVert\)
Adaptive QR LM\(\lVert D^{-1}J^\top r\rVert\)
Constrained methodsLagrangian stationarity norm \(\lVert\nabla_xL\rVert\)
QPKKT stationarity norm
Scalar searchNo gradient evaluation, NaN in error checkpoints

API pages (docs.rs): Solution, GlobalSolution, derivative_free::Solution, ScalarSolution, QuadraticSolution, ConstrainedSolution, SqpSolution.

20.5 Status enums

Status: Converged, MaxIterations, MaxEvaluations, Stagnated, Failed.

TerminationReason:

VariantMapped statusTrigger
GradientToleranceConvergedStationarity norm meets tolerance
KktToleranceConvergedThe three KKT conditions meet tolerance
IntervalToleranceConvergedScalar interval meets tolerance
MaxIterationsMaxIterationsOuter iteration cap
MaxEvaluationsMaxEvaluationsObjective budget cap
ObjectiveStagnationStagnatedValue tolerance triggered
StepStagnationStagnatedStep tolerance triggered
FailedFailedError-checkpoint marker

SearchTermination (value-domain methods): TargetReached, MaxEvaluations, MaxIterations, Stagnated, Cancelled.

API pages (docs.rs): Status, TerminationReason, SearchTermination.

20.6 Evaluation counts

Seven EvaluationCounts fields:

FieldCounted content
objectiveObjective calls; least-squares residual calls; QP model states
gradientGradient requests; least-squares Jacobians
hessianDense Hessians or Hessian-vector products
constraintsNonlinear constraint values or QP constraint states
residualsResidual vector requests
jacobianResidual/constraint Jacobian requests
subproblemSynthesized subproblem evaluations, outside the outer objective budget

Combined value/gradient requests count once in each of the two categories. Only objective consumes max_evaluations.

API page (docs.rs): EvaluationCounts.

20.7 Errors and recovery

VariantMeaning
InvalidInput(&'static str)Option/domain/direction outside its valid set
DimensionMismatch { context, expected, actual }Shape error, vectors recorded as (n,1)
NonFinite(&'static str)Non-finite input/output/intermediate quantity
MissingHessianDense Newton method with an absent analytic Hessian
SingularSystemLinear system singular, inconsistent or unsolvable
InfeasibleConstraint system or linearized subproblem infeasible
LineSearchFailed { evaluations, last_step }No accepted step
IterationLimit { solver, iterations }Nested solver iterations exhausted
SubproblemStopped { solver, reason, iterations }Subproblem below its convergence criterion
EvaluationBudgetExceededInternal budget signal, converted to a report when a valid state exists
SearchStopped(SearchTermination)Value-domain evaluation request after a stop
SearchFailure { source, last_point, evaluations }Value-domain search failure + best point
Evaluation { operation, source }Application callback error, source carrying the display message
SolverFailure { solver, source, last_solution }Local solver failure + complete checkpoint

Recovery methods:

#![allow(unused)]
fn main() {
use nlopt4r::{Method, Options, Vector, minimize};

let problem = (
    |x: &Vector| x[0] * x[0],
    |x: &Vector| Vector::from_vec(vec![2.0 * x[0]]),
);
match minimize(&problem, &Vector::from_element(1, 1.0), Method::Bfgs, &Options::default()) {
    Ok(report) => println!("status {:?}, f = {}", report.status, report.value),
    Err(error) => {
        if let Some(point) = error.last_point() {
            eprintln!("best value-only point: {}", point.value);
        }
        if let Some(report) = error.last_solution() {
            eprintln!("checkpoint {:?}", report.status);
        }
        eprintln!("root cause: {}", error.root_cause());
    }
}
}

Rules:

  • root_cause() unwraps SolverFailure/SearchFailure;
  • last_solution() returns the full local checkpoint of a SolverFailure;
  • last_point() returns the best valid point of a value-domain search;
  • the checkpoint is a fully evaluated state usable as a restart seed; with an exhausted budget it can hold an objective above the smallest value seen;
  • Evaluation operation values: "objective", "gradient", "Hessian", "residuals", "Jacobian", "constraints", "observer".

API page (docs.rs): Error.

20.8 Configuration migration

Stop fields that earlier versions kept at the top level of Options now live in Options::stopping; TrustRegionOptions.solver became TrustRegionOptions.stopping; QP receives &options.stopping; shared constraint criteria live in ConstrainedOptions.solver.stopping.

20.9 Textbook and program cross-reference

The course materials for 最优化方法及其 Matlab 程序设计 (Ma Changfeng, 2010) are external study references; they are not included in this repository or crate. The table below records textbook chapters, MATLAB program names used as mathematical references, and the matching nlopt4r entries. Program names are attribution labels, not redistributed source files.

Textbook chapterMatlab programsnlopt4r entries and components
1 Foundations of optimizationfun.m, gfun.m, Hess.mStopOptions, TerminationReason; chapter 1
2 Line-search techniquesgolds.m, qmin.m, armijo.mline_search::{minimize_scalar_with_options, armijo}; chapter 2
3 Steepest descent and Newton methodsgrad.m, dampnm.m, revisenm.mMethod::{SteepestDescent, DampedNewton, ModifiedNewton}; chapters 3–4
4 Conjugate gradient methodsfrcg.mMethod::FletcherReeves; chapter 3
5 Quasi-Newton methodsbfgs.m, dfp.m, sr1.m, broyden.mMethod::{Bfgs, Dfp, Sr1, Broyden}; chapter 4
6 Trust-region methodstrustq.m, trustm.mtrust_region::{subproblem, minimize}, local::{steihaug, trust_region_cg}; chapter 5
7 Nonlinear least squareslmm.mleast_squares::{levenberg_marquardt, levenberg_marquardt_with_options}; chapter 7
8 Optimality conditionstheoretical derivationsthe three KKT diagnostics in ConstrainedSolution; chapter 1
9 Penalty function methodsmultphr.mconstrained::augmented_lagrangian; chapter 11
10 Feasible direction methodstheoretical derivationsbounded::{projected_gradient, projected_gradient_norm}, quadratic::minimize; chapters 8 and 10
11 Quadratic programmingqpact.m, qlag.m, callqpact.mquadratic::{QuadraticProgram, minimize, equality_constrained}; chapter 10
12 Sequential quadratic programmingsqpm.m, qpsubp.m, newtlagr.m, lagsqp.mconstrained::{sqp_with_restoration, minimize}; chapter 11

Chapters 2, 3, 5, 7, 10, and 11 contain original diagrams drawn for this book to illustrate the cited derivations; each caption names the relevant textbook section and program file.

Theory background

  • Mathematical definitions of stopping criteria: see chapter 12.
  • Convergence quantities per solver: see the corresponding sections of chapters 3–11.

21. Extension Interfaces: core and utils

core and utils expose the infrastructure the solvers use internally: validated callback invocation, strict budgets, best-point recording, observers, box projection and random number generators. External algorithms can build new solvers on these public pieces alone. The theory is in chapters 12 and 8.

21.1 EvaluationContext

pub struct EvaluationContext<'a, P: Evaluator + ?Sized> { /* ... */ }

impl<'a, P: Evaluator + ?Sized> EvaluationContext<'a, P> {
    pub fn new(problem: &'a P, dimension: usize, budget: &BudgetOptions)
        -> Result<Self, Error>;
    pub fn with_observer(self, observer: &'a mut Observer<'a>) -> Self;
    pub fn counts(&self) -> EvaluationCounts;
    pub fn best(&self) -> Option<&EvaluatedPoint>;
    pub fn stop_reason(&self) -> Option<SearchTermination>;
    pub fn evaluate(&mut self, x: &[f64]) -> Result<f64, Error>;
    pub fn evaluate_into(&mut self, x: &[f64], gradient: Option<&mut [f64]>)
        -> Result<f64, Error>;
    pub fn failure(&self, source: Error) -> Error;
}

API pages (docs.rs): EvaluationContext, BudgetOptions, EvaluationCounts, EvaluatedPoint, SearchTermination.

Call semantics:

  1. inputs with an invalid shape or a wrong gradient-buffer length are rejected up front and stay uncounted;
  2. with a budget/target/cancellation criterion already met, the call returns Error::SearchStopped(SearchTermination) and invokes no callback;
  3. a valid call first counts objective (gradient additionally on a gradient request), then invokes the application callback;
  4. non-finite outputs or unwritten gradient-buffer elements report an error; the attempt stays counted;
  5. with all outputs valid, the best point updates (ties keep the earlier point);
  6. the observer runs last, and Control::Stop or an error ends subsequent calls.

EvaluatedPoint fields:

FieldTypeMeaning
xVectorSuccessfully evaluated point
valuef64Finite objective at that point

best() returns the smallest valid point recorded; ties keep the earlier point.

Example:

#![allow(unused)]
fn main() {
use nlopt4r::{core::{BudgetOptions, EvaluationContext}, value_only};

let problem = value_only(|x: &[f64]| Ok::<_, nlopt4r::EvaluationError>(x[0] * x[0]));
let budget = BudgetOptions { max_evaluations: 2, target_value: None };
let mut context = EvaluationContext::new(&problem, 1, &budget)?;
context.evaluate(&[2.0])?;
context.evaluate(&[1.0])?;
assert_eq!(context.best().unwrap().value, 1.0);
assert_eq!(context.counts().objective, 2);
assert!(context.evaluate(&[0.5]).is_err());   // budget is exhausted
Ok::<(), nlopt4r::Error>(())
}

21.2 Observers and failure wrapping

pub enum Control { Continue, Stop }

pub struct EvaluationEvent<'a> {
    pub x: &'a [f64],
    pub value: f64,
    pub best_value: f64,
    pub evaluations: EvaluationCounts,
}

pub type Observer<'a> =
    dyn for<'b> FnMut(&EvaluationEvent<'b>) -> Result<Control, EvaluationError> + 'a;

API pages (docs.rs): Control, EvaluationEvent, Observer.

failure(source), with a best point present, wraps the error as Error::SearchFailure { source, last_point, evaluations } and keeps the checkpoint.

#![allow(unused)]
fn main() {
use nlopt4r::{core::{BudgetOptions, EvaluationContext}, value_only};

let problem = value_only(|x: &[f64]| {
    if x[0] < 0.0 {
        return Err("simulation failed".into());
    }
    Ok::<_, nlopt4r::EvaluationError>(x[0] * x[0])
});
let mut context = EvaluationContext::new(&problem, 1, &BudgetOptions::default())?;
context.evaluate(&[2.0])?;
let source = context.evaluate(&[-1.0]).unwrap_err();
let error = context.failure(source);
assert_eq!(error.last_point().unwrap().value, 4.0);
assert_eq!(context.counts().objective, 2);
Ok::<(), nlopt4r::Error>(())
}

21.3 Bounds

impl Bounds {
    pub fn new(lower: Vec<f64>, upper: Vec<f64>) -> Result<Self, Error>;
    pub fn uniform(n: usize, lower: f64, upper: f64) -> Result<Self, Error>;
    pub fn dimension(&self) -> usize;
    pub fn lower(&self) -> &[f64];
    pub fn upper(&self) -> &[f64];
    pub fn width(&self, i: usize) -> f64;
    pub fn validate_point(&self, x: &[f64]) -> Result<(), Error>;
    pub fn contains(&self, x: &[f64]) -> bool;
    pub fn project(&self, x: &mut [f64]) -> Result<(), Error>;
    pub fn midpoint(&self) -> Vector;
    pub fn from_unit(&self, unit: &[f64]) -> Result<Vector, Error>;
    pub fn to_unit(&self, x: &[f64]) -> Result<Vector, Error>;
    pub fn sample<R: Rng + ?Sized>(&self, rng: &mut R, x: &mut [f64])
        -> Result<(), Error>;
}

API page (docs.rs): Bounds.

Conventions:

  • construction requires finite lower and upper bounds, \(l_i\le u_i\) per coordinate and a positive dimension;
  • width(i) = u_i - l_i, with zero-width coordinates treated as fixed variables;
  • from_unit/to_unit map between the unit box and the physical box, sending zero-width coordinates to the fixed value;
  • project clips out-of-range coordinates to the interval endpoints.

21.4 utils

FunctionRole
validate_slice(x, n, context)Checks slice length and finiteness
solve_dense(a, b)Validates and solves a square linear system
directional_difference(context, x, direction, step)Central difference \((f(x+sd)-f(x-sd))/(2s)\), with both calls counted in the context budget

RNG re-exports: utils::ChaCha8Rng, utils::Rng, utils::SeedableRng. The global algorithms create reproducible streams with ChaCha8Rng::seed_from_u64(seed).

API pages (docs.rs): validate_slice, solve_dense, directional_difference, ChaCha8Rng, Rng, SeedableRng.

The algorithm below uses public pieces alone and completes a full “start at the midpoint, poll coordinates, halve on failure” search in about 30 lines:

use nlopt4r::{Bounds, Error, value_only};
use nlopt4r::core::{BudgetOptions, EvaluationContext};

fn main() -> Result<(), Error> {
    let problem = value_only(|x: &[f64]| {
        Ok::<_, nlopt4r::EvaluationError>((x[0] - 0.3).powi(2) + (x[1] + 0.4).powi(2))
    });
    let bounds = Bounds::uniform(2, -1.0, 1.0)?;
    let budget = BudgetOptions {
        max_evaluations: 400,
        target_value: Some(1e-10),
    };
    let mut context = EvaluationContext::new(&problem, bounds.dimension(), &budget)?;
    let mut x = bounds.midpoint();
    context.evaluate(x.as_slice())?;
    let mut step = 0.5;
    while step > 1e-7 && context.stop_reason().is_none() {
        let before = context.best().expect("initial evaluation").value;
        for i in 0..x.len() {
            if bounds.width(i) == 0.0 {
                continue;
            }
            for sign in [-1.0, 1.0] {
                if context.stop_reason().is_some() {
                    break;
                }
                let mut trial = x.clone();
                trial[i] += sign * step * bounds.width(i);
                bounds.project(trial.as_mut_slice())?;
                context.evaluate(trial.as_slice())?;
            }
        }
        let best = context.best().expect("evaluated point");
        x.copy_from(&best.x);
        if best.value >= before {
            step *= 0.5;
        }
    }
    println!("best f = {}", context.best().unwrap().value);
    Ok(())
}

Key points:

  • stop_reason() covers target hits, budgets, iterations and observer cancellation;
  • checking the stop state before each evaluate keeps callbacks from running after budget exhaustion;
  • Bounds::project keeps trial points feasible;
  • the final state comes from stop_reason(), with None corresponding to the step threshold (this example exits at step <= 1e-7).

The complete external solver example in the repository lives in tools/extension and runs directly as the benchmark tool’s external-pattern algorithm:

cargo test -p nlopt4r-extension-example
cargo run --release --locked -p nlopt4r-bench -- \
  --suite smoke --algorithms external-pattern --seeds 0..3 \
  --dimension 2 --budget-per-dimension 1000 --output target/extension.jsonl

21.6 Composition guide

NeedBuilding block
Strict budget and best pointEvaluationContext
Cancellation and external loggingwith_observer + Control
Checkpoint retention on failurecontext.failure(error)
Finite boxBounds + project/sample
Reproducible random streamChaCha8Rng::seed_from_u64
Difference gradients (diagnostics)utils::directional_difference
Dense linear solveutils::solve_dense

Theory background

  • Budgets, target values and counting semantics: see chapter 12.
  • Box projection and pattern search: see chapter 8.
  • Population initialization and seeds: see chapter 9.

22. Validation, Benchmarks and Site Build

This chapter collects the repository check commands, benchmark runs and the build/release flow of this book. The published crate is https://crates.io/crates/nlopt4r, with API documentation at https://docs.rs/nlopt4r/1.0.1/nlopt4r/.

22.1 Routine checks

cargo test
cargo test --release
cargo fmt --check
cargo clippy --all-targets -- -D warnings
RUSTDOCFLAGS="-D warnings -D missing_docs" cargo doc -p nlopt4r --no-deps
cargo test -p nlopt4r --doc
  • cargo test runs the solver package’s integration tests, unit tests and doctests;
  • cargo test --workspace additionally runs the benchmark, native-reference and extension packages; the native-reference tests need CMake and a C compiler;
  • --release rechecks numerical tests in an optimized build;
  • clippy covers all targets with warnings treated as errors;
  • the rustdoc check rejects missing documentation and broken links;
  • doctests compile and run the public examples.

Current 1.0.1 counts: 90 solver integration tests, 3 solver unit tests, 16 solver doctests, 10 native comparisons and 28 benchmark-tool tests. The extension example has no tests. The historical 118-test baseline for an earlier revision is recorded in docs/BENCHMARK_RESULTS.md.

22.2 Native comparison and NIST

The native comparison tests require CMake and a C compiler and build the bundled NLopt C library:

cargo test -p nlopt4r-reference
cargo test --release -p nlopt4r-reference

This dependency belongs to the unpublished comparison tool package alone; the default cargo test and downstream builds stay pure Rust.

Nonlinear least-squares validation against NIST certified data:

cargo test -p nlopt4r --test nist

22.3 Coverage measurement

cargo llvm-cov -p nlopt4r --json --output-path target/coverage-full.json

Historical baseline at the recorded benchmark revision: line coverage 90.05% (3331/3699), function coverage 93.91% (262/279), region coverage 88.34% (5546/6278), excluding doctests and the native tools. Branch coverage was not instrumented, so no branch-coverage percentage is claimed.

22.4 Benchmark driver

tools/bench is the unpublished nlopt4r-bench executable:

cargo run --release --locked -p nlopt4r-bench -- \
  --suite smoke --algorithms bfgs,lbfgs,de,pso --seeds 0..30 \
  --dimension 4 --budget-per-dimension 1000 --output target/smoke.jsonl
cargo run -p nlopt4r-bench -- --summarize target/smoke.jsonl
OptionMeaning
--suite smoke|smooth|globalProblem group
--algorithms ...Algorithm registry: bfgs, lbfgs, de, pso, pattern-search, nelder-mead, external-pattern
--seeds 0..30Optimizer seed interval, with the right endpoint exclusive
--dimension NDimension for variable-dimension problems; fixed-dimension problems keep their own dimension
--budget-per-dimension NObjective budget = this value × actual dimension
--output path.jsonl|.csvRecord file; an existing file stays intact
--summarize pathOffline summary, accepting both formats

Transform and noise switches:

OptionDefaultEffect
--shift on|offoffTranslate the known minimizer to a seed-selected interior point
--rotate on|offoffApply a seed-selected orthogonal rotation
--instance-seed N0Problem-instance seed, independent of optimizer seeds
--noise none|gaussian|uniform|laplacenoneObservation-noise distribution
--noise-level SIGMA0Standard deviation in objective units
--noise-seed N0Noise-experiment seed

Pairing experiments: same instance seed and same optimizer seed, run separately across the four switch combinations. Noise example:

cargo run --release --locked -p nlopt4r-bench -- \
  --suite smoke --algorithms de,pso --seeds 0..30 \
  --dimension 2 --budget-per-dimension 2000 \
  --shift on --rotate on --instance-seed 42 \
  --noise gaussian --noise-level 0.01 --noise-seed 17 \
  --output target/noisy.jsonl
cargo run --release --locked -p nlopt4r-bench -- --summarize target/noisy.jsonl

Metric definitions:

  • target value \(= f_{\text{ref}}+10^{-6}(1+|f_{\text{ref}}|)\);
  • ERT = sum of first-hit evaluations over successful runs and consumed evaluations over failed runs ÷ success count;
  • zero successes correspond to an infinite ERT;
  • noise experiments separate “visit hits” from “returned recommendation hits”.

Summaries group by budget, target and environment metadata, and distinct configurations stay in separate groups. The full protocol is in docs/BENCHMARKS.md, and the 30-seed measured tables are in docs/BENCHMARK_RESULTS.md.

Criterion kernel checks:

cargo bench --bench kernels
CARGO_NET_OFFLINE=true cargo bench --bench kernels -- --test

22.5 Building this book

mdBook 0.5.4 is required:

cargo install mdbook --version 0.5.4 --locked
mdbook build books/zh
mdbook build books/en
python3 -m http.server 8000 -d book
  • the Chinese book outputs to book/, the English book to book/en/;
  • the site root http://localhost:8000/ serves Chinese, http://localhost:8000/en/ serves English;
  • the top-bar language button switches between /x.html and /en/x.html while keeping the anchor;
  • previewing one language alone works through mdbook serve books/zh or mdbook serve books/en.

Build checks:

mdbook build books/zh && mdbook build books/en
cargo build -p nlopt4r
for f in books/zh/src/*.md; do
  rustdoc --test "$f" --extern nlopt4r=target/debug/libnlopt4r.rlib \
    -L dependency=target/debug/deps --edition 2024
done

rustdoc --test compiles every code block: signature-display blocks carry ignore, and runnable examples execute against the current API. The English book uses the same command.

22.6 Manual deployment to GitHub Pages

The workflow .github/workflows/pages.yml supports manual triggering alone:

  1. open Actions → Deploy nlopt4r book to GitHub Pages → Run workflow in the repository;
  2. the workflow installs mdBook 0.5.4, builds both languages and uploads book/;
  3. deploy-pages publishes to GitHub Pages (Source set to GitHub Actions, HTTPS enforced).

Local rehearsal (with wrkflw installed):

WRKFLW_SKIP_ACTIONS=actions/upload-pages-artifact \
  wrkflw run --runtime emulation --job build .github/workflows/pages.yml

The rehearsal covers checkout, the pinned mdBook installation and both book builds; the upload step is skipped in wrkflw and runs natively on GitHub. The rehearsal reports as partially passing.

Pre-publish checklist:

  • mdbook build books/zh and mdbook build books/en succeed;
  • the book’s runnable code blocks pass rustdoc --test;
  • under the local HTTP server the language switch and the table-of-contents links resolve;
  • the workflow file keeps workflow_dispatch as its single trigger.

22.7 Documentation index

FileContent
docs/BENCHMARKS.mdBenchmark protocol, options, error semantics
docs/BENCHMARK_RESULTS.mdMeasured baseline, pairing experiments, coverage and validation counts
docs/NIST.mdCertified least-squares validation
docs/THEORY.mdMethod selection, assumptions, costs and references
docs/SCALABLE_LOCAL.mdL-BFGS, Newton-CG, Steihaug
docs/FOUNDATIONS.mdBudgets, observers and external algorithm examples
docs/ROBUSTNESS.mdAdaptive QR LM, projected gradient, SQP restoration
docs/GLOBAL.mdDE/PSO parameters and seed protocol
docs/ROADMAP.mdFollow-up extension items

Theory background