optimize

package module
v0.16.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: BSD-3-Clause Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-numerics/optimize

optimize

Docs pkg.go.dev License

Numerical optimisation and root finding in pure Go (CGO=0): minimisation, scalar and system roots, nonlinear least squares, curve fitting with parameter covariance, and linear programming.

🌐 Website · 📚 Documentation

The package covers the parts of scipy.optimize that scientific notebooks use most. Each function documents the SciPy call it corresponds to. The test suite replays SciPy 1.18.1 on standard problems, and it checks solutions, objective values, status codes, messages, and iteration and evaluation counts.

go get github.com/go-numerics/optimize

It works with go-ndarray: curve-fit data, covariances and LP constraint matrices are *ndarray.Array, and results have …Array() accessors.

What is there

Go SciPy Algorithm
Minimize(p, x0, NelderMead, opts) minimize(method='Nelder-Mead') downhill simplex, adaptive option, bounds
Minimize(…, Powell, …) minimize(method='Powell') conjugate directions, bounds
Minimize(…, CG, …) minimize(method='CG') Polak–Ribière+, strong Wolfe
Minimize(…, BFGS, …) minimize(method='BFGS') inverse-Hessian BFGS, O(n²) update (tolerance-validated, not bit-identical to SciPy); Options.SciPyExactUpdate gives SciPy's dense update bit for bit
Minimize(…, NewtonCG, …) minimize(method='Newton-CG') truncated Newton (Hess, HessP or FD)
Minimize(…, LBFGSB, …) minimize(method='L-BFGS-B') L-BFGS-B 3.0 with bounds
Minimize(…, SLSQP, …) with Options.Constraints minimize(method='SLSQP', constraints=…), MATLAB fmincon 'sqp' Kraft's SLSQP: bounds, equality and inequality constraints as Constraint, NonlinearConstraint or LinearConstraint; Lagrange multipliers in Result.Multipliers
Minimize(…, TrustConstr, …) with Options.Constraints minimize(method='trust-constr'), MATLAB fmincon 'interior-point' Byrd–Omojokun trust-region SQP, wrapped in a barrier (interior-point) method when there are inequalities or bounds; BFGS Hessians, or Problem.Hess/HessP; same constraint types; Result.Optimality, ConstrViolation, Multipliers
MinimizeScalar, Fminbound, Bracket minimize_scalar (brent, golden, bounded), fminbound, bracket Brent, golden section, FMIN
Brentq, Brenth, Ridder, Bisect, Newton, RootScalar brentq, brenth, ridder, bisect, newton (Newton/secant/Halley), root_scalar
BrentqExtend R uniroot(extendInt=): no, yes, downX, upX own doubling schedule: the root agrees, the iterates need not
NelderMeadNash, BFGSNash, CGNash R optim Nelder-Mead / BFGS / CG (Nash 1990, algorithms 19, 21, 22) separate from the SciPy-style methods; stated bound and R-iterate status in docs/nash.md
SANN R optim SANN (Belisle 1992) seeded or injectable stream, logarithmic cooling, best point returned; see docs/nash.md
Uncmin R nlm (Dennis–Schnabel), minimize(method='BFGS') line search or dogleg trust region, BFGS secant or finite-difference Hessian, TypSize/FScale scaling, nlm's return codes 1–5 in Result.Status; optimum within 1e-6 on the MGH set, iterates differ from R's; docs/uncmin.md
NLMinB R nlminb, minimize(method='L-BFGS-B') box constraints with R's call shape and defaults; runs this package's L-BFGS-B, not PORT; codes 4, 8, 9, 10 as in R's messages; optimum within 1e-6 on the MGH set (14 of 14 runs of R 4.6.2); docs/nlminb.md
Polyroot R polyroot, numpy.roots Ehrlich-Aberth (not Jenkins-Traub): roots agree within the conditioning bound, not bit for bit. p and p' are evaluated by compensated Horner (error-free transformations, FMA; twice the working precision), so the Chebyshev T20/T30/T40/T50 roots come out distinct and within a few ulp (plain Horner lost two roots of T40). PolyrootContext(ctx, coef, &PolyrootOptions{ConjugateOrder: PositiveImagFirst}) lists conjugate pairs positive imaginary part first like R and polls ctx (every sweep and every 64 roots). Divergence: R fails with "root finding code failed" on some large random inputs (runif(1500)); we converge and return the roots
Root, Fsolve root(method='hybr'), fsolve MINPACK hybrd/hybrj (Powell hybrid)
LeastSquares(…, TRF, …) least_squares(method='trf') trust-region reflective, bounds, robust losses, x_scale
LeastSquares(…, LM, …), Leastsq least_squares(method='lm'), leastsq (with cov_x) MINPACK lmder/lmdif
CurveFit, CurveFitModel curve_fit (sigma 1-D/2-D, absolute_sigma, bounds, losses) LM or TRF, covariance as SciPy; the model per sample (F) or over arrays (Vec, one call per sweep as SciPy's f(xdata, *p))
Linprog linprog revised simplex (default) or interior point; duals
Quadprog (v0.5.0, docs/design-qp.md) MATLAB quadprog, OSQP the API, validation and result blocks of ½xᵀPx + qᵀx s.t. equalities, inequalities, two-sided rows and bounds, with dense or sparse (go-sparse) P and A; solved today: positive definite P by the Goldfarb–Idnani dual active-set method (equalities, inequalities, two-sided rows, bounds; infeasibility certificates; dependent and redundant rows; QPSolver keeps the factors between solves: UpdateQ, UpdateBounds, UpdateMatrixValues and WorkingSet warm starts recover x and the multipliers from the cached factors and drop the constraints whose multiplier turned negative, Goldfarb–Idnani Prop. 8.1–8.2: 0.03 of the cold pivots at a 5% perturbation of q, 0.30 at 50%, 0.80 at 200%, same answer); a singular P, P = 0 (LP) or sparse constraints go to the ADMM method of OSQP v1.0.0 (QPADMM, QPAuto picks it; KKT by go-sparse's quasi-definite LDLᵀ with AMD ordering, Ruiz scaling, adaptive ρ, the unscaled termination test with duality gap, infeasibility and unboundedness certificates, non-convexity detection; defaults 1e-3 as OSQP's; Polish solves OSQP's reduced KKT system with iterative refinement and keeps the result when the residuals drop: x within 1e-6 of Clarabel on 34 of the 35 solved fixture cases at the default 1e-3 settings; for ADMM the QPSolver also keeps its factorisation and iterates: UpdateQ, UpdateBounds (refactor only when a row changes type) and UpdateMatrixValues (rescale, numeric refactor on the stored symbolic factor; an update that breaks quasi-definiteness is refused) and WarmStart/X0/Y0: 0.53 of the cold iterations after a 1% perturbation of q at 1e-6 tolerances): on the 38 problems OSQP can read, status, iteration count and ρ-update count equal OSQP's on all of them, and on 12 generated sparse problems (random QP, equality QP, Lasso, portfolio; sparse P and A, tools/qporacle gen --set sparse). On 33 Maros–Mészáros problems (tiny and small tiers, dense or sparse fixture form, tools/qporacle mm fetch/convert, pinned commit and SHA-256, regenerated on linux/amd64) ADMM at 1e-9 with polishing reaches Clarabel's objective on 27 and ends with OSQP v1.0.0's own status on the other 6 (QSHARE1B, QSHARE2B, QSCAGR7 and QSCTAP1 at the iteration limit, PRIMALC2 and PRIMALC5 with a dual-infeasibility certificate), and the active set reaches it on all 13 with a positive definite P. Against OSQP v1.0.0 and the quadprog package (tools/qpbench, one thread, medians of 5 interleaved rounds, docs/perf.md): ADMM runs OSQP's iterations exactly (25 of 25 instances) in 0.5–0.65× its time on the dense n ≥ 500 problems and 0.8–0.9× on the larger portfolios, but 1.04–1.49× in the solve phase and 2.2–4.9× in the setup on small sparse ones, where go-sparse's AMD, symbolic analysis and LDLᵀ solves are the cause (open defect, not worked around); the active set is 0.68–0.76× the quadprog package's time from n = 500, 1.09× at n = 200 and 2.0× at n = 50 (open defect). QPAuto picks the active set up to n + m = 2500, where it stops being faster than ADMM. Checked against OSQP, Clarabel and quadprog on 39 problems (x to 1e-7 and 1e-8) and against the SLSQP lsei chain on 600 random ones
Brute brute grid then Nelder–Mead polish
DifferentialEvolution (v0.6.0; with Constraints (Lampinen's rule, trust-constr polish) and Integrality) differential_evolution the twelve strategies, immediate and deferred updating, Workers (results identical for every worker count with deferred updating), dithering, LHS / random / array init, X0, custom strategy, callback, L-BFGS-B polish; follows SciPy's random stream exactly (NewRNG(seed) is rng=seed, NewLegacyRNG(seed) is seed=seed); no allocation per generation; a huge PopSize is refused (population capped at 2^27 values)
Basinhopping (v0.6.0) basinhopping Metropolis acceptance (T = 0 is monotonic), adaptive step size, custom TakeStep, both accept-test forms incl. ForceAccept (which skips the Metropolis draw), callback, NIterSuccess; any Minimize method as the local minimiser (SciPy's default choice when Method is empty); follows SciPy's random stream, displacements and Metropolis draws interleaved on one source (NewRNG / NewLegacyRNG)
Direct (v0.6.0; docs/design-global.md) direct DIRECT and DIRECT-L (Original selects Jones' version), a statement-by-statement port of the C code SciPy wraps (MIT, NOTICE); deterministic, same points, Nfev, Nit and status as SciPy; Workers evaluates the points of one rectangle concurrently with identical results; the hidden-constraint code of the C version is ported but not reachable from SciPy's API
CheckGrad, ApproxFprime check_grad, approx_fprime forward differences

Gradients are optional everywhere. Without one, finite differences use the step rules of SciPy's approx_derivative, kept inside the bounds. Non-convergence is reported in Success/Status/Message as SciPy does. Invalid input returns an error.

Examples

Each example below is a runnable, output-checked Go example in example_test.go, and its output was checked against SciPy.

// scipy.optimize.minimize(rosen, x0, jac=rosen_der, method='BFGS')
r, err := optimize.Minimize(optimize.Problem{Func: rosen, Grad: rosenDer},
	[]float64{-1.2, 1}, optimize.BFGS, nil)
// r.X = [1 1], r.Nit = 32 (SciPy: 32), "Optimization terminated successfully."

// scipy.optimize.minimize(f, x0, method='L-BFGS-B', bounds=[(-2, 0.5), (None, None)])
r, _ = optimize.Minimize(optimize.Problem{Func: f}, []float64{0, 0}, optimize.LBFGSB,
	&optimize.Options{Bounds: []optimize.Bound{{Lo: -2, Hi: 0.5}, optimize.Unbounded()}})

// scipy.optimize.minimize(f, x0, method='SLSQP', bounds=[(1, 5)]*4,
//     constraints=[{'type': 'ineq', 'fun': g}, {'type': 'eq', 'fun': h}])     (Hock–Schittkowski 71)
r, _ = optimize.Minimize(optimize.Problem{Func: f}, []float64{1, 5, 5, 1}, optimize.SLSQP,
	&optimize.Options{Bounds: bounds, Constraints: []optimize.ConstraintSpec{
		optimize.Constraint{Kind: optimize.Ineq, M: 1, Func: g},  // x1·x2·x3·x4 − 25 ≥ 0
		optimize.Constraint{Kind: optimize.Eq, M: 1, Func: h},    // Σ xᵢ² − 40 = 0
	}})
// r.Fun = 17.0140172, r.Nit = 5 (SciPy: 5), r.Multipliers

// The same problem by the interior-point method: minimize(..., method='trust-constr')
r, _ = optimize.Minimize(optimize.Problem{Func: f}, []float64{1, 5, 5, 1}, optimize.TrustConstr,
	&optimize.Options{Bounds: bounds, Constraints: cons})
// r.Fun = 17.01402, r.Success, r.Optimality, r.ConstrViolation

// popt, pcov = scipy.optimize.curve_fit(lambda x, a, b, c: a*np.exp(-b*x) + c, x, y)
fit, err := optimize.CurveFit(func(x float64, p []float64) float64 {
	return p[0]*math.Exp(-p[1]*x) + p[2]
}, xdata, ydata, []float64{1, 1, 1}, nil)
// fit.Popt, fit.PcovArray(), fit.Perr()  ->  a = 2.500 ± 0.004, b = 1.300 ± 0.005, c = 0.500 ± 0.002

// The same model over arrays (Model.Vec), called once per sweep as SciPy calls
// f(xdata, *p), so that it can use a vector exp (go-simd/floats):
fit, err = optimize.CurveFitModel(optimize.Model{Vec: func(xs, p, out []float64) {
	for j, v := range xs {
		out[j] = -p[1] * v
	}
	floats.Exp(out, out)
	for j, e := range out {
		out[j] = p[0]*e + p[2]
	}
}}, xdata, ydata, []float64{1, 1, 1}, nil)

// scipy.optimize.brentq(lambda x: x**3 - 2*x - 5, 2, 3)
root, _ := optimize.Brentq(func(x float64) float64 { return x*x*x - 2*x - 5 }, 2, 3, nil)
// root.Root = 2.094551481542…, 7 iterations (as SciPy)

// scipy.optimize.root(fun, [0, 0])        (fun writes f(x) into its second argument)
sol, _ := optimize.Root(optimize.SystemProblem{Func: fun}, []float64{0, 0}, nil)

// scipy.optimize.least_squares(fun, x0, bounds=([0, 0], [2, 0.5]), loss='soft_l1', f_scale=0.1)
ls, _ := optimize.LeastSquares(optimize.LSProblem{Func: resid, M: m}, []float64{1, 0.1}, optimize.TRF,
	&optimize.LSOptions{Bounds: []optimize.Bound{{0, 2}, {0, 0.5}}, Loss: optimize.LossSoftL1, FScale: 0.1})

// scipy.optimize.linprog(c, A_ub=A, b_ub=b, bounds=[(None, None), (-3, None)])
lp, _ := optimize.Linprog([]float64{-1, 4}, optimize.LPConstraints{AUb: A, BUb: b,
	Bounds: []optimize.Bound{optimize.Unbounded(), {Lo: -3, Hi: math.Inf(1)}}}, nil)
// lp.X = [10 -3], lp.Fun = -22, lp.IneqLin.Marginals (HiGHS sign convention)

Callbacks receive the point first and write their outputs into the slices that follow: Func(x), Grad(x, g), FuncGrad(x, g) (SciPy's jac=True), Hess(x, h), HessP(x, p, hp), residuals Func(x, f), Jacobians Jac(x, J). Matrices are row-major []float64.

Accuracy contract

Bound: the solution of every solver family is within a stated tolerance of the optimum, and so is its value: max|x - x*| and |f - f*| at most 1e-3 and 1e-6 for every Minimize method at its default tolerances (measured worst case 1.5e-4 and 1.1e-8, SLSQP on Rosenbrock; BFGS, CG, Powell and trust-constr reach 1e-6 or better, and so does L-BFGS-B on those two problems; L-BFGS-B stops on a relative reduction of f (factr·eps = 2.2e-9 of max(|f|, 1) by default), so its bound on f is relative to the optimum, 1e-6·max(1, |f*|): the measured worst case is |f - f*| = 3.5e-6 at f* = 4.04e4 (8.7e-11 relative) with |x - x*| = 5.8e-4, the same on Options.SciPyExact and on the default kernels, TestAccuracyBoundLBFGSB), 2e-12 + 4·eps·|x*| for the bracketing root finders, 1e-7 for Root/Fsolve (hybr, xtol 1.49e-8), 1e-6 for LeastSquares, Leastsq and CurveFit, 1e-9 for Linprog and 1e-12 for Quadprog on the test problems; the Euclidean norm of the MINPACK ports is within n/2 + 2 ulps of the exact norm (measured: 11.7 ulps at n = 1000), without spurious overflow or underflow. Oracle: exact optima of the test problems (Rosenbrock (1, 1), Himmelblau (3, 2), a line fitted to integers by big.Rat normal equations, a vertex and a quadratic with rational optima) and 300-bit math/big for the irrational ones (the cube root of 2 and 3, the square root of 2) and for the norm; never another float64 implementation. Exact: bit-for-bit SciPy is an option, not the contract: Options.SciPyExactUpdate keeps SciPy's dense BFGS update, and SciPyExact (in RootOptions, LeastsqOptions, LSOptions, CurveFitOptions) makes the MINPACK ports (Root, Fsolve, Leastsq, LM) keep MINPACK's operation order, norm included, so that their iterates and counts equal SciPy's. By default they do so only below 32 equations or residuals; from 32 up they run on FMA and go-simd kernels (tolerance-validated, iteration counts may differ).

The bounds are asserted by TestAccuracyBound… in accuracy_bound_test.go. Matching SciPy's iterates in the last bit is a way of porting, used while a solver is ported and kept where it costs nothing; it never decides whether a faster algorithm may land. A faster default lands when it is within the bound above. docs/design.md records the MINPACK norm measurement (a plain four-accumulator sum is 3.5× faster per call and more accurate on unit-scale inputs (equal elsewhere), but moves a 7 µs LM solve by at most -7% and Root by +3%, and changes the iterate counts): MINPACK's norm stays below 32 equations or residuals and under SciPyExact; from 32 up the default norm is the plain sum (fastEnorm).

How close to SciPy

All numbers below are against SciPy 1.18.1 fixtures generated by testdata/gen/*.py (run with uv run --with scipy --with numpy python …) and embedded in the tests. They are the same on arm64 and amd64, except where noted.

Area Fixtures Result
Minimize (NM, Powell, CG, BFGS, Newton-CG, L-BFGS-B) 79 runs on Rosenbrock n=2/10/100, Beale, Himmelblau, Powell singular, Wood, with and without gradients, bounds, iteration limits every converged SciPy run is matched with an objective at least as good, within the method's own tolerance; on the arithmetic-only problems, 36/38 runs take SciPy's exact path (identical nit, nfev, njev); the 2 exceptions are explained in docs/design.md
L-BFGS-B 44 runs, including 8 problems that reach rare branches (Cholesky failures, the 3.0 backtrack, Cauchy breakpoints) identical nit/nfev/njev/status/message on every analytic-gradient run except Rosenbrock n=100 (513 vs 514 iterations, SciPy's Accelerate BLAS rounding); bit-identical to SciPy's C code built with sequential BLAS
Minimize(SLSQP) 100 runs: 36 Hock–Schittkowski problems and 10 stress cases (infeasible, inconsistent and singular linearisations, fixed variables), with and without derivatives, NonlinearConstraint/LinearConstraint and option variants; SciPy's x86_64 wheel (tools/slsqporacle) 100/100 statuses; 88/100 on SciPy's exact path (nit/nfev/njev, x to 1e-7, multipliers to 1e-6); the other 12 are runs on which SciPy's own arm64 and x86_64 wheels also disagree (docs/design.md)
Minimize(TrustConstr) the same 100 runs (tools/slsqporacle --method trust-constr) success/failure as SciPy on 100/100 (2 are errors in both: more equalities than variables); identical status on 93/100 on arm64, 94/100 on amd64 (the rest are gtol against xtol, both successes); objective within 1e-5 of SciPy or 1e-4 of the known optimum on every success; 65/100 on SciPy's exact path on arm64, 69/100 on amd64 — SciPy's own wheels disagree with each other on 35 runs, and the iterates of the 4 other runs that leave the path were traced to the last bit (docs/design.md)
Root/Fsolve 23 runs (MGH problems with and without Jacobian, failure and option cases) 23/23 identical counts, status and message; x bit-identical
LeastSquares(LM) / Leastsq 39 / 44 runs on the MGH least-squares set 36/39 and 41/44 identical counts; the mismatches are on problems that call exp/sin/cos, where Go's libm and the C library differ in the last ulp
LeastSquares(TRF) 89 runs: MGH problems, bounds, all robust losses, x_scale, 2-/3-point differences 86/89 identical nfev/njev/status (84/89 on amd64); every cost and active mask matches
CurveFit 11 fits (exponentials, Gaussians, sum of two Gaussians, a 2-variable plane, 1-D and 2-D sigma, bounds, absolute_sigma, m = n) popt within 1e-6, pcov within 1e-5 relative, identical nfev on every fit
Scalar roots 71 runs on 11 hard functions (multiple roots, flat, steep, kinks, poles) × 7 methods 68/71 on SciPy's exact path (same root, iterations, calls); the rest differ only through cos/exp in the last ulp
MinimizeScalar, Bracket 36 + 6 runs identical x/nit/nfev/message on arithmetic-only functions
Linprog 46 problems vs HiGHS: Klee–Minty, cycling examples, degenerate, free and upper-bounded variables, redundant rows, infeasible, unbounded, random up to 60×40 46/46 statuses; objective error ≤ 1.8e-15 (simplex) and ≤ 2e-8 (interior point); solutions and duals inside SciPy's optimal sets
Brute 4 grids (the SciPy documentation example, Himmelblau, Rosenbrock 3-D) x and f to 1e-9
DifferentialEvolution 378 runs (tools/globaloracle, SciPy 1.18.1 linux/amd64) on 10 arithmetic-only objectives (incl. 112 with linear / polynomial nonlinear / equality / impossible constraints and integer variables), for both seeding forms (NewRNG: rng=int, PCG64; NewLegacyRNG: seed=int, MT19937): all 12 strategies, immediate and deferred updating, LHS / random / array init, X0, constant and dithered mutation, Atol, Tol, MaxFev, MaxIter 0/1/3, PopSize 1..30, NaN objectives unpolished (296 runs): nfev, nit, message, x, fun, the final population and its energies, constr_violation, bit for bit on every run, i.e. SciPy's exact random path (constraints and integrality included); polished (82 runs): 57 bit-identical; the others differ only in the polisher (L-BFGS-B reproduces SciPy's BLAS/LAPACK summation orders only in part, trust-constr follows another finite-difference path in the last digits; trust-constr results agree within 1e-3); NumPy's mean/std order is pinned on 50 arrays
DifferentialEvolution, Basinhopping, Direct: statistics internal/gofuncs (21 functions of SciPy's go_benchmark_functions, checked against SciPy's classes at three points), SciPy 1.18.1 seeded 100 times: differential_evolution (popsize 20) on 16 transcendental objectives, basinhopping (L-BFGS-B, bounds) on 8, direct once on 21 success counts equal on 16 of 16 DE functions and within Fisher p > 0.4 on all 8 basin-hopping ones (one-sided p < 0.01 is a failure; a planted weakness gives p = 5e-46), median nfev equal on 13 DE functions and within 3 % on the others, 1359 of 1600 DE seeds on SciPy's exact path; DIRECT: same status and success on 21 of 21, same nfev and nit on 19
Basinhopping 224 runs (tools/globaloracle bh, SciPy 1.18.1 linux/amd64): Himmelblau, Rosenbrock, six-hump camel and a quartic with four minima, analytic gradients, BFGS and L-BFGS-B, both seeding forms, T 1 / 0 / 0.3 / -1 / 5, adaptive-step intervals and rates, NIterSuccess, niter 0 and 1, the old and new accept-test forms with ForceAccept every run makes SciPy's decisions: same per-step accept sequence, same nit, failures and message, values within 1e-8; 136 of the 224 are bit-identical in the whole trace, counts, x and fun; the others differ in the last digits of the local minimiser's final iterate, i.e. in L-BFGS-B (BFGS now follows SciPy's evaluation trace bit for bit, see "BFGS and L-BFGS-B last digits" in docs/design-global.md)
Direct 770 runs (tools/globaloracle, SciPy 1.18.1 linux/amd64): 27 objectives (shifted spheres in 1–10 dimensions, Rosenbrock, Goldstein–Price, six-hump camel, Styblinski–Tang, Shekel 5/7/10, Booth, Matyas, Beale, Branin, Hartmann 3/6, Ackley, Rastrigin, NaN/±Inf regions), DIRECT and DIRECT-L, eps fixed and Jones-updated, len_tol/vol_tol/f_min stops, maxfun (incl. the odd-budget rounding) and maxiter limits arithmetic-only objectives (products and sums, 618 of the runs): status, message, nfev, nit, x and fun bit for bit and the first 25 last-evaluated points, on every case; transcendental ones: same status and same counts on every case, fun bit-identical on most (the rest differ in the last digits through cos/exp); the SciPy documentation example gives nfev 2011 and 207

How such close agreement is possible:

  • The ports follow their references statement by statement.
  • Every product that feeds an addition is rounded explicitly, because Go would otherwise fuse it into an FMA on arm64 and other architectures.
  • The tests use FMA-free oracles.

See docs/design.md.

Negative controls. One algorithmic step was broken at a time; each break made the suite fail, and each was then reverted:

Broken step Failing tests
A term dropped from the BFGS update 6
A sign flipped in Moré–Thuente's dcstep 57
The wrong Brent golden constant 4
The Levenberg correction dropped in lmpar 40
A sign flipped in dogleg 17
TRF reflection disabled, or its radius growth changed 20 / 48 of the 89 cases leave SciPy's path
Max instead of min in the simplex ratio test 83
The sign of the interior-point corrector flipped iteration parity drops from 43 to 2 of 46
L-BFGS-B's subspace backtrack skipped, its Cauchy f2 update dropped, or its breakpoint heap disabled named fixtures fail for each

Performance

refbench (bench/), v0.9.0, 2026-11-13: one core on both sides, SciPy 1.18.1, medians of 7 interleaved rounds, 1-minute load 4.7 to 6.9 (Apple M4 Max). The SLSQP and trust-constr rows are tools/slsqpbench, 2026-11-13 (load 7.1 to 8.0). docs/perf.md and docs/perf-table.md have every row and the method.

Options.SciPyExact (L-BFGS-B and SLSQP) selects SciPy's arithmetic bit for bit: sequential sums without FMA and, for SLSQP, the reference loop of the triangular solve (lsi). The default of SLSQP solves it in one floats.AxpyRowsNoFMA pass per column: the same values, except that zero coefficients are no longer skipped, so an Inf (or NaN) in the constraint block meeting a zero coefficient now gives NaN where the reference loop keeps the Inf, and a signed zero may differ. A finite problem is unaffected; the SciPy fixtures keep their path in both modes.

Benchmark Go SciPy Speed-up
Rosenbrock n=2, BFGS 3.58 µs 1.18 ms 330×
Rosenbrock n=100, BFGS (default O(n²) update, tolerance-validated) 5.42 ms 47.3 ms 8.7×
Rosenbrock n=2, L-BFGS-B 70.5 µs 736 µs 10.4×
Rosenbrock n=100, L-BFGS-B 2.23 ms 11.7 ms 5.3×
curve_fit, 10⁴ points, LM (model per point / Model.Vec) 1.37 / 0.78 ms 1.50 / 1.46 ms 1.10× / 1.87×
curve_fit, 10⁴ points, TRF (model per point / Model.Vec) 1.95 / 1.39 ms 2.42 / 2.45 ms 1.24× / 1.76×
curve_fit, 10⁴ points, TRF with bounds (per point / Model.Vec) 2.60 / 1.81 ms 3.69 / 3.61 ms 1.42× / 1.99×
brentq 0.14 µs 4.0 µs 29×
SLSQP, HS71 (analytic / finite differences), slsqpbench, load 7.1–8.0 5.95 / 7.12 µs 117 / 658 µs 20× / 92×
SLSQP, n = 50 with 100 bounds, slsqpbench, load 7.1–8.0 2.76 ms 4.73 ms 1.7×
trust-constr, HS71 (analytic / finite differences), slsqpbench, load 7.1–8.0 527 / 447 µs 33.5 / 35.2 ms 64× / 79×
trust-constr, n = 50 with 100 bounds, slsqpbench, load 7.1–8.0 29.1 ms 72.9 ms 2.5×

Most of SciPy's time on small problems is Python overhead around the callbacks. Even after subtracting SciPy's time spent in its own callbacks, the Go algorithms remain 2–300× faster, depending on the problem.

In curve_fit most of the time is the model: SciPy calls its NumPy expression once per sweep over the 10⁴ points; CurveFit calls a Go closure once per point. Model.Vec (v0.7.0) takes the model over arrays, so it can use a vector exp (go-simd/floats), with the same solver and the same counts as SciPy. BFGS updates the inverse Hessian in O(n²) by default (rank-two form, FMA kernels): tolerance-validated, not bit-identical to SciPy (same minimiser within tolerance, iteration counts within a few percent: n = 100 takes 542 iterations against 544). Options.SciPyExactUpdate selects SciPy's update, two dense n×n products summed in SciPy's order (bit for bit, O(n³), about 90 ms at n = 100 on floats.AxpyRowsNoFMA). The BFGS n = 100 row above is the default update (refbench v0.9.0: 5.42 ms against SciPy's 47.3 ms); no row is slower than SciPy (#53). MINPACK (Root, Fsolve, LM, Leastsq, CurveFit) runs its QR, Q accumulation, Givens sweeps and norms on FMA and go-simd kernels from 32 equations or residuals up (tolerance-validated); SciPyExact in each options type keeps MINPACK's summation order bit for bit. L-BFGS-B likewise runs on FMA and go-simd kernels by default (tolerance-validated, iteration counts may differ from SciPy's by a few); Options.SciPyExact selects SciPy's summation order and x87 dnrm2 bit for bit, at about twice the time.

Not done

The SciPy and MATLAB gaps are listed in docs/coverage.md. docs/roadmap.md lists what Julia's Optim, Roots and LsqFit, R and GSL do better, ranked by gain for cost, with an implementation source and an oracle for each item.

  • minimize: COBYLA/COBYQA, TNC, dogleg/trust-ncg and the other trust-region methods; trust-constr's keep_feasible, sparse Jacobians and SR1 Hessian option. For L-BFGS-B, the hess_inv operator is not provided.
  • Quadprog: a positive semidefinite P in the active-set method (outer proximal-point iterations), OSQP's indirect (PCG) linear-system solver, the Maros–Mészáros medium and full tiers in the benchmark, and the performance defects of docs/perf.md.
  • root / least_squares: root methods other than hybr; the band/col_deriv options; dogbox; the lsmr trust-region solver and sparse Jacobians.
  • linprog: HiGHS-class performance, MILP, singleton-row presolve, crossover and sparse matrices.
  • Global optimisers: (v0.6.0, docs/design-global.md): DE init='sobol' and 'halton' (no QMC engine yet), shgo, dual_annealing; the L-BFGS-B port reproduces SciPy's BLAS/LAPACK summation orders only in part (136 of 224 basin-hopping runs bit-identical, see design-global.md section 14); the comparison of times with SciPy (tools/globalbench): no row slower, 2.4 to 66 times faster, from 3 rounds at load below 8 (docs/perf.md). Direct does not reproduce SciPy's maxfun=0 or eps=0, and ends with status -6 instead of writing out of bounds when the list of candidates (5000 levels) overflows.

Licence

BSD 3-Clause; see LICENSE.

Documentation

Overview

Package optimize provides numerical optimisation and root finding in pure Go: unconstrained and bound-constrained minimisation (Nelder–Mead, Powell, CG, BFGS, Newton-CG, L-BFGS-B), scalar minimisation (Brent, golden section, bounded), scalar roots (Brent, Ridder, bisection, Newton, secant, Halley), systems of equations (MINPACK's hybrid Powell method), nonlinear least squares (MINPACK Levenberg–Marquardt and trust-region reflective with bounds and robust losses), curve fitting with parameter covariance, and linear programming.

The API follows scipy.optimize closely enough that each function documents the SciPy call it corresponds to, and the test suite checks the results against SciPy fixtures; the implementation is independent Go.

Index

Examples

Constants

View Source
const (
	DEConverged  = 0
	DEMaxIter    = 1
	DEMaxFev     = 2
	DEStopped    = 3
	DEInfeasible = 4
)

Statuses of a DEResult.

View Source
const (
	LPOptimal       = 0 // optimisation terminated successfully
	LPIterLimit     = 1 // iteration limit reached
	LPInfeasible    = 2 // problem appears to be infeasible
	LPUnbounded     = 3 // problem appears to be unbounded
	LPNumericalFail = 4 // numerical difficulties encountered
)

LP status codes, as scipy.optimize.linprog reports them in status.

View Source
const (
	// NLMinBRelative: the relative reduction of f fell below RelTol.
	NLMinBRelative = 4
	// NLMinBFalse: the line search could not make progress, the point is
	// probably not a minimum.
	NLMinBFalse = 8
	// NLMinBEvalLimit: more than EvalMax evaluations.
	NLMinBEvalLimit = 9
	// NLMinBIterLimit: more than IterMax iterations.
	NLMinBIterLimit = 10
	// NLMinBGradient: the projected gradient is below GradTol.
	NLMinBGradient = 11
)

Termination codes of NLMinB, Result.Status. 4, 8, 9 and 10 carry the numbers of R's nlminb messages ("relative convergence (4)", "false convergence (8)", ...); NLMinBGradient has no R counterpart.

View Source
const (
	QPOptimal       = 0 // KKT conditions hold within tolerance
	QPIterLimit     = 1
	QPInfeasible    = 2 // with a certificate in PrimalCert
	QPUnbounded     = 3 // with a certificate in DualCert (ADMM only)
	QPNumericalFail = 4
	QPNonConvex     = 5 // ADMM residuals above 1e30 (OSQP_NON_CVX)
	QPInaccurate    = 6 // ADMM met the tolerances ×10 only
)

QP status codes. 0–4 have Linprog's meaning; 5 and 6 are QP-specific.

View Source
const (
	FlagConverged = "converged"
	FlagConvErr   = "convergence error"
	FlagSignErr   = "sign error"
)

Root-finder flags, as SciPy's RootResults.flag strings.

View Source
const (
	// UncminGradient: the relative gradient is close to zero.
	UncminGradient = 1
	// UncminStep: successive iterates are within StepTol.
	UncminStep = 2
	// UncminNoStep: the last global step found no lower point; the iterate
	// may be a local minimum or StepTol is too small.
	UncminNoStep = 3
	// UncminIterLim: the iteration limit was reached.
	UncminIterLim = 4
	// UncminStepMax: StepMax was exceeded five consecutive times.
	UncminStepMax = 5
)

Termination codes of Uncmin (Result.Status), the documented meanings of nlm's `code`.

Variables

View Source
var (
	// ErrDimension reports slices whose lengths disagree.
	ErrDimension = errors.New("optimize: dimension mismatch")
	// ErrMethod reports an unknown or unsupported method.
	ErrMethod = errors.New("optimize: unknown method")
	// ErrBounds reports inconsistent bounds or a starting point outside them.
	ErrBounds = errors.New("optimize: invalid bounds")
	// ErrBracket reports a scalar root bracket whose ends do not change sign.
	ErrBracket = errors.New("optimize: f(a) and f(b) must have different signs")
	// ErrInput reports any other invalid argument.
	ErrInput = errors.New("optimize: invalid input")
)

Errors returned for invalid input. Failure to converge is not an error: it is reported through the Success, Status and Message fields of a result, as SciPy does, so the caller still receives the best point found.

View Source
var ErrNoConvergence = errors.New("optimize: no convergence")

ErrNoConvergence reports an iteration that ran out of sweeps; the result returned with it is the best iterate.

View Source
var ErrNotConverged = errors.New("optimize: optimal parameters not found")

ErrNotConverged is returned by CurveFit when the least-squares solver did not converge (SciPy raises RuntimeError("Optimal parameters not found")). The partial result is returned alongside it.

Functions

func ApproxFprime

func ApproxFprime(f func([]float64) float64, x []float64, epsilon float64) []float64

ApproxFprime returns the forward-difference gradient of f at x with the absolute step epsilon (0 selects SciPy's default sqrt(eps) ≈ 1.49e-8), as scipy.optimize.approx_fprime(xk, f, epsilon) does.

func Bracket

func Bracket(f func(float64) float64, xa, xb float64) (x [3]float64, fx [3]float64, nfev int, err error)

Bracket searches downhill from xa, xb (0 and 1 when both are zero) for three points xa, xb, xc with f(xb) below f(xa) and f(xc); it is scipy.optimize.bracket(func, xa, xb, grow_limit=110, maxiter=1000). It returns the points, their values and the number of evaluations, or a *BracketError.

func CheckGrad

func CheckGrad(f func([]float64) float64, grad func(x, g []float64), x []float64, epsilon float64) float64

CheckGrad returns the Euclidean norm of the difference between grad(x) and a forward-difference gradient of f with absolute step epsilon (0 for the default), like scipy.optimize.check_grad(func, grad, x0, epsilon=...). grad writes the gradient at x into its second argument.

func Float added in v0.6.0

func Float(v float64) *float64

Float returns a pointer to v, for the options where 0 is a meaningful value and the default is not 0 (DE Tol and Recombination, basin hopping T).

func Int added in v0.6.0

func Int(v int) *int

Int returns a pointer to v, for the options where 0 is a meaningful value and the default is not 0 (basin hopping NIter).

func Polyroot added in v0.11.0

func Polyroot(coef []complex128) ([]complex128, error)

Polyroot returns the complex roots of the polynomial

coef[0] + coef[1]·z + … + coef[n]·zⁿ

(coefficients in increasing order, as R's polyroot takes them), by the Ehrlich–Aberth simultaneous iteration (Ehrlich 1967, Aberth 1973) started on Bini's circle of radius from the Cauchy-type bound, with the reversed-polynomial evaluation for |z| > 1 so that high degrees do not overflow. Leading zero coefficients lower the degree and a zero constant term gives exact zero roots. The roots are returned by increasing modulus (ties by argument), the order R's polyroot lists them in for well separated moduli; this is a different algorithm from R's Jenkins–Traub, so equality is within the stated bound, not bit for bit.

The polynomial and its derivative are evaluated by the compensated Horner scheme (Graillat, Langlois & Louvet 2005: error-free transformations, FMA products), accurate as if computed in twice the working precision. A plain Horner evaluation has noise eps·Σ|c_k||z|^k, which for the Chebyshev polynomial T40 near ±1 is as large as the spacing of the roots (two roots collapsed onto one, 75 evaluation-noise units of error); the compensated evaluation returns every root of T20, T30, T40 and T50 distinct and within a few ulp (asserted in TestPolyrootChebyshev against 400-bit roots). For a simple root z the error is bounded by the final rounding plus the compensated noise (n·eps)²·Σ|c_k||z|^k / |p'(z)|. The evaluation costs more than the plain one (ns/op not yet measured on a quiet machine); no allocation is added.

An all-zero or empty coefficient slice is an ErrInput; non-finite coefficients too. A failure to converge in 500 sweeps (multiple or clustered roots at the limit of the precision) returns the best iterate together with ErrNoConvergence.

Polyroot is PolyrootContext with context.Background() and nil options.

Divergence from R, documented and kept: R's polyroot fails with "root finding code failed" on some large random inputs (observed black-box on runif(1500)); this implementation converges on them and returns the roots.

func PolyrootContext added in v0.16.0

func PolyrootContext(ctx context.Context, coef []complex128, opts *PolyrootOptions) ([]complex128, error)

PolyrootContext is Polyroot with an order option and cancellation. ctx.Err() is polled before the first sweep, at the start of every sweep and every 64 roots within a sweep; on cancellation it returns nil and ctx.Err() (the error is ctx's own, so errors.Is(err, context.Canceled) holds).

func SANNTemperature added in v0.13.0

func SANNTemperature(t, tmax int, temp float64) float64

SANNTemperature is the logarithmic cooling schedule at iteration t >= 1 (t = 1 is the first candidate): temp / log(((t-1) div tmax)*tmax + e), with integer division. It is constant over each block of tmax iterations.

Types

type Acceptance added in v0.6.0

type Acceptance int

Acceptance is the verdict of a user accept test.

const (
	// Reject rejects the step (the Metropolis test still draws its number).
	Reject Acceptance = iota
	// Accept lets the later tests decide.
	Accept
	// ForceAccept accepts the step and skips the remaining tests, including
	// the Metropolis draw (SciPy's "force accept").
	ForceAccept
)

type BasinhoppingOptions added in v0.6.0

type BasinhoppingOptions struct {
	// NIter is the number of basin-hopping iterations (nil: 100).
	NIter *int
	// T is the Metropolis temperature (nil: 1); 0 is monotonic basin hopping.
	T *float64
	// StepSize is the initial maximum displacement of the default step
	// (0 selects 0.5).
	StepSize float64
	// Method is the local minimiser; "" follows scipy.optimize.minimize:
	// SLSQP with MinimizeOptions.Constraints, else L-BFGS-B with Bounds,
	// else BFGS.
	Method Method
	// MinimizeOptions are SciPy's minimizer_kwargs (bounds, constraints,
	// tolerances ...).
	MinimizeOptions *Options
	// TakeStep replaces the default random displacement.
	TakeStep StepTaker
	// AcceptTest is SciPy's accept_test(f_new, x_new, f_old, x_old);
	// AcceptTestResult its newer form accept_test(res_new, res_old). At most
	// one may be set. The old point is the last accepted one.
	AcceptTest       func(fNew float64, xNew []float64, fOld float64, xOld []float64) Acceptance
	AcceptTestResult func(resNew, resOld *Result) Acceptance
	// Callback is called with the initial minimum and after each step with a
	// copy of the step's minimum; returning true stops the run (the return
	// value of the initial call is ignored, as in SciPy).
	Callback func(x []float64, f float64, accepted bool) (stop bool)
	// Interval is how often the step size is adapted (0 selects 50).
	Interval int
	// NIterSuccess stops after that many steps without a new global minimum
	// (0: NIter + 2, never).
	NIterSuccess int
	// RNG is the random stream, shared by the displacement and the
	// Metropolis draws as in SciPy; nil is an entropy-seeded PCG64.
	RNG *RandomSource
	// TargetAcceptRate (0.5) and StepwiseFactor (0.9) lie in (0, 1).
	TargetAcceptRate float64
	StepwiseFactor   float64
}

BasinhoppingOptions configures Basinhopping.

type BasinhoppingResult added in v0.6.0

type BasinhoppingResult struct {
	X                    []float64
	Fun                  float64
	Nit                  int
	Nfev, Njev, Nhev     int
	MinimizationFailures int
	// Lowest is the lowest local minimisation found (SciPy's
	// lowest_optimization_result).
	Lowest  *Result
	Success bool
	Message string
}

BasinhoppingResult is the outcome of Basinhopping (SciPy's OptimizeResult).

func Basinhopping added in v0.6.0

func Basinhopping(p Problem, x0 []float64, o *BasinhoppingOptions) (*BasinhoppingResult, error)

Basinhopping finds a global minimum of p by basin hopping; it is scipy.optimize.basinhopping (SciPy 1.18.1) statement by statement. With the same seed, a local minimiser that follows SciPy's path and an objective built from IEEE operations, the sequence of steps is SciPy's.

type Bound

type Bound struct {
	Lo, Hi float64
}

Bound is a closed interval [Lo, Hi] for one variable. Use math.Inf(-1) and math.Inf(1) for a missing side; the zero value Bound{} pins the variable to zero, so use Unbounded() for a free variable.

func Unbounded

func Unbounded() Bound

Unbounded returns the free interval (-Inf, +Inf).

type BracketError

type BracketError struct {
	Xa, Xb, Xc, Fa, Fb, Fc float64
	Nfev                   int
	Msg                    string
}

BracketError reports that Bracket found no valid bracket. It carries the last three points, as SciPy's BracketError does.

func (*BracketError) Error

func (e *BracketError) Error() string

type BracketOptions

type BracketOptions struct {
	Xtol, Rtol float64
	MaxIter    int
}

BracketOptions configures the bracketing root finders. Zero values select SciPy's defaults: Xtol 2e-12, Rtol 4·eps (the smallest allowed), MaxIter 100.

type BruteOptions

type BruteOptions struct {
	// Ns is the number of grid points per axis when Range.Step is 0 (20).
	Ns int
	// NoFinish skips the final local minimisation (SciPy's finish=None).
	NoFinish bool
	// Finish is the local method polishing the best grid point
	// (Nelder-Mead, SciPy's fmin). Finish options come from FinishOptions.
	Finish        Method
	FinishOptions *Options
	// Workers evaluates the grid with this many goroutines (1). The
	// objective must then be safe for concurrent use.
	Workers int
}

BruteOptions configures Brute.

type BruteResult

type BruteResult struct {
	// X and Fun are the minimiser and its value (after the finish step).
	X   []float64
	Fun float64
	// Success is false when the finish step did not converge.
	Success bool
	// Axes holds the coordinates of each grid axis; Jout the objective on
	// the grid, row-major over the axes (shape len(Axes[0]) × …).
	Axes [][]float64
	Jout []float64
}

BruteResult is Brute's full output (SciPy's full_output=True).

func Brute

func Brute(f func([]float64) float64, ranges []Range, o *BruteOptions) (*BruteResult, error)

Brute minimises f by evaluating it on a grid and polishing the best point with a local method; it is scipy.optimize.brute(func, ranges, Ns=20, full_output=True, finish=fmin, workers=...). The finish step may leave the grid's box, as in SciPy.

type CGType added in v0.12.0

type CGType int

CGType selects the beta formula of CGNash.

const (
	// FletcherReeves is beta = g.g / g0.g0.
	FletcherReeves CGType = 1
	// PolakRibiere is beta = g.(g-g0) / g0.g0.
	PolakRibiere CGType = 2
	// BealeSorenson is beta = g.(g-g0) / t.(g-g0), t the previous direction.
	BealeSorenson CGType = 3
)

type ConjugateOrder added in v0.16.0

type ConjugateOrder int

ConjugateOrder selects how roots of equal modulus are listed.

const (
	// ArgumentOrder (the zero value) lists roots of equal modulus by
	// increasing argument in (-π, π]: a conjugate pair comes negative
	// imaginary part first.
	ArgumentOrder ConjugateOrder = iota
	// PositiveImagFirst lists roots of equal modulus by increasing |argument|
	// and, for the two members of a conjugate pair, the one with positive
	// imaginary part first, as R's polyroot lists them.
	PositiveImagFirst
)

type Constraint added in v0.3.0

type Constraint struct {
	// Kind selects c(x) = 0 (Eq) or c(x) >= 0 (Ineq).
	Kind ConstraintKind
	// M is the number of outputs of Func.
	M int
	// Func writes the M constraint values at x into c.
	Func func(x, c []float64)
	// Jac writes the M×n Jacobian at x into jac, row-major. When nil it is
	// estimated by forward differences.
	Jac func(x, jac []float64)
}

Constraint is a block of M constraint functions of one kind, SciPy's dictionary form {'type': 'eq'|'ineq', 'fun': ..., 'jac': ...}.

type ConstraintKind added in v0.3.0

type ConstraintKind int

ConstraintKind tells whether a Constraint is an equality or an inequality.

const (
	// Eq is the equality constraint c(x) = 0 (SciPy type 'eq').
	Eq ConstraintKind = iota
	// Ineq is the inequality constraint c(x) >= 0 (SciPy type 'ineq').
	Ineq
)

type ConstraintSpec added in v0.3.0

type ConstraintSpec interface {
	// contains filtered or unexported methods
}

ConstraintSpec is a general constraint accepted by the constrained minimisers (Options.Constraints): a Constraint, a NonlinearConstraint or a LinearConstraint, the three forms scipy.optimize.minimize accepts. The interface is sealed. SLSQP reduces every form to equality blocks c(x) = 0 and inequality blocks c(x) >= 0; trust-constr keeps SciPy's general form lb <= f(x) <= ub.

type CurveFitOptions

type CurveFitOptions struct {
	// Sigma is the uncertainty of ydata: a 1-D array of standard
	// deviations (the residuals are divided by it) or a 2-D covariance
	// matrix (the residuals are whitened by its Cholesky factor). nil means
	// unit weights.
	Sigma *ndarray.Array
	// AbsoluteSigma uses Sigma in an absolute sense: Pcov is not scaled by
	// the reduced chi-square.
	AbsoluteSigma bool
	// Bounds on the parameters; bounds select TRF.
	Bounds []Bound
	// Method is LM (the default without bounds) or TRF (with bounds).
	Method LSMethod
	// MaxFev, Ftol, Xtol and Gtol are passed to the solver (SciPy's maxfev
	// for LM, max_nfev for TRF; tolerances 1.49012e-8 for LM, 1e-8 for TRF).
	MaxFev           int
	Ftol, Xtol, Gtol float64
	// Loss and FScale select a robust loss (TRF only), as SciPy forwards
	// loss= and f_scale= to least_squares.
	Loss   Loss
	FScale float64
	// Workers evaluates the model over the samples with this many
	// goroutines when there are at least 2048 samples (default 1). The
	// model must then be safe for concurrent use; the result is identical.
	Workers int
	// SciPyExact makes LM follow MINPACK's summation order bit for bit; the
	// default runs the QR factorisation on FMA and go-simd kernels (see
	// LSOptions.SciPyExact). TRF ignores it.
	SciPyExact bool
}

CurveFitOptions configures CurveFit. Zero values select SciPy's defaults.

type CurveFitResult

type CurveFitResult struct {
	// Popt holds the fitted parameters.
	Popt []float64
	// Pcov is the n×n covariance of Popt, row-major. When it cannot be
	// estimated every entry is +Inf and CovOK is false (SciPy warns).
	Pcov  []float64
	CovOK bool
	// Fvec holds the (weighted) residuals at Popt and Nfev the solver's
	// count of residual evaluations (SciPy's infodict['nfev']: MINPACK's
	// count including finite differences for LM, least_squares' count
	// excluding them for TRF).
	Fvec []float64
	Nfev int
	// Status and Message are the solver's (SciPy's ier and mesg).
	Status  int
	Message string
}

CurveFitResult is the outcome of CurveFit: SciPy's (popt, pcov) plus its full_output information.

func CurveFit

func CurveFit(f func(x float64, p []float64) float64, xdata, ydata *ndarray.Array, p0 []float64, o *CurveFitOptions) (*CurveFitResult, error)

CurveFit fits a 1-D model f(x; p) to (xdata, ydata) by nonlinear least squares; it is scipy.optimize.curve_fit(f, xdata, ydata, p0, sigma=..., absolute_sigma=..., bounds=..., method=...). See CurveFitModel for models of several independent variables or with analytic derivatives.

Example

popt, pcov = scipy.optimize.curve_fit(lambda x, a, b, c: a*np.exp(-b*x) + c, x, y)

package main

import (
	"fmt"
	"math"

	"github.com/go-ndarray/ndarray"
	"github.com/go-numerics/optimize"
)

func main() {
	x, _ := ndarray.Linspace(0, 4, 50)
	y := x.Map(func(v float64) float64 { return 2.5*math.Exp(-1.3*v) + 0.5 + 0.01*math.Sin(37*v) })
	model := func(x float64, p []float64) float64 { return p[0]*math.Exp(-p[1]*x) + p[2] }
	r, err := optimize.CurveFit(model, x, y, []float64{1, 1, 1}, nil)
	if err != nil {
		panic(err)
	}
	perr := r.Perr()
	fmt.Printf("a = %.3f ± %.3f, b = %.3f ± %.3f, c = %.3f ± %.3f\n",
		r.Popt[0], perr[0], r.Popt[1], perr[1], r.Popt[2], perr[2])
}
Output:
a = 2.500 ± 0.004, b = 1.300 ± 0.005, c = 0.500 ± 0.002

func CurveFitModel

func CurveFitModel(model Model, xdata, ydata *ndarray.Array, p0 []float64, o *CurveFitOptions) (*CurveFitResult, error)

CurveFitModel is CurveFit for a general Model. xdata is 1-D (m samples) or 2-D (k, m); ydata is 1-D with m elements. p0 sets the number of parameters; nil starts from SciPy's default (ones, or a feasible point inside the bounds) when Bounds gives the count.

Without bounds the default method is MINPACK's Levenberg–Marquardt and the covariance is SciPy leastsq's cov_x; with TRF it is the pseudo-inverse of JᵀJ from the SVD of the final Jacobian, discarding singular values below eps·max(m, n)·s₀. Unless AbsoluteSigma is set the covariance is scaled by the reduced chi-square Σr²/(m − n).

Example (Vec)

The same fit with the model written over arrays, called once per sweep as SciPy calls f(xdata, *p): it can then use a vector exp.

package main

import (
	"fmt"
	"math"

	"github.com/go-ndarray/ndarray"
	"github.com/go-numerics/optimize"
	"github.com/go-simd/floats"
)

func main() {
	x, _ := ndarray.Linspace(0, 4, 50)
	y := x.Map(func(v float64) float64 { return 2.5*math.Exp(-1.3*v) + 0.5 + 0.01*math.Sin(37*v) })
	model := optimize.Model{Vec: func(xs, p, out []float64) {
		for j, v := range xs {
			out[j] = -p[1] * v
		}
		floats.Exp(out, out) // github.com/go-simd/floats
		for j, e := range out {
			out[j] = p[0]*e + p[2]
		}
	}}
	r, err := optimize.CurveFitModel(model, x, y, []float64{1, 1, 1}, nil)
	if err != nil {
		panic(err)
	}
	perr := r.Perr()
	fmt.Printf("a = %.3f ± %.3f, b = %.3f ± %.3f, c = %.3f ± %.3f\n",
		r.Popt[0], perr[0], r.Popt[1], perr[1], r.Popt[2], perr[2])
}
Output:
a = 2.500 ± 0.004, b = 1.300 ± 0.005, c = 0.500 ± 0.002

func (*CurveFitResult) PcovArray

func (r *CurveFitResult) PcovArray() *ndarray.Array

PcovArray returns Pcov as an n×n ndarray.

func (*CurveFitResult) Perr

func (r *CurveFitResult) Perr() []float64

Perr returns the one-standard-deviation errors √diag(Pcov).

func (*CurveFitResult) PoptArray

func (r *CurveFitResult) PoptArray() *ndarray.Array

PoptArray returns Popt as a 1-D ndarray.

type DEInit added in v0.6.0

type DEInit int

DEInit selects how the initial population is drawn.

const (
	// DEInitLatinHypercube is SciPy's init='latinhypercube' (default).
	DEInitLatinHypercube DEInit = iota
	// DEInitRandom is init='random'.
	DEInitRandom
)

type DEOptions added in v0.6.0

type DEOptions struct {
	// Strategy is one of the twelve strategies (Best1Bin).
	Strategy DEStrategy
	// CustomStrategy is SciPy's callable strategy: it writes the trial (in
	// the problem's units) for candidate into trial. population is S×N in the
	// problem's units; it must not be retained. The draws it makes on rng
	// are interleaved with the solver's own.
	CustomStrategy func(candidate int, population [][]float64, rng *RandomSource, trial []float64)
	// MaxIter is the maximum number of generations (nil: 1000). Zero is
	// allowed: the initial population is evaluated and nothing else.
	MaxIter *int
	// MaxFev limits the objective evaluations (0: unlimited), as the
	// maxfun of SciPy's DifferentialEvolutionSolver.
	MaxFev int
	// PopSize is the population multiplier (15): S = max(5, PopSize·N), N
	// counting only the axes whose bounds differ.
	PopSize int
	// Tol is the relative tolerance of the convergence test (0.01).
	Tol *float64
	// Atol is its absolute tolerance (0).
	Atol float64
	// Mutation: nil is the dither (0.5, 1); one value is a constant; two
	// values (sorted) are the dither range.
	Mutation []float64
	// Recombination is the crossover probability (0.7).
	Recombination *float64
	// RNG is the random stream; nil is an entropy-seeded PCG64
	// (not reproducible). NewRNG(seed) is SciPy's rng=seed and
	// NewLegacyRNG(seed) is seed=seed.
	RNG *RandomSource
	// Init selects the initial population when InitPopulation is nil.
	Init DEInit
	// InitPopulation is SciPy's init=array: S×N with S >= 5, clipped to the
	// bounds.
	InitPopulation [][]float64
	// X0 replaces the first member of the initial population.
	X0 []float64
	// Updating selects immediate or deferred updating.
	Updating DEUpdating
	// Workers evaluates the trials of a deferred generation (and the initial
	// population) with this many goroutines. The objective must then be safe
	// for concurrent use.
	Workers int
	// Constraints are NonlinearConstraint, LinearConstraint or (an
	// extension to SciPy) Constraint values, handled by Lampinen's rule. The
	// constraint functions are evaluated serially.
	Constraints []ConstraintSpec
	// Integrality marks the integer variables (nil: none; otherwise one
	// entry per variable). The limits of an integral axis become
	// [ceil(Lo)-0.5, floor(Hi)+0.5] (just inside) and values are rounded.
	Integrality []bool
	// NoPolish skips the final polish (SciPy polish=False): L-BFGS-B, or
	// trust-constr with constraints. It is skipped when every variable is
	// integral.
	NoPolish bool
	// Polish replaces the default polisher (SciPy's callable polish). It
	// receives the bounds the default would use (integral axes pinned to the
	// found value) and the constraints.
	Polish func(f func([]float64) float64, x0 []float64, bounds []Bound, cons []ConstraintSpec) (*Result, error)
	// Callback is called after each generation; returning true stops the
	// run. The result it receives is a copy with Convergence set.
	Callback func(r *DEResult) (stop bool)
}

DEOptions configures DifferentialEvolution. Zero values select SciPy's defaults; the fields where 0 is meaningful are pointers (see Float, Int).

type DEResult added in v0.6.0

type DEResult struct {
	X    []float64
	Fun  float64
	Jac  []float64 // from the polisher, when it improved the point
	Nfev int
	Nit  int
	// Status: 0 converged, 1 maxiter, 2 maxfev, 3 callback stop, 4 the
	// solution violates the constraints. (SciPy has no status; these codes
	// are Go-defined.)
	Status             int
	Success            bool
	Message            string
	Population         [][]float64 // S×N, problem units
	PopulationEnergies []float64
	// Constr holds, per constraint, the violation of each component at X, and
	// ConstrViolation the largest (SciPy's constr_violation and maxcv); both
	// only with constraints.
	Constr          [][]float64
	ConstrViolation float64
	// Convergence is set only in the result handed to a callback:
	// Tol/(convergence+eps).
	Convergence float64
}

DEResult is the outcome of DifferentialEvolution (SciPy's OptimizeResult).

func DifferentialEvolution added in v0.6.0

func DifferentialEvolution(f func(x []float64) float64, bounds []Bound, o *DEOptions) (*DEResult, error)

DifferentialEvolution minimises f over the box bounds; it is scipy.optimize.differential_evolution (SciPy 1.18.1) statement by statement, so that with the same seed (NewRNG for rng=int, NewLegacyRNG for seed=int) and an objective built from IEEE operations only it follows SciPy's path bit for bit.

type DEStrategy added in v0.6.0

type DEStrategy string

DEStrategy names one of SciPy's twelve differential-evolution strategies.

const (
	Best1Bin          DEStrategy = "best1bin" // the default
	Best1Exp          DEStrategy = "best1exp"
	Rand1Bin          DEStrategy = "rand1bin"
	Rand1Exp          DEStrategy = "rand1exp"
	RandToBest1Bin    DEStrategy = "randtobest1bin"
	RandToBest1Exp    DEStrategy = "randtobest1exp"
	CurrentToBest1Bin DEStrategy = "currenttobest1bin"
	CurrentToBest1Exp DEStrategy = "currenttobest1exp"
	Best2Bin          DEStrategy = "best2bin"
	Best2Exp          DEStrategy = "best2exp"
	Rand2Bin          DEStrategy = "rand2bin"
	Rand2Exp          DEStrategy = "rand2exp"
)

The strategies of scipy.optimize.differential_evolution.

type DEUpdating added in v0.6.0

type DEUpdating int

DEUpdating selects when the best member is updated.

const (
	// DEUpdatingDefault is immediate updating, or deferred when Workers > 1
	// (SciPy overrides updating='immediate' the same way).
	DEUpdatingDefault DEUpdating = iota
	// DEImmediate updates the population after each candidate.
	DEImmediate
	// DEDeferred updates it once per generation; the trials of a generation
	// are independent, so they can be evaluated with several workers and the
	// result is the same for every worker count.
	DEDeferred
)

type DirectOptions added in v0.6.0

type DirectOptions struct {
	// Eps is Jones' epsilon, which keeps the search from over-refining
	// near the current best. 0 selects 1e-4; a negative value selects
	// Jones' update eps = max(1e-4*|minf|, |Eps|) after each iteration (the
	// C code's convention, which SciPy passes through). SciPy's eps=0 is
	// not expressible (0 means the default here).
	Eps float64
	// MaxFev is an approximate upper bound on the number of objective
	// evaluations: the budget is checked once per iteration, after all its
	// divisions, so Nfev can exceed it by one iteration's samples. 0 selects
	// 1000*N. SciPy's maxfun=0 (which the C code turns into 100000) is not
	// expressible. Odd budgets are rounded down by the C code's sizing
	// arithmetic (MaxFev 1001 becomes 1000).
	MaxFev int
	// MaxIter is the maximum number of iterations; the C loop runs at most
	// MaxIter-2 of them. 0 selects 1000.
	MaxIter int
	// Original selects Jones' original DIRECT; false selects the locally
	// biased DIRECT-L (SciPy's locally_biased=True, the default).
	Original bool
	// FMin is the known global minimum; nil means unknown.
	FMin *float64
	// FMinRtol stops the search when (fun - FMin)/max(1, |FMin|) <= FMinRtol
	// (FMin != 0 and unknown divides by |FMin|, as the C code does). 0
	// selects 1e-4; negative disables the test. Must be <= 1.
	FMinRtol float64
	// VolTol stops the search when the volume of the hyperrectangle that
	// holds the best point falls below this fraction of the box. 0 selects
	// 1e-16; negative disables the test. Must be <= 1.
	VolTol float64
	// LenTol stops the search when the side-length measure of the
	// hyperrectangle that holds the best point falls below it (half the
	// longest side for DIRECT-L, half the diagonal for the original). 0
	// selects 1e-6; negative disables the test. Must be <= 1.
	LenTol float64
	// Workers evaluates the objective at the points sampled inside one
	// rectangle concurrently (2*k points for k longest sides). The result
	// does not depend on the worker count. The objective must then be safe
	// for concurrent use and must not retain its argument. 0 or 1 is serial.
	Workers int
	// Callback is called after each iteration with a copy of the last
	// evaluated point (SciPy's callback receives this point, although its
	// docstring says "best"), a copy of the best point and its value.
	// Returning true stops the search with status -102, "Forced stop".
	Callback func(xLast, xBest []float64, fBest float64) (stop bool)
}

DirectOptions configure Direct. The zero value (or a nil pointer) selects SciPy's defaults of scipy.optimize.direct: DIRECT-L, eps 1e-4, 1000*N evaluations, 1000 iterations.

type DirectResult added in v0.6.0

type DirectResult struct {
	// X is the best point found; Fun its value.
	X   []float64
	Fun float64
	// Nfev is the number of objective evaluations, Nit the iteration at which
	// the search ended.
	Nfev, Nit int
	// Status is SciPy's ret_code: 1 (MaxFev), 2 (MaxIter), 3 (FMin reached),
	// 4 (VolTol), 5 (LenTol), or negative for an error (-6: maximum number of
	// levels reached; -102: stopped by the callback).
	Status int
	// Success is Status > 2.
	Success bool
	// Message describes the reason for termination.
	Message string
}

DirectResult is the outcome of Direct, the counterpart of the OptimizeResult of scipy.optimize.direct.

func Direct added in v0.6.0

func Direct(f func(x []float64) float64, bounds []Bound, o *DirectOptions) (*DirectResult, error)

Direct finds the global minimum of f over the box bounds with the DIRECT algorithm of Jones, Perttunen and Stuckman (1993) or its locally biased variant DIRECT-L of Gablonsky and Kelley (2001), following SciPy 1.18.1's scipy.optimize.direct, which wraps Gablonsky's C code. The search is deterministic and takes SciPy's path: same points, same Nfev and Nit.

Every bound must be finite with Lo < Hi. f must not retain or modify its argument. A NaN objective value is stored like any other value, as in SciPy: it is never smaller than anything, so such points are never the best. Invalid input returns an error wrapping ErrInput or ErrBounds before any objective call.

Example
r, _ := Direct(dgStyblinskiTangDoc, dgBox(2, -4, 4), &DirectOptions{LenTol: 1e-3})
fmt.Printf("%.4f %.4f %d %d %v\n", r.X[0], r.X[1], r.Nfev, r.Nit, r.Success)
Output:
-2.9044 -2.9044 207 19 true

type ExtendInt added in v0.10.0

type ExtendInt string

ExtendInt selects how BrentqExtend reacts when f has no sign change on the starting interval, with the semantics documented for the extendInt argument of R's uniroot (help page text only).

const (
	// ExtendNo never extends: a missing sign change is ErrBracket.
	ExtendNo ExtendInt = "no"
	// ExtendYes extends the interval on both sides until f changes sign.
	ExtendYes ExtendInt = "yes"
	// ExtendDownX assumes f is monotone decreasing in x and extends only
	// the side that is needed.
	ExtendDownX ExtendInt = "downX"
	// ExtendUpX assumes f is monotone increasing in x and extends only the
	// side that is needed.
	ExtendUpX ExtendInt = "upX"
)

type FDMethod

type FDMethod int

FDMethod selects a finite-difference scheme.

const (
	// FD2Point is the forward difference (SciPy '2-point'), one evaluation
	// per variable, error O(h).
	FD2Point FDMethod = iota
	// FD3Point is the central difference (SciPy '3-point'), two evaluations
	// per variable, error O(h²); it falls back to a one-sided second-order
	// formula next to a bound.
	FD3Point
)

type LPConstraints

type LPConstraints struct {
	// AUb and BUb are the inequality constraints A_ub·x <= b_ub.
	AUb, BUb *ndarray.Array
	// AEq and BEq are the equality constraints A_eq·x == b_eq.
	AEq, BEq *ndarray.Array
	// Bounds gives one interval per variable. nil means linprog's default
	// (0, +Inf) for every variable — note that this differs from Minimize,
	// where nil means unbounded. Use Unbounded() for a free variable.
	Bounds []Bound
}

LPConstraints holds the constraints of a linear program

A_ub·x <= b_ub,  A_eq·x == b_eq,  Bounds[i].Lo <= x[i] <= Bounds[i].Hi,

in the shape of linprog's A_ub, b_ub, A_eq, b_eq and bounds arguments. Any of the matrices may be nil (no such constraints); a non-nil matrix must be 2-D with len(c) columns and its right-hand side 1-D with one entry per row.

type LPDual

type LPDual struct {
	// Residual is the slack of each constraint: b_ub − A_ub·x for
	// inequalities, b_eq − A_eq·x for equalities, x − lb and ub − x for
	// the bounds (±Inf for a missing bound).
	Residual []float64
	// Marginals is the sensitivity of the optimal objective to the
	// constraint's right-hand side (∂fun/∂b), with SciPy's HiGHS sign
	// convention: ineqlin and upper marginals are <= 0, lower marginals
	// are >= 0, eqlin marginals have any sign. They satisfy
	// c = A_ubᵀ·ineqlin + A_eqᵀ·eqlin + lower + upper. nil unless Status
	// is 0.
	Marginals []float64
}

LPDual pairs the residuals of one family of constraints with their marginals (dual values), like the ineqlin, eqlin, lower and upper fields of SciPy's HiGHS result.

type LPMethod

type LPMethod string

LPMethod names a linear-programming algorithm. The values are the strings SciPy's linprog accepts for the matching legacy methods.

const (
	// LPSimplex is a dense bounded-variable revised simplex method with an
	// LU-factorised basis and product-form updates. It is the default: it
	// ends on a vertex, its duals are exact for the final basis, and it
	// certifies infeasibility and unboundedness directly.
	LPSimplex LPMethod = "revised simplex"
	// LPInteriorPoint is the homogeneous self-dual primal–dual
	// interior-point method of Andersen & Andersen with Mehrotra's
	// predictor–corrector, solving dense normal equations by Cholesky. Its
	// solution is interior to the optimal face, not a vertex.
	LPInteriorPoint LPMethod = "interior-point"
)

Linear-programming methods implemented by Linprog.

type LPOptions

type LPOptions struct {
	// Method selects the algorithm; the default is LPSimplex.
	Method LPMethod
	// Tol is the primal and dual feasibility tolerance. Default 1e-9 for
	// LPSimplex and 1e-8 for LPInteriorPoint (SciPy's interior-point
	// default). As in SciPy, the final feasibility check uses 10·√Tol.
	Tol float64
	// MaxIter bounds the iterations (simplex pivots and bound flips over
	// both phases, or interior-point iterations). Default 5000 for
	// LPSimplex and 1000 for LPInteriorPoint, as in SciPy.
	MaxIter int
	// NoPresolve disables the presolve pass (linprog's presolve=False).
	NoPresolve bool
}

LPOptions configures Linprog. Zero values select the defaults listed with each field.

type LPResult

type LPResult struct {
	// X is the solution. When Status is not 0 it is the last point the
	// solver held (it may violate the constraints), or nil when presolve
	// stopped before any solve.
	X []float64
	// Fun is c·X.
	Fun float64
	// Slack is b_ub − A_ub·X and Con is b_eq − A_eq·X.
	Slack, Con []float64
	// IneqLin, EqLin, Lower and Upper hold residuals and marginals of the
	// inequality rows, equality rows, lower bounds and upper bounds.
	IneqLin, EqLin, Lower, Upper LPDual
	// Status is SciPy's code: 0 optimal, 1 iteration limit, 2 infeasible,
	// 3 unbounded, 4 numerical difficulties.
	Status int
	// Success reports Status == 0.
	Success bool
	// Message describes the reason for termination.
	Message string
	// Nit counts iterations over all phases.
	Nit int
}

LPResult is the outcome of Linprog, the counterpart of the OptimizeResult that scipy.optimize.linprog returns.

func Linprog

func Linprog(c []float64, cons LPConstraints, opts *LPOptions) (*LPResult, error)

Linprog minimises c·x subject to cons; it is the counterpart of scipy.optimize.linprog(c, A_ub, b_ub, A_eq, b_eq, bounds, method=...). SciPy's default HiGHS solvers are not available; opts.Method selects a dense revised simplex (default) or a dense interior-point method, after a light version of the presolve SciPy applies to its legacy methods: empty rows and columns and fixed variables are removed, trivial infeasibility and unboundedness are reported with SciPy's messages, and linearly dependent equality rows are dropped (or reported inconsistent). Unlike SciPy, singleton rows are left to the solver. The marginals are those of the original problem, with HiGHS's sign convention.

Invalid input (shapes, NaN or Inf coefficients, NaN bounds, unknown method) is an error wrapping ErrDimension, ErrInput, ErrBounds or ErrMethod. Infeasible, unbounded or unsolved problems are not errors: they are reported through Status, Success and Message.

Example

scipy.optimize.linprog(c, A_ub=A, b_ub=b, bounds=[(None, None), (-3, None)])

package main

import (
	"fmt"
	"math"

	"github.com/go-ndarray/ndarray"
	"github.com/go-numerics/optimize"
)

func main() {
	A, _ := ndarray.FromData([]float64{-3, 1, 1, 2}, 2, 2)
	b, _ := ndarray.FromData([]float64{6, 4}, 2)
	r, _ := optimize.Linprog([]float64{-1, 4}, optimize.LPConstraints{AUb: A, BUb: b,
		Bounds: []optimize.Bound{optimize.Unbounded(), {Lo: -3, Hi: math.Inf(1)}}}, nil)
	fmt.Printf("x = [%.1f %.1f], fun = %.1f, %s\n", r.X[0], r.X[1], r.Fun, r.Message)
}
Output:
x = [10.0 -3.0], fun = -22.0, Optimization terminated successfully.

func (*LPResult) XArray

func (r *LPResult) XArray() *ndarray.Array

XArray returns X as a 1-D ndarray (nil when X is nil).

type LSMethod

type LSMethod string

LSMethod names a least-squares algorithm; the values are SciPy's least_squares method strings.

const (
	// TRF is the trust-region reflective method (SciPy's default), which
	// supports bounds and robust loss functions.
	TRF LSMethod = "trf"
	// LM is the Levenberg–Marquardt method of MINPACK (lmdif/lmder); it
	// needs m >= n and supports neither bounds nor robust losses.
	LM LSMethod = "lm"
)

Least-squares methods.

type LSOptions

type LSOptions struct {
	// Bounds constrains the variables (TRF only). nil means unbounded.
	Bounds []Bound
	// Ftol, Xtol and Gtol are the termination tolerances (1e-8 each).
	// SciPy lets None disable one; here a negative value disables it.
	Ftol, Xtol, Gtol float64
	// MaxNfev bounds function evaluations (100·n; for LM it bounds
	// MINPACK's count, which leaves out finite-difference evaluations).
	MaxNfev int
	// XScale is the characteristic scale of each variable. nil means 1
	// (TRF) or 'jac' (LM, SciPy's default for that method); XScaleJac
	// selects SciPy's x_scale='jac'.
	XScale    []float64
	XScaleJac bool
	// Loss is the robust loss (TRF only; LossLinear by default) and FScale
	// its soft margin between inliers and outliers (1).
	Loss   Loss
	FScale float64
	// DiffStep is the relative finite-difference step (SciPy diff_step);
	// 0 selects the default of the scheme.
	DiffStep float64
	// FDMethod is the finite-difference scheme for TRF (FD2Point). LM uses
	// MINPACK's own forward differences.
	FDMethod FDMethod
	// SciPyExact makes LM follow MINPACK's summation order bit for bit. The
	// default runs the QR factorisation of problems with 32 or more residuals
	// on FMA and go-simd kernels: the same solution within the accuracy
	// contract, not bit-identical to SciPy. TRF ignores it.
	SciPyExact bool
}

LSOptions configures LeastSquares. Zero values select SciPy's defaults.

type LSProblem

type LSProblem struct {
	// Func writes the m residuals at x into f. Required.
	Func func(x, f []float64)
	// Jac writes the m×n Jacobian at x into jac, row-major. Optional:
	// finite differences are used when it is nil.
	Jac func(x, jac []float64)
	// M is the number of residuals. Required.
	M int
}

LSProblem is a nonlinear least-squares problem: minimise ½·Σ ρ(f_i(x)²) over x, with m residuals f_i and n variables.

type LSResult

type LSResult struct {
	// X is the solution.
	X []float64
	// Cost is ½·Σρ(f_i²) at X.
	Cost float64
	// Fun holds the m residuals at X.
	Fun []float64
	// Jac is the m×n Jacobian at X, row-major (modified by the loss, as in
	// SciPy).
	Jac []float64
	// Grad is the gradient of the cost at X.
	Grad []float64
	// Optimality is the first-order optimality measure (max-norm of the
	// scaled gradient, as SciPy defines it per method).
	Optimality float64
	// ActiveMask is -1 or +1 for a variable at its lower or upper bound,
	// 0 otherwise.
	ActiveMask []int
	// Nfev and Njev count residual and Jacobian evaluations.
	Nfev, Njev int
	// Status follows SciPy: -1 improper input, 0 max_nfev reached, 1 gtol,
	// 2 ftol, 3 xtol, 4 both ftol and xtol satisfied.
	Status int
	// Success is Status > 0.
	Success bool
	// Message describes the termination.
	Message string
}

LSResult is the outcome of LeastSquares, mirroring the OptimizeResult of scipy.optimize.least_squares.

func LeastSquares

func LeastSquares(p LSProblem, x0 []float64, method LSMethod, opts *LSOptions) (*LSResult, error)

LeastSquares solves a nonlinear least-squares problem from x0; it is scipy.optimize.least_squares(fun, x0, jac=..., bounds=..., method=..., ftol=..., xtol=..., gtol=..., x_scale=..., loss=..., f_scale=..., diff_step=..., max_nfev=...). method "" selects TRF.

Example

scipy.optimize.least_squares(fun, x0, bounds=([0, 0], [2, 0.5]), loss='soft_l1')

package main

import (
	"fmt"
	"math"

	"github.com/go-numerics/optimize"
)

func main() {
	t := []float64{0, 1, 2, 3, 4, 5}
	y := []float64{1.0, 0.62, 0.36, 0.23, 0.13, 3.0} // the last point is an outlier
	p := optimize.LSProblem{M: len(t), Func: func(x, f []float64) {
		for i := range t {
			f[i] = x[0]*math.Exp(-x[1]*t[i]) - y[i]
		}
	}}
	r, _ := optimize.LeastSquares(p, []float64{1, 0.1}, optimize.TRF, &optimize.LSOptions{
		Bounds: []optimize.Bound{{Lo: 0, Hi: 2}, {Lo: 0, Hi: 0.5}}, Loss: optimize.LossSoftL1, FScale: 0.1})
	fmt.Printf("x = [%.3f %.3f] active %v\n", r.X[0], r.X[1], r.ActiveMask)
}
Output:
x = [0.990 0.466] active [0 0]

func (*LSResult) JacArray

func (r *LSResult) JacArray() *ndarray.Array

JacArray returns Jac as an m×n ndarray.

func (*LSResult) XArray

func (r *LSResult) XArray() *ndarray.Array

XArray returns X as a 1-D ndarray.

type LeastsqOptions

type LeastsqOptions struct {
	// Ftol is the relative error desired in the sum of squares and Xtol the
	// relative error desired in the solution (1.49012e-8 each; a negative
	// value means exactly 0). Gtol is the orthogonality desired between the
	// residuals and the Jacobian columns (0).
	Ftol, Xtol, Gtol float64
	// Maxfev bounds the calls to Func: 0 selects 100·(n+1) with a Jacobian
	// and 200·(n+1) without.
	Maxfev int
	// Epsfcn sets the forward-difference step sqrt(Epsfcn)·|x_j| when there
	// is no Jacobian; 0 selects the machine epsilon.
	Epsfcn float64
	// Factor sets the initial step bound Factor·|diag·x0| (100).
	Factor float64
	// Diag holds n positive scale factors for the variables; nil lets
	// MINPACK scale by the Jacobian column norms.
	Diag []float64
	// SciPyExact follows MINPACK's summation order bit for bit; the default
	// runs problems with 32 or more residuals on FMA and go-simd kernels
	// (the same solution within the accuracy contract, not bit-identical).
	SciPyExact bool
}

LeastsqOptions configures Leastsq. Zero values select the defaults of scipy.optimize.leastsq.

type LeastsqResult

type LeastsqResult struct {
	// X is the solution (or the last iterate).
	X []float64
	// CovX is inv(JᵀJ) at X, n×n row-major, from the final R and
	// permutation; nil when R is singular or the run did not converge
	// (Ier not in 1..4). Multiply it by the residual variance to obtain the
	// covariance of X.
	CovX []float64
	// Nfev counts calls to Func, including those of the finite-difference
	// Jacobian; Njev counts calls to Jac (0 without one).
	Nfev, Njev int
	// Fvec holds the residuals at X.
	Fvec []float64
	// Fjac is SciPy's infodict['fjac']: an n×m row-major array whose rows
	// are the columns of MINPACK's final QR workspace, so that the upper
	// triangle of its transpose's first n rows is R with Jac·P = Q·R.
	Fjac []float64
	// Ipvt is the permutation P: column j of P is column Ipvt[j]
	// (zero-based) of the identity.
	Ipvt []int
	// Qtf is the first n components of Qᵀ·Fvec.
	Qtf []float64
	// Ier is MINPACK's info: 1 to 4 mean a solution was found, 5 to 8 that
	// it was not.
	Ier int
	// Mesg is SciPy's message for Ier.
	Mesg string
}

LeastsqResult is the full output of Leastsq: SciPy's tuple (x, cov_x, infodict, mesg, ier).

func Leastsq

func Leastsq(p LSProblem, x0 []float64, opts *LeastsqOptions) (*LeastsqResult, error)

Leastsq minimises the sum of squares of p.M residuals with MINPACK's Levenberg–Marquardt method; it is scipy.optimize.leastsq(func, x0, Dfun=p.Jac, full_output=True, ftol, xtol, gtol, maxfev, epsfcn, factor, diag). Without p.Jac it runs lmdif (forward differences), otherwise lmder. Non-convergence is reported through Ier and Mesg.

func (*LeastsqResult) CovXArray

func (r *LeastsqResult) CovXArray() *ndarray.Array

CovXArray returns CovX as an n×n ndarray, or nil when absent.

func (*LeastsqResult) FjacArray

func (r *LeastsqResult) FjacArray() *ndarray.Array

FjacArray returns Fjac as an n×m ndarray.

func (*LeastsqResult) Success

func (r *LeastsqResult) Success() bool

Success reports whether Ier is 1, 2, 3 or 4, as SciPy's leastsq judges it.

func (*LeastsqResult) XArray

func (r *LeastsqResult) XArray() *ndarray.Array

XArray returns X as a 1-D ndarray.

type LinearConstraint added in v0.3.0

type LinearConstraint struct {
	A      *ndarray.Array
	Lb, Ub []float64
}

LinearConstraint is Lb <= A·x <= Ub, SciPy's LinearConstraint. A is 2-D with n columns (or 1-D, one row); Lb and Ub follow NonlinearConstraint's rules.

type Loss

type Loss string

Loss names a robust loss ρ for LeastSquares (SciPy's loss argument).

const (
	LossLinear Loss = "linear"  // ρ(z) = z
	LossSoftL1 Loss = "soft_l1" // ρ(z) = 2((1+z)^½ − 1)
	LossHuber  Loss = "huber"   // ρ(z) = z if z <= 1 else 2z^½ − 1
	LossCauchy Loss = "cauchy"  // ρ(z) = ln(1+z)
	LossArctan Loss = "arctan"  // ρ(z) = arctan(z)
)

Loss functions, with z = (f/FScale)².

type Method

type Method string

Method names a minimisation algorithm. The values are the strings SciPy's minimize accepts for its method argument.

const (
	NelderMead Method = "Nelder-Mead"
	Powell     Method = "Powell"
	CG         Method = "CG"
	BFGS       Method = "BFGS"
	NewtonCG   Method = "Newton-CG"
	LBFGSB     Method = "L-BFGS-B"
	// SLSQP is sequential least-squares quadratic programming; it is the
	// method that accepts Options.Constraints.
	SLSQP Method = "SLSQP"
	// TrustConstr is the trust-region interior-point method (SciPy
	// 'trust-constr', MATLAB fmincon 'interior-point'); it also accepts
	// Options.Constraints.
	TrustConstr Method = "trust-constr"
)

Methods implemented by Minimize.

type Model

type Model struct {
	// F returns the model value at sample x for parameters p. Required
	// unless Vec is set.
	F func(x, p []float64) float64
	// Vec evaluates the model at every sample in one call, as SciPy calls
	// f(xdata, *p) once on the whole array: out[j] is the model value at
	// sample j. xs holds xdata's values in row-major order: m values for
	// 1-D xdata, k·m for 2-D xdata of shape (k, m), where xs[i*m+j] is
	// variable i of sample j. xs is a private copy of xdata that Vec must
	// not modify. When Vec is set it is used instead of F. A model written
	// over arrays can use vector kernels (go-simd/floats' Exp, for
	// example), which a call per sample cannot; with the same arithmetic
	// per sample, Vec and F give the same result to the last bit. With
	// Workers > 1 and 1-D xdata, Vec is called concurrently on contiguous
	// chunks of the samples (xs and out are then sub-slices).
	Vec func(xs, p, out []float64)
	// Grad writes ∂f/∂p at sample x into grad (len(p) values). Optional:
	// finite differences are used when it is nil (SciPy's jac=callable).
	Grad func(x, p, grad []float64)
	// contains filtered or unexported fields
}

Model is a curve-fitting model y = f(x; p) evaluated at one sample. For 1-D xdata x has one element; for xdata of shape (k, m) — k independent variables, m samples, SciPy's layout — x holds the k values of one sample.

type NLMinBOptions added in v0.15.0

type NLMinBOptions struct {
	// EvalMax bounds the evaluations of f (R eval.max, 200); with a finite
	// difference gradient the extra evaluations of the gradient are not counted.
	EvalMax int
	// IterMax bounds the iterations (R iter.max, 150).
	IterMax int
	// RelTol is the relative reduction of f below which the run has converged
	// (R rel.tol, 1e-10).
	RelTol float64
	// GradTol stops the run when the largest component of the projected
	// gradient falls below it (1e-12). R has no such test.
	GradTol float64
}

NLMinBOptions are the options of NLMinB; zero values select R's defaults where there is one.

type NashOptions added in v0.12.0

type NashOptions struct {
	// AbsTol stops the run when f <= AbsTol; only used when HasAbsTol is set.
	AbsTol    float64
	HasAbsTol bool
	// RelTol is the relative convergence tolerance on f (default
	// sqrt(machine epsilon) = 1.49e-8).
	RelTol float64
	// MaxIter bounds function evaluations (Nelder-Mead; default 500) or
	// gradient evaluations (BFGS, CG; default 100).
	MaxIter int
	// Alpha, Beta, Gamma are the reflection, contraction and expansion
	// factors of Nelder-Mead (defaults 1, 0.5, 2).
	Alpha, Beta, Gamma float64
	// Type is the CG beta formula (default FletcherReeves).
	Type CGType
	// NDEps is the central-difference step used when no gradient is given
	// (default 1e-3, per coordinate, unscaled).
	NDEps float64
	// Refined makes CGNash depart from R's observed iterates where R is
	// slow or stops early: the accepted step is fitted by the quadratic
	// through f(0), the slope and f(step) (R's iterates move to half the
	// accepted step), convergence tests the gradient norm alone, and a
	// negative Polak-Ribiere or Beale-Sorenson beta restarts the search (R
	// tests the beta numerator itself). The default reproduces R.
	Refined bool
}

NashOptions are the controls of NelderMeadNash, BFGSNash and CGNash. The zero value selects the defaults noted on each field.

type NewtonOptions

type NewtonOptions struct {
	// Fprime is the derivative; nil selects the secant method.
	Fprime func(float64) float64
	// Fprime2 is the second derivative; with Fprime it selects Halley's
	// method.
	Fprime2 func(float64) float64
	// X1 is the second starting point of the secant method; 0 means
	// x0·(1+1e-4) ± 1e-4, as in SciPy. Set X1Set to use an explicit 0.
	X1    float64
	X1Set bool
	// Tol and Rtol are the absolute and relative tolerances on successive
	// iterates (numpy.isclose semantics).
	Tol, Rtol float64
	MaxIter   int
}

NewtonOptions configures Newton. Zero values select SciPy's defaults: Tol 1.48e-8, Rtol 0, MaxIter 50.

type NonlinearConstraint added in v0.3.0

type NonlinearConstraint struct {
	// M is the number of outputs of Func.
	M int
	// Func writes the M constraint values at x into c.
	Func func(x, c []float64)
	// Jac writes the M×n Jacobian, row-major; nil means finite differences.
	Jac func(x, jac []float64)
	// Lb and Ub bound Func(x).
	Lb, Ub []float64
}

NonlinearConstraint is Lb <= Func(x) <= Ub, SciPy's NonlinearConstraint. Lb and Ub have M entries or one entry broadcast to all; nil means -Inf and +Inf. Components with Lb == Ub are equalities; components unbounded on both sides are ignored, as SciPy does.

type Options

type Options struct {
	// Bounds constrains the variables (L-BFGS-B, SLSQP, trust-constr,
	// Nelder-Mead and Powell, as in SciPy). nil means unbounded.
	Bounds []Bound
	// Constraints are general equality and inequality constraints
	// (SLSQP and trust-constr): Constraint, NonlinearConstraint or
	// LinearConstraint values, SciPy's constraints argument. Other methods
	// return an error when it is set, where SciPy only warns.
	Constraints []ConstraintSpec
	// BarrierTol is trust-constr's barrier-parameter tolerance for the xtol
	// test (1e-8).
	BarrierTol float64
	// InitialTrRadius, InitialConstrPenalty, InitialBarrierParameter and
	// InitialBarrierTolerance are trust-constr's initial trust radius (1),
	// merit penalty (1), barrier parameter (0.1) and barrier subproblem
	// tolerance (0.1).
	InitialTrRadius, InitialConstrPenalty            float64
	InitialBarrierParameter, InitialBarrierTolerance float64
	// Tol is minimize's tol argument: it sets the method's main tolerance
	// the way SciPy does (Nelder-Mead: Xatol and Fatol; Powell: Xtol and
	// Ftol; CG and BFGS: Gtol; Newton-CG: Xtol; L-BFGS-B: Ftol and Gtol;
	// SLSQP: Ftol; trust-constr: Gtol, Xtol and BarrierTol) when those
	// fields are zero.
	Tol float64
	// MaxIter bounds the iterations (Nelder-Mead 200·n, Powell 1000·n,
	// CG, BFGS and Newton-CG 200·n, L-BFGS-B 15000, SLSQP 100,
	// trust-constr 1000). For Nelder-Mead and
	// Powell, setting only one of MaxIter and MaxFev leaves the other
	// unlimited, as in SciPy.
	MaxIter int
	// MaxFev bounds function evaluations (Nelder-Mead 200·n, Powell 1000·n,
	// L-BFGS-B 15000).
	MaxFev int
	// Gtol is the gradient tolerance: CG and BFGS stop when the Norm-norm
	// of the gradient is below it (1e-5); L-BFGS-B stops when the max-norm
	// of the projected gradient is below it (SciPy pgtol, 1e-5);
	// trust-constr stops when the max-norm of the Lagrangian gradient and
	// the constraint violation are both below it (1e-8).
	Gtol float64
	// Ftol is the relative reduction tolerance: Powell (1e-4),
	// L-BFGS-B ((f_k - f_{k+1})/max(|f_k|,|f_{k+1}|,1) <= Ftol, 2.22e-9);
	// for SLSQP it is the accuracy goal of the stopping tests (1e-6).
	Ftol float64
	// Xtol is the step tolerance: Powell (1e-4), Newton-CG (1e-5),
	// trust-constr's trust radius (1e-8).
	Xtol float64
	// Xatol and Fatol are Nelder-Mead's absolute tolerances (1e-4 each).
	Xatol, Fatol float64
	// Adaptive makes Nelder-Mead adapt its coefficients to the dimension.
	Adaptive bool
	// InitialSimplex is Nelder-Mead's initial simplex, n+1 points.
	InitialSimplex [][]float64
	// Direc is Powell's initial set of directions, n vectors.
	Direc [][]float64
	// Norm is the order of the gradient norm for CG and BFGS (+Inf).
	Norm float64
	// Eps is the absolute finite-difference step for gradient-based
	// methods when no gradient is given (sqrt(eps) ≈ 1.49e-8 for CG and
	// BFGS, 1e-8 for L-BFGS-B). It is ignored when FiniteDiffRelStep is set.
	Eps float64
	// FiniteDiffRelStep selects a relative finite-difference step instead
	// of the absolute Eps (SciPy finite_diff_rel_step with jac='2-point').
	FiniteDiffRelStep float64
	// FDMethod is the finite-difference scheme (FD2Point).
	FDMethod FDMethod
	// M is the number of L-BFGS-B correction pairs (10).
	M int
	// MaxLS bounds L-BFGS-B line-search steps per iteration (20).
	MaxLS int
	// C1 and C2 are the Wolfe constants for CG (1e-4, 0.4) and BFGS
	// (1e-4, 0.9).
	C1, C2 float64
	// HessInv0 is BFGS's initial inverse Hessian, n*n row-major (identity).
	HessInv0 []float64
	// SciPyExactUpdate makes BFGS update the inverse Hessian as SciPy does,
	// bit for bit: two dense n×n products, O(n³) per iteration (about 2× SciPy's
	// time at n = 100 on one core). The default is the equivalent rank-two
	// update, H − ρ(s uᵀ + u sᵀ) + (ρ² yᵀu + ρ) s sᵀ with u = H y, in O(n²)
	// with FMA kernels: the same minimiser within tolerance and comparable
	// iteration counts, validated against SciPy by tolerance, NOT bit-identical
	// to it. An asymmetric HessInv0 always takes the dense update.
	SciPyExactUpdate bool
	// SciPyExact makes L-BFGS-B and SLSQP follow SciPy's arithmetic bit for
	// bit: sequential sums without FMA (each product rounded before it is
	// added) and, for L-BFGS-B, OpenBLAS's extended-precision dnrm2. The
	// default runs the same algorithms on FMA and SIMD kernels (go-simd/floats)
	// with reordered sums: the same minimiser within the accuracy contract,
	// iteration counts that may differ by a few, NOT bit-identical to SciPy.
	SciPyExact bool
	// XRtol is BFGS's relative step tolerance (0: disabled).
	XRtol float64
	// Callback is called after each iteration with a copy of the current
	// point and the objective value; returning true stops the minimisation,
	// which then reports Success false and Status 99 (SciPy's callback
	// raising StopIteration).
	Callback func(x []float64, f float64) (stop bool)
}

Options configures Minimize. Zero values select the SciPy defaults of the chosen method, listed with each field.

type PolyrootOptions added in v0.16.0

type PolyrootOptions struct {
	// ConjugateOrder orders roots of equal modulus (relative tolerance 1e-12).
	ConjugateOrder ConjugateOrder
}

PolyrootOptions configures PolyrootContext. A nil *PolyrootOptions is the zero value.

type Problem

type Problem struct {
	// Func returns f(x).
	Func func(x []float64) float64
	// Grad writes ∇f(x) into grad (SciPy's jac=callable).
	Grad func(x, grad []float64)
	// FuncGrad returns f(x) and writes ∇f(x) into grad in one call
	// (SciPy's jac=True). It takes precedence over Func and Grad.
	FuncGrad func(x, grad []float64) float64
	// Hess writes the n×n Hessian at x into hess, row-major (SciPy's hess).
	Hess func(x, hess []float64)
	// HessP writes the Hessian at x times p into hp (SciPy's hessp).
	HessP func(x, p, hp []float64)
}

Problem describes a scalar objective for Minimize. Func is required unless FuncGrad is set. Derivatives are optional: when neither Grad nor FuncGrad is given, gradient-based methods use finite differences with SciPy's step rules (see Options.Eps, Options.FiniteDiffRelStep, Options.FDMethod).

Every callback receives the point first and writes its outputs into the slices that follow; it must not retain x.

type QPConstraints added in v0.5.0

type QPConstraints struct {
	// AUb·x <= BUb. AUb is m×n (or one row of length n); BUb has one entry
	// per row, +Inf for a vacuous row.
	AUb, BUb *ndarray.Array
	// AEq·x = BEq, with finite right-hand sides.
	AEq, BEq *ndarray.Array
	// Linear holds blocks Lb <= A·x <= Ub, the type of Minimize's constraints.
	Linear []LinearConstraint
	// ASparse holds rows l <= ASparse·x <= u (QPADMM only); L and U have one
	// entry per row, or one entry broadcast, or nil for -Inf and +Inf.
	ASparse *sparse.CSC[float64]
	L, U    []float64
	// Bounds are the variable bounds; nil means free, as in Minimize (not
	// Linprog's (0, +Inf)).
	Bounds []Bound
}

QPConstraints mirrors quadprog's (A, b, Aeq, beq, lb, ub) and adds the two-sided rows of OSQP. Every part is optional.

type QPMethod added in v0.5.0

type QPMethod string

QPMethod names a quadratic-programming algorithm.

const (
	// QPAuto picks the method: QPActiveSet when P is given dense and positive
	// definite, no ASparse is given and n + m <= 2000, QPADMM otherwise.
	QPAuto QPMethod = ""
	// QPActiveSet is the Goldfarb–Idnani dual active-set method: dense,
	// P positive definite.
	QPActiveSet QPMethod = "active-set"
	// QPADMM is OSQP's ADMM method: dense or sparse, P positive semidefinite.
	QPADMM QPMethod = "admm"
)

type QPOptions added in v0.5.0

type QPOptions struct {
	Method QPMethod
	// MaxIter is the iteration limit: 10·(n + m) for the active set, 4000 for
	// ADMM when zero.
	MaxIter int
	// FeasTol is the active set's primal feasibility tolerance (default 1e-9).
	FeasTol float64
	// ADMM settings: the zero value of each selects OSQP v1.0.0's default
	// (EpsAbs and EpsRel 1e-3, EpsPrimInf and EpsDualInf 1e-4, Rho 0.1,
	// Sigma 1e-6, Alpha 1.6, ScalingIter 10, AdaptiveRhoInterval 50,
	// CheckInterval 25, PolishDelta 1e-6, PolishRefine 3). A negative
	// ScalingIter or AdaptiveRhoInterval disables that step.
	EpsAbs, EpsRel         float64
	EpsPrimInf, EpsDualInf float64
	Rho, Sigma, Alpha      float64
	ScalingIter            int
	AdaptiveRhoInterval    int
	CheckInterval          int
	Polish                 bool
	PolishDelta            float64
	PolishRefine           int
	NoDualGapCheck         bool
	// X0 and Y0 (lengths n and the number of canonical rows) warm-start ADMM,
	// WorkingSet (canonical row indices) warm-starts the active set; both are
	// validated.
	X0, Y0     []float64
	WorkingSet []int
}

QPOptions tunes Quadprog. The zero value selects every default.

type QPProblem added in v0.5.0

type QPProblem struct {
	// P is n×n and is symmetrised as (P+Pᵀ)/2, as MATLAB's quadprog does.
	P *ndarray.Array
	// PSparse is n×n and holds the entries with row <= column only.
	PSparse *sparse.CSC[float64]
	// Q has length n and defines n.
	Q    []float64
	Cons QPConstraints
}

QPProblem is min ½xᵀPx + qᵀx subject to the constraints. Give P either dense (P) or sparse (PSparse, upper triangle only, as OSQP takes it), never both; nil for both means P = 0 (an LP, ADMM only).

type QPResult added in v0.5.0

type QPResult struct {
	X   []float64
	Fun float64
	// Residuals and marginals per family of constraints, one entry per input
	// row (a row unbounded on both sides has residual +Inf and marginal 0).
	// The marginal of a row a is the coefficient with which it enters
	// P·x + q = Σ marginal·a, so that
	//   P·x + q = AUbᵀ·IneqLin + AEqᵀ·EqLin + Aᵀ·Linear + A_sparseᵀ·Sparse
	//             + Lower + Upper,
	// the sign convention of Linprog (HiGHS). The residual of a two-sided row
	// (Linear, Sparse) is the slack of its nearer finite side. Lower and Upper
	// are indexed by variable; a variable pinned by lb == ub puts its marginal
	// in Lower when it is >= 0 and in Upper otherwise.
	IneqLin, EqLin, Linear, Sparse, Lower, Upper LPDual
	// Y holds OSQP-form multipliers (P·x + q + Aᵀy = 0, so y = −marginal) of
	// the canonical rows (design-qp.md §2.2: AEq rows, AUb rows, the Linear
	// blocks, the ASparse rows, then the finite bounds, rows unbounded on both
	// sides dropped).
	Y []float64
	// ActiveSet lists the canonical rows in the final working set.
	ActiveSet []int
	// PrimalCert and DualCert are the certificates of infeasibility and
	// unboundedness (nil until the solvers that produce them exist).
	PrimalCert, DualCert []float64
	// Optimality is ‖P·x + q − Σ marginal·a‖∞ recomputed from scratch,
	// ConstrViolation the largest violation of a canonical row, DualityGap the
	// gap between the primal and dual objectives (0 for a direct solve).
	Optimality, ConstrViolation, DualityGap float64
	Status                                  int
	// Success reports Status == QPOptimal.
	Success bool
	Message string
	// Method is the method that ran (QPAuto resolved).
	Method     QPMethod
	Nit        int
	RhoUpdates int
	Polished   bool
}

QPResult is the outcome of Quadprog.

func Quadprog added in v0.5.0

func Quadprog(p QPProblem, opts *QPOptions) (*QPResult, error)

Quadprog solves p once: NewQPSolver followed by Solve.

type QPSolver added in v0.5.0

type QPSolver struct {
	// contains filtered or unexported fields
}

QPSolver holds a validated problem and the factors of the last solve. It is not safe for concurrent use. The updates and warm starts are in qp_solver.go.

func NewQPSolver added in v0.5.0

func NewQPSolver(p QPProblem, opts *QPOptions) (*QPSolver, error)

NewQPSolver validates p and builds the canonical rows. It reports every invalid input as an error (ErrDimension, ErrInput, ErrBounds or ErrMethod) before allocating anything proportional to the data it did not receive.

func (*QPSolver) Solve added in v0.5.0

func (s *QPSolver) Solve() (*QPResult, error)

Solve runs the solver chosen at construction.

func (*QPSolver) UpdateBounds added in v0.5.0

func (s *QPSolver) UpdateBounds(l, u []float64) error

UpdateBounds replaces the sides l and u of the canonical rows (design-qp.md §2.2: AEq rows, AUb rows, the Linear blocks, the ASparse rows, then the finite bounds; one entry per canonical row, -Inf and +Inf for a missing side). A row keeps the kind it was created with: a finite side cannot become infinite or the reverse, and an equality (l == u) cannot become an interval or the reverse; otherwise the error is ErrBounds. The active-set factors are kept. ADMM takes any sides and refactors only if a row changes type (OSQP's update_rho_vec).

func (*QPSolver) UpdateMatrixValues added in v0.5.0

func (s *QPSolver) UpdateMatrixValues(p, a []float64) error

UpdateMatrixValues replaces the values of P and of the dense constraint rows without changing their patterns. p holds the n×n values row-major for a dense P (symmetrised as (P+Pᵀ)/2), or the entries of PSparse in their stored order; a holds the dense canonical rows (AEq, AUb, the Linear blocks) row-major, the bound rows excluded, followed by the entries of ASparse in its CSC storage order (ADMM only). nil keeps the old values. The active-set factors are rebuilt on the next Solve, seeded with the previous active set; a P that is no longer positive definite is rejected and nothing changes. The ADMM solver reruns its scaling and refactors numerically on the stored symbolic factor (a new ordering only if the nonzero pattern of a dense P changed), keeps ρ and the iterates as the warm start, and rejects a P that makes the KKT matrix not quasi-definite, leaving the solver as it was.

func (*QPSolver) UpdateQ added in v0.5.0

func (s *QPSolver) UpdateQ(q []float64) error

UpdateQ replaces the linear term; every factor is kept.

func (*QPSolver) WarmStart added in v0.5.0

func (s *QPSolver) WarmStart(x, y []float64) error

WarmStart sets the starting point of the next Solve: x (length n) and y (the canonical rows' multipliers), either may be nil. The active set ignores them (it starts from its working set, design-qp.md §5); they are validated all the same, and kept for the ADMM solver.

type RandomSource added in v0.6.0

type RandomSource struct {
	// contains filtered or unexported fields
}

RandomSource is the random stream of a stochastic solver. Exactly one of a NumPy Generator or a legacy RandomState is behind it, so the solvers can reproduce SciPy's draws for both seeding forms (SciPy's rng=int and seed=int). A RandomSource is not safe for concurrent use; the solvers draw only on the calling goroutine.

func NewLegacyRNG added in v0.6.0

func NewLegacyRNG(seed uint32) *RandomSource

NewLegacyRNG is SciPy's seed=seed: RandomState(seed), MT19937 with the legacy seeding.

func NewRNG added in v0.6.0

func NewRNG(seed uint64) *RandomSource

NewRNG is SciPy's rng=seed: Generator(PCG64(SeedSequence(seed))).

func RNGFromGenerator added in v0.6.0

func RNGFromGenerator(g *random.Generator) *RandomSource

RNGFromGenerator wraps a NumPy-compatible Generator (a nil g is an entropy-seeded PCG64).

func RNGFromRandomState added in v0.6.0

func RNGFromRandomState(r *random.RandomState) *RandomSource

RNGFromRandomState wraps a legacy RandomState (a nil r is an entropy-seeded one).

func (*RandomSource) FillIntN added in v0.6.0

func (s *RandomSource) FillIntN(dst []int64, high int64) error

FillIntN is integers(0, high, size=len(dst)).

func (*RandomSource) FillUniform added in v0.6.0

func (s *RandomSource) FillUniform(dst []float64, low, high float64) error

FillUniform is uniform(low, high, size=len(dst)), in order. It draws nothing and returns an error when high-low is NaN or infinite (and, for a Generator, negative).

func (*RandomSource) Float64 added in v0.6.0

func (s *RandomSource) Float64() float64

Float64 is next_double: one draw in [0, 1).

func (*RandomSource) IntN added in v0.6.0

func (s *RandomSource) IntN(high int64) int64

IntN is integers(0, high) with size=None; it panics when high <= 0.

func (*RandomSource) ShuffleInt64 added in v0.6.0

func (s *RandomSource) ShuffleInt64(d []int64)

ShuffleInt64 is shuffle of a one-dimensional int64 array.

func (*RandomSource) Uniform added in v0.6.0

func (s *RandomSource) Uniform(low, high float64) float64

Uniform is uniform(low, high) with size=None: low + (high-low)·U, the product rounded before the sum.

type Range

type Range struct {
	Lo, Hi, Step float64
}

Range is one axis of a Brute grid. With Step 0 the axis holds Ns points from Lo to Hi inclusive (SciPy's (low, high) tuple, i.e. slice(low, high, Ns*1j)); with Step > 0 it holds Lo, Lo+Step, … below Hi (slice(low, high, step)).

type Result

type Result struct {
	// X is the solution.
	X []float64
	// Fun is the objective value at X.
	Fun float64
	// Jac is the gradient at X, when the method computes one.
	Jac []float64
	// HessInv is the final inverse-Hessian approximation as an n*n row-major
	// matrix (BFGS only, nil otherwise).
	HessInv []float64
	// Multipliers are the Lagrange multipliers of the constraints at X.
	// SLSQP: equalities first and then inequalities, in the order of the
	// standardised constraint blocks (SciPy's result.multipliers).
	// trust-constr: one per component of each constraint of
	// Options.Constraints, in order, with SciPy's sign (its result.v
	// without the bounds).
	Multipliers []float64
	// Optimality is the max-norm of the Lagrangian gradient and
	// ConstrViolation the largest constraint violation at X (trust-constr).
	Optimality, ConstrViolation float64
	// Nit, Nfev, Njev and Nhev count iterations and evaluations of the
	// objective, the gradient and the Hessian. Function evaluations spent on
	// finite-difference gradients are counted in Nfev, and each such gradient
	// also counts once in Njev, as in SciPy.
	Nit, Nfev, Njev, Nhev int
	// Status is a method-specific termination code; 0 means success.
	Status int
	// Success reports whether the method met its convergence criteria.
	Success bool
	// Message describes the reason for termination.
	Message string
}

Result is the outcome of Minimize, the counterpart of SciPy's OptimizeResult for scipy.optimize.minimize.

func BFGSNash added in v0.12.0

func BFGSNash(f func([]float64) float64, grad func(x, g []float64), x0 []float64, o *NashOptions) (*Result, error)

BFGSNash minimises f from x0 by Nash's variable metric method (algorithm 21): an inverse-Hessian BFGS update with a backtracking line search from step 1. grad may be nil, in which case central differences of step NDEps are used (their evaluations are added to Nfev). Nit and Njev count gradient evaluations (MaxIter, default 100, bounds them). Status 0 is convergence, 1 the iteration limit.

func CGNash added in v0.12.0

func CGNash(f func([]float64) float64, grad func(x, g []float64), x0 []float64, o *NashOptions) (*Result, error)

CGNash minimises f from x0 by Nash's conjugate gradients (algorithm 22) with the beta formula o.Type (Fletcher-Reeves by default), restarts every n directions, and a line search that backtracks from the previous step and then interpolates quadratically. grad may be nil as in BFGSNash. MaxIter (default 100) bounds gradient evaluations. Status 0 is convergence, 1 the iteration limit.

func Minimize

func Minimize(p Problem, x0 []float64, method Method, opts *Options) (*Result, error)

Minimize minimises p from x0 with the given method; it is scipy.optimize.minimize(fun, x0, method=..., jac=..., hess=..., bounds=..., tol=..., options=...).

Invalid input returns an error; non-convergence returns a Result with Success false.

Example

scipy.optimize.minimize(rosen, x0, jac=rosen_der, method='BFGS')

package main

import (
	"fmt"
	"math"

	"github.com/go-numerics/optimize"
)

func main() {
	rosen := func(x []float64) float64 {
		return 100*math.Pow(x[1]-x[0]*x[0], 2) + math.Pow(1-x[0], 2)
	}
	grad := func(x, g []float64) {
		g[0] = -400*x[0]*(x[1]-x[0]*x[0]) - 2*(1-x[0])
		g[1] = 200 * (x[1] - x[0]*x[0])
	}
	r, err := optimize.Minimize(optimize.Problem{Func: rosen, Grad: grad}, []float64{-1.2, 1}, optimize.BFGS, nil)
	if err != nil {
		panic(err)
	}
	fmt.Printf("x = [%.6f %.6f], nit = %d, %s\n", r.X[0], r.X[1], r.Nit, r.Message)
}
Output:
x = [1.000000 1.000000], nit = 32, Optimization terminated successfully.
Example (Bounds)

scipy.optimize.minimize(f, x0, method='L-BFGS-B', bounds=[(-2, 0.5), (None, None)])

package main

import (
	"fmt"

	"github.com/go-numerics/optimize"
)

func main() {
	f := func(x []float64) float64 { return (x[0]-1)*(x[0]-1) + (x[1]+2)*(x[1]+2) }
	opts := &optimize.Options{Bounds: []optimize.Bound{{Lo: -2, Hi: 0.5}, optimize.Unbounded()}}
	r, _ := optimize.Minimize(optimize.Problem{Func: f}, []float64{0, 0}, optimize.LBFGSB, opts)
	fmt.Printf("x = [%.4f %.4f]\n", r.X[0], r.X[1])
}
Output:
x = [0.5000 -2.0000]
Example (Slsqp)

Hock–Schittkowski problem 71: scipy.optimize.minimize(f, [1, 5, 5, 1], method='SLSQP', bounds=[(1, 5)]*4,

constraints=[{'type': 'ineq', 'fun': g}, {'type': 'eq', 'fun': h}])
package main

import (
	"fmt"

	"github.com/go-numerics/optimize"
)

func main() {
	f := func(x []float64) float64 { return x[0]*x[3]*(x[0]+x[1]+x[2]) + x[2] }
	g := func(x, c []float64) { c[0] = x[0]*x[1]*x[2]*x[3] - 25 }
	h := func(x, c []float64) { c[0] = x[0]*x[0] + x[1]*x[1] + x[2]*x[2] + x[3]*x[3] - 40 }
	bound := optimize.Bound{Lo: 1, Hi: 5}
	r, err := optimize.Minimize(optimize.Problem{Func: f}, []float64{1, 5, 5, 1}, optimize.SLSQP,
		&optimize.Options{
			Bounds: []optimize.Bound{bound, bound, bound, bound},
			Constraints: []optimize.ConstraintSpec{
				optimize.Constraint{Kind: optimize.Ineq, M: 1, Func: g},
				optimize.Constraint{Kind: optimize.Eq, M: 1, Func: h},
			}})
	if err != nil {
		panic(err)
	}
	fmt.Printf("f = %.7f, x = [%.4f %.4f %.4f %.4f], nit = %d, %s\n",
		r.Fun, r.X[0], r.X[1], r.X[2], r.X[3], r.Nit, r.Message)
}
Output:
f = 17.0140172, x = [1.0000 4.7430 3.8212 1.3794], nit = 5, Optimization terminated successfully
Example (TrustConstr)

Hock–Schittkowski problem 71 by the interior-point method: scipy.optimize.minimize(f, [1, 5, 5, 1], method='trust-constr', bounds=..., constraints=...)

package main

import (
	"fmt"

	"github.com/go-numerics/optimize"
)

func main() {
	f := func(x []float64) float64 { return x[0]*x[3]*(x[0]+x[1]+x[2]) + x[2] }
	g := func(x, c []float64) { c[0] = x[0]*x[1]*x[2]*x[3] - 25 }
	h := func(x, c []float64) { c[0] = x[0]*x[0] + x[1]*x[1] + x[2]*x[2] + x[3]*x[3] - 40 }
	bound := optimize.Bound{Lo: 1, Hi: 5}
	r, err := optimize.Minimize(optimize.Problem{Func: f}, []float64{1, 5, 5, 1}, optimize.TrustConstr,
		&optimize.Options{
			Bounds: []optimize.Bound{bound, bound, bound, bound},
			Constraints: []optimize.ConstraintSpec{
				optimize.Constraint{Kind: optimize.Ineq, M: 1, Func: g},
				optimize.Constraint{Kind: optimize.Eq, M: 1, Func: h},
			}})
	if err != nil {
		panic(err)
	}
	fmt.Printf("f = %.5f, x = [%.3f %.3f %.3f %.3f], success = %v\n",
		r.Fun, r.X[0], r.X[1], r.X[2], r.X[3], r.Success)
}
Output:
f = 17.01402, x = [1.000 4.743 3.821 1.379], success = true

func NLMinB added in v0.15.0

func NLMinB(f func([]float64) float64, grad func(x, g []float64), x0, lower, upper []float64, o *NLMinBOptions) (*Result, error)

NLMinB minimises f(x) subject to lower <= x <= upper, the counterpart of R's nlminb. lower and upper may be nil (free) or hold one value per variable, with +-Inf for a missing side. grad may be nil: a forward finite difference (turned backward at an upper bound) then supplies it. A start outside the box is moved onto it. The algorithm is a limited-memory quasi-Newton method with projected search (L-BFGS-B), not PORT: it finds the same optimum within the bound of docs/nlminb.md, with another path.

Failure to converge is not an error: Result.Status holds the code, Message the text and Success tells whether the run converged (4 or 11).

func NelderMeadNash added in v0.12.0

func NelderMeadNash(f func([]float64) float64, x0 []float64, o *NashOptions) (*Result, error)

NelderMeadNash minimises f from x0 by Nash's Nelder-Mead (algorithm 19). The objective must be finite at x0 (ErrInput otherwise); a non-finite value elsewhere is treated as a very large one. Status 0 is convergence (the simplex values agree to RelTol or f <= AbsTol), 1 the evaluation limit, 10 a degenerate simplex. Nfev counts evaluations.

func SANN added in v0.13.0

func SANN(f func([]float64) float64, x0 []float64, o *SANNOptions) (*Result, error)

SANN minimises f from x0 by simulated annealing with Metropolis acceptance (Belisle 1992): a candidate is always accepted when it does not increase f, and otherwise with probability exp(-(f(cand)-f(x))/T) for the temperature T of SANNTemperature. It returns the best point visited, which need not be the last one. A non-finite f at a candidate rejects it; f must be finite at x0 (ErrInput otherwise). Nfev is MaxIter; Status is always 0, as there is no convergence criterion.

Draws per iteration, in order: the candidate (n normals for the default kernel), then one uniform only when the candidate is worse.

func Uncmin added in v0.14.0

func Uncmin(f func([]float64) float64, grad func(x, g []float64), x0 []float64, o *UncminOptions) (*Result, error)

Uncmin minimises f from x0. grad, when non-nil, fills g with the gradient of f at x; otherwise forward differences are used, switched to central differences once when a global step fails. Result.Status is the nlm-style code (UncminGradient ... UncminStepMax), Success is true for codes 1 and 2, Nit counts iterations, Nfev includes the evaluations spent on finite differences and Nhev the gradient evaluations of the finite-difference Hessian. Result.Jac is the gradient at X.

func (*Result) HessInvArray

func (r *Result) HessInvArray() *ndarray.Array

HessInvArray returns HessInv as an n×n ndarray, or nil when absent.

func (*Result) XArray

func (r *Result) XArray() *ndarray.Array

XArray returns X as a 1-D ndarray.

type RootOptions

type RootOptions struct {
	// Xtol stops the iteration when the relative error between two
	// consecutive iterates is at most Xtol (1.49012e-8; a negative value
	// means exactly 0).
	Xtol float64
	// Maxfev bounds the calls to Func: 0 selects 200·(n+1) without a
	// Jacobian (forward-difference calls included) and 100·(n+1) with one.
	Maxfev int
	// Eps sets the forward-difference step sqrt(Eps)·|x_j| when there is no
	// Jacobian (SciPy's eps for root, epsfcn for fsolve); 0 selects the
	// machine epsilon.
	Eps float64
	// Factor sets the initial step bound Factor·|Diag·x0| (100).
	Factor float64
	// Diag holds n positive scale factors for the variables; nil lets
	// MINPACK scale by the Jacobian column norms.
	Diag []float64
	// SciPyExact follows MINPACK's summation order bit for bit; the default
	// runs systems of 32 or more equations on FMA and go-simd kernels (the
	// same root within the accuracy contract, not bit-identical).
	SciPyExact bool
}

RootOptions configures Root and Fsolve. Zero values select SciPy's defaults.

type RootResult

type RootResult struct {
	// X is the solution (or the last iterate).
	X []float64
	// Fun holds F(X).
	Fun []float64
	// Fjac is SciPy's fjac: the orthogonal factor Q of the QR factorisation
	// of the final approximate Jacobian, stored column-wise, so that as an
	// n×n row-major array it reads Qᵀ (row i is column i of Q).
	Fjac []float64
	// R is the upper-triangular factor packed by rows (n(n+1)/2 entries).
	R []float64
	// Qtf is Qᵀ·Fun.
	Qtf []float64
	// Nfev counts calls to Func, including those of finite differences;
	// Njev counts calls to Jac (0 without one). SciPy's root and fsolve
	// report two more calls: those their wrappers make outside MINPACK (a
	// shape check and the initial evaluation), which do not happen here.
	Nfev, Njev int
	// Status is MINPACK's info: 1 converged, 2 Maxfev reached, 3 Xtol too
	// small, 4 and 5 no progress.
	Status int
	// Success is Status == 1.
	Success bool
	// Message is SciPy's message for Status.
	Message string
}

RootResult is the outcome of Root and Fsolve, mirroring the OptimizeResult of scipy.optimize.root(method='hybr').

func Fsolve

func Fsolve(p SystemProblem, x0 []float64, opts *RootOptions) (*RootResult, error)

Fsolve is scipy.optimize.fsolve(func, x0, fprime=p.Jac, full_output=True, xtol, maxfev, epsfcn=opts.Eps, factor, diag): the same computation as Root, returning the same result (SciPy's infodict holds Fun as fvec, Nfev, Njev, Fjac, R and Qtf; ier is Status and mesg Message).

func Root

func Root(p SystemProblem, x0 []float64, opts *RootOptions) (*RootResult, error)

Root solves the square system p.Func(x) = 0 from x0 with Powell's hybrid method of MINPACK; it is scipy.optimize.root(fun, x0, jac=p.Jac, method='hybr', options={'xtol', 'maxfev', 'eps', 'factor', 'diag'}) (the 'band' and 'col_deriv' options are not supported). Without p.Jac it runs hybrd, otherwise hybrj. Non-convergence is reported through Status and Message.

Example

scipy.optimize.root(fun, [0, 0], method='hybr')

package main

import (
	"fmt"
	"math"

	"github.com/go-numerics/optimize"
)

func main() {
	fun := func(x, f []float64) {
		f[0] = x[0] + 0.5*math.Pow(x[0]-x[1], 3) - 1
		f[1] = 0.5*math.Pow(x[1]-x[0], 3) + x[1]
	}
	r, _ := optimize.Root(optimize.SystemProblem{Func: fun}, []float64{0, 0}, nil)
	fmt.Printf("x = [%.6f %.6f] %v\n", r.X[0], r.X[1], r.Success)
}
Output:
x = [0.841164 0.158836] true

func (*RootResult) FjacArray

func (r *RootResult) FjacArray() *ndarray.Array

FjacArray returns Fjac as an n×n ndarray.

func (*RootResult) XArray

func (r *RootResult) XArray() *ndarray.Array

XArray returns X as a 1-D ndarray.

type RootScalarOptions

type RootScalarOptions struct {
	// Bracket [a, b] for the bracketing methods.
	Bracket []float64
	// Fprime and Fprime2 are the first and second derivatives.
	Fprime, Fprime2 func(float64) float64
	// X0 and X1 are starting points for Newton, Halley and the secant
	// method; X0Set/X1Set mark them as given (0 is a valid start).
	X0, X1       float64
	X0Set, X1Set bool
	// Xtol, Rtol and MaxIter override the method's defaults.
	Xtol, Rtol float64
	MaxIter    int
}

RootScalarOptions configures RootScalar.

type RootScalarResult

type RootScalarResult struct {
	// Root is the estimated root.
	Root float64
	// Iterations and FunctionCalls count the work done (derivative
	// evaluations count as function calls for Newton and Halley).
	Iterations, FunctionCalls int
	// Converged reports whether the tolerance was met.
	Converged bool
	// Flag is "converged", "convergence error" or a message describing the
	// failure.
	Flag string
	// Method is the algorithm used.
	Method string
}

RootScalarResult describes a scalar root search, like SciPy's RootResults.

func Bisect

func Bisect(f func(float64) float64, a, b float64, o *BracketOptions) (*RootScalarResult, error)

Bisect finds a root of f in [a, b] by bisection; it is scipy.optimize.bisect.

func Brenth

func Brenth(f func(float64) float64, a, b float64, o *BracketOptions) (*RootScalarResult, error)

Brenth is Brentq with hyperbolic instead of inverse quadratic extrapolation (Bus & Dekker 1975); it is scipy.optimize.brenth.

func Brentq

func Brentq(f func(float64) float64, a, b float64, o *BracketOptions) (*RootScalarResult, error)

Brentq finds a root of f in [a, b], where f(a) and f(b) have opposite signs, with Brent's (1973) method using inverse quadratic extrapolation; it is scipy.optimize.brentq(f, a, b, xtol, rtol, maxiter, full_output=True). The returned root x satisfies |x − x₀| <= 4·(Xtol + Rtol·|x₀|) for the exact root x₀.

A bracket without a sign change returns ErrBracket; a NaN function value returns an error together with the result describing where it happened; running out of iterations is reported by Converged false.

Example

scipy.optimize.brentq(lambda x: x**3 - 2*x - 5, 2, 3)

package main

import (
	"fmt"

	"github.com/go-numerics/optimize"
)

func main() {
	r, _ := optimize.Brentq(func(x float64) float64 { return x*x*x - 2*x - 5 }, 2, 3, nil)
	fmt.Printf("%.12f after %d iterations\n", r.Root, r.Iterations)
}
Output:
2.094551481542 after 7 iterations

func BrentqExtend added in v0.10.0

func BrentqExtend(f func(float64) float64, a, b float64, ext ExtendInt, o *BracketOptions) (*RootScalarResult, error)

BrentqExtend is Brentq with an extendInt option. When f(a) and f(b) have the same sign the interval is widened, doubling the step each time, until a sign change is found (never beyond ±MaxFloat64: the search then fails with ErrBracket), and Brentq runs on the widened bracket. With ExtendUpX (ExtendDownX) f is assumed increasing (decreasing), so only the lower end moves when f(a) has the wrong sign for a root to its right, and only the upper end moves otherwise; contradictory end values are ErrBracket. The returned FunctionCalls include the extension evaluations.

The expansion schedule (start step b−a, doubled each time) is this package's own; R's exact steps are not reproduced, so only the root, not the iterates, is comparable with uniroot(extendInt=...).

func Newton

func Newton(f func(float64) float64, x0 float64, o *NewtonOptions) (*RootScalarResult, error)

Newton finds a root of f near x0 with the Newton–Raphson method (given Fprime), Halley's method (given Fprime and Fprime2) or the secant method (neither); it is scipy.optimize.newton(func, x0, fprime, tol=1.48e-8, maxiter=50, fprime2, x1, rtol=0, full_output=True, disp=False).

Failure to converge (including a zero derivative) is reported by Converged false and Flag "convergence error", not as an error.

func Ridder

func Ridder(f func(float64) float64, a, b float64, o *BracketOptions) (*RootScalarResult, error)

Ridder finds a root of f in [a, b] with Ridders' (1979) method; it is scipy.optimize.ridder.

func RootScalar

func RootScalar(f func(float64) float64, method string, o *RootScalarOptions) (*RootScalarResult, error)

RootScalar finds a root of a scalar function; it is scipy.optimize.root_scalar(f, method, bracket, fprime, fprime2, x0, x1, xtol, rtol, maxiter). method is one of "brentq", "brenth", "ridder", "bisect", "newton", "halley", "secant", or "" to choose as SciPy does: a bracket selects brentq; otherwise x0 with Fprime selects newton (halley with Fprime2), x0 with x1 the secant method, and x0 alone Newton with a finite-difference derivative.

type SANNOptions added in v0.13.0

type SANNOptions struct {
	// MaxIter is the number of objective evaluations, the initial one
	// included (default 10000). SANN has no convergence test.
	MaxIter int
	// TMax is the number of evaluations at each temperature (default 10).
	TMax int
	// Temp is the starting temperature (default 10).
	Temp float64
	// Scale multiplies the standard deviation of the default Gaussian kernel,
	// which is the current temperature (default 1).
	Scale float64
	// Rand is the random stream; nil selects a PCG stream seeded by Seed.
	Rand SANNRand
	// Seed seeds the default stream (ignored when Rand is set).
	Seed uint64
	// Candidate generates the next candidate point cand from the current
	// point x at temperature temp, drawing from r. nil selects the Gaussian
	// Markov kernel cand[i] = x[i] + Scale*temp*N(0,1), drawn in index order.
	Candidate func(x, cand []float64, temp float64, r SANNRand)
}

SANNOptions are the controls of SANN. The zero value selects the defaults noted on each field.

type SANNRand added in v0.13.0

type SANNRand interface {
	Float64() float64
	NormFloat64() float64
}

SANNRand is the random stream of SANN: uniform draws on [0, 1) for the acceptance test and standard normal draws for the default candidate kernel. A caller that must reproduce another system's stream plugs its own.

type ScalarMethod

type ScalarMethod string

ScalarMethod names a scalar minimisation algorithm; the values are the method strings of scipy.optimize.minimize_scalar.

const (
	// Brent is Brent's method: parabolic interpolation safeguarded by
	// golden-section steps, from a bracket.
	Brent ScalarMethod = "brent"
	// Bounded is Brent's method restricted to a finite interval (the
	// algorithm of fminbound).
	Bounded ScalarMethod = "bounded"
	// Golden is the golden-section search, from a bracket.
	Golden ScalarMethod = "golden"
)

Scalar minimisation methods.

type ScalarOptions

type ScalarOptions struct {
	// Bracket is a bracketing interval for Brent and Golden: two points
	// (xa, xb) from which Bracket searches downhill, or three points
	// (xa, xb, xc) with xa < xb < xc and f(xb) < f(xa), f(xc). nil starts
	// the downhill search from (0, 1).
	Bracket []float64
	// Bounds is the interval for the Bounded method; setting it selects
	// Bounded when the method is "".
	Bounds *Bound
	// Tol is minimize_scalar's tol: it sets Xtol (Brent, Golden) or Xatol
	// (Bounded) when those are zero.
	Tol float64
	// Xtol is the relative tolerance of Brent (1.48e-8) and Golden
	// (√eps ≈ 1.49e-8).
	Xtol float64
	// Xatol is the absolute tolerance of Bounded (1e-5).
	Xatol float64
	// MaxIter bounds iterations (Brent 500, Golden 5000) or function
	// evaluations (Bounded 500).
	MaxIter int
}

ScalarOptions configures MinimizeScalar. Zero values select SciPy's defaults.

type ScalarResult

type ScalarResult struct {
	X, Fun    float64
	Nit, Nfev int
	Status    int // Bounded only: 0 solution found, 1 maxfun, 2 NaN
	Success   bool
	Message   string
}

ScalarResult is the outcome of MinimizeScalar, the OptimizeResult of scipy.optimize.minimize_scalar.

func Fminbound

func Fminbound(f func(float64) float64, x1, x2, xtol float64, maxfun int) (*ScalarResult, error)

Fminbound minimises f on [x1, x2] with absolute tolerance xtol (1e-5 when 0) and at most maxfun evaluations (500 when 0); it is scipy.optimize.fminbound(func, x1, x2, xtol, maxfun, full_output=True).

func MinimizeScalar

func MinimizeScalar(f func(float64) float64, method ScalarMethod, o *ScalarOptions) (*ScalarResult, error)

MinimizeScalar minimises a function of one variable; it is scipy.optimize.minimize_scalar(fun, bracket=..., bounds=..., method=..., tol=..., options={'xtol'/'xatol', 'maxiter'}). method "" selects Brent, or Bounded when o.Bounds is set.

A failed bracket search is not an error: as in SciPy, the result then holds the best of the three points and Success is false.

type StepSizer added in v0.6.0

type StepSizer interface {
	StepTaker
	StepSize() float64
	SetStepSize(float64)
}

StepSizer is a StepTaker with an adjustable step size.

type StepTaker added in v0.6.0

type StepTaker interface{ TakeStep(x []float64) }

StepTaker displaces x in place. If it also implements StepSizer it is wrapped by the adaptive step-size controller, as SciPy does for any take_step that has a stepsize attribute.

type SystemProblem

type SystemProblem struct {
	// Func writes the n values of F at x into f. Required. It must not
	// modify x.
	Func func(x, f []float64)
	// Jac writes the n×n Jacobian of F at x into jac, row-major
	// (jac[i*n+j] = ∂F_i/∂x_j). Optional: MINPACK's forward differences are
	// used when it is nil.
	Jac func(x, jac []float64)
}

SystemProblem is a square system of nonlinear equations F(x) = 0 with n equations in n unknowns.

type UncminHessian added in v0.14.0

type UncminHessian int

UncminHessian selects how Uncmin forms its model Hessian.

const (
	// UncminSecant keeps a BFGS approximation, started at
	// max(|f|, FScale)*I in scaled variables.
	UncminSecant UncminHessian = iota
	// UncminFiniteDiff rebuilds the Hessian at every iterate by forward
	// differences of the gradient.
	UncminFiniteDiff
)

type UncminMethod added in v0.14.0

type UncminMethod int

UncminMethod selects the globalisation strategy of Uncmin.

const (
	// UncminLineSearch backtracks along the Newton step (quadratic then
	// cubic interpolation). R's nlm uses this one.
	UncminLineSearch UncminMethod = iota
	// UncminDogleg takes the dogleg step of a trust region.
	UncminDogleg
)

type UncminOptions added in v0.14.0

type UncminOptions struct {
	// Method is the global strategy (default UncminLineSearch).
	Method UncminMethod
	// Hessian is the model Hessian (default UncminSecant).
	Hessian UncminHessian
	// TypSize is the typical size of each parameter at the optimum
	// (default 1 each); the variables are x/TypSize inside the method.
	TypSize []float64
	// FScale is the typical size of f at the optimum (default 1).
	FScale float64
	// NDigit is the number of reliable digits of f, which sets the
	// finite-difference steps (default 12).
	NDigit int
	// GradTol stops on a small relative gradient (default 1e-6).
	GradTol float64
	// StepMax is the largest scaled step (default
	// max(1000*||x0/TypSize||, 1000)).
	StepMax float64
	// StepTol stops on a small relative step (default 1e-6).
	StepTol float64
	// IterLim is the iteration limit (default 100).
	IterLim int
}

UncminOptions are the controls of Uncmin, named after nlm's arguments. The zero value selects the defaults noted on each field.

Directories

Path Synopsis
internal
gofuncs
Package gofuncs holds Go twins of functions from the Jamil & Yang (2013) benchmark collection as SciPy ships it (benchmarks/benchmarks/ go_benchmark_functions at v1.18.1, BSD-3): their bounds, their known global minimum fglob, and SciPy's success rule.
Package gofuncs holds Go twins of functions from the Jamil & Yang (2013) benchmark collection as SciPy ships it (benchmarks/benchmarks/ go_benchmark_functions at v1.18.1, BSD-3): their bounds, their known global minimum fglob, and SciPy's success rule.
tools
globalbench module
globaloracle module
nofma module
qpbench module
qporacle module
slsqpbench module
slsqporacle module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址