packages

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.

#Fitting and optimization

Fitting a model to data, finding the input that makes a cost smallest and finding where a function is zero are one family of problems, and optimize solves all three. Objectives are ordinary closures. Written over optimize::Dual instead of f64, a closure gets its exact gradient by automatic differentiation, so you never write a derivative by hand.

#Find a root

Where is cos x = x? brentq needs an interval where the function changes sign, and from there it always converges. newton is faster from a good start but needs the derivative; newton_ad takes a closure over Dual and gets the derivative by itself.

nabi
use optimize::Dual;

let f = |x: f64| -> f64 { x.cos() - x };
let r = try optimize::brentq(f, 0.0, 1.0);
println(f"cos x = x at x = {r.x:.12} ({r.iterations} iterations)");

let g = |x: Dual| -> Dual { x.cos() - x };
let n = try optimize::newton_ad(g, 0.5);
println(f"newton: {n.x:.12} ({n.iterations} iterations)");
text
cos x = x at x = 0.739085133215 (6 iterations)
newton: 0.739085133215 (4 iterations)

#Minimize a function

The Rosenbrock function has its minimum at (1, 1) at the bottom of a long curved valley, which makes it a standard test. bfgs follows the gradient and builds a picture of the curvature as it goes. The result says how it stopped, where and after how many steps.

nabi
use optimize::Dual;
use core::array::Vector;

let rosen = |x: Vector<Dual>| -> Dual { 100.0 * (x[1] - x[0] ** 2) ** 2 + (1.0 - x[0]) ** 2 };
let m = try optimize::bfgs(rosen, [-1.2, 1.0]);
println(f"{m.status:?} at x = {m.x:.6}, f = {m.fun:.1e}, {m.iterations} iterations");
text
Converged at x = [1.000000, 1.000000], f = 3.8e-19, 37 iterations

With bounds on the variables, use lbfgsb; with general constraints, minimize and its methods; without any gradient at all (a simulation, a measurement), nelder_mead. A plain closure over f64 works everywhere too, with the gradient by finite differences.

nabi
use optimize::{Bounds, Dual};
use core::array::Vector;

let rosen = |x: Vector<Dual>| -> Dual { 100.0 * (x[1] - x[0] ** 2) ** 2 + (1.0 - x[0]) ** 2 };
let box = try Bounds::new([-2.0, -2.0], [0.5, 2.0]);
let m = try optimize::lbfgsb(rosen, [-1.2, 1.0], box);
println(f"inside the box: x = {m.x:.4}");

let nm = try optimize::nelder_mead(|x: Vector<f64>| -> f64 { (x[0] - 3.0) ** 2 + (x[1] + 1.0) ** 2 }, [0.0, 0.0]);
println(f"no gradient: x = {nm.x:.4}");
text
inside the box: x = [0.5000, 0.2500]
no gradient: x = [3.0000, -1.0000]

#Fit a curve

curve_fit adjusts the parameters of a model y = f(x; p) until it matches the data in the least-squares sense, and reports a standard error for each parameter. The model takes one x and the parameter vector. Here the decay of a radioactive sample: counts per minute over time, with a constant background.

nabi
use optimize::Dual;
use core::array::Vector;

let t: Vector<f64> = [0, 5, 10, 15, 20, 30, 40, 50, 60];
let counts: Vector<f64> = [1011, 760, 590, 455, 362, 238, 169, 128, 110];

// counts = a e^(-t / tau) + c
let model = |t: f64, p: Vector<Dual>| -> Dual { p[0] * (-t / p[1]).exp() + p[2] };
let fit = try optimize::curve_fit(model, t, counts, [1000.0, 20.0, 50.0]);
let (a, tau, c) = (fit.params[0], fit.params[1], fit.params[2]);
println(f"a = {a:.0}, tau = {tau:.2} min, background {c:.0}");
println(f"half-life {tau * 2.0f64.ln():.2} min +- {fit.stderr[1] * 2.0f64.ln():.2}");
text
a = 921, tau = 16.45 min, background 87
half-life 11.40 min +- 0.13

Give the starting guess some thought: a nonlinear fit finds the minimum nearest to where it starts. Plotting the data first is usually enough. For a model that is linear in its parameters (a polynomial, a sum of known functions), least squares or stats::polyfit need no guess at all.

#Linear programming

A linear program maximizes or minimizes a linear cost under linear constraints: a factory makes two products, each needing machine time and labour, and has only so much of each. Lp builds the problem row by row (le for <= constraints); linprog minimizes, so a profit to maximize goes in with its sign flipped.

nabi
use optimize::Lp;

// Profit 30 per chair and 50 per table. A chair takes 1 h of machine time
// and 2 h of labour, a table 2 h and 3 h; 40 machine hours and 70 labour
// hours are available.
let lp = Lp::new([-30.0, -50.0]).le([[1, 2], [2, 3]], [40.0, 70.0]);
let r = try optimize::linprog(lp);
println(f"chairs {r.x[0]:.0}, tables {r.x[1]:.0}, profit {-r.fun:.0}");
text
chairs 20, tables 10, profit 1100

quadprog solves problems with a quadratic cost. Integer variables are not supported.

#What next

  • Differential equations: models that are equations for a rate of change.
  • Derivatives: the automatic differentiation behind Dual, on your own functions.
  • The items below: every method of minimize (Method), the Options, and the global optimizers differential_evolution, basin_hopping and simulated_annealing.

Modules

  • ops Notation for optimization (feature ops, 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 ==.
  • problems Standard 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}
  • Dual
  • Smooth
  • Var
  • derivative
  • grad
  • jacobian
  • value_grad

Structs

BoundsSource

pub struct Bounds

Box constraints lo[i] <= x[i] <= hi[i]; an infinite bound is no bound. x ∈ b tests a point.

nabi
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);
  • pub lo: Vector<f64>§

    Source

    The lower bounds.

  • pub hi: Vector<f64>§

    Source

    The upper bounds.

  • pub fn new(lo: Vector<f64>, hi: Vector<f64>) throws (OptimizeError) -> Bounds§

    Source

    From the lower and upper bounds; throws when the lengths differ, a bound is NaN, or lo[i] > hi[i].

    nabi
    use optimize::Bounds;
    
    assert((try? Bounds::new([1.0], [0.0])) == none);
    
  • pub fn uniform(n: usize, lo: f64, hi: f64) throws (OptimizeError) -> Bounds§

    Source

    The same interval [lo, hi] for each of n variables.

    nabi
    let b = try optimize::Bounds::uniform(3, -1.0, 1.0);
    assert(b.len() == 3 && b.hi[2] == 1.0);
    
  • pub fn ranges(rs: List<RangeInclusive<f64>>) throws (OptimizeError) -> Bounds§

    Source

    From one inclusive range per variable: [0.0..=1.0, -2.0..=2.0].

    nabi
    let b = try optimize::Bounds::ranges([0.0..=1.0, -2.0..=2.0]);
    assert(b.lo[1] == -2.0);
    
  • pub fn free(n: usize) -> Bounds§

    Source

    No bounds on n variables.

    nabi
    assert(optimize::Bounds::free(2).lo[0] == -f64::INFINITY);
    
  • pub fn len(self) -> usize§

    Source

    The number of variables.

    nabi
    assert(optimize::Bounds::free(4).len() == 4);
    
  • pub fn project(self, x: Vector<f64>) -> Vector<f64>§

    Source

    The nearest point of the box to x.

    nabi
    let b = try optimize::Bounds::uniform(2, 0.0, 1.0);
    assert(b.project([-1.0, 0.5])[0] == 0.0);
    
  • pub fn holds(self, x: Vector<f64>) -> bool§

    Source

    Whether x is inside (the same as x ∈ self).

    nabi
    let 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 Constrained

The 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.

nabi
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);
  • pub x: Vector<f64>§

    Source

    The point.

  • pub fun: f64§

    Source

    f(x).

  • pub multipliers: Vector<f64>§

    Source

    The Lagrange multipliers.

  • pub violation: f64§

    Source

    The largest constraint violation at x.

  • pub status: Status§

    Source

    Why the run stopped.

  • pub iterations: usize§

    Source

    Outer (multiplier) iterations.

  • pub inner: usize§

    Source

    Inner iterations, summed.

  • pub nfev: usize§

    Source

    Evaluations of f (the constraints' are not counted).

  • pub message: str§

    Source

    status in words.

  • pub fn success(self) -> bool§

    Source

    Whether it converged with the constraints met.

    nabi
    use 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 Constraint

A 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.

nabi
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);
  • pub fn le<F: IntoObjective>(c: F, b: f64) -> Constraint§

    Source

    c(x) <= b.

    nabi
    use core::array::Vector;
    
    let c = optimize::Constraint::le(|x: Vector<f64>| -> f64 { x[0] }, 2.0);
    assert(c.violation([3.0]) == 1.0);
    
  • pub fn ge<F: IntoObjective>(c: F, b: f64) -> Constraint§

    Source

    c(x) >= b.

    nabi
    use core::array::Vector;
    
    let c = optimize::Constraint::ge(|x: Vector<f64>| -> f64 { x[0] }, 2.0);
    assert(c.violation([1.5]) == 0.5);
    
  • pub fn eq<F: IntoObjective>(c: F, b: f64) -> Constraint§

    Source

    c(x) = b.

    nabi
    use 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);
    
  • pub fn violation(self, x: Vector<f64>) -> f64§

    Source

    How far x is from satisfying it: max(0, c(x) - b) for <=, |c(x) - b| for =.

    nabi
    use core::array::Vector;
    
    let c = optimize::Constraint::eq(|x: Vector<f64>| -> f64 { x[0] }, 1.0);
    assert(c.violation([0.0]) == 1.0);
    
  • pub fn holds(self, x: Vector<f64>, tol: f64 = 1e-8) -> bool§

    Source

    Whether x satisfies it within tol.

    nabi
    use 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 LineStep

A step found by a line search.

nabi
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);
  • pub alpha: f64§

    Source

    The step length a.

  • pub x: Vector<f64>§

    Source

    x + a p.

  • pub fun: f64§

    Source

    f(x + a p).

  • pub grad: Vector<f64>§

    Source

    The gradient at x + a p (empty after Backtracking).

  • pub nfev: usize§

    Source

    Function evaluations used.

  • pub success: bool§

    Source

    Whether the conditions were met.

LpSource

pub struct Lp

A 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.

nabi
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);
  • pub fn new(c: Vector<f64>) -> Lp§

    Source

    Minimize c^T x subject to x >= 0.

    nabi
    let r = try optimize::linprog(optimize::Lp::new([1.0, 2.0]));
    assert(r.fun == 0.0);
    
  • pub fn le(self, a: Matrix<f64>, b: Vector<f64>) -> Lp§

    Source

    With the rows a x <= b.

    nabi
    let lp = optimize::Lp::new([-1.0]).le([[2]], [3.0]);
    assert((try optimize::linprog(lp)).x[0] == 1.5);
    
  • pub fn ge(self, a: Matrix<f64>, b: Vector<f64>) -> Lp§

    Source

    With the rows a x >= b.

    nabi
    let lp = optimize::Lp::new([1.0]).ge([[1]], [2.0]);
    assert((try optimize::linprog(lp)).x[0] == 2.0);
    
  • pub fn eq(self, a: Matrix<f64>, b: Vector<f64>) -> Lp§

    Source

    With the rows a x = b.

    nabi
    let lp = optimize::Lp::new([1.0, 1.0]).eq([[1, 2]], [4.0]);
    assert((try optimize::linprog(lp)).fun == 2.0);
    
  • pub fn bounds(self, b: Bounds) -> Lp§

    Source

    With the box b in place of x >= 0 (Bounds::free(n) for no bounds at all).

    nabi
    let 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 LpSolution

The solution of an Lp or Qp.

nabi
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);
  • pub x: Vector<f64>§

    Source

    The solution (for Infeasible or Unbounded, the last point).

  • pub fun: f64§

    Source

    The objective at x.

  • pub slack: Vector<f64>§

    Source

    b_ub - A_ub x for the le / ge rows (in the <= form).

  • pub residual: Vector<f64>§

    Source

    b_eq - A_eq x.

  • pub status: Status§

    Source

    Converged, Infeasible, Unbounded or MaxIterations.

  • pub iterations: usize§

    Source

    Pivots (simplex) or iterations (interior point).

  • pub message: str§

    Source

    status in words.

  • pub fn success(self) -> bool§

    Source

    Whether an optimum was found.

    nabi
    let 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 Qp

A 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.

nabi
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);
  • pub fn new(q: Matrix<f64>, c: Vector<f64>) -> Qp§

    Source

    Minimize x^T q x / 2 + c^T x over free x.

    nabi
    let r = try optimize::quadprog(optimize::Qp::new([[1]], [-3.0]));
    assert((r.x[0] - 3.0).abs() < 1e-8);
    
  • pub fn le(self, a: Matrix<f64>, b: Vector<f64>) -> Qp§

    Source

    With the rows a x <= b.

    nabi
    let qp = optimize::Qp::new([[1]], [-3.0]).le([[1]], [1.0]);
    assert(((try optimize::quadprog(qp)).x[0] - 1.0).abs() < 1e-8);
    
  • pub fn ge(self, a: Matrix<f64>, b: Vector<f64>) -> Qp§

    Source

    With the rows a x >= b.

    nabi
    let qp = optimize::Qp::new([[1]], [3.0]).ge([[1]], [1.0]);
    assert(((try optimize::quadprog(qp)).x[0] - 1.0).abs() < 1e-8);
    
  • pub fn eq(self, a: Matrix<f64>, b: Vector<f64>) -> Qp§

    Source

    With the rows a x = b.

    nabi
    let 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);
    
  • pub fn bounds(self, b: Bounds) -> Qp§

    Source

    With the box b.

    nabi
    let 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 Fit

A fitted model: the parameters, their covariance and standard errors, and the fit's residuals.

nabi
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);
  • pub params: Vector<f64>§

    Source

    The fitted parameters.

  • pub cov: Matrix<f64>§

    Source

    Their covariance matrix (infinite when it cannot be estimated: no more data than parameters).

  • pub stderr: Vector<f64>§

    Source

    sqrt(diag(cov)).

  • pub residuals: Vector<f64>§

    Source

    y - f(x; params), unweighted.

  • pub rss: f64§

    Source

    The weighted residual sum of squares.

  • pub dof: usize§

    Source

    Degrees of freedom, data points minus parameters.

  • The least-squares run underneath.

  • pub fn success(self) -> bool§

    Source

    Whether the solver converged.

    nabi
    use 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 LeastSquares

The result of a least-squares fit.

nabi
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);
  • pub x: Vector<f64>§

    Source

    The solution.

  • pub cost: f64§

    Source

    The cost sum rho(r^2) / 2 at x.

  • pub fun: Vector<f64>§

    Source

    The residuals at x.

  • pub jac: Matrix<f64>§

    Source

    The Jacobian at x (of the loss-scaled residuals).

  • pub optimality: f64§

    Source

    ||J^T r||_inf at x (scaled for Trf), the first-order optimality measure.

  • pub status: pkg::Status§

    Source

    Why the run stopped.

  • pub iterations: usize§

    Source

    Iterations.

  • pub nfev: usize§

    Source

    Residual evaluations, those of difference Jacobians included.

  • pub njev: usize§

    Source

    Jacobian evaluations.

  • pub message: str§

    Source

    status in words, with the test that stopped it.

  • pub fn success(self) -> bool§

    Source

    Whether a tolerance was met.

    nabi
    use 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 LsqOptions

Tolerances and limits of the least-squares solvers.

nabi
use optimize::LsqOptions;

let o = LsqOptions { ftol: 1e-14, max_nfev: 500 };
assert(o.gtol == 1e-10);
  • pub ftol: f64 = 1e-10§

    Source

    Stop when the cost falls by less than ftol * cost in a successful step.

  • pub xtol: f64 = 1e-10§

    Source

    Stop when a step is below xtol * (xtol + ||x||).

  • pub gtol: f64 = 1e-10§

    Source

    Stop when ||J^T r||_inf <= gtol (scaled by the distance to the bounds for Trf).

  • pub max_nfev: usize = 0§

    Source

    The residual-evaluation limit (Jacobian differences included); 0 means 100 n (200 n with difference Jacobians).

  • pub loss: Loss = Loss::Linear§

    Source

    The robust loss.

  • pub f_scale: f64 = 1.0§

    Source

    The residual scale C of the loss: residuals well below it count as in plain least squares.

ResidualsSource

pub struct Residuals

A 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.

nabi
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);
  • pub fn new(r: fn(Vector<f64>) -> Vector<f64>) -> Residuals§

    Source

    r with its Jacobian by forward differences.

    nabi
    use core::array::Vector;
    
    let r = optimize::Residuals::new(|x: Vector<f64>| -> Vector<f64> { x .* 2.0 });
    assert(r.value([1.0])[0] == 2.0);
    
  • pub fn dual(r: fn(Vector<Dual>) -> Vector<Dual>) -> Residuals§

    Source

    r written over dual numbers: the Jacobian by forward-mode AD.

    nabi
    use 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);
    
  • pub fn with_jac(self, j: fn(Vector<f64>) -> Matrix<f64>) -> Residuals§

    Source

    With the exact Jacobian (m x n).

    nabi
    use 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);
    
  • pub fn with_diff(self, d: Diff) -> Residuals§

    Source

    With the finite-difference scheme for the Jacobian.

    nabi
    use 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);
    
  • pub fn value(self, x: Vector<f64>) -> Vector<f64>§

    Source

    r(x).

    nabi
    use core::array::Vector;
    
    assert(optimize::Residuals::new(|x: Vector<f64>| -> Vector<f64> { x }).value([5.0])[0] == 5.0);
    
  • pub fn jacobian(self, x: Vector<f64>) -> Matrix<f64>§

    Source

    The Jacobian at x.

    nabi
    use 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

ObjectiveSource

pub struct Objective

A 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.

nabi
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);
  • pub fn new(f: fn(Vector<f64>) -> f64) -> Objective§

    Source

    f alone: the gradient by central differences, the Hessian by differences of the gradient.

    nabi
    use core::array::Vector;
    
    let o = optimize::Objective::new(|x: Vector<f64>| -> f64 { x[0] * x[0] });
    assert(o.value([3.0]) == 9.0);
    
  • pub fn dual(f: fn(Vector<Dual>) -> Dual) -> Objective§

    Source

    f written over dual numbers: the value and the exact gradient by forward-mode AD (n passes), the Hessian by differences of that gradient.

    nabi
    use 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);
    
  • pub fn reverse(f: fn(Vector<Var>) -> Var) -> Objective§

    Source

    f recorded on a tape: the value and the exact gradient by reverse-mode AD (one evaluation and one backward sweep, whatever n is), the Hessian by differences of that gradient. The choice for many variables.

    nabi
    use 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);
    
  • pub fn complex(f: fn(Vector<Complex<f64>>) -> Complex<f64>) -> Objective§

    Source

    f written over complex numbers: the gradient by the complex step (n evaluations, exact to rounding). f must be the analytic continuation of the real function (see Smooth).

    nabi
    use 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);
    
  • pub fn with_grad(self, g: fn(Vector<f64>) -> Vector<f64>) -> Objective§

    Source

    With the exact gradient g.

    nabi
    use 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);
    
  • pub fn with_value_grad(self, fg: fn(Vector<f64>) -> (f64, Vector<f64>)) -> Objective§

    Source

    With one function that gives the value and the gradient together (cheaper when they share work); f stays for value-only calls.

    nabi
    use 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);
    
  • pub fn with_hess(self, h: fn(Vector<f64>) -> Matrix<f64>) -> Objective§

    Source

    With the exact Hessian h (used by newton_cg, trust_dogleg, trust_ncg).

    nabi
    use 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);
    
  • pub fn with_hessp(self, hv: fn(Vector<f64>, Vector<f64>) -> Vector<f64>) -> Objective§

    Source

    With the Hessian-vector product hv(x, v) = H(x) v, which is all newton_cg and trust_ncg need (no n x n matrix).

    nabi
    use 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);
    
  • pub fn with_diff(self, d: Diff) -> Objective§

    Source

    With the finite-difference scheme for the gradient (when it is not given): Diff::Forward halves the cost, Diff::Central (the default) is more accurate.

    nabi
    use 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);
    
  • pub fn value(self, x: Vector<f64>) -> f64§

    Source

    f(x).

    nabi
    use core::array::Vector;
    
    assert(optimize::Objective::new(|x: Vector<f64>| -> f64 { x.sum() }).value([1.0, 2.0]) == 3.0);
    
  • pub fn gradient(self, x: Vector<f64>) -> Vector<f64>§

    Source

    The gradient at x, by the way this objective was built.

    nabi
    use 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);
    
  • pub fn hessian(self, x: Vector<f64>) -> Matrix<f64>§

    Source

    The Hessian at x: given, from Hessian-vector products, by differences of a known gradient, or by second differences of f.

    nabi
    use 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

MinimumSource

pub struct Minimum

The result of a minimization.

nabi
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
  • pub x: Vector<f64>§

    Source

    The best point found.

  • pub fun: f64§

    Source

    f(x).

  • pub grad: Vector<f64>§

    Source

    The gradient at x (empty for methods without gradients).

  • pub status: Status§

    Source

    Why the run stopped.

  • pub iterations: usize§

    Source

    Iterations taken.

  • pub nfev: usize§

    Source

    Function evaluations, finite-difference ones included.

  • pub ngev: usize§

    Source

    Gradient evaluations (given or by AD).

  • pub nhev: usize§

    Source

    Hessian evaluations (or Hessian-vector products).

  • pub message: str§

    Source

    status in words, with the method's detail.

  • pub fn success(self) -> bool§

    Source

    Whether the run converged.

    nabi
    assert((try optimize::nelder_mead(optimize::problems::booth::<f64>, [0.0, 0.0])).success());
    
Trait implementations 1
  • impl Display for Minimum

OptionsSource

pub struct Options

Tolerances and limits for the multivariate solvers. Every field has a default, so write only what you change: Options { gtol: 1e-10 }.

nabi
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);
  • pub gtol: f64 = 1e-6§

    Source

    Stop when ||grad f||_inf <= gtol (gradient methods).

  • pub ftol: f64 = 1e-12§

    Source

    Stop when f falls by less than ftol * max(1, |f|) in an iteration (and, for the simplex methods, when the values spread less than that).

  • pub xtol: f64 = 1e-12§

    Source

    Stop when a step changes x by less than xtol * (1 + ||x||).

  • pub max_iter: usize = 0§

    Source

    The iteration limit; 0 picks the method's default (200 n for most, 1000 n for the simplex methods).

  • pub max_eval: usize = 0§

    Source

    The function-evaluation limit; 0 means none.

  • Source

    The line search of the gradient methods.

  • pub memory: usize = 10§

    Source

    The memory of lbfgs and lbfgsb (pairs kept).

  • pub callback: fn(Step) -> bool | none = none§

    Source

    Called after every iteration; return true to stop.

StepSource

pub struct Step

One iteration, as the callback sees it.

nabi
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);
  • pub iteration: usize§

    Source

    The iteration just finished, from 1.

  • pub x: Vector<f64>§

    Source

    The current point.

  • pub fun: f64§

    Source

    f(x).

  • pub gnorm: f64§

    Source

    ||grad f(x)||_inf, or NaN for a method without gradients.

BracketSource

pub struct Bracket

Three 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.

nabi
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);
  • pub a: f64§

    Source

    One end.

  • pub b: f64§

    Source

    The inner point.

  • pub c: f64§

    Source

    The other end.

  • pub fa: f64§

    Source

    f(a).

  • pub fb: f64§

    Source

    f(b).

  • pub fc: f64§

    Source

    f(c).

  • pub nfev: usize§

    Source

    Evaluations spent finding it.

  • pub fn new(f: fn(f64) -> f64, a: f64, b: f64, c: f64) throws (OptimizeError) -> Bracket§

    Source

    Checks that (a, b, c) brackets a minimum of f; throws BadBracket naming what fails.

    nabi
    use optimize::Bracket;
    
    let f = |x: f64| -> f64 { x * x };
    assert((try? Bracket::new(f, 1.0, 2.0, 3.0)) == none);
    

ScalarMinSource

pub struct ScalarMin

A minimum of a scalar function.

nabi
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);
  • pub x: f64§

    Source

    The minimizer.

  • pub fun: f64§

    Source

    f(x).

  • pub iterations: usize§

    Source

    Iterations taken.

  • pub nfev: usize§

    Source

    Evaluations of f, the bracket search's included.

  • pub status: Status§

    Source

    Converged, MaxIterations or NotFinite.

  • pub fn success(self) -> bool§

    Source

    Whether the tolerance was met.

    nabi
    assert((try optimize::bounded(|x: f64| -> f64 { x * x }, -1.0, 2.0)).success());
    
Trait implementations 1
  • impl Display for ScalarMin

RootSource

pub struct Root

A root of a scalar function.

nabi
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);
  • pub x: f64§

    Source

    The root.

  • pub fx: f64§

    Source

    f(x).

  • pub iterations: usize§

    Source

    Iterations taken.

  • pub nfev: usize§

    Source

    Evaluations of f (and of its derivatives, for the open methods).

  • pub status: Status§

    Source

    Converged, MaxIterations, NotFinite or, for the open methods, Stalled (a zero derivative).

  • pub fn success(self) -> bool§

    Source

    Whether the tolerance was met.

    nabi
    assert((try optimize::bisect(|x: f64| -> f64 { x - 1.0 }, 0.0, 3.0)).success());
    
Trait implementations 1
  • impl Display for Root

SystemRootSource

pub struct SystemRoot

A root of a system of equations.

nabi
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);
  • pub x: Vector<f64>§

    Source

    The root.

  • pub fun: Vector<f64>§

    Source

    F(x).

  • pub status: Status§

    Source

    Why the run stopped.

  • pub iterations: usize§

    Source

    Iterations.

  • pub nfev: usize§

    Source

    Evaluations of F, those of difference Jacobians included.

  • pub njev: usize§

    Source

    Jacobian evaluations (or refreshes).

  • pub message: str§

    Source

    status in words.

  • pub fn success(self) -> bool§

    Source

    Whether ||F(x)||_inf <= tol was reached.

    nabi
    use 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 Diff

A finite-difference scheme.

nabi
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());
  • Forward§

    Source

    (f(x + h) - f(x)) / h: one evaluation per variable, about 8 correct digits.

  • Central§

    Source

    (f(x + h) - f(x - h)) / 2h: two evaluations per variable, about 10 to 11 correct digits.

OptimizeErrorSource

pub enum OptimizeError

What was wrong with the input of a call.

nabi
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"));
  • NoSignChange§

    Source

    f(a) and f(b) have the same sign, so [a, b] brackets no root.

  • BadBracket§

    Source

    A bracket (a, b, c) for a minimum is not one: f(b) must be below f(a) and f(c) with b between them.

  • BadBounds§

    Source

    Bound index has lo > hi.

  • ShapeMismatch§

    Source

    The operands' shapes do not fit; what names them.

  • NotFinite§

    Source

    The input, or the function at the start, is NaN or infinite.

  • BadOption§

    Source

    An option is out of range; what names it and the range.

  • A problem with no variables.

  • Linalg§

    Source

    A linear-algebra step failed on the input (a singular design matrix, say).

Trait implementations 3
  • impl Display for OptimizeError
  • impl Error for OptimizeError
  • impl From<LinalgError> for OptimizeError

LineSearchSource

pub enum LineSearch

A line search for the gradient methods (Options.line_search).

nabi
use optimize::{LineSearch, Options};

let o = Options { line_search: LineSearch::StrongWolfe };
assert((try optimize::bfgs(optimize::problems::rosenbrock(), [-1.2, 1.0], o)).success());
  • MoreThuente§

    Source

    More-Thuente: strong Wolfe conditions by safeguarded cubic steps (MINPACK-2), the most robust; the default.

  • StrongWolfe§

    Source

    Strong Wolfe conditions by bracketing and cubic zoom (Nocedal and Wright, Algorithms 3.5 and 3.6).

  • Backtracking§

    Source

    Armijo backtracking with quadratic interpolation: sufficient decrease only, the cheapest; fine for Newton-type steps.

LpMethodSource

pub enum LpMethod

The method of linprog.

nabi
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);
  • Simplex§

    Source

    Two-phase simplex: exact vertices, finite on degenerate problems.

  • InteriorPoint§

    Source

    Mehrotra predictor-corrector: few iterations on large problems; the answer is within the tolerance of a vertex, not on one.

LossSource

pub enum Loss

The loss rho of the residuals, as a function of z = r^2.

nabi
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);
  • Linear§

    Source

    rho(z) = z: ordinary least squares.

  • SoftL1§

    Source

    2 (sqrt(1 + z) - 1): a smooth L1 loss.

  • z for z <= 1, 2 sqrt(z) - 1 beyond: Huber's loss.

  • Cauchy§

    Source

    ln(1 + z): Cauchy (Lorentzian); strongly downweights outliers.

  • Arctan§

    Source

    atan(z): bounded, ignores far outliers almost entirely.

  • pub fn rho(self, z: f64) -> f64§

    Source

    rho(z).

    nabi
    assert(optimize::Loss::SoftL1.rho(3.0) == 2.0);
    

LsqMethodSource

pub enum LsqMethod

The least-squares method.

nabi
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 Conjugate

The beta formula of cg.

nabi
use optimize::Conjugate;

let m = try optimize::cg(optimize::problems::rosenbrock(), [-1.2, 1.0], Conjugate::FletcherReeves);
assert(m.fun < 1e-8);
  • PolakRibiere§

    Source

    Polak-Ribiere+: max(0, g^T (g - g_old) / g_old^T g_old).

  • FletcherReeves§

    Source

    Fletcher-Reeves: g^T g / g_old^T g_old.

MethodSource

pub enum Method

A method for minimize.

nabi
use optimize::Method;

let m = try optimize::minimize(optimize::problems::rosenbrock(), [-1.2, 1.0], method: Method::NewtonCg);
assert(m.success());

StatusSource

pub enum Status

Why a run stopped.

nabi
use optimize::Status;

assert(Status::Converged.success());
assert(!Status::MaxIterations.success());
assert(f"{Status::MaxIterations}".contains("max_iter"));
  • Converged§

    Source

    A tolerance was met.

  • MaxIterations§

    Source

    max_iter iterations ran out.

  • MaxEvaluations§

    Source

    max_eval function evaluations ran out.

  • LineSearchFailed§

    Source

    No step along the search direction lowered f enough; usually the gradient is wrong or the precision of f is used up.

  • Stopped§

    Source

    The callback asked to stop.

  • NotFinite§

    Source

    The function gave NaN or an infinity.

  • Infeasible§

    Source

    No point satisfies the constraints.

  • Unbounded§

    Source

    The objective has no lower bound on the feasible set.

  • Stalled§

    Source

    No more progress: steps and decreases fell below the tolerances while the gradient test was not met.

  • pub fn success(self) -> bool§

    Source

    Whether the run reached a tolerance.

    nabi
    assert(optimize::Status::Converged.success());
    
Trait implementations 1
  • impl Display for Status

BroydenSource

pub enum Broyden

Which Broyden update.

nabi
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 Model

A 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).

nabi
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);
  • fn residuals(self, x: Vector<f64>, y: Vector<f64>, w: Vector<f64>) -> Residuals§

    Source

    The weighted residuals w_i (f(x_i; p) - y_i) as a function of p.

IntoResidualsSource

pub trait IntoResiduals

What the least-squares and root solvers accept: Residuals, or a closure over f64 (Residuals::new) or Dual (Residuals::dual).

nabi
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);

IntoObjectiveSource

pub trait IntoObjective

What 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).

nabi
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);

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).

nabi
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.

nabi
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.

nabi
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).

nabi
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.

nabi
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.

nabi
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.

nabi
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.

nabi
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.

nabi
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.

nabi
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.

nabi
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).

nabi
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);

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).

nabi
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).

nabi
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.

nabi
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.

nabi
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.

nabi
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).

nabi
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.

nabi
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.

nabi
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.

nabi
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.

nabi
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.

nabi
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.

nabi
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.

nabi
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.

nabi
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.

nabi
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.

nabi
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).

nabi
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.

nabi
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.

nabi
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.

nabi
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.

nabi
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.

nabi
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.

nabi
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'.

nabi
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.

nabi
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.

nabi
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.

nabi
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.

nabi
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.

nabi
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).

nabi
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.

nabi
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);