optimize
On this page
Numerical optimization on core's Array: roots and minima of scalar
functions, unconstrained minimization (simplex, Powell, conjugate
gradients, BFGS, L-BFGS, Newton-CG, trust regions), bounds (L-BFGS-B,
projected gradient), nonlinear constraints (augmented Lagrangian),
linear and convex quadratic programs (simplex, interior point),
nonlinear least squares and curve fitting (Levenberg-Marquardt,
trust-region reflective, robust losses), systems of equations
(Newton, Broyden, hybrid Powell) and global search (differential
evolution, basin hopping, simulated annealing).
Derivatives come from the user, from automatic differentiation
(autodiff's Dual forward mode or Var reverse mode), from the
complex step, or from finite differences. Bad input throws an
OptimizeError that says what to write instead; a run that does not
converge returns its result with the reason in status.
Pure Nabi on f64: every target, wasm included, gets the same results.
Modules
opsNotation for optimization (featureops, on by default): 2.0ε the dual number 0 + 2ε:x + 1.0εseeds a derivative c ⩽ b the constraint c(x) <= b (level of<=) c ⩾ b the constraint c(x) >= b c ≐ b the constraint c(x) = b (level of==) ∇(f) the gradient of f as a function (autodiff's∇) ∂(f) the derivative of f as a function (autodiff's∂)≤,≥and≡cannot be used: the lexer reads them as the fixed<=,>=and==.problemsStandard test functions with known minima (More, Garbow and Hillstrom 1981; Jamil and Yang 2013).
Re-exports
autodiff::{Dual, Smooth, Var, derivative, grad, jacobian, value_grad}Source
pub use autodiff::{Dual, Smooth, Var, derivative, grad, jacobian, value_grad}DualSmoothVarderivativegradjacobianvalue_grad
Structs
BoundsSource
pub struct BoundsBox constraints lo[i] <= x[i] <= hi[i]; an infinite bound is no
bound. x ∈ b tests a point.
use optimize::Bounds;
use core::array::Vector;
let b = try Bounds::new([0.0, -1.0], [1.0, f64::INFINITY]);
let x: Vector<f64> = [0.5, 7.0];
assert(x ∈ b);
assert(b.project([2.0, -3.0])[0] == 1.0);
The lower bounds.
The upper bounds.
Sourcepub fn new(§lo: Vector<f64>, hi: Vector<f64>) throws (OptimizeError) -> Bounds From the lower and upper bounds; throws when the lengths differ, a bound is NaN, or
lo[i] > hi[i].nabiuse optimize::Bounds; assert((try? Bounds::new([1.0], [0.0])) == none);
Sourcepub fn uniform(§n: usize, lo: f64, hi: f64) throws (OptimizeError) -> Bounds The same interval
[lo, hi]for each ofnvariables.nabilet b = try optimize::Bounds::uniform(3, -1.0, 1.0); assert(b.len() == 3 && b.hi[2] == 1.0);
Sourcepub fn ranges(§rs: List<RangeInclusive<f64>>) throws (OptimizeError) -> Bounds From one inclusive range per variable:
[0.0..=1.0, -2.0..=2.0].nabilet b = try optimize::Bounds::ranges([0.0..=1.0, -2.0..=2.0]); assert(b.lo[1] == -2.0);No bounds on
nvariables.nabiassert(optimize::Bounds::free(2).lo[0] == -f64::INFINITY);The number of variables.
nabiassert(optimize::Bounds::free(4).len() == 4);The nearest point of the box to
x.nabilet b = try optimize::Bounds::uniform(2, 0.0, 1.0); assert(b.project([-1.0, 0.5])[0] == 0.0);Whether
xis inside (the same asx ∈ self).nabilet b = try optimize::Bounds::uniform(1, 0.0, 1.0); assert(b.holds([1.0]) && !b.holds([1.5]));
Trait implementations 1
impl ops::Contains<core::array::Array<f64, 1>> for Bounds
ConstrainedSource
pub struct ConstrainedThe result of a constrained minimization: the minimum, the
Lagrange multipliers and the largest constraint violation at x.
There is one multiplier per constraint, in order, for the
constraint written as h(x) <= 0 or h(x) = 0 with h = c - b
(b - c for >=), so that grad f + sum l grad h = 0; those of
the inequalities are >= 0.
use optimize::Constraint;
use core::array::Vector;
let f = |x: Vector<f64>| -> f64 { x[0] ** 2 + x[1] ** 2 };
let on_line = Constraint::eq(|x: Vector<f64>| -> f64 { x[0] + x[1] }, 1.0);
let r = try optimize::auglag(f, [0.0, 0.0], [on_line]);
assert(r.success() && (r.x[0] - 0.5).abs() < 1e-6 && r.violation < 1e-8);
assert((r.multipliers[0] + 1.0).abs() < 1e-5);
The point.
f(x).The Lagrange multipliers.
The largest constraint violation at
x.Why the run stopped.
Outer (multiplier) iterations.
Inner iterations, summed.
Evaluations of
f(the constraints' are not counted).statusin words.Whether it converged with the constraints met.
nabiuse core::array::Vector; let r = try optimize::auglag(|x: Vector<f64>| -> f64 { x[0] ** 2 }, [1.0], []); assert(r.success());
Trait implementations 1
impl Display for Constrained
ConstraintSource
pub struct ConstraintA nonlinear constraint c(x) <= b, c(x) >= b or c(x) = b on a
scalar function c (any IntoObjective: a closure over f64,
Dual or Complex<f64>, or an Objective with its gradient).
The operators c ⩽ b, c ⩾ b and c ≐ b of optimize::ops build
the same.
use optimize::Constraint;
use core::array::Vector;
let c = Constraint::le(|x: Vector<f64>| -> f64 { x[0] + x[1] }, 1.0);
assert(c.violation([0.75, 0.75]) == 0.5);
assert(c.violation([0.25, 0.25]) == 0.0);
Sourcepub fn le<F: IntoObjective>(§c: F, b: f64) -> Constraint c(x) <= b.nabiuse core::array::Vector; let c = optimize::Constraint::le(|x: Vector<f64>| -> f64 { x[0] }, 2.0); assert(c.violation([3.0]) == 1.0);
Sourcepub fn ge<F: IntoObjective>(§c: F, b: f64) -> Constraint c(x) >= b.nabiuse core::array::Vector; let c = optimize::Constraint::ge(|x: Vector<f64>| -> f64 { x[0] }, 2.0); assert(c.violation([1.5]) == 0.5);
Sourcepub fn eq<F: IntoObjective>(§c: F, b: f64) -> Constraint c(x) = b.nabiuse core::array::Vector; let c = optimize::Constraint::eq(|x: Vector<f64>| -> f64 { x[0] * x[1] }, 1.0); assert(c.violation([2.0, 1.0]) == 1.0);How far
xis from satisfying it:max(0, c(x) - b)for<=,|c(x) - b|for=.nabiuse core::array::Vector; let c = optimize::Constraint::eq(|x: Vector<f64>| -> f64 { x[0] }, 1.0); assert(c.violation([0.0]) == 1.0);Whether
xsatisfies it withintol.nabiuse core::array::Vector; let c = optimize::Constraint::ge(|x: Vector<f64>| -> f64 { x[0] }, 0.0); assert(c.holds([0.0], 0.0));
LineStepSource
pub struct LineStepA step found by a line search.
use core::array::Vector;
let p: Vector<f64> = [1.0, 1.0];
let s = try optimize::line_search(optimize::problems::rosenbrock(), [-1.2, 1.0], p);
assert(s.success && s.fun < 24.2);
The step length
a.x + a p.f(x + a p).The gradient at
x + a p(empty afterBacktracking).Function evaluations used.
Whether the conditions were met.
LpSource
pub struct LpA linear program, built up by its methods: Lp::new(c) minimizes
c^T x over x >= 0; add rows with le, ge and eq and replace
the default bounds with bounds.
use optimize::Lp;
// max 3x + 2y with x + y <= 4, x + 3y <= 6, x <= 3: minimize the negative.
let lp = Lp::new([-3.0, -2.0]).le([[1, 1], [1, 3], [1, 0]], [4.0, 6.0, 3.0]);
let r = try optimize::linprog(lp);
assert(r.success() && r.fun == -11.0 && r.x[0] == 3.0 && r.x[1] == 1.0);
Minimize
c^T xsubject tox >= 0.nabilet r = try optimize::linprog(optimize::Lp::new([1.0, 2.0])); assert(r.fun == 0.0);With the rows
a x <= b.nabilet lp = optimize::Lp::new([-1.0]).le([[2]], [3.0]); assert((try optimize::linprog(lp)).x[0] == 1.5);With the rows
a x >= b.nabilet lp = optimize::Lp::new([1.0]).ge([[1]], [2.0]); assert((try optimize::linprog(lp)).x[0] == 2.0);With the rows
a x = b.nabilet lp = optimize::Lp::new([1.0, 1.0]).eq([[1, 2]], [4.0]); assert((try optimize::linprog(lp)).fun == 2.0);With the box
bin place ofx >= 0(Bounds::free(n)for no bounds at all).nabilet lp = optimize::Lp::new([1.0]).bounds(try optimize::Bounds::uniform(1, -5.0, 5.0)); assert((try optimize::linprog(lp)).x[0] == -5.0);
LpSolutionSource
pub struct LpSolutionThe solution of an Lp or Qp.
let r = try optimize::linprog(optimize::Lp::new([1.0]).ge([[1]], [1.0]));
assert(r.success() && r.slack.len() == 1 && r.slack[0] == 0.0);
The solution (for
InfeasibleorUnbounded, the last point).The objective at
x.b_ub - A_ub xfor thele/gerows (in the<=form).b_eq - A_eq x.Converged,Infeasible,UnboundedorMaxIterations.Pivots (simplex) or iterations (interior point).
statusin words.Whether an optimum was found.
nabilet lp = optimize::Lp::new([1.0]).le([[1]], [-1.0]); // x <= -1 and x >= 0 let r = try optimize::linprog(lp); assert(!r.success() && r.status == optimize::Status::Infeasible);
Trait implementations 1
impl Display for LpSolution
QpSource
pub struct QpA convex quadratic program: minimize x^T Q x / 2 + c^T x with the
rows and bounds of an Lp (le, ge, eq, bounds; x is
free unless bounded). Q must be symmetric positive semidefinite.
use optimize::Qp;
// min x^2 + y^2 - 2x - 5y with x + 2y <= 3 (Q = 2 I).
let qp = Qp::new([[2, 0], [0, 2]], [-2.0, -5.0]).le([[1, 2]], [3.0]);
let r = try optimize::quadprog(qp);
assert(r.success() && (r.x[0] - 0.4).abs() < 1e-7 && (r.x[1] - 1.3).abs() < 1e-7);
Minimize
x^T q x / 2 + c^T xover freex.nabilet r = try optimize::quadprog(optimize::Qp::new([[1]], [-3.0])); assert((r.x[0] - 3.0).abs() < 1e-8);With the rows
a x <= b.nabilet qp = optimize::Qp::new([[1]], [-3.0]).le([[1]], [1.0]); assert(((try optimize::quadprog(qp)).x[0] - 1.0).abs() < 1e-8);With the rows
a x >= b.nabilet qp = optimize::Qp::new([[1]], [3.0]).ge([[1]], [1.0]); assert(((try optimize::quadprog(qp)).x[0] - 1.0).abs() < 1e-8);With the rows
a x = b.nabilet qp = optimize::Qp::new([[1, 0], [0, 1]], [0.0, 0.0]).eq([[1, 1]], [2.0]); assert(((try optimize::quadprog(qp)).x[0] - 1.0).abs() < 1e-8);With the box
b.nabilet qp = optimize::Qp::new([[1]], [-3.0]).bounds(try optimize::Bounds::uniform(1, 0.0, 2.0)); assert(((try optimize::quadprog(qp)).x[0] - 2.0).abs() < 1e-7);
FitSource
pub struct FitA fitted model: the parameters, their covariance and standard errors, and the fit's residuals.
use core::array::Vector;
let x: Vector<f64> = [0.0, 1.0, 2.0, 3.0];
let y: Vector<f64> = [1.0, 3.1, 4.9, 7.0];
let fit = try optimize::curve_fit(|x: f64, p: Vector<f64>| -> f64 { p[0] + p[1] * x }, x, y, [0.0, 1.0]);
assert((fit.params[1] - 1.98).abs() < 1e-8);
assert(fit.stderr[1] > 0.0 && fit.dof == 2);
The fitted parameters.
Their covariance matrix (infinite when it cannot be estimated: no more data than parameters).
sqrt(diag(cov)).y - f(x; params), unweighted.The weighted residual sum of squares.
Degrees of freedom, data points minus parameters.
Sourcepub solver: LeastSquares§The least-squares run underneath.
Whether the solver converged.
nabiuse core::array::Vector; let fit = try optimize::curve_fit(|x: f64, p: Vector<f64>| -> f64 { p[0] * x }, [1.0, 2.0], [2.0, 4.0], [1.0]); assert(fit.success() && (fit.params[0] - 2.0).abs() < 1e-10);
LeastSquaresSource
pub struct LeastSquaresThe result of a least-squares fit.
use core::array::Vector;
let r = try optimize::least_squares(|x: Vector<f64>| -> Vector<f64> { x .- 3.0 }, [0.0]);
assert(r.success() && r.cost < 1e-20 && r.fun.len() == 1);
The solution.
The cost
sum rho(r^2) / 2atx.The residuals at
x.The Jacobian at
x(of the loss-scaled residuals).||J^T r||_infatx(scaled forTrf), the first-order optimality measure.Why the run stopped.
Iterations.
Residual evaluations, those of difference Jacobians included.
Jacobian evaluations.
statusin words, with the test that stopped it.Whether a tolerance was met.
nabiuse core::array::Vector; assert((try optimize::least_squares(|x: Vector<f64>| -> Vector<f64> { x }, [1.0])).success());
Trait implementations 1
impl Display for LeastSquares
LsqOptionsSource
pub struct LsqOptionsTolerances and limits of the least-squares solvers.
use optimize::LsqOptions;
let o = LsqOptions { ftol: 1e-14, max_nfev: 500 };
assert(o.gtol == 1e-10);
Stop when the cost falls by less than
ftol * costin a successful step.Stop when a step is below
xtol * (xtol + ||x||).Stop when
||J^T r||_inf <= gtol(scaled by the distance to the bounds forTrf).The residual-evaluation limit (Jacobian differences included); 0 means
100 n(200 nwith difference Jacobians).The robust loss.
The residual scale
Cof the loss: residuals well below it count as in plain least squares.
ResidualsSource
pub struct ResidualsA vector function r: R^n -> R^m (residuals, or the equations of a
root problem) with its Jacobian. Built from a closure over f64
(forward differences), over Dual (exact, n passes) or with
with_jac.
use optimize::Residuals;
use core::array::{Array, Matrix, Vector};
let r = Residuals::new(|x: Vector<f64>| -> Vector<f64> { Array::from([x[0] - 1.0, 10.0 * (x[1] - x[0] ** 2)]) })
.with_jac(|x: Vector<f64>| -> Matrix<f64> { Array::from_list([1.0, 0.0, -20.0 * x[0], 10.0], [2, 2]) });
assert(r.jacobian([2.0, 0.0])[1, 0] == -40.0);
rwith its Jacobian by forward differences.nabiuse core::array::Vector; let r = optimize::Residuals::new(|x: Vector<f64>| -> Vector<f64> { x .* 2.0 }); assert(r.value([1.0])[0] == 2.0);rwritten over dual numbers: the Jacobian by forward-mode AD.nabiuse optimize::Dual; use core::array::{Array, Vector}; let r = optimize::Residuals::dual(|x: Vector<Dual>| -> Vector<Dual> { Array::from([x[0] * x[1]]) }); assert(r.jacobian([3.0, 4.0])[0, 1] == 3.0);With the exact Jacobian (
m x n).nabiuse core::array::{Array, Matrix, Vector}; let r = optimize::Residuals::new(|x: Vector<f64>| -> Vector<f64> { x .* 3.0 }) .with_jac(|_x: Vector<f64>| -> Matrix<f64> { Array::full([1, 1], 3.0) }); assert(r.jacobian([0.0])[0, 0] == 3.0);With the finite-difference scheme for the Jacobian.
nabiuse core::array::Vector; let r = optimize::Residuals::new(|x: Vector<f64>| -> Vector<f64> { x .** 2.0 }).with_diff(optimize::Diff::Central); assert((r.jacobian([1.0])[0, 0] - 2.0).abs() < 1e-9);r(x).nabiuse core::array::Vector; assert(optimize::Residuals::new(|x: Vector<f64>| -> Vector<f64> { x }).value([5.0])[0] == 5.0);The Jacobian at
x.nabiuse core::array::Vector; let r = optimize::Residuals::new(|x: Vector<f64>| -> Vector<f64> { x .* 4.0 }); assert((r.jacobian([1.0])[0, 0] - 4.0).abs() < 1e-6);
Trait implementations 1
impl IntoResiduals for Residuals
ObjectiveSource
pub struct ObjectiveA function to minimize, f: R^n -> R, with its derivatives. Every
solver takes an Objective or anything that becomes one
(IntoObjective): a plain closure |x: Vector<f64>| -> f64 (the
gradient by central differences), a closure over Dual numbers
(the gradient by forward-mode AD, exact), over Var (reverse-mode
AD, exact, one sweep) or over Complex<f64>
(the complex step, exact). Add what you know with the builder
methods.
use optimize::Objective;
use core::array::{Array, Vector};
let f = |x: Vector<f64>| -> f64 { (x[0] - 1.0) ** 2 + 10.0 * (x[1] + 2.0) ** 2 };
let g = |x: Vector<f64>| -> Vector<f64> { Array::from([2.0 * (x[0] - 1.0), 20.0 * (x[1] + 2.0)]) };
let m = try optimize::bfgs(Objective::new(f).with_grad(g), [0.0, 0.0]);
assert(m.success() && (m.x[1] + 2.0).abs() < 1e-6);
falone: the gradient by central differences, the Hessian by differences of the gradient.nabiuse core::array::Vector; let o = optimize::Objective::new(|x: Vector<f64>| -> f64 { x[0] * x[0] }); assert(o.value([3.0]) == 9.0);fwritten over dual numbers: the value and the exact gradient by forward-mode AD (npasses), the Hessian by differences of that gradient.nabiuse optimize::{Dual, Objective}; use core::array::Vector; let o = Objective::dual(|x: Vector<Dual>| -> Dual { x[0] * x[0] * x[1] }); assert(o.gradient([2.0, 3.0])[0] == 12.0);frecorded on a tape: the value and the exact gradient by reverse-mode AD (one evaluation and one backward sweep, whatevernis), the Hessian by differences of that gradient. The choice for many variables.nabiuse optimize::{Objective, Var}; use core::array::Vector; let o = Objective::reverse(|x: Vector<Var>| -> Var { x[0] * x[0] * x[1] }); assert(o.gradient([2.0, 3.0])[0] == 12.0);fwritten over complex numbers: the gradient by the complex step (nevaluations, exact to rounding).fmust be the analytic continuation of the real function (seeSmooth).nabiuse optimize::{Objective, Smooth}; use core::array::Vector; use core::num::Complex; fn f<T: Smooth>(x: Vector<T>) -> T { x[0].exp() } let o = Objective::complex(f::<Complex<f64>>); assert(o.gradient([0.0])[0] == 1.0);With the exact gradient
g.nabiuse optimize::Objective; use core::array::Vector; let o = Objective::new(|x: Vector<f64>| -> f64 { x[0] ** 2 }).with_grad(|x: Vector<f64>| -> Vector<f64> { x .* 2.0 }); assert(o.gradient([1.5])[0] == 3.0);With one function that gives the value and the gradient together (cheaper when they share work);
fstays for value-only calls.nabiuse optimize::Objective; use core::array::Vector; let o = Objective::new(|x: Vector<f64>| -> f64 { x[0] ** 2 }) .with_value_grad(|x: Vector<f64>| -> (f64, Vector<f64>) { (x[0] ** 2, x .* 2.0) }); assert(o.gradient([2.0])[0] == 4.0);With the exact Hessian
h(used bynewton_cg,trust_dogleg,trust_ncg).nabiuse optimize::Objective; use core::array::{Array, Matrix, Vector}; let o = Objective::new(|x: Vector<f64>| -> f64 { x[0] ** 2 }) .with_hess(|_x: Vector<f64>| -> Matrix<f64> { Array::full([1, 1], 2.0) }); assert(o.hessian([0.0])[0, 0] == 2.0);With the Hessian-vector product
hv(x, v) = H(x) v, which is allnewton_cgandtrust_ncgneed (non x nmatrix).nabiuse optimize::Objective; use core::array::Vector; let o = Objective::new(|x: Vector<f64>| -> f64 { x[0] ** 2 }) .with_hessp(|_x: Vector<f64>, v: Vector<f64>| -> Vector<f64> { v .* 2.0 }); assert(o.hessian([1.0])[0, 0] == 2.0);With the finite-difference scheme for the gradient (when it is not given):
Diff::Forwardhalves the cost,Diff::Central(the default) is more accurate.nabiuse optimize::{Diff, Objective}; use core::array::Vector; let o = Objective::new(|x: Vector<f64>| -> f64 { x[0] ** 2 }).with_diff(Diff::Forward); assert((o.gradient([1.0])[0] - 2.0).abs() < 1e-6);f(x).nabiuse core::array::Vector; assert(optimize::Objective::new(|x: Vector<f64>| -> f64 { x.sum() }).value([1.0, 2.0]) == 3.0);The gradient at
x, by the way this objective was built.nabiuse core::array::Vector; let g = optimize::Objective::new(|x: Vector<f64>| -> f64 { 3.0 * x[0] }).gradient([1.0]); assert((g[0] - 3.0).abs() < 1e-9);The Hessian at
x: given, from Hessian-vector products, by differences of a known gradient, or by second differences off.nabiuse core::array::Vector; let h = optimize::Objective::new(|x: Vector<f64>| -> f64 { x[0] * x[1] }).hessian([1.0, 1.0]); assert((h[0, 1] - 1.0).abs() < 1e-5);
Trait implementations 1
impl IntoObjective for Objective
MinimumSource
pub struct MinimumThe result of a minimization.
let m = try optimize::bfgs(optimize::problems::rosenbrock(), [-1.2, 1.0]);
assert(m.success());
assert((m.x[0] - 1.0).abs() < 1e-5 && m.fun < 1e-10);
println(f"{m}"); // status, f, iterations and evaluations
The best point found.
f(x).The gradient at
x(empty for methods without gradients).Why the run stopped.
Iterations taken.
Function evaluations, finite-difference ones included.
Gradient evaluations (given or by AD).
Hessian evaluations (or Hessian-vector products).
statusin words, with the method's detail.Whether the run converged.
nabiassert((try optimize::nelder_mead(optimize::problems::booth::<f64>, [0.0, 0.0])).success());
Trait implementations 1
impl Display for Minimum
OptionsSource
pub struct OptionsTolerances and limits for the multivariate solvers. Every field has
a default, so write only what you change: Options { gtol: 1e-10 }.
use optimize::Options;
let o = Options { gtol: 1e-10, max_iter: 50 };
let m = try optimize::lbfgs(optimize::problems::rosenbrock(), [-1.2, 1.0], o);
assert(m.iterations <= 50);
Stop when
||grad f||_inf <= gtol(gradient methods).Stop when
ffalls by less thanftol * max(1, |f|)in an iteration (and, for the simplex methods, when the values spread less than that).Stop when a step changes
xby less thanxtol * (1 + ||x||).The iteration limit; 0 picks the method's default (
200 nfor most,1000 nfor the simplex methods).The function-evaluation limit; 0 means none.
Sourcepub line_search: LineSearch = LineSearch::MoreThuente§The line search of the gradient methods.
The memory of
lbfgsandlbfgsb(pairs kept).Called after every iteration; return
trueto stop.
StepSource
pub struct StepOne iteration, as the callback sees it.
use optimize::{Options, Step};
let o = Options { callback: |s: Step| -> bool { s.iteration >= 3 } };
let m = try optimize::bfgs(optimize::problems::rosenbrock(), [-1.2, 1.0], o);
assert(m.status == optimize::Status::Stopped && m.iterations == 3);
The iteration just finished, from 1.
The current point.
f(x).||grad f(x)||_inf, or NaN for a method without gradients.
BracketSource
pub struct BracketThree points a < b < c (or a > b > c) with f(b) < f(a) and
f(b) < f(c): a local minimum lies between a and c.
use optimize::Bracket;
let f = |x: f64| -> f64 { (x - 2.0) ** 2 };
let br = try Bracket::new(f, 0.0, 1.0, 5.0);
assert(br.fb == 1.0);
One end.
The inner point.
The other end.
f(a).f(b).f(c).Evaluations spent finding it.
Sourcepub fn new(§f: fn(f64) -> f64, a: f64, b: f64, c: f64) throws (OptimizeError) -> Bracket Checks that
(a, b, c)brackets a minimum off; throwsBadBracketnaming what fails.nabiuse optimize::Bracket; let f = |x: f64| -> f64 { x * x }; assert((try? Bracket::new(f, 1.0, 2.0, 3.0)) == none);
ScalarMinSource
pub struct ScalarMinA minimum of a scalar function.
let m = try optimize::minimize_scalar(|x: f64| -> f64 { (x - 1.5) ** 2 + 2.0 });
assert(m.success() && (m.x - 1.5).abs() < 1e-7 && m.fun == 2.0);
The minimizer.
f(x).Iterations taken.
Evaluations of
f, the bracket search's included.Converged,MaxIterationsorNotFinite.Whether the tolerance was met.
nabiassert((try optimize::bounded(|x: f64| -> f64 { x * x }, -1.0, 2.0)).success());
Trait implementations 1
impl Display for ScalarMin
RootSource
pub struct RootA root of a scalar function.
let r = try optimize::brentq(|x: f64| -> f64 { x * x - 2.0 }, 0.0, 2.0);
assert(r.success() && (r.x - 2.0f64.sqrt()).abs() < 1e-12);
The root.
f(x).Iterations taken.
Evaluations of
f(and of its derivatives, for the open methods).Converged,MaxIterations,NotFiniteor, for the open methods,Stalled(a zero derivative).Whether the tolerance was met.
nabiassert((try optimize::bisect(|x: f64| -> f64 { x - 1.0 }, 0.0, 3.0)).success());
Trait implementations 1
impl Display for Root
SystemRootSource
pub struct SystemRootA root of a system of equations.
use optimize::Dual;
use core::array::{Array, Vector};
let f = |x: Vector<Dual>| -> Vector<Dual> { Array::from([x[0] * x[0] + x[1] * x[1] - 4.0, x[0] - x[1]]) };
let r = try optimize::root(f, [1.0, 0.5]);
assert(r.success() && (r.x[0] - 2.0f64.sqrt()).abs() < 1e-10);
The root.
F(x).Why the run stopped.
Iterations.
Evaluations of
F, those of difference Jacobians included.Jacobian evaluations (or refreshes).
statusin words.Whether
||F(x)||_inf <= tolwas reached.nabiuse core::array::Vector; assert((try optimize::root(|x: Vector<f64>| -> Vector<f64> { x .- 1.0 }, [0.0])).success());
Trait implementations 1
impl Display for SystemRoot
Enums
DiffSource
pub enum DiffA finite-difference scheme.
use optimize::Diff;
use core::array::Vector;
let x: Vector<f64> = [1.0];
let f = |x: Vector<f64>| -> f64 { x[0] ** 3 };
let fw = optimize::approx_grad(f, x, Diff::Forward)[0];
let ce = optimize::approx_grad(f, x, Diff::Central)[0];
assert((ce - 3.0).abs() < (fw - 3.0).abs());
(f(x + h) - f(x)) / h: one evaluation per variable, about 8 correct digits.(f(x + h) - f(x - h)) / 2h: two evaluations per variable, about 10 to 11 correct digits.
OptimizeErrorSource
pub enum OptimizeErrorWhat was wrong with the input of a call.
use optimize::OptimizeError;
let e = try {
_ = try optimize::brentq(|x: f64| -> f64 { x * x + 1.0 }, -1.0, 1.0);
OptimizeError::Empty
} catch e: OptimizeError { e };
assert(e is OptimizeError::NoSignChange);
assert(f"{e}".contains("bracket_root"));
f(a)andf(b)have the same sign, so[a, b]brackets no root.A bracket
(a, b, c)for a minimum is not one:f(b)must be belowf(a)andf(c)withbbetween them.Bound
indexhaslo > hi.The operands' shapes do not fit;
whatnames them.The input, or the function at the start, is NaN or infinite.
An option is out of range;
whatnames it and the range.A problem with no variables.
A linear-algebra step failed on the input (a singular design matrix, say).
Trait implementations 3
impl Display for OptimizeErrorimpl Error for OptimizeErrorimpl From<LinalgError> for OptimizeError
LineSearchSource
pub enum LineSearchA line search for the gradient methods (Options.line_search).
use optimize::{LineSearch, Options};
let o = Options { line_search: LineSearch::StrongWolfe };
assert((try optimize::bfgs(optimize::problems::rosenbrock(), [-1.2, 1.0], o)).success());
More-Thuente: strong Wolfe conditions by safeguarded cubic steps (MINPACK-2), the most robust; the default.
Strong Wolfe conditions by bracketing and cubic zoom (Nocedal and Wright, Algorithms 3.5 and 3.6).
Armijo backtracking with quadratic interpolation: sufficient decrease only, the cheapest; fine for Newton-type steps.
LpMethodSource
pub enum LpMethodThe method of linprog.
use optimize::{Lp, LpMethod};
let lp = Lp::new([-1.0, -2.0]).le([[1, 1]], [4.0]).bounds(try optimize::Bounds::uniform(2, 0.0, 3.0));
let a = try optimize::linprog(lp, LpMethod::Simplex);
let b = try optimize::linprog(lp, LpMethod::InteriorPoint);
assert(a.fun == -7.0 && (b.fun + 7.0).abs() < 1e-7);
Two-phase simplex: exact vertices, finite on degenerate problems.
Mehrotra predictor-corrector: few iterations on large problems; the answer is within the tolerance of a vertex, not on one.
LossSource
pub enum LossThe loss rho of the residuals, as a function of z = r^2.
use optimize::Loss;
assert(Loss::Linear.rho(4.0) == 4.0);
assert(Loss::Huber.rho(4.0) == 3.0); // 2 sqrt(z) - 1 past z = 1
assert(Loss::Cauchy.rho(0.0) == 0.0);
rho(z) = z: ordinary least squares.2 (sqrt(1 + z) - 1): a smooth L1 loss.zforz <= 1,2 sqrt(z) - 1beyond: Huber's loss.ln(1 + z): Cauchy (Lorentzian); strongly downweights outliers.atan(z): bounded, ignores far outliers almost entirely.rho(z).nabiassert(optimize::Loss::SoftL1.rho(3.0) == 2.0);
LsqMethodSource
pub enum LsqMethodThe least-squares method.
use optimize::LsqMethod;
use core::array::{Array, Vector};
let r = |x: Vector<f64>| -> Vector<f64> { Array::from([x[0] - 2.0, x[0] * x[1] - 1.0]) };
let a = try optimize::least_squares(r, [1.0, 1.0], method: LsqMethod::Lm);
let b = try optimize::least_squares(r, [1.0, 1.0], method: LsqMethod::Trf);
assert((a.x[1] - 0.5).abs() < 1e-8 && (b.x[1] - 0.5).abs() < 1e-8);
Levenberg-Marquardt (unbounded only); the default without bounds.
Trust-region reflective; takes bounds; the default with them.
ConjugateSource
pub enum ConjugateThe beta formula of cg.
use optimize::Conjugate;
let m = try optimize::cg(optimize::problems::rosenbrock(), [-1.2, 1.0], Conjugate::FletcherReeves);
assert(m.fun < 1e-8);
Polak-Ribiere+:
max(0, g^T (g - g_old) / g_old^T g_old).Fletcher-Reeves:
g^T g / g_old^T g_old.
MethodSource
pub enum MethodA method for minimize.
use optimize::Method;
let m = try optimize::minimize(optimize::problems::rosenbrock(), [-1.2, 1.0], method: Method::NewtonCg);
assert(m.success());
nelder_mead: values only.powell: values only.cgwith Polak-Ribiere+.bfgs, the default without bounds or constraints.lbfgs.newton_cg.trust_dogleg.trust_ncg.lbfgsb, the default with bounds.projected_gradient(bounds).auglag, the default with constraints.
StatusSource
pub enum StatusWhy a run stopped.
use optimize::Status;
assert(Status::Converged.success());
assert(!Status::MaxIterations.success());
assert(f"{Status::MaxIterations}".contains("max_iter"));
A tolerance was met.
max_iteriterations ran out.max_evalfunction evaluations ran out.No step along the search direction lowered
fenough; usually the gradient is wrong or the precision offis used up.The callback asked to stop.
The function gave NaN or an infinity.
No point satisfies the constraints.
The objective has no lower bound on the feasible set.
No more progress: steps and decreases fell below the tolerances while the gradient test was not met.
Whether the run reached a tolerance.
nabiassert(optimize::Status::Converged.success());
Trait implementations 1
impl Display for Status
BroydenSource
pub enum BroydenWhich Broyden update.
use optimize::Broyden;
use core::array::Vector;
let f = |x: Vector<f64>| -> Vector<f64> { x .** 3.0 .- 8.0 };
let r = try optimize::broyden(f, [1.5], Broyden::Bad);
assert((r.x[0] - 2.0).abs() < 1e-8);
Broyden's first ("good") method: rank-1 updates of the Jacobian.
Broyden's second ("bad") method: rank-1 updates of its inverse.
Traits
ModelSource
pub trait ModelA model y = f(x; p) for curve_fit: a closure |x: f64, p: Vector<f64>| -> f64 (Jacobian by differences) or |x: f64, p: Vector<Dual>| -> Dual (exact Jacobian by AD).
use optimize::{Dual, Model};
use core::array::Vector;
let f = |x: f64, p: Vector<Dual>| -> Dual { p[0] * (p[1] * x).exp() };
let r = f.residuals([0.0, 1.0], [1.0, 2.0], [1.0, 1.0]);
assert(r.value([1.0, 0.0])[1] == -1.0);
The weighted residuals
w_i (f(x_i; p) - y_i)as a function ofp.
IntoResidualsSource
pub trait IntoResidualsWhat the least-squares and root solvers accept: Residuals, or a
closure over f64 (Residuals::new) or Dual
(Residuals::dual).
use optimize::{Dual, IntoResiduals};
use core::array::Vector;
let r = (|x: Vector<Dual>| -> Vector<Dual> { x }).into_residuals();
assert(r.jacobian([1.0, 2.0])[1, 1] == 1.0);
The residuals.
IntoObjectiveSource
pub trait IntoObjectiveWhat a solver accepts as its objective: an Objective, or a closure
over f64 (Objective::new), Dual (Objective::dual), Var
(Objective::reverse) or Complex<f64> (Objective::complex).
use optimize::{Dual, IntoObjective};
use core::array::Vector;
let o = (|x: Vector<Dual>| -> Dual { x[0].exp() }).into_objective();
assert(o.gradient([0.0])[0] == 1.0);
The objective.
Functions
lbfgsbSource
pub fn lbfgsb<F: IntoObjective, X: AsVector<f64>>(f: F, x0: X, bounds: Bounds, opts: Options = Options {}) throws (OptimizeError) -> Minimum L-BFGS-B: L-BFGS on box constraints bounds (Byrd, Lu, Nocedal
and Zhu). x0 is projected into the box first. Stops when the
projected gradient ||P(x - g) - x||_inf <= gtol or the relative
decrease of f falls below ftol. opts.memory pairs are kept;
opts.line_search is ignored (it is always More-Thuente, capped at
the box).
use optimize::Bounds;
// The minimum of Rosenbrock with x[0] <= 0.5 is on that bound.
let b = try Bounds::new([-2.0, -2.0], [0.5, 2.0]);
let m = try optimize::lbfgsb(optimize::problems::rosenbrock(), [-1.2, 1.0], b);
assert(m.success() && m.x[0] == 0.5 && (m.x[1] - 0.25).abs() < 1e-5);
projected_gradientSource
pub fn projected_gradient<F: IntoObjective, X: AsVector<f64>>(f: F, x0: X, bounds: Bounds, opts: Options = Options {}) throws (OptimizeError) -> Minimum Projected gradient descent on a box with Barzilai-Borwein steps and
a nonmonotone line search (SPG). Simple and cheap per iteration;
lbfgsb usually needs fewer iterations on smooth problems.
use optimize::Bounds;
use core::array::Vector;
let f = |x: Vector<f64>| -> f64 { (x[0] - 3.0) ** 2 + (x[1] + 1.0) ** 2 };
let b = try Bounds::uniform(2, 0.0, 2.0);
let m = try optimize::projected_gradient(f, [1.0, 1.0], b);
assert(m.success() && (m.x[0] - 2.0).abs() < 1e-8 && m.x[1] == 0.0);
auglagSource
pub fn auglag<F: IntoObjective, X: AsVector<f64>>(f: F, x0: X, cons: List<Constraint>, bounds: Bounds? = none, ctol: f64 = 1e-8, opts: Options = Options {}) throws (OptimizeError) -> Constrained Minimizes f subject to cons (and the box bounds) by the
augmented Lagrangian method with L-BFGS-B inside. Converges when the
largest violation is below ctol and the inner problem converged
with the multipliers settled. Works with any smooth f and
constraints; give gradients (or write them over Dual) for speed.
use optimize::Constraint;
use core::array::Vector;
// Hock-Schittkowski 71.
let f = |x: Vector<f64>| -> f64 { x[0] * x[3] * (x[0] + x[1] + x[2]) + x[2] };
let prod = Constraint::ge(|x: Vector<f64>| -> f64 { x[0] * x[1] * x[2] * x[3] }, 25.0);
let sq = Constraint::eq(|x: Vector<f64>| -> f64 { x[0] ** 2 + x[1] ** 2 + x[2] ** 2 + x[3] ** 2 }, 40.0);
let b = try optimize::Bounds::uniform(4, 1.0, 5.0);
let r = try optimize::auglag(f, [1.0, 5.0, 5.0, 1.0], [prod, sq], bounds: b);
assert(r.success() && (r.fun - 17.0140173).abs() < 1e-5);
approx_gradSource
pub fn approx_grad(f: fn(Vector<f64>) -> f64, x: Vector<f64>, scheme: Diff = Diff::Central) -> Vector<f64> The gradient of f at x by finite differences (n or 2n
evaluations, plus f(x) for Forward).
use core::array::Vector;
let x: Vector<f64> = [1.0, 2.0];
let g = optimize::approx_grad(|x: Vector<f64>| -> f64 { x[0] * x[1] }, x);
assert((g[0] - 2.0).abs() < 1e-9 && (g[1] - 1.0).abs() < 1e-9);
approx_hessianSource
pub fn approx_hessian(f: fn(Vector<f64>) -> f64, x: Vector<f64>) -> Matrix<f64> The Hessian of f at x by central second differences of f
(2n^2 + 1 evaluations, about 5 to 6 correct digits), symmetric.
use core::array::Vector;
let x: Vector<f64> = [1.0, 2.0];
let h = optimize::approx_hessian(|x: Vector<f64>| -> f64 { x[0] ** 2 * x[1] }, x);
assert((h[0, 0] - 4.0).abs() < 1e-5 && (h[0, 1] - 2.0).abs() < 1e-5);
approx_jacobianSource
pub fn approx_jacobian(f: fn(Vector<f64>) -> Vector<f64>, x: Vector<f64>, scheme: Diff = Diff::Forward) -> Matrix<f64> The Jacobian (m x n) of a vector function at x by finite
differences.
use core::array::{Array, Vector};
let f = |x: Vector<f64>| -> Vector<f64> { Array::from([x[0] * x[1], x[0] - x[1]]) };
let x: Vector<f64> = [2.0, 3.0];
let j = optimize::approx_jacobian(f, x);
assert((j[0, 0] - 3.0).abs() < 1e-9 && (j[1, 1] + 1.0).abs() < 1e-9);
check_gradSource
pub fn check_grad(f: fn(Vector<f64>) -> f64, g: fn(Vector<f64>) -> Vector<f64>, x: Vector<f64>) -> f64 How far a gradient g is from central differences of f at x:
||g(x) - approx||_2 / max(1, ||approx||_2). Below about 1e-6
the gradient is right.
use core::array::{Array, Vector};
let f = |x: Vector<f64>| -> f64 { x[0] ** 2 + x[0] * x[1] };
let good = |x: Vector<f64>| -> Vector<f64> { Array::from([2.0 * x[0] + x[1], x[0]]) };
let bad = |x: Vector<f64>| -> Vector<f64> { Array::from([2.0 * x[0], x[0]]) };
let x: Vector<f64> = [1.0, 2.0];
assert(optimize::check_grad(f, good, x) < 1e-8);
assert(optimize::check_grad(f, bad, x) > 0.1);
complex_step_gradSource
pub fn complex_step_grad(f: fn(Vector<Complex<f64>>) -> Complex<f64>, x: Vector<f64>) -> Vector<f64> The gradient of f at x by the complex step: f written over
Complex<f64> (see Smooth), n evaluations, exact to rounding.
use optimize::Smooth;
use core::array::Vector;
use core::num::Complex;
fn f<T: Smooth>(x: Vector<T>) -> T { x[0].exp() / (x[1].sin() + T::of(2.0)) }
let x: Vector<f64> = [0.5, 1.0];
let g = optimize::complex_step_grad(f::<Complex<f64>>, x);
let want = 0.5f64.exp() / (1.0f64.sin() + 2.0);
assert((g[0] - want).abs() < 1e-15);
hessian_from_gradSource
pub fn hessian_from_grad(g: fn(Vector<f64>) -> Vector<f64>, x: Vector<f64>) -> Matrix<f64> The Hessian from a gradient by central differences of g (2n
gradient evaluations), symmetrized: (J + J^T) / 2.
use core::array::{Array, Vector};
let g = |x: Vector<f64>| -> Vector<f64> { Array::from([2.0 * x[0] * x[1], x[0] ** 2]) };
let x: Vector<f64> = [1.0, 2.0];
let h = optimize::hessian_from_grad(g, x);
assert((h[0, 1] - 2.0).abs() < 1e-8 && (h[0, 0] - 4.0).abs() < 1e-8);
basin_hoppingSource
pub fn basin_hopping<F: IntoObjective, X: AsVector<f64>>(f: F, x0: X, niter: usize = 100, temperature: f64 = 1.0, step: f64 = 0.5, bounds: Bounds? = none, niter_success: usize = 0, seed: u64 = 0, opts: Options = Options {}) throws (OptimizeError) -> Minimum Basin hopping: repeated local minimizations (L-BFGS, or L-BFGS-B
with bounds) from random jumps of the last accepted minimum, each
coordinate moved uniformly within step; a jump is kept with the
Metropolis probability exp(-(f_new - f_old) / temperature). The
step adapts every 50 hops towards half of them accepted. Returns the
lowest minimum seen; Converged once the best has not changed for
niter_success hops (when nonzero), else after niter hops.
use core::array::Vector;
// A 1-D function with many local minima; the global one is near -0.195.
let f = |x: Vector<f64>| -> f64 { (14.5 * x[0] - 0.3).cos() + (x[0] + 0.2) * x[0] };
let m = try optimize::basin_hopping(f, [1.0], niter: 200, seed: 3);
assert((m.x[0] + 0.195).abs() < 1e-3 && (m.fun + 1.0009).abs() < 1e-4);
differential_evolutionSource
pub fn differential_evolution<F: IntoObjective>(f: F, bounds: Bounds, seed: u64 = 0, popsize: usize = 15, mutation: (f64, f64) = (0.5, 1.0), recombination: f64 = 0.7, tol: f64 = 0.01, atol: f64 = 0.0, max_iter: usize = 1000, polish: bool = true, opts: Options = Options {}) throws (OptimizeError) -> Minimum Differential evolution on a finite box: a population of popsize * n points (Latin hypercube start) evolves by best1bin (mutant =
best + F (a - b), binomial crossover with probability
recombination, F drawn from mutation each generation). Stops when
the population's values spread less than tol * |mean| + atol,
then polishes the best point with L-BFGS-B (polish). Needs only
values of f; slow but hard to fool.
use optimize::Bounds;
let b = try Bounds::uniform(2, -5.12, 5.12);
let m = try optimize::differential_evolution(optimize::problems::rastrigin::<f64>, b, seed: 7);
assert(m.success() && m.fun < 1e-8);
simulated_annealingSource
pub fn simulated_annealing<F: IntoObjective>(f: F, bounds: Bounds, x0: Vector<f64>? = none, max_iter: usize = 5000, restart: usize = 500, seed: u64 = 0, polish: bool = true, opts: Options = Options {}) throws (OptimizeError) -> Minimum Simulated annealing on a finite box with the fast schedule: Cauchy
moves of scale 0.2 sqrt(T_k / T_0) (hi - lo) (reflected into the
box), the temperature T_k = T_0 / k with T_0 from the spread of f over
20 random points, Metropolis acceptance, and a restart from the best
point every restart iterations; L-BFGS-B polishes the best point
at the end (polish).
use optimize::Bounds;
let b = try Bounds::uniform(2, -5.0, 5.0);
let m = try optimize::simulated_annealing(optimize::problems::himmelblau::<f64>, b, seed: 11);
assert(m.fun < 1e-10);
line_searchSource
pub fn line_search<F: IntoObjective>(f: F, x: Vector<f64>, p: Vector<f64>, method: LineSearch = LineSearch::MoreThuente, c1: f64 = 1e-4, c2: f64 = 0.9) throws (OptimizeError) -> LineStep Searches along p from x for a step meeting the Armijo (c1)
and strong curvature (c2) conditions, starting from alpha = 1.
Throws when p is not a descent direction or the shapes differ.
use core::array::Vector;
use optimize::LineSearch;
let f = optimize::problems::rosenbrock();
let x: Vector<f64> = [0.0, 0.0];
let p = f.gradient(x) .* -1.0;
let s = try optimize::line_search(f, x, p, method: LineSearch::StrongWolfe);
assert(s.success && s.fun < 1.0);
linprogSource
pub fn linprog(lp: Lp, method: LpMethod = LpMethod::Simplex, max_iter: usize = 0, tol: f64 = 1e-9) throws (OptimizeError) -> LpSolution Solves a linear program by the simplex method (default) or the interior-point method (which hands a problem it cannot finish, typically an infeasible or unbounded one, to the simplex method).
use optimize::Lp;
// A diet problem: two foods, two nutrients, cheapest mix.
let lp = Lp::new([0.6, 0.35]).ge([[5, 7], [4, 2]], [8.0, 15.0]);
let r = try optimize::linprog(lp);
assert(r.success() && (r.x[0] - 3.75).abs() < 1e-12);
quadprogSource
pub fn quadprog(qp: Qp, max_iter: usize = 0, tol: f64 = 1e-9) throws (OptimizeError) -> LpSolution Solves a convex quadratic program by the interior-point method.
Q must be symmetric positive semidefinite (an indefinite Q
gives a stationary point, or NotFinite / MaxIterations).
use optimize::Qp;
// Least distance: the point of x + y = 1, x, y >= 0 nearest (1, 1).
let qp = Qp::new([[2, 0], [0, 2]], [-2.0, -2.0]).eq([[1, 1]], [1.0]).bounds(try optimize::Bounds::uniform(2, 0.0, 1.0));
let r = try optimize::quadprog(qp);
assert((r.x[0] - 0.5).abs() < 1e-7);
curve_fitSource
pub fn curve_fit<M: Model>(f: M, xdata: Vector<f64>, ydata: Vector<f64>, p0: Vector<f64>, sigma: Vector<f64>? = none, absolute_sigma: bool = false, bounds: Bounds? = none, opts: LsqOptions = LsqOptions {}) throws (OptimizeError) -> Fit Fits y ~ f(x; p) from p0 by least squares. sigma gives each
point's standard deviation (weights 1 / sigma); with
absolute_sigma the covariance takes them as exact, otherwise it is
scaled by the residual variance (as SciPy's curve_fit). bounds
box the parameters (trust-region reflective), opts.loss makes the
fit robust.
use optimize::Dual;
use core::array::Vector;
// NIST StRD Misra1a, certified b1 = 238.94212918, b2 = 5.5015643181e-4.
let x: Vector<f64> = [77.6, 114.9, 141.1, 190.8, 239.9, 289.0, 332.8, 378.4, 434.8, 477.3, 536.8, 593.1, 689.1, 760.0];
let y: Vector<f64> = [10.07, 14.73, 17.94, 23.93, 29.61, 35.18, 40.02, 44.82, 50.76, 55.05, 61.01, 66.40, 75.47, 81.78];
let model = |x: f64, b: Vector<Dual>| -> Dual { b[0] * (1.0 - (b[1] * -x).exp()) };
let fit = try optimize::curve_fit(model, x, y, [500.0, 1e-4]);
assert((fit.params[0] / 238.94212918 - 1.0).abs() < 1e-8);
assert((fit.stderr[0] / 2.7070075241 - 1.0).abs() < 1e-6);
least_squaresSource
pub fn least_squares<R: IntoResiduals, X: AsVector<f64>>(r: R, x0: X, bounds: pkg::Bounds? = none, method: LsqMethod? = none, opts: LsqOptions = LsqOptions {}) throws (pkg::OptimizeError) -> LeastSquares Nonlinear least squares: minimizes sum rho(r_i(x)^2) / 2 from
x0, by Levenberg-Marquardt without bounds and trust-region
reflective with them (or as method says). r is any
IntoResiduals: give the Jacobian, write r over Dual, or let
forward differences estimate it.
use optimize::{Bounds, Dual};
use core::array::{Array, Vector};
// Rosenbrock as residuals.
let r = |x: Vector<Dual>| -> Vector<Dual> { Array::from([(x[1] - x[0] * x[0]) * 10.0, 1.0 - x[0]]) };
let s = try optimize::least_squares(r, [-1.2, 1.0]);
assert(s.success() && (s.x[0] - 1.0).abs() < 1e-8);
let b = try optimize::least_squares(r, [-1.2, 1.0], bounds: try Bounds::new([-2.0, -2.0], [0.5, 2.0]));
assert((b.x[0] - 0.5).abs() < 1e-6);
cgSource
pub fn cg<F: IntoObjective, X: AsVector<f64>>(f: F, x0: X, beta: Conjugate = Conjugate::PolakRibiere, opts: Options = Options {}) throws (OptimizeError) -> Minimum Nonlinear conjugate gradients with a strong Wolfe line search
(c2 = 0.1), restarting along -g every n iterations and
whenever the direction stops descending. O(n) memory; often more
iterations than lbfgs, each a little cheaper.
let m = try optimize::cg(optimize::problems::rosenbrock(), [-1.2, 1.0]);
assert(m.success() && (m.x[1] - 1.0).abs() < 1e-4);
nelder_meadSource
pub fn nelder_mead<F: IntoObjective, X: AsVector<f64>>(f: F, x0: X, step: f64 = 0.05, adaptive: bool = true, opts: Options = Options {}) throws (OptimizeError) -> Minimum The Nelder-Mead simplex method. The start simplex is x0 and n
points that each scale one coordinate by 1 + step (5% by default;
a zero coordinate moves to 0.00025); adaptive scales the expansion, contraction
and shrink coefficients with n (Gao and Han), which helps beyond a
few variables. Stops when the values at the vertices agree to
ftol * max(1, |f|) and the simplex is smaller than
sqrt(xtol) (1 + |x|) (f is flat to O(dx^2) near a minimum, so a
tighter simplex only measures rounding).
let m = try optimize::nelder_mead(optimize::problems::rosen::<f64>, [-1.2, 1.0]);
assert(m.success() && (m.x[0] - 1.0).abs() < 1e-5);
newton_cgSource
pub fn newton_cg<F: IntoObjective, X: AsVector<f64>>(f: F, x0: X, opts: Options = Options {}) throws (OptimizeError) -> Minimum Newton-CG: a line-search Newton method whose step comes from a few
CG iterations on H p = -g with Hessian-vector products. Fast near
a minimum and cheap in memory; give with_hessp (or with_hess)
when you can, otherwise each product costs a gradient.
use core::array::{Array, Vector};
let x0: Vector<f64> = Array::full([50], 0.5);
let m = try optimize::newton_cg(optimize::problems::rosenbrock(), x0);
assert(m.success() && m.fun < 1e-10);
powellSource
pub fn powell<F: IntoObjective, X: AsVector<f64>>(f: F, x0: X, opts: Options = Options {}) throws (OptimizeError) -> Minimum Powell's method: n line minimizations per iteration along a
direction set, replacing the direction of largest decrease by the
overall step when that helps (it keeps the set from collapsing).
Stops when an iteration lowers f by less than ftol (|f| + |f_old|) / 2.
let m = try optimize::powell(optimize::problems::powell_singular::<f64>, [3.0, -1.0, 0.0, 1.0]);
assert(m.success() && m.fun < 1e-12);
bfgsSource
pub fn bfgs<F: IntoObjective, X: AsVector<f64>>(f: F, x0: X, opts: Options = Options {}) throws (OptimizeError) -> Minimum BFGS: a quasi-Newton method that builds an estimate of the inverse
Hessian from gradient changes, with a strong Wolfe line search.
Superlinear near a minimum; O(n^2) memory and work per iteration,
so for n beyond a few thousand use lbfgs. Stops when
||grad||_inf <= gtol.
let m = try optimize::bfgs(optimize::problems::rosenbrock(), [-1.2, 1.0]);
assert(m.success() && (m.x[0] - 1.0).abs() < 1e-5);
lbfgsSource
pub fn lbfgs<F: IntoObjective, X: AsVector<f64>>(f: F, x0: X, opts: Options = Options {}) throws (OptimizeError) -> Minimum L-BFGS: BFGS with the inverse Hessian kept as the last
opts.memory step pairs (two-loop recursion, Nocedal and Wright
Algorithm 7.4). O(m n) per iteration, so it handles large n.
use core::array::{Array, Vector};
let x0: Vector<f64> = Array::full([100], -1.0);
let m = try optimize::lbfgs(optimize::problems::rosenbrock(), x0);
assert(m.success() && m.fun < 1e-10);
trust_doglegSource
pub fn trust_dogleg<F: IntoObjective, X: AsVector<f64>>(f: F, x0: X, radius: f64 = 1.0, opts: Options = Options {}) throws (OptimizeError) -> Minimum Trust-region Newton with the dogleg step: one Cholesky
factorization of the Hessian per iteration. For positive definite
Hessians (at an indefinite one it takes the Cauchy point);
quadratic convergence near a minimum. radius is the starting trust
radius.
use optimize::Objective;
let f = Objective::new(optimize::problems::rosen::<f64>).with_grad(optimize::problems::rosen_grad).with_hess(optimize::problems::rosen_hess);
let m = try optimize::trust_dogleg(f, [-1.2, 1.0]);
assert(m.success() && (m.x[0] - 1.0).abs() < 1e-6);
trust_ncgSource
pub fn trust_ncg<F: IntoObjective, X: AsVector<f64>>(f: F, x0: X, radius: f64 = 1.0, opts: Options = Options {}) throws (OptimizeError) -> Minimum Trust-region Newton-CG (Steihaug): truncated CG on the model with
Hessian-vector products, stopping at the trust boundary or at
negative curvature. Handles indefinite Hessians and large n.
use core::array::{Array, Vector};
let x0: Vector<f64> = Array::full([20], -0.5);
let m = try optimize::trust_ncg(optimize::problems::rosenbrock(), x0);
assert(m.success() && m.fun < 1e-10);
minimizeSource
pub fn minimize<F: IntoObjective, X: AsVector<f64>>(f: F, x0: X, method: Method? = none, bounds: pkg::Bounds? = none, constraints: List<pkg::Constraint> = [], opts: Options = Options {}) throws (OptimizeError) -> Minimum Minimizes f from x0 with method, or the default for the
problem: BFGS without bounds or constraints, L-BFGS-B with bounds,
the augmented Lagrangian with constraints. The methods' own
functions (bfgs, lbfgsb, ...) take the same arguments and some
more.
use optimize::{Bounds, Constraint};
use core::array::Vector;
let f = optimize::problems::rosenbrock();
assert((try optimize::minimize(f, [-1.2, 1.0])).success());
let b = try Bounds::uniform(2, -0.5, 0.5);
let m = try optimize::minimize(f, [0.0, 0.0], bounds: b);
assert(m.x ∈ b && m.x[0] == 0.5);
let disk = Constraint::le(|x: Vector<f64>| -> f64 { x[0] ** 2 + x[1] ** 2 }, 1.0);
let c = try optimize::minimize(f, [0.0, 0.0], constraints: [disk]);
assert((c.x[0] - 0.7864).abs() < 1e-3);
boundedSource
pub fn bounded(f: fn(f64) -> f64, lo: f64, hi: f64, xtol: f64 = 1e-5, max_iter: usize = 500) throws (OptimizeError) -> ScalarMin The minimum of f on [lo, hi] by Brent's method (as Brent's
fmin, from the golden-section point), to xtol absolute. A
minimum at an end comes back within xtol of it.
let m = try optimize::bounded(|x: f64| -> f64 { x.sin() }, 0.0, 6.0);
assert((m.x - 1.5 * f64::PI).abs() < 1e-5);
let e = try optimize::bounded(|x: f64| -> f64 { x }, 1.0, 2.0);
assert((e.x - 1.0).abs() < 1e-5);
bracketSource
pub fn bracket(f: fn(f64) -> f64, a: f64 = 0.0, b: f64 = 1.0, grow: f64 = 110.0, max_iter: usize = 1000) throws (OptimizeError) -> Bracket Searches downhill from a and b for a bracket of a minimum:
golden-ratio steps with parabolic extrapolation, each step at most
grow times the last. Throws BadBracket if f keeps falling
for max_iter steps (no minimum in reach) or turns NaN.
let br = try optimize::bracket(|x: f64| -> f64 { (x - 10.0) ** 2 }, 0.0, 1.0);
assert(br.fb < br.fa && br.fb < br.fc);
brentSource
pub fn brent(f: fn(f64) -> f64, br: Bracket, tol: f64 = 1.4901161193847656e-8, max_iter: usize = 500) throws (OptimizeError) -> ScalarMin Brent's method inside a bracket: parabolic interpolation through the three best points, golden section when that is not safe. Superlinear on smooth functions, never worse than golden section by more than a constant.
let f = |x: f64| -> f64 { x.cos() };
let m = try optimize::brent(f, try optimize::bracket(f, 2.0, 3.0));
assert((m.x - f64::PI).abs() < 1e-7);
goldenSource
pub fn golden(f: fn(f64) -> f64, br: Bracket, tol: f64 = 1.4901161193847656e-8, max_iter: usize = 5000) throws (OptimizeError) -> ScalarMin Golden-section search inside a bracket: the interval shrinks by
0.618 per evaluation until it is below tol |b| (tol at least
sqrt(eps), since f is flat to rounding within that of a
minimum).
let f = |x: f64| -> f64 { (x - 2.0) ** 2 };
let m = try optimize::golden(f, try optimize::bracket(f));
assert((m.x - 2.0).abs() < 1e-7);
minimize_scalarSource
pub fn minimize_scalar(f: fn(f64) -> f64, a: f64 = 0.0, b: f64 = 1.0, tol: f64 = 1.4901161193847656e-8) throws (OptimizeError) -> ScalarMin Minimizes a scalar function: brackets a minimum from a and b,
then runs brent in it.
let m = try optimize::minimize_scalar(|x: f64| -> f64 { x ** 4 - 3.0 * x }, 0.0, 1.0);
assert((m.x - 0.75f64.cbrt()).abs() < 1e-7);
bisectSource
pub fn bisect(f: fn(f64) -> f64, a: f64, b: f64, xtol: f64 = 2e-12, rtol: f64 = 8.881784197001252e-16, max_iter: usize = 100) throws (OptimizeError) -> Root Bisection on a bracket [a, b] with f(a) f(b) < 0: halves it
until it is below xtol + rtol |x|. One evaluation per iteration,
one bit per iteration; never fails.
let r = try optimize::bisect(|x: f64| -> f64 { x.cos() - x }, 0.0, 1.0);
assert((r.x - 0.7390851332151607).abs() < 1e-11);
bracket_rootSource
pub fn bracket_root(f: fn(f64) -> f64, a: f64, b: f64, max_iter: usize = 60) throws (OptimizeError) -> (f64, f64) Widens [a, b] until f changes sign over it: each step moves the
end that the secant through both ends points past, to where the
secant crosses zero plus half the width, but by at least one width
and at most two. Throws after max_iter steps.
let (a, b) = try optimize::bracket_root(|x: f64| -> f64 { x - 100.0 }, 0.0, 1.0);
assert(a <= 100.0 && 100.0 <= b);
brentqSource
pub fn brentq(f: fn(f64) -> f64, a: f64, b: f64, xtol: f64 = 2e-12, rtol: f64 = 8.881784197001252e-16, max_iter: usize = 100) throws (OptimizeError) -> Root Brent's method on a bracket: inverse quadratic interpolation and
secant steps, falling back to bisection, so it is as safe as
bisect and superlinear on smooth functions. The usual choice.
let r = try optimize::brentq(|x: f64| -> f64 { x ** 3 - 2.0 * x - 5.0 }, 2.0, 3.0);
assert((r.x - 2.0945514815423265).abs() < 1e-12);
halleySource
pub fn halley(f: fn(f64) -> f64, df: fn(f64) -> f64, d2f: fn(f64) -> f64, x0: f64, tol: f64 = 1.48e-8, rtol: f64 = 0.0, max_iter: usize = 50) throws (OptimizeError) -> Root Halley's method with the first and second derivatives: cubic convergence near a simple root.
let f = |x: f64| -> f64 { x ** 3 - 2.0 };
let r = try optimize::halley(f, |x: f64| -> f64 { 3.0 * x * x }, |x: f64| -> f64 { 6.0 * x }, 1.0);
assert((r.x - 2.0f64.cbrt()).abs() < 1e-14 && r.iterations <= 5);
newtonSource
pub fn newton(f: fn(f64) -> f64, df: fn(f64) -> f64, x0: f64, tol: f64 = 1.48e-8, rtol: f64 = 0.0, max_iter: usize = 50) throws (OptimizeError) -> Root Newton's method from x0 with the derivative df: quadratic
convergence near a simple root. Stops when a step is below
tol; a zero derivative gives Stalled.
let r = try optimize::newton(|x: f64| -> f64 { x * x - 2.0 }, |x: f64| -> f64 { 2.0 * x }, 1.0);
assert((r.x - 2.0f64.sqrt()).abs() < 1e-14 && r.iterations < 8);
newton_adSource
pub fn newton_ad(f: fn(Dual) -> Dual, x0: f64, tol: f64 = 1.48e-8, rtol: f64 = 0.0, max_iter: usize = 50) throws (OptimizeError) -> Root Newton's method with the derivative by forward-mode AD: write f
over Dual, one evaluation per iteration gives f and f'.
use optimize::Dual;
let r = try optimize::newton_ad(|x: Dual| -> Dual { x.cos() - x }, 1.0);
assert((r.x - 0.7390851332151607).abs() < 1e-14);
ridderSource
pub fn ridder(f: fn(f64) -> f64, a: f64, b: f64, xtol: f64 = 2e-12, rtol: f64 = 8.881784197001252e-16, max_iter: usize = 100) throws (OptimizeError) -> Root Ridders' method on a bracket: an exponential fit through the ends and the midpoint; quadratic convergence, two evaluations per iteration, always inside the bracket.
let r = try optimize::ridder(|x: f64| -> f64 { x.exp() - 2.0 }, 0.0, 2.0);
assert((r.x - 2.0f64.ln()).abs() < 1e-12);
secantSource
pub fn secant(f: fn(f64) -> f64, x0: f64, x1: f64, tol: f64 = 1.48e-8, rtol: f64 = 0.0, max_iter: usize = 50) throws (OptimizeError) -> Root The secant method from x0 and x1: no derivative, order 1.618
near a simple root.
let r = try optimize::secant(|x: f64| -> f64 { x.exp() - 3.0 }, 0.0, 1.0);
assert((r.x - 3.0f64.ln()).abs() < 1e-12);
toms748Source
pub fn toms748(f: fn(f64) -> f64, a: f64, b: f64, xtol: f64 = 2e-12, rtol: f64 = 8.881784197001252e-16, max_iter: usize = 100) throws (OptimizeError) -> Root TOMS 748 (Alefeld, Potra and Shi) on a bracket: inverse cubic and
Newton-quadratic steps with a double-length secant step and a
bisection guard, so the bracket shrinks by at least half every
iteration. Asymptotic efficiency index 1.65, usually fewer
evaluations than brentq.
let r = try optimize::toms748(|x: f64| -> f64 { x ** 3 - 2.0 * x - 5.0 }, 2.0, 3.0);
assert((r.x - 2.0945514815423265).abs() < 1e-12);
broydenSource
pub fn broyden<R: IntoResiduals, X: AsVector<f64>>(f: R, x0: X, kind: Broyden = Broyden::Good, tol: f64 = 1e-10, xtol: f64 = 1e-14, max_iter: usize = 200) throws (OptimizeError) -> SystemRoot Broyden's quasi-Newton method: one Jacobian at the start (given,
AD or differences), then rank-1 updates from each step, with a
backtracking line search on |F|; the Jacobian is refreshed when a
step fails. Superlinear near a root, one evaluation per iteration.
use optimize::Broyden;
use core::array::{Array, Vector};
let f = |x: Vector<f64>| -> Vector<f64> { Array::from([x[0] + 0.5 * (x[0] - x[1]) ** 3 - 1.0, 0.5 * (x[1] - x[0]) ** 3 + x[1]]) };
let r = try optimize::broyden(f, [0.0, 0.0], Broyden::Good);
assert(r.success() && (r.x[0] - 0.8411639).abs() < 1e-6);
hybrSource
pub fn hybr<R: IntoResiduals, X: AsVector<f64>>(f: R, x0: X, tol: f64 = 1e-10, xtol: f64 = 1e-14, max_iter: usize = 200, factor: f64 = 100.0) throws (OptimizeError) -> SystemRoot Powell's hybrid method: a dogleg step between Gauss-Newton and
steepest descent on |F + J p| inside a scaled trust region,
Broyden updates of J between fresh Jacobians. As robust as the
trust region, as fast as Newton near a root; the default of root.
use optimize::Dual;
use core::array::{Array, Vector};
// Powell's badly scaled function: root near (1.098e-5, 9.106).
let f = |x: Vector<Dual>| -> Vector<Dual> { Array::from([x[0] * x[1] * 1e4 - 1.0, (-x[0]).exp() + (-x[1]).exp() - 1.0001]) };
let r = try optimize::hybr(f, [0.0, 1.0]);
assert(r.success() && (r.x[1] - 9.106146739867).abs() < 1e-8);
rootSource
pub fn root<R: IntoResiduals, X: AsVector<f64>>(f: R, x0: X, tol: f64 = 1e-10) throws (OptimizeError) -> SystemRoot Solves F(x) = 0 from x0 by Powell's hybrid method (hybr).
use core::array::{Array, Vector};
let f = |x: Vector<f64>| -> Vector<f64> { Array::from([x[0] + 2.0 * x[1] - 2.0, x[0] ** 2 + 4.0 * x[1] ** 2 - 4.0]) };
let r = try optimize::root(f, [1.0, 2.0]);
assert(r.success() && r.x[0].abs() < 1e-8 && (r.x[1] - 1.0).abs() < 1e-8);
root_newtonSource
pub fn root_newton<R: IntoResiduals, X: AsVector<f64>>(f: R, x0: X, tol: f64 = 1e-10, xtol: f64 = 1e-14, max_iter: usize = 100) throws (OptimizeError) -> SystemRoot Newton's method for F(x) = 0 with a backtracking line search on
|F|^2 / 2: quadratic convergence near a root with a nonsingular
Jacobian. Stops when ||F||_inf <= tol.
use optimize::Dual;
use core::array::{Array, Vector};
let f = |x: Vector<Dual>| -> Vector<Dual> { Array::from([x[0].exp() - x[1], x[0] + x[1] - 2.0]) };
let r = try optimize::root_newton(f, [0.0, 0.0]);
assert(r.success() && r.iterations < 10);