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 class | Entry points | Required derivatives |
|---|---|---|
| Smooth unconstrained, small/medium | minimize + Method | Gradient; Newton variants also a Hessian |
| Smooth unconstrained, large | local::lbfgs | Gradient |
| Hessian-vector products available | local::newton_cg, local::trust_region_cg | Gradient and HVP |
| Small dense trust region | trust_region::minimize | Gradient and Hessian |
| Finite box, gradient available | bounded::projected_gradient | Gradient |
| Finite box, derivative-free local search | derivative_free::{pattern_search, nelder_mead} | Objective values |
| Finite box, multimodal global search | global::{differential_evolution, particle_swarm} | Objective values |
| Residuals and Jacobians | least_squares::levenberg_marquardt_with_options | Jacobian |
| Convex quadratic programming | quadratic::minimize | Model data |
| Nonlinear constraints | constrained::sqp_with_restoration, constrained::augmented_lagrangian | Gradient 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\).
EvaluationCountsrecords 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 class | Standard form | Main 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
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
First-order box stationarity is characterized by the unit-step gradient mapping
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
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}\):
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:
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 family | Reported convergence quantity |
|---|---|
| Unconstrained gradient/quasi-Newton/trust region | \(|g|_2\) |
| Box-constrained projected gradient | \(|x-P(x-g)|_2\) |
| Nonlinear constraints | Lagrangian 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 checkpoint | NaN (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
- Report structures
Solution,Status,TerminationReason: see chapter 20. - Box constraints and projection: see chapter 16 and chapter 21.
- Constraint diagnostics and multipliers: see chapter 19.
- API pages (docs.rs):
Objective,Evaluator,Bounds,Solution.
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
Armijo backtracking starts at \(\alpha_0=1\) and tries \(\alpha_k=\alpha_0\kappa^k\), accepting a step that satisfies
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 }, withevaluationsthe number of trials andlast_stepthe 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:
with \(0<c_1<c_2<1\); the defaults are \(c_1=10^{-4}\) and \(c_2=0.9\).
The implementation has two stages:
- from the initial step 1, trial steps expand by doubling until a bracket holds an acceptable point;
- 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.
2.3 Scalar search
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
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
| Type | Field | Meaning |
|---|---|---|
Step | alpha | Accepted step length |
Step | value | Objective at the accepted point |
Step | evaluations | Number of trials |
StrongWolfeStep | alpha, value, gradient | Accepted step, objective, analytic gradient |
StrongWolfeStep | evaluations | Combined value/gradient callbacks (origin counted separately) |
ScalarSolution | x, value, bracket | Best point, objective, remaining interval |
ScalarSolution | status, termination_reason | Interval convergence or a budget/iteration stop |
ScalarSolution | evaluations | Objective calls, including endpoint evaluations |
2.5 Parameter defaults
| Option type | Field | Default | Valid range |
|---|---|---|---|
ArmijoOptions | initial_step | 1 | Positive finite |
ArmijoOptions | contraction | 0.5 | \((0,1)\) |
ArmijoOptions | sufficient_decrease | 0.2 | \((0,1)\) |
ArmijoOptions | max_iterations | 60 | Positive integer |
StrongWolfeOptions | sufficient_decrease | \(10^{-4}\) | \(0<c_1<c_2\) |
StrongWolfeOptions | curvature | 0.9 | \(c_1<c_2<1\) |
StrongWolfeOptions | initial_step / maximum_step | 1 / \(10^{20}\) | Positive finite, initial at most maximum |
StrongWolfeOptions | max_evaluations | 80 | Positive integer |
ScalarOptions | interval_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,StrongWolfeStepand 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
Normalized gradient takes the unit-length direction
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
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
| Method | Main work per step | Storage | Typical rate |
|---|---|---|---|
| Steepest descent | 1 gradient + line search | \(O(n)\) | Linear; slow on ill-conditioned problems |
| Normalized gradient | 1 gradient + line search | \(O(n)\) | Linear |
| Fletcher–Reeves | 1 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
minimizeand theMethodenum: see chapter 16.- Callback interfaces: see chapter 15.
- API pages (docs.rs):
minimize,Method.
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
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:
starting from \(\sigma=|g_k|\) and doubling until a Cholesky factorization succeeds, then solving
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
nlopt4r implements four dense updates:
BFGS (\(\phi=1\)):
DFP (\(\phi=0\)):
SR1:
Broyden convex family (\(0\le\phi\le 1\)), interpolating between DFP and inverse BFGS:
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
| Method | Work per step | Storage | Derivatives |
|---|---|---|---|
| DampedNewton | 1 Hessian + \(O(n^3)\) solve + line search | \(O(n^2)\) | Gradient and Hessian |
| ModifiedNewton | Cholesky attempts + linear solves | \(O(n^2)\) | Gradient and Hessian |
| Bfgs / Dfp / Sr1 / Broyden | rank-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
- The
Methodenum andminimize: see chapter 16. - The Hessian callback
Function::with_hessian: see chapter 15. - Line-search settings
Options::line_search: see chapter 2 and chapter 20. - API pages (docs.rs):
minimize,Method,Options.
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
and the subproblem reads
A global minimizer \(d^\ast\) satisfies
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 }, withvaluethe model change \(q(d)\) andmultiplierthe \(\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:
- compute \(g_k\) and test the gradient tolerance;
- solve the subproblem for a step \(d_k\) and predicted decrease \(q_k(d_k)\);
- compute the ratio
- accept when \(\rho_k>\tau_a\), default \(\tau_a=0.15\);
- 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})\);
- 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 theHessianVectortrait: 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
A correction pair is admitted when
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:
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_evaluationscovers objective calls, including the start evaluation, rejected trials and failed callbacks;gradient_tolerancetests \(|g|\);- optional
value_toleranceandstep_tolerancereport stagnation; evaluations.subproblemrecords inner CG solves.
Software interface
local::{lbfgs, newton_cg, trust_region_cg}and their option types: see chapter 16.- A complete
HessianVectorexample: 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:
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
Levenberg–Marquardt adds damping:
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
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
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
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
in Solution::gradient_norm, with the test
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.objectiveandevaluations.residuals; - each Jacobian call counts in
evaluations.jacobianandevaluations.gradient; - the objective budget
max_evaluationscovers 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
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
- The
LeastSquarestrait, both LM entry points andLmOptions: see chapter 18. - Tuple adapters for residuals and Jacobians: see chapter 15.
- NIST test command: see chapter 22.
- API reference (docs.rs):
least_squares.
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
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:
- project the initial point into the box;
- compute the gradient \(g_k\);
- take the negative projected mapping \(d_k=P(x_k-g_k)-x_k\);
- run Armijo backtracking along the feasible segment \(x_k+\alpha d_k\), projecting each trial;
- stop when \(|G(x_k)|\le\tau_g\).
For step lengths \(\alpha\le1\), box convexity and the projection inequality give
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}\).
8.3 Coordinate pattern search
derivative_free::pattern_search polls coordinate directions with a normalized step \(h\):
- for each free coordinate \(i\), evaluate \(x\pm h,(u_i-l_i)\) with trials projected into the box;
- after a poll, take the best point among all evaluated points;
- halve the step, \(h\leftarrow h/2\), when the poll produces no improvement;
- 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, reportingStagnated; - 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:
| Field | Meaning |
|---|---|
x, value | Best evaluated point and its objective |
iterations | Completed poll/simplex iterations |
evaluations | Objective calls (gradient counts remain zero) |
termination_reason | TargetReached, MaxEvaluations, MaxIterations, Stagnated or Cancelled |
BudgetOptions::target_value supplies the target stop: reaching it returns TargetReached early.
Software interface
bounded::projected_gradientandBounds: see chapter 16 and chapter 21.derivative_free::{pattern_search, nelder_mead, Options}: see chapter 17.- The
SearchTerminationenum: see chapter 20. - API pages (docs.rs):
projected_gradient,Bounds.
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:
- initialization: sample
population_sizepoints uniformly in the box, or validate a caller-supplied population; - for each target \(i\), draw three distinct donors \(a,b,c\) with \(i\) excluded from the donor set;
- mutation vector
- 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\);
- bound repair: a mutant component below its lower bound becomes
and one above its upper bound becomes
- 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:
| Field | Default | Valid range |
|---|---|---|
population_size | 40 | \(\ge 4\) |
max_generations | 1000 | Nonnegative integer |
weight (\(F\)) | 0.8 | \(0<F\le2\) |
crossover (\(CR\)) | 0.9 | \(0\le CR\le1\) |
seed | 0 | Any 64-bit unsigned integer |
budget.max_evaluations | 10000 | Positive integer |
budget.target_value | None | Finite value |
9.2 Particle swarm
The velocity and position updates of global::particle_swarm:
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_limitsupplies \(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:
| Field | Default | Valid range |
|---|---|---|
population_size | 40 | \(\ge 2\) |
max_generations | 1000 | Nonnegative integer |
inertia (\(w\)) | 0.7 | \(0\le w<1\) |
cognitive (\(c_1\)) | 1.5 | Finite nonnegative |
social (\(c_2\)) | 1.5 | Finite nonnegative |
velocity_limit | 0.2 | \(0<v\le1\) |
seed | 0 | Any 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:
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:
| Field | Meaning |
|---|---|
x, value | Best evaluated point and its objective |
generations | Completed generations (initialization and an unfinished generation excluded) |
evaluations | Callback counts, including initialization |
termination_reason | TargetReached, MaxEvaluations, MaxIterations, Stagnated or Cancelled |
seed | Seed of this run |
diversity | Maximum 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_observervariants call the observer after each valid evaluation;Control::Stopcancels after the current evaluation; an observer error propagates with the best point retained;- cancellation, budget and generation caps are ordinary reports, with
termination_reasonrecording 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
with \(H\) symmetric positive semidefinite, checked against the threshold
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
The active-set iteration:
- solve the KKT system for the step \(d\) and multipliers \(\nu\);
- check inequality rows along \(d\): a blocking row (\(A_i(x+\alpha d)=b_i\) reached first) joins the active set;
- with no blocking row, update \(x\); check inequality multiplier signs and drop rows with negative multipliers;
- 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\):
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:
- square systems try full-pivot LU; a residual within \(10^{-10}(1+|b|)\) accepts that solution;
- remaining cases use the SVD minimum-norm solution with truncation threshold \(10^{-12}\max(|A|,1)\);
- 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
QuadraticSolutionwith 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.QuadraticSolutionfields 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
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:
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
the update is
Multipliers interpolate along the step:
The line search uses the \(l_1\) exact penalty function
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
The restoration iteration:
- assemble residuals and Jacobian rows from the equality rows and the currently violated inequality rows;
- solve a damped augmented QR system for the direction;
- backtrack on the actual nonlinear objective \(\theta\);
- 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
with the Lagrangian Hessian supplied by the caller. LagrangeSqp adds the stabilization term
The line-search merit function is
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
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:
- 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); - multiplier updates
- residual \(r=\max(\text{violation},\text{complementarity})\) triggers a penalty doubling when \(k\ge2\) and \(r>0.8,r_{\text{prev}}\);
- 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
Constraintsconstructors and theConstrainedProblemtrait: see chapter 19.SqpOptions,SqpSolution,SqpErrorandRestorationEvent: see chapter 19.- Line search and budgets: see chapter 2 and chapter 12.
- API reference (docs.rs):
constrained.
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:
| Field | Default | Meaning |
|---|---|---|
max_iterations | 5000 | Outer iteration cap; 0 still evaluates the initial point and checks convergence |
max_evaluations | None | Strict objective-call cap; None leaves iterations as the sole limit |
gradient_tolerance | \(10^{-6}\) | Stationarity (gradient/KKT/interval) tolerance |
value_tolerance | None | Optional objective-stagnation tolerance |
step_tolerance | None | Optional accepted-step stagnation tolerance |
Mixed tolerances meet the condition
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:
- on a satisfied convergence criterion, return convergence (
GradientTolerance,KktToleranceorIntervalTolerance); - on reaching the objective-call budget, return
MaxEvaluations; - on reaching the iteration cap, return
MaxIterations; - on a satisfied enabled stagnation criterion at an accepted step, return a
Stagnatedreason.
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:
| Field | Counted object |
|---|---|
objective | Objective or residual calls, including rejected trials and failed callbacks |
gradient | Gradient requests; least-squares Jacobian requests count here |
hessian | Dense Hessian or Hessian-vector product requests |
constraints | Nonlinear constraint value or model-state evaluations |
residuals | Residual vector requests |
jacobian | Residual or constraint Jacobian requests |
subproblem | Synthesized 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:
| Value | Meaning |
|---|---|
Converged | A solver convergence criterion holds |
MaxIterations | Iteration cap exhausted |
MaxEvaluations | Objective budget exhausted |
Stagnated | An enabled stagnation criterion holds |
Failed | State 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:
| Variant | Trigger |
|---|---|
InvalidInput | An option, domain, direction or precondition fails |
DimensionMismatch | Vector or matrix shape mismatch, with expected and actual shapes |
NonFinite | A non-finite value in inputs, callback outputs or intermediate arithmetic |
MissingHessian | A dense Newton method requests a Hessian the problem leaves absent |
SingularSystem | A linear system that is singular, inconsistent or numerically unsolvable |
Infeasible | A constraint system or linearized subproblem infeasible |
LineSearchFailed | Line-search trials exhausted, with trial count and final step |
IterationLimit | A nested solver exhausts its iterations, with solver name and count |
SubproblemStopped | A synthesized subproblem stops, with solver name, reason and count |
EvaluationBudgetExceeded | Internal objective-budget signal |
SearchStopped | An extra evaluation request on a stopped context |
SearchFailure | Value-search failure, with best point and counts |
Evaluation | An application callback fails, with operation class and message |
SolverFailure | A local solve fails, with outer name, source error and checkpoint |
12.6 Checkpoints and recovery
Error wrappers retain valid state:
Error::root_cause()unwrapsSolverFailure/SearchFailureand returns the underlying class;Error::last_solution()returns the local solver’s full evaluation checkpoint with statusFailed;Error::last_point()returns the best evaluated point of a value search;Error::source()chains follow the standardstd::error::Errorconvention.
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
IterationLimitorSubproblemStoppedwhen their iterations run out; - callback panics propagate under the Rust unwinding rules.
Software interface
StopOptions,Tolerance,EvaluationCounts: see chapter 20.- Error-handling examples and recovery methods: see chapter 20.
- Defaults per solver family: see chapters 16–19.
- API pages (docs.rs):
StopOptions,EvaluationCounts,Error.
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) andglobal(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 dimensionobjective 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
- 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:
- 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
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:
| Problem | BFGS | L-BFGS | DE | PSO |
|---|---|---|---|---|
| Sphere | 30/30; 3.00 | 30/30; 3.00 | 30/30; 1420.67 | 30/30; 1343.23 |
| Rosenbrock | 30/30; 62.87 | 30/30; 39.30 | 30/30; 2232.73 | 24/30; 3879.67 |
| Booth | 30/30; 13.07 | 30/30; 10.53 | 30/30; 1744.53 | 30/30; 1773.03 |
| Rastrigin | 0/30 | 0/30 | 29/30; 3534.10 | 30/30; 2513.23 |
| Linear fit | 30/30; 9.00 | 30/30; 10.20 | 30/30; 1517.37 | 30/30; 1448.27 |
| Coupled QP | 30/30; 11.70 | 30/30; 7.27 | 30/30; 1320.60 | 30/30; 1173.60 |
global suite, requested dimension 4 (fixed-dimension problems keep dimension 2):
| Problem | Dimension/budget | DE | PSO |
|---|---|---|---|
| Ackley | 4 / 8000 | 2/30 | 30/30; 5067.03 |
| Alpine | 4 / 8000 | 0/30 | 30/30; 4891.83 |
| Easom | 2 / 4000 | 30/30; 1722.60 | 30/30; 1499.43 |
| Griewank | 4 / 8000 | 0/30 | 0/30 |
| Himmelblau | 2 / 4000 | 30/30; 2977.20 | 30/30; 1942.23 |
| Levy | 4 / 8000 | 30/30; 4402.57 | 30/30; 2351.37 |
| Qing | 4 / 8000 | 0/30 | 30/30; 3096.20 |
| Rastrigin | 4 / 8000 | 0/30 | 7/30; 31449.29 |
| Schwefel-222 | 4 / 8000 | 1/30 | 30/30; 5193.03 |
Native L-BFGS comparison (same ChaCha8 starting points, unbounded domain, history 10):
| Problem | Dimension/budget | Native NLopt | nlopt4r |
|---|---|---|---|
| Sphere | 2 / 4000 | 30/30; 3.00 | 30/30; 3.00 |
| Rosenbrock | 2 / 4000 | 30/30; 37.83 | 30/30; 43.30 |
| Sphere | 20 / 40000 | 30/30; 3.00 | 30/30; 3.00 |
| Rosenbrock | 20 / 40000 | 25/30; 166.52 | 25/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.mdin 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 testavailable; - the build fetches
nalgebra,randandrand_chachafrom 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
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);Vectoris an alias ofnalgebra::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:
| Field | Meaning |
|---|---|
x, value | Returned point and objective value |
gradient_norm | Stationarity norm of the solver family (section 1.7) |
iterations | Outer iteration count |
status | Converged, MaxIterations, MaxEvaluations, Stagnated or Failed |
termination_reason | The specific criterion |
evaluations | Per-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
- Problem form and convergence quantities: see chapter 1.
- Quasi-Newton methods and BFGS: see chapter 4.
- Stopping and report fields: see chapter 12 and chapter 20.
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 returningSome.
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: Nonerequests 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
| Need | Interface |
|---|---|
| Analytic objective returning values directly | Objective or a closure tuple |
| Buffered writes, shared value/gradient computation | Function or Evaluator |
| Application errors reported upward | Function, Evaluator or try_* hooks |
| Objective values alone | value_only |
| Hessian-vector products | local::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
- Derivatives in optimality conditions: see chapter 1.
- Hessians in Newton and trust-region methods: see chapter 4 and chapter 5.
- Counts and budgets: see chapter 12.
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:
| Variant | Direction/model | Memory |
|---|---|---|
SteepestDescent | \(d=-g\) | \(O(n)\) |
NormalizedGradient | \(d=-g/\lVert g\rVert\) | \(O(n)\) |
FletcherReeves | Conjugate gradient, restart every \(n+1\) steps | \(O(n)\) |
DampedNewton | Dense Newton system + Armijo | \(O(n^2)\) |
ModifiedNewton | Positive-definite shifted Hessian | \(O(n^2)\) |
Bfgs | Dense inverse BFGS | \(O(n^2)\) |
Dfp | Dense inverse DFP | \(O(n^2)\) |
Sr1 | Symmetric 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;
Stepfields: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:
| Field | Default |
|---|---|
initial_step | 1 |
contraction | 0.5 |
sufficient_decrease | 0.2 |
max_iterations | 60 |
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_normis the gradient-mapping norm \(\lVert x-P(x-g)\rVert\), zero at active boundary points;- uses the gradient tolerance of
Options::stoppingand the Armijo parameters ofOptions::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_sizecorrection 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:
| Field | Default |
|---|---|
stopping | StopOptions::default() |
line_search | StrongWolfeOptions::default() |
history_size | 10 |
curvature_tolerance | 1e-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:
| Field | Default |
|---|---|
stopping | StopOptions::default() |
line_search | StrongWolfeOptions::default() |
max_cg_iterations | 100 |
cg_tolerance | 0.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_thresholdaccepts 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:
| Field | Default |
|---|---|
stopping | StopOptions::default() |
initial_radius | 1 |
maximum_radius | 2 |
acceptance_threshold | 0.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:
| Variant | Condition |
|---|---|
ResidualTolerance | Residual norm reaches relative_tolerance times the starting norm |
Boundary | Positive-curvature CG reaches the trust-region boundary |
NegativeCurvature | A direction of nonpositive curvature continues to the better point on the boundary |
MaxIterations | Inner 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.
16.9 Scalar search
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_scalaris the convenience entry: one absolute interval tolerance and an iteration cap, with the relative tolerance fixed at \(\sqrt{\varepsilon_{\text{mach}}}\);minimize_scalar_with_optionstakes the fullScalarOptionsand a strict objective budget;ScalarMethod::GoldenSectionandScalarMethod::Parabolic(Brent-protected interpolation);- interval defaults: absolute \(10^{-8}\), relative \(\sqrt{\varepsilon_{\text{mach}}}\);
ScalarSolutionfields: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
| Scenario | Entry |
|---|---|
| Small scale with analytic Hessian | Method::DampedNewton, Method::ModifiedNewton |
| Small scale, gradient only | Method::Bfgs, Method::Dfp, Method::Sr1 |
| Medium to large scale, gradient only | local::lbfgs |
| Large scale with computable Hessian-vector products | local::newton_cg, local::trust_region_cg |
| Variables with lower and upper bounds | bounded::projected_gradient |
| One-dimensional continuous unimodal | line_search::minimize_scalar* |
| Few variables, nonsmooth objective | derivative_free (chapter 17) |
Theory background
- Line-search conditions: see chapter 2.
- Quasi-Newton and Newton methods: see chapter 4.
- Trust regions: see chapter 5.
- Large scale and matrix-free: see chapter 6.
- Bounded projection: see chapter 8.
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:
| Field | Default | Notes |
|---|---|---|
budget | BudgetOptions::default() | 10000 objective calls, no target value |
seed | 0 | ChaCha8 seed |
population_size | 40 | At least 4 |
max_generations | 1000 | Generation zero still runs initialization |
weight | 0.8 | \(F\in(0,2]\) |
crossover | 0.9 | \(CR\in[0,1]\) |
initial_population | None | Optional 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:
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:
| Field | Default | Notes |
|---|---|---|
budget | BudgetOptions::default() | 10000 objective calls |
seed | 0 | ChaCha8 seed |
population_size | 40 | At least 2 |
max_generations | 1000 | Initialization counted separately |
inertia | 0.7 | \(\omega\in[0,1)\) |
cognitive | 1.5 | \(c_1\ge0\) |
social | 1.5 | \(c_2\ge0\) |
velocity_limit | 0.2 | \(c_v\in(0,1]\) |
initial_population | None | Feasible 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:
| Field | Meaning |
|---|---|
x, value | Best point and value over all valid evaluations |
generations | Complete generations, with initialization and an unfinished generation excluded |
evaluations | Attempted-call counts |
termination_reason | TargetReached, MaxEvaluations, MaxIterations, Stagnated or Cancelled |
seed | Seed of this run |
diversity | Maximum 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.
17.6 Bounded derivative-free local search
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
x0must be finite, of the correct dimension and feasible.
derivative_free::Options defaults:
| Field | Default |
|---|---|
budget | 10000 objective calls |
max_iterations | 2000 |
initial_step | 0.1 (fraction of the coordinate width, in \((0,1]\)) |
step_tolerance | 1e-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_evaluationsis a strict cap, and the count includes initialization and failed callbacks;- with
target_valuepresent, any valid point reaching \(f(x)\le\) target stops the search; max_generations = 0still 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
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
| Entry | Step computation | Damping | Use |
|---|---|---|---|
levenberg_marquardt | Normal equations \((J^\top J+\mu I)d=-J^\top r\), \(\mu=\max(\lVert r\rVert,10^{-12})\), Armijo backtracking | Fixed rule | Well-conditioned problems with small residuals |
levenberg_marquardt_with_options | Column-scaled augmented QR, adaptive \(\mu\) | Nielsen update | Ill-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:
| Field | Default | Notes |
|---|---|---|
stopping | StopOptions::default() | Gradient tolerance applies to the column-scaled stationarity quantity |
initial_damping | 1e-3 | At or above the damping lower bound |
minimum_damping | 1e-15 | Damping lower bound |
acceptance_ratio | 1e-4 | Actual/predicted decrease ratio threshold, in \([0,1)\) |
max_damping_trials | 40 | Damping trials per accepted iterate |
Convergence quantity of the adaptive variant:
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:
- the inequality direction is \(A_i x\ge b_i\);
- with zero constraint rows the matrices have shape \(0\times n\);
QuadraticProgram::unconstrainedbuilds empty constraints fromlinear.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,
API page (docs.rs): QuadraticSolution.
QuadraticSolution fields:
| Field | Meaning |
|---|---|
solution | Iteration/objective/stationarity report; check solution.converged() first |
equality_multipliers | Equality multipliers \(\mu\) satisfying \(Hx+c-A_e^\top\mu-A_i^\top\lambda=0\) |
inequality_multipliers | Active inequality multipliers, nonnegative; zero outside the active set |
constraint_violation | Maximum 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 withKktTolerance; - 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,SingularSystemand 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:
with Lagrangian
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:
| Constructor | Use |
|---|---|
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
Evaluatoror theObjectiveadapter; lagrangian_hessianreturns the Hessian of \(L\), and both exact-Hessian methods require it;- a failing constraint callback reports as
Error::Evaluation { operation: "constraints" }throughtry_constraints.
19.3 Entries and options
API pages (docs.rs): Method, minimize, augmented_lagrangian, ConstrainedOptions, ConstrainedSolution.
| Entry | Algorithm | Constraint types |
|---|---|---|
minimize(..., Method::Sqp, ...) | Powell damped BFGS + \(l_1\) exact penalty | Equalities and inequalities |
minimize(..., Method::NewtonLagrange, ...) | Newton on the KKT equations | Equalities alone |
minimize(..., Method::LagrangeSqp, ...) | SQP with a stabilized Lagrange Hessian | Equalities alone |
sqp_with_restoration | SQP + feasibility restoration phase | Equalities and inequalities |
augmented_lagrangian | PHR multiplier/penalty iteration + BFGS inner loop | Equalities and inequalities |
ConstrainedOptions defaults:
| Field | Default | Notes |
|---|---|---|
solver | Options::default() | Outer stopping and Armijo parameters |
feasibility_tolerance | 1e-6 | Feasibility and complementarity threshold |
max_inner_iterations | 1000 | PHR inner budget; other entries ignore it |
initial_penalty | 2 | PHR 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:
PHR instead updates multipliers by \(\mu\leftarrow\mu-\rho h\) and \(\lambda\leftarrow\max(0,\lambda-\rho g)\). Its inner objective is
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_reductionratio; - one
RestorationEventper attempt.
SqpOptions defaults:
| Field | Default |
|---|---|
solver | ConstrainedOptions::default() |
max_subproblem_iterations | 1000 (per QP phase) |
max_subproblem_evaluations | 10000 (whole run) |
max_restoration_iterations | 100 (per attempt) |
restoration_reduction | 0.1 |
restoration_damping | 1e-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:
| Field | Meaning |
|---|---|
source | Solver error with its source chain |
restoration | Restoration attempts so far |
last_constrained | Complete outer checkpoint (with multipliers), None before a valid state appears |
19.5 Reading results
API page (docs.rs): ConstrainedSolution.
ConstrainedSolution fields:
| Field | Meaning |
|---|---|
solution | Objective, Lagrangian stationarity norm, iterations and status |
equality_multipliers | \(\mu\) |
inequality_multipliers | \(\lambda\ge0\), zero for inactive constraints |
constraint_violation | Maximum of equality residuals and the negative part of inequality residuals |
complementarity | \(\lVert\min(g,\lambda)\rVert\) (component-wise) |
inner_iterations | Total PHR inner iterations, zero for other entries |
The convergence conditions hold simultaneously:
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,constraintsandjacobian; - 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
| Module | Contents |
|---|---|
| root | Vector, Matrix, Objective, Evaluator, Function, ValueOnly, value_only, Bounds, EvaluationCounts, StopOptions, TerminationReason, Tolerance, EvaluationError, Solution, Status, Error, minimize, Method, Options |
line_search | armijo, minimize_scalar, minimize_scalar_with_options, ScalarMethod, ScalarOptions, ScalarSolution |
local | lbfgs, newton_cg, trust_region_cg, steihaug, strong_wolfe, HessianVector, SteihaugTermination |
bounded | projected_gradient, projected_gradient_norm |
trust_region | Dense Newton trust region minimize, subproblem, plus Steihaug-family re-exports |
problem | Bounds (construction, projection, unit-box mapping, sampling) |
derivative_free | pattern_search, nelder_mead |
global | differential_evolution, particle_swarm and observer variants |
least_squares | LeastSquares, the two LM entries |
quadratic | QuadraticProgram, minimize, equality_constrained |
constrained | ConstrainedProblem, Constraints, SQP/PHR entries |
core | EvaluationContext, BudgetOptions, EvaluatedPoint, Control, EvaluationEvent, Observer, SearchTermination |
utils | validate_slice, solve_dense, directional_difference, RNG re-exports |
Each module page lists its functions, structs, traits and enums.
20.2 Stopping and tolerances
StopOptions:
| Field | Default | Constraint |
|---|---|---|
max_iterations | 5000 | Zero allowed, still running the initial evaluation and convergence check |
max_evaluations | None | Some(0) invalid |
gradient_tolerance | 1e-6 | Positive finite |
value_tolerance | None | Tolerance |
step_tolerance | None | Tolerance |
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 type | Defaults |
|---|---|
LbfgsOptions | history_size = 10, curvature_tolerance = 1e-10, remaining fields from the stopping/strong-Wolfe defaults |
NewtonCgOptions | max_cg_iterations = 100, cg_tolerance = 0.1 |
SteihaugOptions | max_iterations = 100, relative_tolerance = 0.1 |
TrustRegionCgOptions | radius 1→100, acceptance threshold 0.1, subproblem SteihaugOptions::default() |
TrustRegionOptions | initial_radius = 1, maximum_radius = 2, acceptance_threshold = 0.15 |
LmOptions | initial_damping = 1e-3, minimum_damping = 1e-15, acceptance_ratio = 1e-4, max_damping_trials = 40 |
derivative_free::Options | budget 10000, max_iterations = 2000, initial_step = 0.1, step_tolerance = 1e-8 |
DeOptions | population 40, generations 1000, weight = 0.8, crossover = 0.9, seed 0, budget 10000 |
PsoOptions | population 40, generations 1000, inertia = 0.7, cognitive = 1.5, social = 1.5, velocity_limit = 0.2, seed 0, budget 10000 |
ConstrainedOptions | feasibility_tolerance = 1e-6, max_inner_iterations = 1000, initial_penalty = 2, outer Options::default() |
SqpOptions | subproblem iterations 1000, subproblem evaluations 10000, restoration iterations 100, restoration reduction 0.1, restoration damping 1e-3 |
Valid domains:
| Quantity | Allowed 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
| Type | Key fields |
|---|---|
Solution | x, value, gradient_norm, iterations, status, termination_reason, evaluations |
GlobalSolution | the point/value/counts above + generations, seed, diversity, termination_reason: SearchTermination |
derivative_free::Solution | x, value, iterations, evaluations, termination_reason |
ScalarSolution | x, value, bracket, iterations, status, termination_reason, evaluations |
QuadraticSolution | solution, equality_multipliers, inequality_multipliers, constraint_violation |
ConstrainedSolution | solution, multipliers, constraint_violation, complementarity, inner_iterations |
SqpSolution | constrained, restoration |
gradient_norm by solver family:
| Solver family | gradient_norm |
|---|---|
| Unconstrained and trust region | \(\lVert\nabla f\rVert\) |
| Bounded projected gradient | Gradient mapping \(\lVert x-P(x-g)\rVert\) |
| Adaptive QR LM | \(\lVert D^{-1}J^\top r\rVert\) |
| Constrained methods | Lagrangian stationarity norm \(\lVert\nabla_xL\rVert\) |
| QP | KKT stationarity norm |
| Scalar search | No 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:
| Variant | Mapped status | Trigger |
|---|---|---|
GradientTolerance | Converged | Stationarity norm meets tolerance |
KktTolerance | Converged | The three KKT conditions meet tolerance |
IntervalTolerance | Converged | Scalar interval meets tolerance |
MaxIterations | MaxIterations | Outer iteration cap |
MaxEvaluations | MaxEvaluations | Objective budget cap |
ObjectiveStagnation | Stagnated | Value tolerance triggered |
StepStagnation | Stagnated | Step tolerance triggered |
Failed | Failed | Error-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:
| Field | Counted content |
|---|---|
objective | Objective calls; least-squares residual calls; QP model states |
gradient | Gradient requests; least-squares Jacobians |
hessian | Dense Hessians or Hessian-vector products |
constraints | Nonlinear constraint values or QP constraint states |
residuals | Residual vector requests |
jacobian | Residual/constraint Jacobian requests |
subproblem | Synthesized 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
| Variant | Meaning |
|---|---|
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 |
MissingHessian | Dense Newton method with an absent analytic Hessian |
SingularSystem | Linear system singular, inconsistent or unsolvable |
Infeasible | Constraint 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 |
EvaluationBudgetExceeded | Internal 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()unwrapsSolverFailure/SearchFailure;last_solution()returns the full local checkpoint of aSolverFailure;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;
Evaluationoperationvalues:"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 chapter | Matlab programs | nlopt4r entries and components |
|---|---|---|
| 1 Foundations of optimization | fun.m, gfun.m, Hess.m | StopOptions, TerminationReason; chapter 1 |
| 2 Line-search techniques | golds.m, qmin.m, armijo.m | line_search::{minimize_scalar_with_options, armijo}; chapter 2 |
| 3 Steepest descent and Newton methods | grad.m, dampnm.m, revisenm.m | Method::{SteepestDescent, DampedNewton, ModifiedNewton}; chapters 3–4 |
| 4 Conjugate gradient methods | frcg.m | Method::FletcherReeves; chapter 3 |
| 5 Quasi-Newton methods | bfgs.m, dfp.m, sr1.m, broyden.m | Method::{Bfgs, Dfp, Sr1, Broyden}; chapter 4 |
| 6 Trust-region methods | trustq.m, trustm.m | trust_region::{subproblem, minimize}, local::{steihaug, trust_region_cg}; chapter 5 |
| 7 Nonlinear least squares | lmm.m | least_squares::{levenberg_marquardt, levenberg_marquardt_with_options}; chapter 7 |
| 8 Optimality conditions | theoretical derivations | the three KKT diagnostics in ConstrainedSolution; chapter 1 |
| 9 Penalty function methods | multphr.m | constrained::augmented_lagrangian; chapter 11 |
| 10 Feasible direction methods | theoretical derivations | bounded::{projected_gradient, projected_gradient_norm}, quadratic::minimize; chapters 8 and 10 |
| 11 Quadratic programming | qpact.m, qlag.m, callqpact.m | quadratic::{QuadraticProgram, minimize, equality_constrained}; chapter 10 |
| 12 Sequential quadratic programming | sqpm.m, qpsubp.m, newtlagr.m, lagsqp.m | constrained::{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:
- inputs with an invalid shape or a wrong gradient-buffer length are rejected up front and stay uncounted;
- with a budget/target/cancellation criterion already met, the call returns
Error::SearchStopped(SearchTermination)and invokes no callback; - a valid call first counts
objective(gradientadditionally on a gradient request), then invokes the application callback; - non-finite outputs or unwritten gradient-buffer elements report an error; the attempt stays counted;
- with all outputs valid, the best point updates (ties keep the earlier point);
- the observer runs last, and
Control::Stopor an error ends subsequent calls.
EvaluatedPoint fields:
| Field | Type | Meaning |
|---|---|---|
x | Vector | Successfully evaluated point |
value | f64 | Finite 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_unitmap between the unit box and the physical box, sending zero-width coordinates to the fixed value;projectclips out-of-range coordinates to the interval endpoints.
21.4 utils
| Function | Role |
|---|---|
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.
21.5 A custom bounded pattern search
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
evaluatekeeps callbacks from running after budget exhaustion; Bounds::projectkeeps trial points feasible;- the final state comes from
stop_reason(), withNonecorresponding to the step threshold (this example exits atstep <= 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
| Need | Building block |
|---|---|
| Strict budget and best point | EvaluationContext |
| Cancellation and external logging | with_observer + Control |
| Checkpoint retention on failure | context.failure(error) |
| Finite box | Bounds + project/sample |
| Reproducible random stream | ChaCha8Rng::seed_from_u64 |
| Difference gradients (diagnostics) | utils::directional_difference |
| Dense linear solve | utils::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 testruns the solver package’s integration tests, unit tests and doctests;cargo test --workspaceadditionally runs the benchmark, native-reference and extension packages; the native-reference tests need CMake and a C compiler;--releaserechecks numerical tests in an optimized build;clippycovers 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
| Option | Meaning |
|---|---|
--suite smoke|smooth|global | Problem group |
--algorithms ... | Algorithm registry: bfgs, lbfgs, de, pso, pattern-search, nelder-mead, external-pattern |
--seeds 0..30 | Optimizer seed interval, with the right endpoint exclusive |
--dimension N | Dimension for variable-dimension problems; fixed-dimension problems keep their own dimension |
--budget-per-dimension N | Objective budget = this value × actual dimension |
--output path.jsonl|.csv | Record file; an existing file stays intact |
--summarize path | Offline summary, accepting both formats |
Transform and noise switches:
| Option | Default | Effect |
|---|---|---|
--shift on|off | off | Translate the known minimizer to a seed-selected interior point |
--rotate on|off | off | Apply a seed-selected orthogonal rotation |
--instance-seed N | 0 | Problem-instance seed, independent of optimizer seeds |
--noise none|gaussian|uniform|laplace | none | Observation-noise distribution |
--noise-level SIGMA | 0 | Standard deviation in objective units |
--noise-seed N | 0 | Noise-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 tobook/en/; - the site root
http://localhost:8000/serves Chinese,http://localhost:8000/en/serves English; - the top-bar language button switches between
/x.htmland/en/x.htmlwhile keeping the anchor; - previewing one language alone works through
mdbook serve books/zhormdbook 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:
- open Actions → Deploy nlopt4r book to GitHub Pages → Run workflow in the repository;
- the workflow installs mdBook 0.5.4, builds both languages and uploads
book/; deploy-pagespublishes 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/zhandmdbook build books/ensucceed;- 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_dispatchas its single trigger.
22.7 Documentation index
| File | Content |
|---|---|
docs/BENCHMARKS.md | Benchmark protocol, options, error semantics |
docs/BENCHMARK_RESULTS.md | Measured baseline, pairing experiments, coverage and validation counts |
docs/NIST.md | Certified least-squares validation |
docs/THEORY.md | Method selection, assumptions, costs and references |
docs/SCALABLE_LOCAL.md | L-BFGS, Newton-CG, Steihaug |
docs/FOUNDATIONS.md | Budgets, observers and external algorithm examples |
docs/ROBUSTNESS.md | Adaptive QR LM, projected gradient, SQP restoration |
docs/GLOBAL.md | DE/PSO parameters and seed protocol |
docs/ROADMAP.md | Follow-up extension items |
Theory background
- Benchmark metrics and measured results: see chapter 13.
- Coverage measurement and validation-count interpretation: see chapter 13 and chapter 12.