Optimizers¶
Check out How to select a local optimizer to see how to select an algorithm and specify
algo_options when using maximize or minimize. The default algorithm options are
discussed in The default algorithm options and their type hints are documented in Types.
Optimizers from SciPy¶
optimagic supports most SciPy algorithms and SciPy is automatically installed when you install optimagic.
scipy_lbfgsb
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.scipy_lbfgsb(stopping_maxiter=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_lbfgsb",
algo_options={"stopping_maxiter": 1_000},
)
Description and available options:
- class optimagic.optimizers.scipy_optimizers.ScipyLBFGSB[source]¶
Minimize a scalar differentiable function using the L-BFGS-B algorithm.
The optimizer is taken from scipy, which uses the code written by the original authors of the algorithm (L-BFGS-B v3.0). This code includes the corrections and improvements that were introduced in a follow up paper. Since SciPy 1.15, SciPy uses a C translation of the original Fortran code; older versions call the Fortran code directly.
lbfgsb is a limited memory version of the original bfgs algorithm, that deals with lower and upper bounds via an active set approach.
The lbfgsb algorithm is well suited for differentiable scalar optimization problems with up to several hundred parameters.
It is a quasi-newton line search algorithm. At each trial point it evaluates the criterion function and its gradient to find a search direction. It then approximates the hessian using the stored history of gradients and uses the hessian to calculate a candidate step size. Then it uses a gradient based line search algorithm to determine the actual step length. Since the algorithm always evaluates the gradient and criterion function jointly, the user should provide a
fun_and_jacfunction that exploits the synergies in the calculation of criterion and gradient.The lbfgsb algorithm is almost perfectly scale invariant. Thus, it is not necessary to scale the parameters.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Converge if the relative change in the objective function is less than this value.
More formally, this is expressed as
\[\frac{f^k - f^{k+1}}{\max\{{|f^k|, |f^{k+1}|, 1}\}} \leq \textsf{convergence\_ftol\_rel}.\]
- convergence_gtol_abs: NonNegativeFloat = 1e-05¶
Converge if the largest absolute value of the projected gradient of the objective function is less than this value.
- stopping_maxfun: PositiveInt = 1000000¶
Maximum number of function evaluations.
- stopping_maxiter: PositiveInt = 1000000¶
Maximum number of iterations.
- limited_memory_storage_length: PositiveInt = 10¶
The maximum number of variable metric corrections used to define the limited memory matrix. This is the ‘maxcor’ parameter in the SciPy documentation.
The default value is taken from SciPy’s L-BFGS-B implementation. Larger values use more memory but may converge faster for some problems.
- max_line_search_steps: PositiveInt = 20¶
The maximum number of line search steps. This is the ‘maxls’ parameter in the SciPy documentation.
The default value is taken from SciPy’s L-BFGS-B implementation.
scipy_slsqp
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.scipy_slsqp(stopping_maxiter=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_slsqp",
algo_options={"stopping_maxiter": 1_000},
)
Description and available options:
- class optimagic.optimizers.scipy_optimizers.ScipySLSQP[source]¶
Minimize a scalar function of one or more variables using the SLSQP algorithm.
SLSQP stands for Sequential Least Squares Programming. It is a sequential quadratic programming (SQP) line search algorithm that solves a quadratic approximation of the problem in each iteration. It uses first derivatives of the objective function and the constraints.
SLSQP is well suited for continuously differentiable scalar optimization problems with up to several hundred parameters. It supports bounds as well as nonlinear equality and inequality constraints.
The optimizer is taken from SciPy, which wraps the SLSQP optimization subroutine originally implemented by [algo_1].
- convergence_ftol_abs: NonNegativeFloat = 1e-08¶
Absolute precision goal for the value of the objective function in the stopping criterion.
optimagic’s default is 1e-8, which is stricter than SciPy’s default of 1e-6.
- stopping_maxiter: PositiveInt = 1000000¶
If the maximum number of iterations is reached, the optimization stops, but we do not count this as convergence.
scipy_neldermead
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.scipy_neldermead(stopping_maxiter=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_neldermead",
algo_options={"stopping_maxiter": 1_000},
)
Description and available options:
- class optimagic.optimizers.scipy_optimizers.ScipyNelderMead[source]¶
Minimize a scalar function using the Nelder-Mead simplex algorithm.
The Nelder-Mead algorithm ([algo_2]) is a direct search method (based on function comparison) and is often applied to nonlinear optimization problems for which derivatives are not known. It maintains a simplex of
n + 1points (wherenis the number of parameters) that is updated via reflection, expansion, contraction and shrinkage operations. Bounds are supported.Unlike most modern optimization methods, the Nelder-Mead heuristic can converge to a non-stationary point, unless the problem satisfies stronger conditions than are necessary for modern methods.
Nelder-Mead is never the best algorithm to solve a problem but rarely the worst. Its popularity is likely due to historic reasons and much larger than its properties warrant.
Note
The SciPy argument
initial_simplexis not supported by optimagic because it is not compatible with optimagic’s handling of constraints.- stopping_maxiter: PositiveInt = 1000000¶
If the maximum number of iterations is reached, the optimization stops, but we do not count this as convergence.
- stopping_maxfun: PositiveInt = 1000000¶
If the maximum number of function evaluations is reached, the optimization stops, but we do not count this as convergence.
- convergence_ftol_abs: NonNegativeFloat = 1e-08¶
Absolute difference in the criterion value between iterations that is tolerated to declare convergence.
As no relative tolerances can be passed to Nelder-Mead, optimagic sets a non-zero default of 1e-8, which is stricter than SciPy’s default of 1e-4.
- convergence_xtol_abs: NonNegativeFloat = 1e-08¶
Absolute difference in parameters between iterations that is tolerated to declare convergence.
As no relative tolerances can be passed to Nelder-Mead, optimagic sets a non-zero default of 1e-8, which is stricter than SciPy’s default of 1e-4.
scipy_powell
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.scipy_powell(stopping_maxiter=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_powell",
algo_options={"stopping_maxiter": 1_000},
)
Description and available options:
- class optimagic.optimizers.scipy_optimizers.ScipyPowell[source]¶
Minimize a scalar function using the modified Powell method.
Powell’s method ([algo_4]) is a conjugate direction method that minimizes the function by a sequence of one-dimensional searches: In each iteration it performs a bidirectional line search along each vector of a direction set and updates the direction set such that the search directions become approximately conjugate.
The algorithm is derivative-free: In contrast to gradient-based algorithms like
scipy_bfgsorscipy_conjugate_gradient, the criterion function need not be differentiable and no derivatives are evaluated. Bounds are supported.Warning
In our benchmark using a quadratic objective function, the Powell algorithm did not find the optimum very precisely (less than 4 decimal places). If you require high precision, you should refine an optimum found with Powell with another local optimizer.
Note
The SciPy argument
direc, which is the initial set of direction vectors, is not supported by optimagic because it is incompatible with how optimagic handles constraints.- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Tolerance of the one-dimensional line searches. This is the ‘xtol’ parameter in the SciPy documentation.
SciPy only uses this value to control the precision of the line searches along the search directions; it is not a separate stopping criterion. Powell’s method stops based on
convergence_ftol_rel,stopping_maxfunandstopping_maxiter.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Stop when the relative improvement between two iterations is smaller than this.
More formally, the optimization stops if
\[2 (f^k - f^{k+1}) \leq \textsf{convergence\_ftol\_rel} \cdot (|f^k| + |f^{k+1}|) + 10^{-20},\]where \(f^k\) and \(f^{k+1}\) are the criterion values before and after one iteration, i.e., one line search along each vector of the direction set.
- stopping_maxfun: PositiveInt = 1000000¶
If the maximum number of function evaluations is reached, the optimization stops, but we do not count this as convergence.
- stopping_maxiter: PositiveInt = 1000000¶
If the maximum number of iterations is reached, the optimization stops, but we do not count this as convergence.
scipy_bfgs
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.scipy_bfgs(stopping_maxiter=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_bfgs",
algo_options={"stopping_maxiter": 1_000},
)
Description and available options:
- class optimagic.optimizers.scipy_optimizers.ScipyBFGS[source]¶
Minimize a scalar differentiable function using the BFGS algorithm.
BFGS stands for Broyden-Fletcher-Goldfarb-Shanno algorithm (see [algo_5]). It is a quasi-Newton line search algorithm for unconstrained nonlinear optimization problems. At each iteration it computes a search direction from the gradient and an approximation of the inverse Hessian that is built up from the history of gradient evaluations, and then performs a line search that satisfies the strong Wolfe conditions.
BFGS is not guaranteed to converge unless the function has a quadratic Taylor expansion near an optimum. However, BFGS can have acceptable performance even for non-smooth optimization instances.
Bounds and other constraints are not supported. For problems with bound constraints or with a very large number of parameters, consider the limited-memory variant
scipy_lbfgsbinstead.- convergence_gtol_abs: NonNegativeFloat = 1e-05¶
Stop if the norm of the gradient (as defined by the
normoption) is smaller than this value.With the default infinity norm, this means that the optimization stops when all elements of the gradient are smaller than this value. The default value is taken from SciPy.
- stopping_maxiter: PositiveInt = 1000000¶
If the maximum number of iterations is reached, the optimization stops, but we do not count this as convergence.
- norm: NonNegativeFloat = inf¶
Order of the vector norm that is used to calculate the gradient’s “score” that is compared to the gradient tolerance to determine convergence.
The default is infinity, which means that the largest entry of the gradient vector is compared to the gradient tolerance.
- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Relative tolerance in the parameters. Terminate successfully if the step size is less than
xk * convergence_xtol_relwherexkis the current parameter vector. This is the ‘xrtol’ parameter in the SciPy documentation.optimagic’s default is 1e-5, while SciPy’s default is 0.
- display: bool = False¶
Set to True to print convergence messages.
This is the ‘disp’ parameter in the SciPy documentation.
- armijo_condition: NonNegativeFloat = 0.0001¶
Parameter for the Armijo condition rule of the line search. This is the ‘c1’ parameter in the SciPy documentation. It ensures
\[f(x_k + \alpha p_k) \leq f(x_k) + \textsf{armijo\_condition} \cdot \alpha \nabla f(x_k)^\top p_k,\]so each step yields at least a fraction
armijo_conditionof the predicted decrease. Smaller values allow more aggressive steps, larger values enforce more conservative ones. The default value is taken from SciPy.
- curvature_condition: NonNegativeFloat = 0.9¶
Parameter for the curvature condition rule of the line search. This is the ‘c2’ parameter in the SciPy documentation. Together with the Armijo condition, it forms the strong Wolfe conditions. It ensures
\[|\nabla f(x_k + \alpha p_k)^\top p_k| \leq \textsf{curvature\_condition} \cdot |\nabla f(x_k)^\top p_k|,\]so the slope at the new point is sufficiently reduced in absolute value. Smaller values require a more exact line search, larger values accept steps sooner. SciPy requires
0 < armijo_condition < curvature_condition < 1. The default value is taken from SciPy.
scipy_conjugate_gradient
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.scipy_conjugate_gradient(stopping_maxiter=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_conjugate_gradient",
algo_options={"stopping_maxiter": 1_000},
)
Description and available options:
- class optimagic.optimizers.scipy_optimizers.ScipyConjugateGradient[source]¶
Minimize a scalar function using a nonlinear conjugate gradient algorithm.
The conjugate gradient method finds local optima of a differentiable function using only first derivatives; no Hessian information is required, which keeps the memory requirements low. SciPy’s implementation is based on the Polak-Ribiere variant of the algorithm, described in [algo_5], pp. 120-122. Bounds and other constraints are not supported.
Conjugate gradient methods tend to work better when:
the criterion has a unique global minimizing point, and no local minima or other stationary points,
the criterion is, at least locally, reasonably well approximated by a quadratic function,
the criterion is continuous and has a continuous gradient,
the gradient is not too large, e.g., has a norm less than 1000,
the initial guess is reasonably close to the criterion’s global minimizer.
- convergence_gtol_abs: NonNegativeFloat = 1e-05¶
Stop if the norm of the gradient (as defined by the
normoption) is smaller than this value.With the default infinity norm, this means that the optimization stops when all elements of the gradient are smaller than this value. The default value is taken from SciPy.
- stopping_maxiter: PositiveInt = 1000000¶
If the maximum number of iterations is reached, the optimization stops, but we do not count this as convergence.
- norm: NonNegativeFloat = inf¶
Order of the vector norm that is used to calculate the gradient’s “score” that is compared to the gradient tolerance to determine convergence.
The default is infinity, which means that the largest entry of the gradient vector is compared to the gradient tolerance.
scipy_newton_cg
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.scipy_newton_cg(stopping_maxiter=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_newton_cg",
algo_options={"stopping_maxiter": 1_000},
)
Description and available options:
- class optimagic.optimizers.scipy_optimizers.ScipyNewtonCG[source]¶
Minimize a scalar function using Newton’s conjugate gradient algorithm.
Newton’s conjugate gradient algorithm computes the search direction in each iteration by approximately solving the Newton equations with a conjugate gradient method that only requires an approximation of the Hessian. It is practical for both small and large problems (see [algo_5], p. 140).
Warning
In our benchmark using a quadratic objective function, the newton_cg algorithm did not find the optimum very precisely (less than 4 decimal places). If you require high precision, you should refine an optimum found with newton_cg with another local optimizer.
Newton-CG methods are also called truncated Newton methods.
scipy_newton_cgdiffers fromscipy_truncated_newtonbecausescipy_newton_cg’s algorithm is written purely in Python using NumPy and SciPy, whilescipy_truncated_newton’s algorithm calls a C function,scipy_newton_cg’s algorithm is only for unconstrained minimization, whilescipy_truncated_newton’s algorithm supports bounds.
Conjugate gradient methods tend to work better when:
the criterion has a unique global minimizing point, and no local minima or other stationary points,
the criterion is, at least locally, reasonably well approximated by a quadratic function,
the criterion is continuous and has a continuous gradient,
the gradient is not too large, e.g., has a norm less than 1000,
the initial guess is reasonably close to the criterion’s global minimizer.
- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Stop when the average absolute change of the parameters between two iterations is at most this value. This is the ‘xtol’ parameter in the SciPy documentation.
More precisely, Newton-CG stops when the L1 norm of the step is at most
n * convergence_xtol_rel, wherenis the number of parameters. Despite its name, this is an absolute and not a relative criterion.
- stopping_maxiter: PositiveInt = 1000000¶
If the maximum number of iterations is reached, the optimization stops, but we do not count this as convergence.
scipy_cobyla
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.scipy_cobyla(stopping_maxiter=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_cobyla",
algo_options={"stopping_maxiter": 1_000},
)
Description and available options:
- class optimagic.optimizers.scipy_optimizers.ScipyCOBYLA[source]¶
Minimize a scalar function of one or more variables using the COBYLA algorithm.
COBYLA stands for Constrained Optimization By Linear Approximation. It is a derivative-free trust-region method that models the objective and constraint functions by linear interpolation at the vertices of a simplex. For more information on COBYLA see [algo_6], [algo_7] and [algo_8].
COBYLA supports nonlinear constraints. Natively, it can only handle inequality constraints; optimagic converts each equality constraint into two inequality constraints before passing the problem to SciPy. Bounds are not supported by this optimizer in optimagic.
Since SciPy 1.16, SciPy uses the pure-Python implementation of COBYLA from the PRIMA package; older SciPy versions wrap Powell’s original Fortran implementation of the algorithm.
- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Stop when the relative movement between parameter vectors is smaller than this.
In case of COBYLA this is a lower bound on the size of the trust region and can be seen as the required accuracy in the variables, but this accuracy is not guaranteed.
- stopping_maxiter: PositiveInt = 1000000¶
Maximum number of criterion evaluations. If it is reached, the optimization stops, but we do not count this as convergence.
This is passed as ‘maxiter’ to SciPy, but SciPy’s COBYLA interprets it as the maximum number of function evaluations, not iterations.
- trustregion_initial_radius: PositiveFloat | None = None¶
Initial value of the trust region radius. This is the ‘rhobeg’ parameter in the SciPy documentation.
Since a linear approximation is likely only good near the current simplex, the linear program is given the further requirement that the solution, which will become the next evaluation point, must be within a radius RHO_j from x_j. RHO_j only decreases, never increases. The initial RHO_j is the
trustregion_initial_radius. In this way COBYLA’s iterations behave like a trust region algorithm. If None (the default), optimagic uses0.1 * max(max(abs(x0)), 1), wherex0are the start parameters. SciPy’s default is 1.
scipy_truncated_newton
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.scipy_truncated_newton(stopping_maxfun=100_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_truncated_newton",
algo_options={"stopping_maxfun": 100_000},
)
Description and available options:
- class optimagic.optimizers.scipy_optimizers.ScipyTruncatedNewton[source]¶
Minimize a scalar function using the truncated Newton (TNC) algorithm.
A truncated Newton method computes the search direction in each iteration by approximately solving the Newton equations with a conjugate gradient iteration that is truncated after a limited number of steps ([algo_9], [algo_10]). This makes the algorithm suitable for differentiable scalar problems with many parameters. Bounds are supported.
scipy_truncated_newtondiffers fromscipy_newton_cgbecausescipy_newton_cg’s algorithm is written purely in Python using NumPy and SciPy, whilescipy_truncated_newtonwraps a C implementation,scipy_newton_cg’s algorithm is only for unconstrained minimization, whilescipy_truncated_newton’s algorithm supports bounds.
Conjugate gradient methods tend to work better when:
the criterion has a unique global minimizing point, and no local minima or other stationary points,
the criterion is, at least locally, reasonably well approximated by a quadratic function,
the criterion is continuous and has a continuous gradient,
the gradient is not too large, e.g., has a norm less than 1000,
the initial guess is reasonably close to the criterion’s global minimizer.
Note
optimagic does not support the SciPy arguments
scaleandoffsetbecause they are not compatible with the way optimagic handles constraints. It also does not supportmesg_num, which is an additional way to control the verbosity of the optimizer.- convergence_ftol_abs: NonNegativeFloat = 0¶
Absolute difference in the criterion value between iterations after scaling that is tolerated to declare convergence.
optimagic’s default of 0 is equivalent to SciPy’s default.
- convergence_xtol_abs: NonNegativeFloat = 0¶
Absolute difference in parameters between iterations after scaling that is tolerated to declare convergence.
optimagic’s default is 0, while SciPy’s default sets this tolerance to the square root of the machine precision.
- convergence_gtol_abs: NonNegativeFloat = 1e-05¶
Stop if the value of the projected gradient (after applying x scaling factors) is smaller than this value.
optimagic’s default is 1e-5. In SciPy, a negative value (SciPy’s default) means that the tolerance is set to
1e-2 * sqrt(finite_difference_precision).
- stopping_maxfun: PositiveInt = 1000000¶
If the maximum number of function evaluations is reached, the optimization stops, but we do not count this as convergence.
- max_hess_evaluations_per_iteration: int = -1¶
Maximum number of hessian*vector evaluations per main iteration. This is the ‘maxCGit’ parameter in the SciPy documentation.
If
max_hess_evaluations_per_iteration == 0, the direction chosen is-gradient. Ifmax_hess_evaluations_per_iteration < 0, it is set tomax(1, min(50, n/2))where n is the length of the parameter vector. This is also the default.
- max_step_for_line_search: NonNegativeFloat = 0¶
Maximum step for the line search. This is the ‘stepmx’ parameter in the SciPy documentation.
It may be increased during the optimization. If too small, it is set to 10.0. The default value is taken from SciPy.
- line_search_severity: float = -1¶
Severity of the line search. This is the ‘eta’ parameter in the SciPy documentation.
If < 0 or > 1, it is set to 0.25. The default value is taken from SciPy.
- finite_difference_precision: NonNegativeFloat = 0¶
Relative precision for finite difference calculations. This is the ‘accuracy’ parameter in the SciPy documentation.
If it is smaller than the machine precision, it is set to the square root of the machine precision. The default value is taken from SciPy.
- criterion_rescale_factor: float = -1¶
Scaling factor (in log10) used to trigger rescaling of the criterion function. This is the ‘rescale’ parameter in the SciPy documentation.
If 0, rescale at each iteration. If a large value, never rescale. If < 0, it is set to 1.3. The default value is taken from SciPy.
scipy_trust_constr
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.scipy_trust_constr(stopping_maxiter=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_trust_constr",
algo_options={"stopping_maxiter": 1_000},
)
Description and available options:
- class optimagic.optimizers.scipy_optimizers.ScipyTrustConstr[source]¶
Minimize a scalar function of one or more variables subject to constraints.
scipy_trust_constris a trust-region algorithm for constrained optimization. It is the most versatile constrained minimization algorithm implemented in SciPy and the most appropriate for large-scale problems. It supports bounds as well as nonlinear constraints. Natively, it can handle both equality and inequality constraints; optimagic converts each equality constraint into two inequality constraints before passing the problem to SciPy.It switches between two implementations depending on the problem definition. For equality-constrained problems it is an implementation of the Byrd-Omojokun trust-region SQP method described in [algo_11] and in [algo_12], p. 549. When inequality constraints are imposed as well, it switches to the trust-region interior point method described in [algo_13]. This interior point algorithm, in turn, solves inequality constraints by introducing slack variables and solving a sequence of equality-constrained barrier problems for progressively smaller values of the barrier parameter. The previously described equality-constrained SQP method is used to solve the subproblems with increasing levels of accuracy as the iterate gets closer to a solution. Because optimagic passes equality constraints as pairs of inequality constraints and SciPy treats finite bounds as inequality constraints, optimagic uses the interior point method whenever bounds or nonlinear constraints are present.
It approximates the Hessian using the Broyden-Fletcher-Goldfarb-Shanno (BFGS) Hessian update strategy, so no Hessian needs to be provided.
Warning
In our benchmark using a quadratic objective function, the trust_constr algorithm did not find the optimum very precisely (less than 4 decimal places). If you require high precision, you should refine an optimum found with trust_constr with another local optimizer.
- convergence_gtol_abs: NonNegativeFloat = 1e-08¶
Tolerance for termination by the norm of the Lagrangian gradient.
The algorithm will terminate when both the infinity norm (i.e., max abs value) of the Lagrangian gradient and the constraint violation are smaller than this value. The default value of 1e-8 is taken from SciPy.
- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Tolerance for termination by the change of the independent variable.
The algorithm will terminate when the radius of the trust region used in the algorithm is smaller than this value. optimagic’s default is 1e-5, while SciPy’s default is 1e-8.
- stopping_maxiter: PositiveInt = 1000000¶
If the maximum number of iterations is reached, the optimization stops, but we do not count this as convergence.
- trustregion_initial_radius: PositiveFloat | None = None¶
Initial value of the trust region radius.
The trust radius gives the maximum distance between solution points in consecutive iterations. It reflects the trust the algorithm puts in the local approximation of the optimization problem. For an accurate local approximation the trust region should be large and for an approximation valid only close to the current point it should be a small one. The trust radius is automatically updated throughout the optimization process, with
trustregion_initial_radiusbeing its initial value. If None (the default), optimagic uses0.1 * max(max(abs(x0)), 1), wherex0are the start parameters. SciPy’s default is 1.
scipy_ls_dogbox
How to use this algorithm:
import numpy as np
import optimagic as om
@om.mark.least_squares
def fun(x):
return x
om.minimize(
fun=fun,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.scipy_ls_dogbox(stopping_maxfun=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
@om.mark.least_squares
def fun(x):
return x
om.minimize(
fun=fun,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_ls_dogbox",
algo_options={"stopping_maxfun": 1_000},
)
Description and available options:
- class optimagic.optimizers.scipy_optimizers.ScipyLSDogbox[source]¶
Minimize a nonlinear least-squares problem using a rectangular trust region method.
The dogbox algorithm ([algo_14]) operates in a trust-region framework, but uses rectangular trust regions as opposed to conventional ellipsoids. The intersection of the trust region and the bounds is again rectangular, so in each iteration a bound-constrained quadratic subproblem is solved approximately by Powell’s dogleg method.
The algorithm can only be used for least-squares problems, i.e. the objective function must be marked with the
mark.least_squaresdecorator. The typical use case is small problems with bounds, where it often outperformsscipy_ls_trf. It is not recommended for problems with a rank-deficient Jacobian.- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Stop when the relative improvement of the cost function between two iterations is below this value.
More precisely, the optimization stops when
dF < convergence_ftol_rel * Fand there was an adequate agreement between a local quadratic model and the true model in the last step.
- convergence_gtol_rel: NonNegativeFloat = 1e-08¶
Stop when the uniform norm of the gradient with respect to the variables that are not at their bounds is below this value.
The default value is taken from SciPy.
- stopping_maxfun: PositiveInt = 1000000¶
If the maximum number of function evaluations is reached, the optimization stops, but we do not count this as convergence.
- relative_step_size_diff_approx: NonNegativeFloat | None = None¶
Relative step size for SciPy’s finite difference approximation of the Jacobian. This is the ‘diff_step’ parameter in the SciPy documentation.
The actual step is computed as
x * relative_step_size_diff_approx. If None (default), it is chosen automatically. Note that optimagic always passes a Jacobian function (either the user-provided derivative or optimagic’s numerical derivative) to SciPy, in which case this option has no effect.
- tr_solver: Literal['exact', 'lsmr'] | None = None¶
Method for solving the trust-region subproblems.
‘exact’ is suitable for not very large problems with dense Jacobian matrices. The computational complexity per iteration is comparable to a singular value decomposition of the Jacobian matrix.
‘lsmr’ is suitable for problems with sparse and large Jacobian matrices. It uses the iterative procedure
scipy.sparse.linalg.lsmrfor finding a solution of a linear least-squares problem and only requires matrix-vector product evaluations.
If None (default), the solver is chosen based on the type of Jacobian returned on the first iteration.
scipy_ls_trf
How to use this algorithm:
import numpy as np
import optimagic as om
@om.mark.least_squares
def fun(x):
return x
om.minimize(
fun=fun,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.scipy_ls_trf(stopping_maxfun=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
@om.mark.least_squares
def fun(x):
return x
om.minimize(
fun=fun,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_ls_trf",
algo_options={"stopping_maxfun": 1_000},
)
Description and available options:
- class optimagic.optimizers.scipy_optimizers.ScipyLSTRF[source]¶
Minimize a nonlinear least-squares problem using the Trust Region Reflective method.
The Trust Region Reflective (TRF) algorithm ([algo_15], [algo_16]) is an interior trust-region method for bound-constrained minimization. In each iteration it solves a trust-region subproblem augmented by a special diagonal quadratic term, where the shape of the trust region is determined by the distance from the bounds and the direction of the gradient.
The algorithm can only be used for least-squares problems, i.e. the objective function must be marked with the
mark.least_squaresdecorator. It is particularly suitable for large problems with bounds and is a generally robust method; it is SciPy’s default least-squares method. For small problems with bounds,scipy_ls_dogboxcan be more efficient, and for small unconstrained problemsscipy_ls_lmis usually the best choice.- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Stop when the relative improvement of the cost function between two iterations is below this value.
More precisely, the optimization stops when
dF < convergence_ftol_rel * Fand there was an adequate agreement between a local quadratic model and the true model in the last step.
- convergence_gtol_rel: NonNegativeFloat = 1e-08¶
Stop when the uniform norm of the gradient, scaled to account for the presence of bounds, is below this value.
The default value is taken from SciPy.
- stopping_maxfun: PositiveInt = 1000000¶
If the maximum number of function evaluations is reached, the optimization stops, but we do not count this as convergence.
- relative_step_size_diff_approx: NonNegativeFloat | None = None¶
Relative step size for SciPy’s finite difference approximation of the Jacobian. This is the ‘diff_step’ parameter in the SciPy documentation.
The actual step is computed as
x * relative_step_size_diff_approx. If None (default), it is chosen automatically. Note that optimagic always passes a Jacobian function (either the user-provided derivative or optimagic’s numerical derivative) to SciPy, in which case this option has no effect.
- tr_solver: Literal['exact', 'lsmr'] | None = None¶
Method for solving the trust-region subproblems.
‘exact’ is suitable for not very large problems with dense Jacobian matrices. The computational complexity per iteration is comparable to a singular value decomposition of the Jacobian matrix.
‘lsmr’ is suitable for problems with sparse and large Jacobian matrices. It uses the iterative procedure
scipy.sparse.linalg.lsmrfor finding a solution of a linear least-squares problem and only requires matrix-vector product evaluations.
If None (default), the solver is chosen based on the type of Jacobian returned on the first iteration.
- tr_solver_options: dict[str, Any] | None = None¶
Keyword options passed to the trust-region solver. This is the ‘tr_options’ parameter in the SciPy documentation.
If
tr_solver='exact', the options are ignored.If
tr_solver='lsmr', the options are passed toscipy.sparse.linalg.lsmr. Additionally, the ‘regularize’ option (bool, default True) adds a regularization term to the normal equation, which improves convergence if the Jacobian is rank-deficient.
scipy_ls_lm
How to use this algorithm:
import numpy as np
import optimagic as om
@om.mark.least_squares
def fun(x):
return x
om.minimize(
fun=fun,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.scipy_ls_lm(stopping_maxfun=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
@om.mark.least_squares
def fun(x):
return x
om.minimize(
fun=fun,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_ls_lm",
algo_options={"stopping_maxfun": 1_000},
)
Description and available options:
- class optimagic.optimizers.scipy_optimizers.ScipyLSLM[source]¶
Minimize a nonlinear least-squares problem using the Levenberg-Marquardt method.
SciPy’s implementation wraps the classic Levenberg-Marquardt algorithm as implemented in MINPACK ([algo_17]). It is usually the most efficient method for small, unconstrained least-squares problems.
The algorithm can only be used for least-squares problems, i.e. the objective function must be marked with the
mark.least_squaresdecorator. It does not handle bounds or sparse Jacobians and requires that the number of residuals is at least as large as the number of parameters. For problems with bounds, usescipy_ls_trforscipy_ls_dogboxinstead.- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Stop when the relative improvement of the cost function between two iterations is below this value.
More precisely, the optimization stops when
dF < convergence_ftol_rel * Fand there was an adequate agreement between a local quadratic model and the true model in the last step.
- convergence_gtol_rel: NonNegativeFloat = 1e-08¶
Stop when the maximum absolute value of the cosine of the angles between the columns of the Jacobian and the residual vector is below this value.
The default value is taken from SciPy.
- stopping_maxfun: PositiveInt = 1000000¶
If the maximum number of function evaluations is reached, the optimization stops, but we do not count this as convergence.
- relative_step_size_diff_approx: NonNegativeFloat | None = None¶
Relative step size for SciPy’s finite difference approximation of the Jacobian. This is the ‘diff_step’ parameter in the SciPy documentation.
The actual step is computed as
x * relative_step_size_diff_approx. If None (default), it is chosen automatically. Note that optimagic always passes a Jacobian function (either the user-provided derivative or optimagic’s numerical derivative) to SciPy, in which case this option has no effect.
scipy_basinhopping
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.scipy_basinhopping(n_local_optimizations=10),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_basinhopping",
algo_options={"n_local_optimizations": 10},
)
Description and available options:
- class optimagic.optimizers.scipy_optimizers.ScipyBasinhopping[source]¶
Find the global minimum of a scalar function using the basin-hopping algorithm.
Basin-hopping ([algo_18]) is a two-phase method that combines a global stepping algorithm with local minimization at each step. Designed to mimic the natural process of energy minimization of clusters of atoms, it works well for similar problems with “funnel-like, but rugged” energy landscapes.
This algorithm is mainly supported for completeness. Consider using optimagic’s built-in multistart optimization for a similar approach that can run multiple optimizations in parallel, supports all local algorithms in optimagic (as opposed to just those from SciPy) and allows for a better visualization of the multistart history.
optimagic always passes a derivative (the user-provided one or a numerical derivative) to the local minimization method.
Bounds are only enforced by the local optimization algorithm, which therefore needs to support bounds; the random displacement steps ignore them.
- local_algorithm: Literal['Nelder-Mead', 'Powell', 'CG', 'BFGS', 'Newton-CG', 'L-BFGS-B', 'TNC', 'COBYLA', 'SLSQP', 'trust-constr', 'dogleg', 'trust-ncg', 'trust-exact', 'trust-krylov'] | Callable = 'L-BFGS-B'¶
The local optimization algorithm to be used.
Can be the name of a SciPy local minimizer or a custom function for local minimization. “dogleg”, “trust-ncg”, “trust-exact” and “trust-krylov” require a Hessian (or Hessian-vector product), which optimagic does not pass; it needs to be supplied via
local_algo_options. optimagic’s default is “L-BFGS-B”, while SciPy uses the default method ofscipy.optimize.minimize(“BFGS” without bounds, “L-BFGS-B” with bounds).
- n_local_optimizations: PositiveInt = 100¶
The total number of local optimizations, including the one at the start parameters.
SciPy runs one local optimization at the start parameters plus one per basin-hopping iteration, so optimagic passes
niter = n_local_optimizations - 1to SciPy (values below 2 behave like 2). The default of 100 thus corresponds to SciPy’sniter=99; SciPy’s defaultniter=100runs 101 local optimizations.
- temperature: NonNegativeFloat = 1.0¶
The “temperature” parameter for the acceptance or rejection criterion.
Higher temperatures mean that larger jumps in the function value will be accepted. For best results, it should be comparable to the separation (in function value) between local minima. The default is 1.0, as in SciPy.
- stepsize: NonNegativeFloat = 0.5¶
Maximum step size for use in the random displacement.
The default is 0.5, as in SciPy.
- local_algo_options: dict[str, Any] | None = None¶
Additional keyword arguments for the local minimizer.
Check the documentation of the local SciPy algorithms for details on what is supported.
- take_step: Callable | None = None¶
Replace the default step-taking routine with this callable.
The default is None, which uses SciPy’s default step-taking routine.
- accept_test: Callable | None = None¶
Define a test to judge the acceptance of steps.
The default is None, which uses SciPy’s default acceptance test.
- interval: PositiveInt = 50¶
Determines how often the step size is updated.
The default is 50, as in SciPy.
- convergence_n_unchanged_iterations: PositiveInt | None = None¶
Stop the run if the global minimum candidate remains the same for this number of iterations. This is the ‘niter_success’ parameter in the SciPy documentation.
The default is None, as in SciPy.
- seed: int | np.random.Generator | np.random.RandomState | None = None¶
Seed or random number generator that makes the stochastic parts of the algorithm reproducible.
The default is None, as in SciPy.
- target_accept_rate: NonNegativeFloat = 0.5¶
The target acceptance rate that is used to adjust the step size.
If the current acceptance rate is greater than the target, the step size is increased; otherwise, it is decreased. The range is (0, 1) and the default is 0.5, as in SciPy.
- stepwise_factor: NonNegativeFloat = 0.9¶
The step size is multiplied or divided by this factor upon each update.
The range is (0, 1) and the default is 0.9, as in SciPy.
scipy_brute
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.scipy_brute(n_grid_points=50),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_brute",
algo_options={"n_grid_points": 50},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.scipy_optimizers.ScipyBrute[source]¶
Find the global minimum of a scalar function over a given range by brute force.
Brute force evaluates the criterion function at each point of a rectangular grid defined by the bounds. Since the number of grid points grows exponentially with the number of parameters, the algorithm is only suited for problems with very few parameters. Finite bounds are required for all parameters.
The start values are not actually used because the grid is defined solely by the bounds. They are still necessary for optimagic to infer the number and format of the parameters.
The function evaluations can be parallelized over multiple cores. Due to the parallelization, this algorithm cannot collect a history of parameters and criterion evaluations.
- n_grid_points: PositiveInt = 20¶
The number of grid points per parameter dimension used for the brute force search. This is the ‘Ns’ parameter in the SciPy documentation.
The default is 20, as in SciPy.
- polishing_function: Callable | None = None¶
Function to seek a more precise minimum near the best grid point. This is the ‘finish’ parameter in the SciPy documentation.
SciPy calls it as
polishing_function(func, x_best, args=()), i.e., with the criterion function and the best grid point as positional arguments, and also passesfull_outputanddispas keyword arguments if the function accepts them (asscipy.optimize.fmindoes). optimagic’s default is None, which means that no polishing is performed, while SciPy’s default isscipy.optimize.fmin.
- n_cores: PositiveInt = 1¶
The number of cores on which the function is evaluated in parallel.
The default is 1.
- batch_evaluator: BatchEvaluatorLiteral | BatchEvaluator = 'joblib'¶
An optimagic batch evaluator that is used for the parallel function evaluations.
The default is “joblib”.
scipy_differential_evolution
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.scipy_differential_evolution(
population_size_multiplier=10,
),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_differential_evolution",
algo_options={"population_size_multiplier": 10},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.scipy_optimizers.ScipyDifferentialEvolution[source]¶
Find the global minimum of a scalar function using differential evolution.
Differential evolution ([algo_19]) is a stochastic, population-based evolutionary algorithm. It does not use gradient information, so the criterion function does not need to be differentiable. In each generation, candidate solutions are mutated by mixing them with other candidate solutions of the population and are kept if they improve the criterion value.
The algorithm can search large areas of the candidate space, but this often comes at the cost of requiring more criterion evaluations than gradient-based methods. It is a good choice for global optimization of non-smooth or noisy problems with a moderate number of parameters. Finite bounds are required for all parameters. Nonlinear equality and inequality constraints are supported; equality constraints are enforced up to the constraint’s
tol.The start values are not used by the algorithm, but they are still necessary for optimagic to infer the number and format of the parameters.
Note
Due to optimagic’s general parameter format, the SciPy arguments
integralityandvectorizedare not supported. The SciPy argumentupdatingis always set to “deferred” so that the population can be evaluated in parallel.- strategy: Literal['best1bin', 'best1exp', 'rand1exp', 'randtobest1exp', 'currenttobest1exp', 'best2exp', 'rand2exp', 'randtobest1bin', 'currenttobest1bin', 'best2bin', 'rand2bin', 'rand1bin'] | Callable = 'best1bin'¶
The differential evolution strategy that is used to create trial candidates.
The default is “best1bin”, as in SciPy.
- stopping_maxiter: PositiveInt = 1000¶
The maximum number of generations over which the entire population is evolved.
The maximum number of criterion evaluations (without polishing) is
(stopping_maxiter + 1) * population_size_multiplier * number of parameters.
- population_size_multiplier: NonNegativeInt = 15¶
A multiplier for setting the total population size. This is the ‘popsize’ parameter in the SciPy documentation.
The number of individuals in the population is
population_size_multiplier * number of parameters. The default is 15, as in SciPy.
- convergence_ftol_rel: NonNegativeFloat = 0.01¶
Relative tolerance for convergence. This is the ‘tol’ parameter in the SciPy documentation.
The optimization stops when the standard deviation of the criterion values in the population is smaller than
convergence_ftol_abs + convergence_ftol_rel * |mean criterion value|. The default is 0.01, as in SciPy.
- mutation_constant: NonNegativeFloat | Tuple[NonNegativeFloat, NonNegativeFloat] = (0.5, 1)¶
The differential weight, denoted by F in the literature. This is the ‘mutation’ parameter in the SciPy documentation.
Should be within [0, 2). If a tuple
(min, max)is given, dithering is used: the mutation constant is randomly changed on a generation by generation basis, which can help speed up convergence significantly. The default is (0.5, 1), as in SciPy.
- recombination_constant: NonNegativeFloat = 0.7¶
The crossover probability, denoted by CR in the literature. This is the ‘recombination’ parameter in the SciPy documentation.
It determines the probability that two solution vectors are combined to produce a new solution vector. Should be between 0 and 1. Increasing this value allows a larger number of mutants to progress into the next generation, but at the risk of population stability. The default is 0.7, as in SciPy.
- seed: int | np.random.Generator | np.random.RandomState | None = None¶
Seed or random number generator that makes the stochastic parts of the algorithm reproducible.
The default is None, as in SciPy.
- polish: bool = True¶
If True, the best population member is polished at the end.
SciPy uses L-BFGS-B for unconstrained problems and trust-constr for constrained problems to slightly improve the minimum. The default is True, as in SciPy.
- sampling_method: Literal['latinhypercube', 'random', 'sobol', 'halton'] | NDArray[np.float64] = 'latinhypercube'¶
Method used to generate the initial population. This is the ‘init’ parameter in the SciPy documentation.
Can be “latinhypercube”, “sobol”, “halton”, “random”, or an array specifying the initial population of shape (total population size, number of parameters). The initial population is clipped to the bounds before use. The default is “latinhypercube”, as in SciPy.
- convergence_ftol_abs: NonNegativeFloat = 1e-08¶
Absolute tolerance for convergence. This is the ‘atol’ parameter in the SciPy documentation.
See
convergence_ftol_relfor the exact convergence criterion. optimagic’s default is 1e-8, while SciPy’s default is 0.
- n_cores: PositiveInt = 1¶
The number of cores on which the population is evaluated in parallel.
The default is 1.
- batch_evaluator: BatchEvaluatorLiteral | BatchEvaluator = 'joblib'¶
An optimagic batch evaluator that is used for the parallel function evaluations.
The default is “joblib”.
scipy_shgo
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.scipy_shgo(n_sampling_points=256),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_shgo",
algo_options={"n_sampling_points": 256},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.scipy_optimizers.ScipySHGO[source]¶
Find the global minimum of a scalar function using simplicial homology global optimization (SHGO).
SHGO ([algo_20]) is appropriate for solving general purpose nonlinear programming and black-box optimization problems to global optimality (low-dimensional problems). It samples the search space, builds a simplicial complex on the sampled points from which promising candidate minimizers are derived, and refines the candidates with a local optimization algorithm. Nonlinear constraints are supported.
With the default “simplicial” sampling method, the algorithm has theoretical guarantees of convergence to the global minimum in finite time for Lipschitz smooth functions.
Note
Bounds are required for all parameters. SciPy replaces infinite bounds by -1e50 and 1e50.
Note
If nonlinear constraints are used, only the local algorithms “COBYLA”, “SLSQP” and “trust-constr” take the constraints into account during the local refinement; the other local algorithms ignore them. Inequality constraints are also used to discard infeasible sampling points.
- local_algorithm: Literal['Nelder-Mead', 'Powell', 'CG', 'BFGS', 'Newton-CG', 'L-BFGS-B', 'TNC', 'COBYLA', 'SLSQP', 'trust-constr', 'dogleg', 'trust-ncg', 'trust-exact', 'trust-krylov'] | Callable = 'L-BFGS-B'¶
The local optimization algorithm to be used.
Can be the name of a SciPy local minimizer. Custom functions for local minimization are not supported by SciPy’s shgo and raise an error. Only “COBYLA”, “SLSQP” and “trust-constr” support constraints. “dogleg”, “trust-ncg”, “trust-exact” and “trust-krylov” require a Hessian (or Hessian-vector product), which optimagic does not pass; it needs to be supplied via
local_algo_options. optimagic’s default is “L-BFGS-B”, while SciPy’s default is “SLSQP”.
- local_algo_options: dict[str, Any] | None = None¶
Additional keyword arguments for the local minimizer.
Check the documentation of the local SciPy algorithms for details on what is supported.
- n_sampling_points: PositiveInt = 128¶
The number of sampling points used in the construction of the simplicial complex. This is the ‘n’ parameter in the SciPy documentation.
optimagic’s default is 128, while SciPy’s default is 100 (which SciPy replaces by
2 ** n_params + 1for the “simplicial” sampling method).
- n_simplex_iterations: PositiveInt = 1¶
The number of iterations used in the construction of the simplicial complex. This is the ‘iters’ parameter in the SciPy documentation.
The default is 1, as in SciPy. SciPy ignores this option if any of the options ‘maxiter’, ‘maxfev’, ‘maxev’, ‘minhgrd’ or ‘f_min’ is set. Since optimagic always passes
stopping_maxfunas ‘maxev’, this option currently has no effect.
- sampling_method: Literal['simplicial', 'halton', 'sobol'] | Callable = 'simplicial'¶
The method used for sampling the search space.
The default “simplicial” provides the theoretical guarantee of convergence to the global minimum in finite time. The “halton” and “sobol” methods are faster in terms of sampling point generation at the cost of losing this guarantee. A custom sampling function can also be passed.
- max_sampling_evaluations: PositiveInt | None = None¶
The maximum number of criterion evaluations in the feasible domain during the sampling phase. This is the ‘maxfev’ option in the SciPy documentation.
- convergence_minimum_criterion_value: float | None = None¶
Specify the global minimum of the criterion function when it is known. This is the ‘f_min’ option in the SciPy documentation.
For maximization problems, flip the sign.
- convergence_minimum_criterion_tolerance: NonNegativeFloat = 0.0001¶
Specify the relative error between the current best minimum and the supplied global criterion minimum that is allowed. This is the ‘f_tol’ option in the SciPy documentation.
The default is 1e-4, as in SciPy.
- stopping_maxiter: PositiveInt | None = None¶
The maximum number of iterations.
If reached, the optimization stops, but we do not count this as convergence.
- stopping_maxfun: PositiveInt = 1000¶
The maximum number of sampling evaluations, including points outside the feasible domain. This is the ‘maxev’ option in the SciPy documentation.
optimagic’s default is 1000, while SciPy’s default is None (no limit).
- stopping_max_processing_time: PositiveFloat | None = None¶
The maximum time allowed for the optimization. This is the ‘maxtime’ option in the SciPy documentation.
- minimum_homology_group_rank_differential: PositiveInt | None = None¶
The minimum difference in the rank of the homology group between iterations. This is the ‘minhgrd’ option in the SciPy documentation.
The rank of the homology group approximately corresponds to the number of locally convex subdomains (and thus local minima) found so far. The algorithm terminates as soon as the rank grows by at most this value in one iteration.
- symmetry: List | bool = False¶
Specify whether the criterion function contains symmetric variables.
The search space (and therefore performance) can be improved by exploiting symmetries.
- minimize_every_iteration: bool = True¶
Specify whether promising global sampling points are passed to the local algorithm in every iteration.
- max_local_minimizations_per_iteration: PositiveInt | bool = False¶
The maximum number of local optimizations per iteration. This is the ‘local_iter’ option in the SciPy documentation.
If False (the default), all promising candidates from the minimizer pool are refined, i.e. there is no limit.
- infinity_constraints: bool = True¶
Specify whether sampling points outside the feasible domain are saved. This is the ‘infty_constraints’ option in the SciPy documentation.
If True, the infeasible points are stored with a criterion value of infinity, which requires more memory but fewer criterion evaluations. The default is True, as in SciPy.
scipy_dual_annealing
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.scipy_dual_annealing(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_dual_annealing",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.scipy_optimizers.ScipyDualAnnealing[source]¶
Find the global minimum of a scalar function using dual annealing.
Dual annealing is a stochastic global optimization algorithm that implements the generalized simulated annealing (GSA) algorithm ([algo_21], [algo_22], [algo_23]), which couples classical and fast simulated annealing via a distorted Cauchy-Lorentz visiting distribution, and combines it with a local search that is applied to accepted candidate solutions.
The algorithm does not require derivatives of the criterion function for the annealing phase (derivatives are passed to the local search algorithm) and is suited for noisy or multi-modal problems. Finite bounds are required for all parameters.
- stopping_maxiter: PositiveInt = 1000¶
The maximum number of global search iterations.
The default is 1000, as in SciPy.
- local_algorithm: Literal['Nelder-Mead', 'Powell', 'CG', 'BFGS', 'Newton-CG', 'L-BFGS-B', 'TNC', 'COBYLA', 'SLSQP', 'trust-constr', 'dogleg', 'trust-ncg', 'trust-exact', 'trust-krylov'] | Callable = 'L-BFGS-B'¶
The local optimization algorithm to be used.
Can be the name of a SciPy local minimizer or a custom function for local minimization. “dogleg”, “trust-ncg”, “trust-exact” and “trust-krylov” require a Hessian (or Hessian-vector product), which optimagic does not pass; it needs to be supplied via
local_algo_options. The default is “L-BFGS-B”, as in SciPy. Since optimagic always passes the local algorithm and its options to SciPy, SciPy’s default cap on the number of iterations of each local search does not apply.
- local_algo_options: dict[str, Any] | None = None¶
Additional keyword arguments for the local minimizer.
Check the documentation of the local SciPy algorithms for details on what is supported.
- initial_temperature: PositiveFloat = 5230.0¶
The temperature the algorithm starts with.
Higher values facilitate a wider search of the energy landscape and allow the algorithm to escape local minima that it is trapped in. The range is (0.01, 5e4] and the default is 5230.0, as in SciPy.
- restart_temperature_ratio: PositiveFloat = 2e-05¶
Reannealing starts when the temperature has decreased to
initial_temperature * restart_temperature_ratio.The range is (0, 1) and the default is 2e-5, as in SciPy.
- visit: PositiveFloat = 2.62¶
Specify the thickness of the visiting distribution’s tails.
Higher values give the visiting distribution a heavier tail, which makes the algorithm jump to more distant regions. The range is (1, 3] and the default is 2.62, as in SciPy.
- accept: NegativeFloat = -5.0¶
Controls the probability of acceptance.
Lower values lead to a smaller acceptance probability. The range is (-1e4, -5] and the default is -5.0, as in SciPy.
- stopping_maxfun: PositiveInt = 1000000¶
Soft limit for the number of criterion evaluations.
If the algorithm is in the middle of a local search when this limit is reached, the limit is exceeded and the algorithm stops after the local search is done. optimagic’s default is 1,000,000, while SciPy’s default is 1e7.
scipy_direct
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.scipy_direct(stopping_maxfun=10_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_direct",
algo_options={"stopping_maxfun": 10_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.scipy_optimizers.ScipyDirect[source]¶
Find the global minimum of a scalar function using the DIRECT algorithm.
DIRECT stands for DIviding RECTangles ([algo_24]). It is a deterministic, derivative-free global optimization algorithm based on Lipschitzian optimization without knowledge of the Lipschitz constant. The algorithm normalizes the search space to a unit hypercube, samples the criterion function at the center of the hypercube and then iteratively divides the most promising hyperrectangles.
By default, the locally biased variant DIRECT_L ([algo_25]) is used, which is often faster on problems without too many local minima.
Finite bounds are required for all parameters. The start values are not used by the algorithm, but they are still necessary for optimagic to infer the number and format of the parameters.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
The minimum required difference of the criterion values between the current best hyperrectangle and the next potentially optimal hyperrectangle to be divided. This is the ‘eps’ parameter in the SciPy documentation.
It determines the trade-off between local and global search: the smaller the value, the more local the search becomes. optimagic’s default is 2e-9, while SciPy’s default is 1e-4.
- stopping_maxfun: PositiveInt = 1000000¶
Approximate upper bound on the number of criterion evaluations.
If reached, the optimization stops, but we do not count this as convergence. optimagic’s default is 1,000,000. Note that SciPy caps this value if necessary to limit DIRECT’s memory usage to approximately 1 GiB.
- stopping_maxiter: PositiveInt = 1000¶
The maximum number of iterations.
If reached, the optimization stops, but we do not count this as convergence. The default is 1000, as in SciPy.
- locally_biased: bool = True¶
If True (default), use the locally biased variant of the algorithm known as DIRECT_L ([algo_25]).
Set it to False to use the original, unbiased DIRECT algorithm, which is recommended for very difficult problems with many local minima.
- convergence_minimum_criterion_value: float = -inf¶
Specify the global minimum of the criterion function when it is known. This is the ‘f_min’ parameter in the SciPy documentation.
The default is minus infinity, meaning that the global minimum is unknown. For maximization problems, flip the sign.
- convergence_minimum_criterion_tolerance: NonNegativeFloat = 0.0001¶
Specify the relative error between the current best minimum and the supplied global minimum that is allowed. This is the ‘f_min_rtol’ parameter in the SciPy documentation.
It is only used if
convergence_minimum_criterion_valueis set. The default is 1e-4, as in SciPy.
- volume_hyperrectangle_tolerance: NonNegativeFloat = 1e-16¶
Stop when the volume of the hyperrectangle containing the lowest criterion value is smaller than this fraction of the complete search space. This is the ‘vol_tol’ parameter in the SciPy documentation.
The range is (0, 1) and the default is 1e-16, as in SciPy.
- length_hyperrectangle_tolerance: NonNegativeFloat = 1e-06¶
Stopping criterion based on the length of the hyperrectangle containing the lowest criterion value. This is the ‘len_tol’ parameter in the SciPy documentation.
If
locally_biasedis True, terminate when half of the normalized maximal side length of this hyperrectangle is smaller than this value. Iflocally_biasedis False, terminate when half of the normalized diagonal of this hyperrectangle is smaller than this value. The range is (0, 1) and the default is 1e-6, as in SciPy.
Own optimizers¶
We implement a few algorithms from scratch. They are currently considered experimental.
bhhh
How to use this algorithm:
import numpy as np
import optimagic as om
@om.mark.likelihood
def fun(x):
return x**2
om.minimize(
fun=fun,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.bhhh(stopping_maxiter=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
@om.mark.likelihood
def fun(x):
return x**2
om.minimize(
fun=fun,
params=np.array([1.0, 2.0, 3.0]),
algorithm="bhhh",
algo_options={"stopping_maxiter": 1_000},
)
Description and available options:
- class optimagic.optimizers.bhhh.BHHH[source]¶
Minimize a likelihood function using the BHHH algorithm.
BHHH ([algo_26]) can - and should ONLY - be used for minimizing (or maximizing) a likelihood function. It is similar to the Newton-Raphson algorithm, but replaces the Hessian matrix with the outer product of the gradients of the likelihood contributions. This approximation is based on the information matrix equality ([algo_27]) and is thus only valid when minimizing (or maximizing) a likelihood function. In exchange, the approximated Hessian is always positive semidefinite and no second derivatives are needed.
To use bhhh, the objective function must be a likelihood function, i.e. a function that is decorated with
om.mark.likelihoodand returns the likelihood contributions of each observation rather than their sum.The algorithm is a local optimizer that uses first derivatives of the likelihood contributions. It does not support bounds or constraints.
Note
This is a pure-Python implementation within optimagic. It is currently considered experimental.
Warning
The implementation steps along \(+H^{-1} g\), where \(g\) is the sum over observations of the Jacobian of the contributions. With derivatives that are consistent with
fun(including numerical derivatives), it therefore moves uphill and does not minimize (nor, viamaximize, maximize). It only works if the Jacobian has the opposite sign of the derivative offun.- converence_gtol_abs: NonNegativeFloat = 1e-08¶
Stopping criterion for the gradient tolerance.
The algorithm converges when the inner product of the aggregated gradient and the candidate search direction falls below this value.
- stopping_maxiter: PositiveInt = 200¶
Maximum number of iterations.
If reached, terminate.
neldermead_parallel
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.neldermead_parallel(n_cores=2),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="neldermead_parallel",
algo_options={"n_cores": 2},
)
Description and available options:
- class optimagic.optimizers.neldermead.NelderMeadParallel[source]¶
Minimize a scalar function using a parallel Nelder-Mead algorithm.
This is a parallel Nelder-Mead algorithm following [algo_28], which generalizes the classic simplex algorithm of Nelder and Mead ([algo_2]) to parallel processors. In each iteration, instead of reflecting only the worst vertex of the simplex, the p worst vertices are reflected (and possibly expanded or contracted) simultaneously, so that up to p criterion evaluations can be carried out in parallel. With
n_cores=1, the algorithm behaves like a standard sequential Nelder-Mead algorithm.As a direct search method, it does not require derivatives of the objective function and can handle a moderate amount of noise or non-smoothness. It is a local optimizer for scalar objective functions and does not support bounds or constraints. Parallelization is most beneficial when a single criterion evaluation is expensive and the number of parameters is large relative to the number of available cores.
The algorithm was implemented in optimagic by Jacek Barszczewski.
Note
This is a pure-Python implementation within optimagic. It is currently considered experimental.
- init_simplex_method: InitSimplexLiteral | InitSimplexCallable = 'gao_han'¶
Method to create the initial simplex.
Either the name of one of the implemented methods, i.e. “pfeffer” (due to L. Pfeffer at Stanford; the default in MATLAB’s fminsearch and SciPy), “nash” ([algo_29]; the default in R’s optim), “gao_han” ([algo_3]) or “varadhan_borchers” ([algo_30]), or a callable that takes the initial parameter vector as argument and returns the initial simplex as an array of shape (j + 1, j), where j is the number of parameters. The default is “gao_han”. See [algo_31] for a discussion of the importance of the choice of the initial simplex.
- n_cores: PositiveInt = 1¶
Degree of parallelization.
The default is 1 (no parallelization). The number of vertices that are reflected in parallel is capped at the number of parameters minus 1; the evaluations of the initial and of shrunk simplices use
n_coresas given.
- adaptive: bool = True¶
Adjust the parameters of the Nelder-Mead algorithm to the dimension of the problem, following [algo_3].
The default is True.
- stopping_maxiter: PositiveInt = 1000000¶
Maximum number of algorithm iterations.
- convergence_ftol_abs: NonNegativeFloat = 1e-08¶
Maximal absolute difference between the function value at the first vertex of the simplex (the best vertex at the start of the iteration) and the function values at the remaining vertices.
Convergence requires that this criterion and
convergence_xtol_absare satisfied at the same time.
- convergence_xtol_abs: NonNegativeFloat = 1e-08¶
Maximal absolute coordinate-wise difference (infinity norm) between the first vertex of the simplex (the best vertex at the start of the iteration) and the remaining vertices.
Convergence requires that this criterion and
convergence_ftol_absare satisfied at the same time.
- batch_evaluator: BatchEvaluator | BatchEvaluatorLiteral = 'joblib'¶
Batch evaluator used for parallel function evaluations.
See Batch evaluators for details. The default is “joblib”.
pounders
How to use this algorithm:
import numpy as np
import optimagic as om
@om.mark.least_squares
def fun(x):
return x
om.minimize(
fun=fun,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pounders(stopping_maxiter=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
@om.mark.least_squares
def fun(x):
return x
om.minimize(
fun=fun,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pounders",
algo_options={"stopping_maxiter": 1_000},
)
Description and available options:
- class optimagic.optimizers.pounders.Pounders[source]¶
Minimize a nonlinear least-squares problem using the POUNDERS algorithm.
POUNDERS ([algo_32], [algo_33]) is a derivative-free trust-region algorithm that is tailored to nonlinear least-squares problems. This is a pure-Python implementation of the POUNDERS algorithm from the Toolkit for Advanced Optimization (TAO), which is part of PETSc. In contrast to the wrapped TAO version (
tao_pounders), it runs on all platforms and supports parallel function evaluations.POUNDERS can be a useful tool for economists who estimate structural models using indirect inference, because unlike commonly used algorithms such as Nelder-Mead, it exploits the least-squares structure of the objective function by building and maintaining interpolation-based quadratic models of the residuals. It may therefore require fewer criterion evaluations to arrive at a local optimum than general-purpose derivative-free optimizers.
Use pounders for smooth least-squares problems with a moderate number of parameters when derivatives are not available. The objective function must be a least-squares function, i.e. a function that is decorated with
om.mark.least_squaresand returns the residuals rather than the sum of their squares. Bound constraints are supported; other constraint types are not. The start parameters plustrustregion_initial_radiusmust not exceed the upper bounds; otherwise aValueErroris raised.Besides the gradient-based criteria below, the algorithm also stops if the same interpolation model is used in two successive iterations without a change of the trust-region radius.
Note
Scaling the problem is necessary such that bounds correspond to the unit hypercube \([0, 1]^n\). For unconstrained problems, scale each parameter such that unit changes in parameters result in similar order-of-magnitude changes in the criterion value(s).
- convergence_gtol_abs: NonNegativeFloat = 1e-08¶
Convergence tolerance for the absolute gradient norm.
Stop if the norm of the gradient is less than this value. The gradient is that of the quadratic surrogate model of half the sum of squared residuals at the accepted point, i.e. \(J^\top r\) for the model Jacobian \(J\) of the residuals \(r\).
- convergence_gtol_rel: NonNegativeFloat = 1e-08¶
Convergence tolerance for the relative gradient norm.
Stop if the norm of the gradient (see
convergence_gtol_abs) divided by the criterion value, i.e. the sum of squared residuals, is less than this value.
- convergence_gtol_scaled: NonNegativeFloat | bool = False¶
Convergence tolerance for the scaled gradient norm.
Stop if the norm of the gradient divided by the norm of the gradient at the initial parameters is less than this value. Disabled, i.e. set to False, by default.
- max_interpolation_points: PositiveInt | None = None¶
Maximum number of interpolation points.
By default, 2 * n + 1 points are used, where n is the number of parameters.
- stopping_maxiter: PositiveInt = 2000¶
Maximum number of iterations.
If reached, terminate.
- trustregion_initial_radius: PositiveFloat = 0.1¶
Initial trust-region radius.
- trustregion_minimal_radius: PositiveFloat = 1e-06¶
Minimal trust-region radius.
- trustregion_maximal_radius: PositiveFloat = 1000000.0¶
Maximal trust-region radius.
- trustregion_shrinking_factor_not_successful: PositiveFloat = 0.5¶
Shrinking factor of the trust-region radius.
It is applied whenever the radius is not expanded and the model is fully linear (i.e. “valid”), including iterations in which the candidate is accepted.
- trustregion_expansion_factor_successful: PositiveFloat = 2¶
Expansion factor of the trust-region radius.
It is applied if the ratio of actual to predicted reduction is at least
trustregion_threshold_successfuland the step is not short.
- theta1: PositiveFloat = 1e-05¶
Threshold for adding the current candidate vector to the model.
Used when searching for affine (i.e. model-improving) points.
- theta2: PositiveFloat = 0.0001¶
Threshold for adding the current candidate vector to the model.
Used when computing the feature matrices of the residual model.
- trustregion_threshold_acceptance: NonNegativeFloat = 0¶
First threshold for accepting the solution vector of the trust-region subproblem as the best candidate.
The candidate is accepted if the ratio of actual to predicted reduction exceeds this value and the model is fully linear (i.e. “valid”).
- trustregion_threshold_successful: NonNegativeFloat = 0.1¶
Second threshold for accepting the solution vector of the trust-region subproblem as the best candidate.
If the ratio of actual to predicted reduction reaches this value, the candidate is accepted even if the model is not fully linear, and the trust-region radius is expanded unless the step is short.
- c1: NonNegativeFloat | None = None¶
Threshold for accepting the norm of the current candidate vector.
Used when searching for affine points in case the set of model-improving points is zero. By default, it is set to sqrt(n), where n is the number of parameters.
- c2: NonNegativeFloat = 10¶
Threshold for accepting the norm of the current candidate vector.
Used when searching for affine points in case the set of model-improving points is not zero. The default is 10.
- trustregion_subproblem_solver: Literal['bntr', 'gqtpar'] = 'bntr'¶
Solver used for the trust-region subproblem.
Two internal solvers are supported: “bntr” (Bounded Newton Trust Region; the default, supports bound constraints) and “gqtpar” (based on [algo_34]; does not support bound constraints).
- trustregion_subsolver_options: dict[str, Any] | None = None¶
Options dictionary containing the stopping criteria for the trust-region subproblem solver.
It takes different keys depending on the subproblem solver used, with the exception of the stopping criterion “maxiter” (default 50), which is always included.
If the subsolver “bntr” is used, the dictionary may additionally contain the tolerance levels “gtol_abs” (default 1e-8), “gtol_rel” (default 1e-8), and “gtol_scaled” (default 0), the maximum number of gradient descent iterations “maxiter_gradient_descent” (default 5), and the “conjugate_gradient_method” used to solve the subproblem. Available conjugate gradient methods are “cg” (with the two additional stopping criteria “gtol_abs_cg”, default 1e-8, and “gtol_rel_cg”, default 1e-6), “steihaug_toint”, and “trsbox” (default).
If the subsolver “gqtpar” is employed, the two stopping criteria are “k_easy” (default 0.1) and “k_hard” (default 0.2).
None of the dictionary keys need to be specified by default, but can be.
- n_cores: PositiveInt = 1¶
Number of processes used to parallelize the function evaluations.
The default is 1 (no parallelization).
Optimizers from the Toolkit for Advanced Optimization (TAO)¶
We wrap the pounders algorithm from the Toolkit for Advanced Optimization. To use it you need to have petsc4py installed.
tao_pounders
How to use this algorithm:
import numpy as np
import optimagic as om
@om.mark.least_squares
def fun(x):
return x
om.minimize(
fun=fun,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.tao_pounders(stopping_maxiter=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
@om.mark.least_squares
def fun(x):
return x
om.minimize(
fun=fun,
params=np.array([1.0, 2.0, 3.0]),
algorithm="tao_pounders",
algo_options={"stopping_maxiter": 1_000},
)
Description and available options:
- class optimagic.optimizers.tao_optimizers.TAOPounders[source]¶
Minimize a nonlinear least-squares problem using the POUNDERS algorithm.
POUNDERS (Practical Optimization Using No Derivatives for sums of Squares, [algo_32]) is a derivative-free trust-region algorithm that is tailored to nonlinear least-squares problems. It is part of the Toolkit for Advanced Optimization (TAO, [algo_33]), which is distributed together with PETSc, and is wrapped in optimagic via petsc4py.
Instead of working only with the scalar sum of squares, POUNDERS exploits the availability of the full vector of residuals: it maintains an interpolation-based quadratic model of each residual around the current iterate (building on the minimal norm Hessian models of [algo_35]) and combines these models according to the known least-squares structure of the objective. Candidate steps are obtained by minimizing the combined model inside a dynamically resized trust region.
Use POUNDERS if your criterion function is a nonlinear sum of squares, evaluating the residuals is expensive (e.g., each evaluation requires a simulation), derivatives are not available, and the residuals are possibly slightly noisy. This makes it a useful tool for economists who estimate structural models using indirect inference or the method of simulated moments. Compared to Levenberg-Marquardt style solvers, which need the Jacobian of the residuals (either analytically or via finite differences, which costs many extra evaluations per iteration and is unreliable for noisy functions), POUNDERS gets by without any derivative information. Compared to derivative-free algorithms that ignore the least-squares structure, such as Nelder-Mead, it typically requires far fewer criterion evaluations to arrive at a local optimum. If the residuals are smooth, cheap to evaluate, and derivatives are available, a derivative-based least-squares solver is usually the better choice.
Scale the problem such that the bounds correspond to the unit hypercube \([0, 1]^n\). For unconstrained problems, scale each parameter such that unit changes in the parameters result in similar order-of-magnitude changes in the criterion value(s).
Note
This algorithm requires the petsc4py package, which is not available on Windows. Windows users can use optimagic’s own
poundersalgorithm instead.- convergence_gtol_abs: NonNegativeFloat = 1e-05¶
Stop if the norm of the gradient falls below this value.
\[\lVert g(X) \rVert \leq \textsf{convergence\_gtol\_abs}\]This is the absolute gradient tolerance
gatolin the TAO documentation. In TAO’s POUNDERS, \(g\) is the gradient of the quadratic model, scaled by the trust-region radius. Setting this option to zero restores TAO’s default (1e-8) instead of disabling the criterion.
- convergence_gtol_rel: NonNegativeFloat = 1e-08¶
Stop if the norm of the gradient relative to the criterion value falls below this value.
\[\frac{\lVert g(X) \rVert}{|f(X)|} \leq \textsf{convergence\_gtol\_rel}\]This is the relative gradient tolerance
grtolin the TAO documentation. Setting this option to zero restores TAO’s default (1e-8) instead of disabling the criterion.
- convergence_gtol_scaled: NonNegativeFloat = 1e-08¶
Stop if the norm of the gradient falls below this fraction of the norm of the gradient at the start parameters \(X_0\).
\[\frac{\lVert g(X) \rVert}{\lVert g(X_0) \rVert} \leq \textsf{convergence\_gtol\_scaled}\]This is the gradient reduction tolerance
gttolin the TAO documentation. Setting this option to zero restores TAO’s default (0), which disables the criterion.
- trustregion_initial_radius: NonNegativeFloat | None = None¶
Initial value of the trust region radius. It must be larger than zero.
If None (the default), the radius is set to \(0.1 \max(\lVert x_0 \rVert_\infty, 1)\), where \(x_0\) are the start parameters.
- stopping_maxiter: PositiveInt = 1000000¶
Maximum number of iterations.
If reached, the optimization stops, but this is not counted as successful convergence. POUNDERS can also stop on its own if the same interpolation model is used in two successive iterations without a change of the trust-region radius (message “step size small”).
Optimizers from the Numerical Algorithms Group (NAG)¶
We wrap two algorithms from the numerical algorithms group. To use them, you need to install each of them separately:
pip install DFO-LSpip install Py-BOBYQA
nag_dfols
How to use this algorithm:
import numpy as np
import optimagic as om
@om.mark.least_squares
def fun(x):
return x
om.minimize(
fun=fun,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nag_dfols(stopping_maxfun=10_000),
)
or using the string interface:
import numpy as np
import optimagic as om
@om.mark.least_squares
def fun(x):
return x
om.minimize(
fun=fun,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nag_dfols",
algo_options={"stopping_maxfun": 10_000},
)
Description and available options:
- class optimagic.optimizers.nag_optimizers.NagDFOLS[source]¶
Minimize a function with least-squares structure using the DFO-LS algorithm.
The DFO-LS algorithm [algo_36] is a model-based derivative-free trust-region algorithm developed by the Numerical Algorithms Group and researchers at the University of Oxford. It is designed to solve the nonlinear least-squares minimization problem (with optional bound constraints)
\[\begin{split}\min_{x\in\mathbb{R}^n} &\quad f(x) := \sum_{i=1}^{m}r_{i}(x)^2 \\ \text{s.t.} &\quad \text{lower\_bounds} \leq x \leq \text{upper\_bounds}\end{split}\]The \(r_{i}\) are the least-squares residuals. To use DFO-LS, decorate your criterion function with
om.mark.least_squaresand return the residuals instead of their sum of squares.DFO-LS is a derivative-free algorithm: it does not require the user to provide the derivatives of \(f(x)\) or \(r_{i}(x)\), nor does it attempt to estimate them internally (by using finite differencing, for instance). Instead, it constructs an interpolation-based model of the residuals that exploits the least-squares structure of the problem and minimizes this model within a trust region.
There are two main situations when using a derivative-free algorithm (such as DFO-LS) is preferable to a derivative-based algorithm (which is the vast majority of least-squares solvers):
If the residuals are noisy, then calculating or even estimating their derivatives may be impossible (or at least very inaccurate). By noisy we mean that if we evaluate \(r_{i}(x)\) multiple times at the same value of x, we get different results. This may happen when a Monte Carlo simulation is used, for instance.
If the residuals are expensive to evaluate, then estimating derivatives (which requires n evaluations of each \(r_{i}(x)\) for every point of interest x) may be prohibitively expensive. Derivative-free methods are designed to solve the problem with the fewest number of evaluations of the criterion as possible.
DFO-LS was developed by the same group as Py-BOBYQA (
nag_pybobyqa), its general-purpose scalar counterpart. If your problem has least-squares structure, DFO-LS typically needs far fewer criterion evaluations than Py-BOBYQA and other scalar optimizers because it exploits this structure.There are five possible convergence criteria:
when the lower trust region radius is shrunk below a minimum (
convergence_minimal_trustregion_radius_tolerance).when the improvements of iterations become very small (
convergence_slow_progress). This is similar to a relative criterion tolerance, but more general, because you can specify not only the threshold for convergence but also a period over which the improvements must have been very small.when a sufficient reduction of the criterion value relative to its value at the start parameters has been reached, i.e. when \(f(x_k)/f(x_0) \leq \textsf{convergence\_ftol\_scaled}\).
when all evaluations on the interpolation points fall within a scaled version of the noise level of the criterion function. This is only applicable if the criterion function is noisy. You can specify this criterion with
convergence_noise_corrected_criterion_tolerance.when the criterion value falls below 1e-12. This is
model.abs_tolin the DFO-LS documentation and cannot be changed through optimagic.
If resets are enabled (see
trustregion_reset_options; this is the default for noisy criterion functions), criteria 1, 2 and 4 trigger a reset instead of terminating the optimization.DFO-LS supports resetting the optimization and doing a fast start by starting with a smaller interpolation set and growing it dynamically. For more information see the detailed DFO-LS documentation and [algo_36].
Remember to cite [algo_36] when using DFO-LS in addition to optimagic.
Note
We recommend to install DFO-LS version 1.5.3 or higher. Versions 1.5.0 or lower also work, but the versions 1.5.1 and 1.5.2 contain bugs that can lead to errors being raised.
Note
The following arguments of
dfols.solveare not supported by optimagic:scaling_within_bounds,init.run_in_parallel,do_logging,print_progressand all their advanced options.- clip_criterion_if_overflowing: bool = True¶
Whether to clip the criterion if it would raise an
OverflowErrorotherwise.
- convergence_minimal_trustregion_radius_tolerance: NonNegativeFloat = 1e-08¶
Stop when the lower trust-region radius falls below this value.
If resets are enabled, a reset is triggered instead. This criterion is approximately equivalent to an absolute parameter tolerance and corresponds to
rhoendin the DFO-LS documentation, from which the default value is taken.
- convergence_noise_corrected_criterion_tolerance: NonNegativeFloat = 1.0¶
Stop when the evaluations on the set of interpolation points all fall within this factor of the noise level.
If resets are enabled (the default for noisy criterion functions), a reset is triggered instead. The default is 1, i.e. when all evaluations are within the noise level. If you want to not use this criterion but still flag your criterion function as noisy, set this tolerance to 0.0.
Warning
Very small values, as in most other tolerances, don’t make sense here.
- convergence_ftol_scaled: NonNegativeFloat = 0.0¶
Stop if the criterion value falls below this fraction of its value at the start parameters, i.e. terminate if \(f(x_k)/f(x_0) \leq \textsf{convergence\_ftol\_scaled}\) is reached.
This is
model.rel_tolin the DFO-LS documentation. With the default of 0.0 this criterion is deactivated. Note that DFO-LS additionally stops successfully when the criterion value falls below 1e-12 (model.abs_tol), which cannot be changed through optimagic.
- convergence_slow_progress: dict[str, Any] | None = None¶
Specification of when to terminate (or reset) the optimization because of only slow improvements.
This is similar to a relative criterion tolerance, only that instead of a single improvement the average improvement over several iterations must be small. DFO-LS measures improvements in \(\log f\). Possible entries are:
threshold_to_characterize_as_slow(float): Threshold whether an improvement is insufficient. Note that the improvement is divided by thecomparison_period, so this is the required average improvement per iteration over the comparison period. Default is 1e-8, whereas DFO-LS itself defaults to 1e-4.max_insufficient_improvements(int): Number of consecutive insufficient improvements before termination (or reset). Default is20 * len(x).comparison_period(int): How many iterations to go back to calculate the improvement. For example 5 would mean that each criterion evaluation is compared to the criterion value from 5 iterations before. Default is 5.
- initial_directions: Literal['coordinate', 'random'] = 'coordinate'¶
Whether to draw the initial directions used to build the first interpolation set as coordinate directions (“coordinate”) or random directions (“random”).
- interpolation_rounding_error: float = 0.1¶
Scaling factor that controls when the interpolation base point is re-centered to reduce roundoff errors.
Internally, all the NAG algorithms store interpolation points with respect to a base point \(x_b\); that is, they store \(\{y_t - x_b\}\), which reduces the risk of roundoff errors. The base point \(x_b\) is shifted to the current iterate \(x_k\) when \(\text{proposed step} \leq \textsf{interpolation\_rounding\_error} \cdot \|x_k - x_b\|\). This is
general.rounding_error_constantin the DFO-LS documentation, from which the default value is taken.
- noise_additive_level: float | None = None¶
Amount of additive noise in the criterion function.
It is used for determining the presence of noise and for the convergence criterion that all evaluations on the interpolation points are within the noise level. 0 means no additive noise. Only additive or multiplicative noise can be specified, not both.
- noise_multiplicative_level: float | None = None¶
Amount of multiplicative noise in the criterion function.
It is used for determining the presence of noise and for the convergence criterion that all evaluations on the interpolation points are within the noise level. 0 means no multiplicative noise. Only additive or multiplicative noise can be specified, not both.
- noise_n_evals_per_point: NonNegativeInt | None = None¶
How often to evaluate the criterion function at each point.
This is only applicable for criterion functions with noise, when averaging multiple evaluations at the same point produces a more accurate value. The solver calls the value positionally as
f(upper_trustregion_radius, lower_trustregion_radius, n_iterations, n_resets)(i.e. with \(\Delta\), \(\rho\), the number of iterations and the number of resets) and expects the number of evaluations as an integer. The default is no averaging, i.e. to evaluate the criterion only once at each point.Warning
Currently, only the default
Noneworks: a callable is rejected by the validation of algorithm options (InvalidAlgoOptionError), and an integer raises aTypeErrorinside the solver because it is not callable.
- random_directions_orthogonal: bool = True¶
Whether to make randomly drawn initial directions orthogonal.
This is only relevant if
initial_directionsis “random”.
- stopping_maxfun: PositiveInt = 1000000¶
Maximum number of criterion evaluations.
If reached, the optimization stops, but this is not counted as successful convergence.
- threshold_for_safety_step: NonNegativeFloat = 0.5¶
Threshold for when to call the safety step (\(\gamma_s\)).
A safety step is called when \(\text{proposed step} \leq \textsf{threshold\_for\_safety\_step} \cdot \rho_k\), where \(\rho_k\) is the current lower trust-region radius. The default value is taken from DFO-LS.
- trustregion_expansion_factor_successful: NonNegativeFloat = 2.0¶
Ratio by which to expand the upper trust-region radius \(\Delta_k\) in very successful iterations (\(\gamma_{inc}\) in the notation of the paper).
The default value is taken from DFO-LS.
- trustregion_expansion_factor_very_successful: NonNegativeFloat = 4.0¶
Ratio of the proposed step (\(\|s_k\|\)) by which to expand the upper trust-region radius (\(\Delta_k\)) in very successful iterations (\(\overline{\gamma}_{inc}\) in the notation of the paper).
The default value is taken from DFO-LS.
- trustregion_fast_start_options: dict[str, Any] | None = None¶
Options to start the optimization while building the full trust-region model.
To activate this, set the number of interpolation points at which to evaluate the criterion before doing the first step (
min_inital_points) to something smaller than the number of parameters. Possible entries are:min_inital_points(int): Number of initial interpolation points in addition to the start point. This should only be changed to a value less thanlen(x), and only if the default setup cost oflen(x) + 1evaluations of the criterion is impractical. In that case, keeptrustregion_n_interpolation_pointsat its default oflen(x) + 1(DFO-LS requires at leastlen(x) + 1interpolation points). If the default is used, all the other parameters have no effect. Default istrustregion_n_interpolation_points - 1. If the default setup costs of the evaluations are very large, DFO-LS can start with less thanlen(x)interpolation points and add points to the trust-region model with every iteration. Note that the option name is indeedmin_inital_points, i.e. it contains a spelling mistake.method(“jacobian”, “trustregion” or “auto”): When there are less interpolation points thanlen(x), the model is underdetermined. This can be fixed in two ways: If “jacobian”, the interpolated Jacobian is perturbed to have full rank, allowing the trust-region step to include components in the full search space. If “trustregion”, the trust-region step is perturbed by an orthogonal direction not yet searched. The default is “auto”. Note that in optimagic “auto” currently always behaves like “jacobian”: DFO-LS’s automatic switch to “trustregion” when there are fewer residuals than parameters is not triggered. Set “trustregion” explicitly in that case.scale_of_trustregion_step_perturbation(float): When adding new search directions, the length of the step is the trust-region radius multiplied by this value. The default is 1.scale_of_jacobian_components_perturbation(float): Magnitude of the extra components added to the Jacobian. The default is 1e-2.floor_of_jacobian_singular_values(float): Floor the singular values of the Jacobian at this factor of the last non-zero value. This option currently has no effect: optimagic does not pass it to DFO-LS and raises a warning if it is not 1, so DFO-LS’s default factor of 1 is always used.jacobian_max_condition_number(float): Cap on the condition number of the Jacobian after applying floors to singular values (effectively another floor on the smallest singular value, since the largest singular value is fixed).geometry_improving_steps(bool): Whether to do geometry-improving steps in the trust-region algorithm, as per the usual algorithm during the fast start.safety_steps(bool): Whether to perform safety steps.shrink_upper_radius_in_safety_steps(bool): During the fast start, whether to shrink the upper trust-region radius in safety steps.full_geometry_improving_step(bool): During the fast start, whether to do a full geometry-improving step within safety steps (the same as the post fast start phase of the algorithm). Since this involves reducing the upper trust-region radius, this can only beTrueifshrink_upper_radius_in_safety_stepsisFalse.reset_trustregion_radius_after_fast_start(bool): Whether to reset the upper trust-region radius to its initial value at the end of the fast start phase.reset_min_trustregion_radius_after_fast_start(bool): Whether to reset the minimum trust-region radius (\(\rho_k\)) to its initial value at the end of the fast start phase.shrinking_factor_not_successful(float): Ratio by which to shrink the trust-region radius when the realized improvement does not match thetrustregion_threshold_successfulduring the fast start phase. The default is 0.98 if the criterion is noisy and 0.5 else, i.e. DFO-LS’s default oftrustregion_shrinking_factor_not_successful. It does not follow a user-specified value of that option.n_extra_search_directions_per_iteration(int): Number of new search directions to add with each iteration where we do not have a full set of search directions. This approach is not recommended! Default is 0.
- trustregion_initial_radius: NonNegativeFloat | None = None¶
Initial value of the trust-region radius.
This is
rhobegin the DFO-LS documentation. By default it is set to \(0.1 \max(\|x_0\|_{\infty}, 1)\), as in DFO-LS.
- trustregion_method_to_replace_extra_points: Literal['geometry_improving', 'momentum'] | None = 'geometry_improving'¶
If replacing extra points in successful iterations, whether to use geometry improving steps (“geometry_improving”) or the momentum method (“momentum”).
This is only relevant if
trustregion_n_extra_points_to_replace_successful > 0.
- trustregion_n_extra_points_to_replace_successful: NonNegativeInt = 0¶
The number of extra points (other than accepting the trust-region step) to replace in successful iterations.
This is
regression.num_extra_stepsin the DFO-LS documentation. It is useful whentrustregion_n_interpolation_points > len(x) + 1.
- trustregion_n_interpolation_points: NonNegativeInt | None = None¶
The number of interpolation points to use.
This is
nptin the DFO-LS documentation. The default islen(x) + 1, as in DFO-LS. If using resets, this is the number of points to use in the first run of the solver, before any resets.
- trustregion_precondition_interpolation: bool = True¶
Whether to scale the interpolation linear system to improve conditioning.
The default value is taken from DFO-LS.
- trustregion_reset_options: dict[str, Any] | None = None¶
Options for resetting the optimization.
Possible entries are:
use_resets(bool): Whether to do resets when the lower trust-region radius (\(\rho_k\)) reaches the stopping criterion (\(\rho_{end}\)), or (optionally) when all interpolation points are within the noise level. The default isTrueif the criterion is noisy.minimal_trustregion_radius_tolerance_scaling_at_reset(float): Factor with which the trust-region stopping criterion is multiplied at each reset.reset_type(str): Whether to use “soft” or “hard” resets. The default is “soft”.move_center_at_soft_reset(bool): Whether to move the trust-region center (\(x_k\)) to the best new point evaluated instead of keeping it constant.points_to_replace_at_soft_reset(int): Number of interpolation points to move at each soft reset.reuse_criterion_value_at_hard_reset(bool): Whether or not to recycle the criterion value at the best iterate found when performing a hard reset. This saves one criterion evaluation.max_iterations_without_new_best_after_soft_reset(int): The maximum number of successful steps in a given run where the new criterion value is worse than the best value found in previous runs before terminating. The default isstopping_maxfun.auto_detect(bool): Whether or not to automatically determine when to reset. This is an additional condition and resets can still be triggered by a small upper trust-region radius, etc. There are two criteria used: upper trust-region radius shrinkage (no increases over the history, more decreases than no changes) and changes in the model Jacobian (consistently increasing trend as measured by the slope and correlation coefficient of the line of best fit).auto_detect_history(int): How many iterations of model changes and trust region radii to store.auto_detect_min_jacobian_increase(float): Minimum rate of increase of \(\log(\|J_k - J_{k-1}\|_F)\), i.e. of the change in the model Jacobian, over past iterations to cause a reset.auto_detect_min_correlations(float): Minimum correlation of the data set \((k, \log(\|J_k - J_{k-1}\|_F))\) required to cause a reset.max_consecutive_unsuccessful_resets(int): Maximum number of consecutive unsuccessful resets allowed (i.e. resets which did not outperform the best known value from earlier runs).max_interpolation_points(int): Maximum allowed value of the number of interpolation points. This is useful if the number of interpolation points increases with each reset, e.g. whenn_extra_interpolation_points_per_soft_reset > 0. The default istrustregion_n_interpolation_points.n_extra_interpolation_points_per_soft_reset(int): Number of points to add to the interpolation set with each reset (soft or hard). The default is 0.n_extra_interpolation_points_per_hard_reset(int): With each hard reset, the number of initial search directions is increased by the difference between this value andn_extra_interpolation_points_per_soft_reset. It must therefore be at leastn_extra_interpolation_points_per_soft_reset; otherwise DFO-LS rejects the input and the optimization fails with an error. The default is 0.n_additional_extra_points_to_replace_per_reset(int): This parameter modifiestrustregion_n_extra_points_to_replace_successful. With each reset it is increased by this number.
- trustregion_shrinking_factor_not_successful: NonNegativeFloat | None = None¶
Ratio by which to shrink the upper trust-region radius when the realized improvement does not match the
trustregion_threshold_successful.This is
tr_radius.gamma_decin the DFO-LS documentation. The default is 0.98 if the criterion is noisy and 0.5 else, as in DFO-LS.
- trustregion_shrinking_factor_lower_radius: NonNegativeFloat | None = None¶
Ratio by which to shrink the lower trust-region radius (\(\rho_k\)) (\(\alpha_1\) in the notation of the paper).
The default is 0.9 if the criterion is noisy and 0.1 else, as in DFO-LS.
- trustregion_shrinking_factor_upper_radius: NonNegativeFloat | None = None¶
Ratio of the current lower trust-region radius (\(\rho_k\)) by which to shrink the upper trust-region radius (\(\Delta_k\)) when the lower one is shrunk (\(\alpha_2\) in the notation of the paper).
The default is 0.95 if the criterion is noisy and 0.5 else, as in DFO-LS.
nag_pybobyqa
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nag_pybobyqa(
convergence_minimal_trustregion_radius_tolerance=1e-6,
),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nag_pybobyqa",
algo_options={"convergence_minimal_trustregion_radius_tolerance": 1e-6},
)
Description and available options:
- class optimagic.optimizers.nag_optimizers.NagPyBOBYQA[source]¶
Minimize a scalar function using the BOBYQA algorithm.
BOBYQA ([algo_37], [algo_38], [algo_39]) is a derivative-free trust-region method. It is designed to solve nonlinear local minimization problems (with optional bound constraints).
This wraps Py-BOBYQA, a flexible Python implementation of Powell’s BOBYQA (Bound Optimization BY Quadratic Approximation, [algo_37]) developed by the Numerical Algorithms Group and researchers at the University of Oxford [algo_38]. In each iteration, the algorithm builds a quadratic model that interpolates the criterion function at a set of points and minimizes this model within a trust region. Compared to Powell’s original implementation, Py-BOBYQA adds features for noisy problems (averaging of multiple evaluations and noise-aware termination), multiple restarts, and a heuristic for escaping local minima (
seek_global_optimum, [algo_39]).Remember to cite [algo_37] and [algo_38] when using Py-BOBYQA in addition to optimagic. If you take advantage of the
seek_global_optimumoption, cite [algo_39] additionally.There are two main situations when using a derivative-free algorithm like BOBYQA is preferable to derivative-based algorithms:
The criterion function is not deterministic, i.e. if we evaluate the criterion function multiple times at the same parameter vector we get different results.
The criterion function is very expensive to evaluate and only finite differences are available to calculate its derivative.
Py-BOBYQA was developed by the same group as DFO-LS (
nag_dfols). If your criterion function has least-squares structure, usenag_dfolsinstead, which exploits this structure and typically needs far fewer criterion evaluations.The detailed documentation of the algorithm can be found in the Py-BOBYQA documentation.
There are four possible convergence criteria:
when the lower trust-region radius is shrunk below a minimum (
convergence_minimal_trustregion_radius_tolerance). This is approximately equivalent to an absolute parameter tolerance.when the criterion value falls below an absolute, user-specified value (
convergence_criterion_value), the optimization terminates successfully.when insufficient improvements have been gained over a certain number of iterations (
convergence_slow_progress). The (absolute) threshold for what constitutes an insufficient improvement, how many iterations have to be insufficient and with which iteration to compare can all be specified by the user.when all evaluations on the interpolation points fall within a scaled version of the noise level of the criterion function (
convergence_noise_corrected_criterion_tolerance). This is only applicable if the criterion function is noisy.
If resets are enabled (see
trustregion_reset_options; this is the default for noisy criterion functions and ifseek_global_optimumisTrue), criteria 1, 3 and 4 trigger a reset instead of terminating the optimization.Note
The following arguments of
pybobyqa.solveare not supported by optimagic:scaling_within_bounds,init.run_in_parallel,do_logging,print_progressand all their advanced options.- clip_criterion_if_overflowing: bool = True¶
Whether to clip the criterion if it would raise an
OverflowErrorotherwise.
- convergence_minimal_trustregion_radius_tolerance: NonNegativeFloat = 1e-08¶
Stop when the lower trust-region radius falls below this value.
If resets are enabled, a reset is triggered instead. This criterion is approximately equivalent to an absolute parameter tolerance and corresponds to
rhoendin the Py-BOBYQA documentation, from which the default value is taken.
- convergence_noise_corrected_criterion_tolerance: NonNegativeFloat = 1.0¶
Stop when the evaluations on the set of interpolation points all fall within this factor of the noise level.
If resets are enabled (the default for noisy criterion functions), a reset is triggered instead. The default is 1, i.e. when all evaluations are within the noise level. If you want to not use this criterion but still flag your criterion function as noisy, set this tolerance to 0.0.
Warning
Very small values, as in most other tolerances, don’t make sense here.
- convergence_criterion_value: float | None = None¶
Terminate successfully if the criterion value falls below this threshold.
This is deactivated (i.e. set to -inf) by default. It is
model.abs_tolin the Py-BOBYQA documentation.
- convergence_slow_progress: dict[str, Any] | None = None¶
Specification of when to terminate (or reset) the optimization because of only slow improvements.
This is similar to an absolute criterion tolerance, only that instead of a single improvement the average improvement over several iterations must be small. Possible entries are:
threshold_to_characterize_as_slow(float): Threshold whether an improvement is insufficient. Note that the improvement is divided by thecomparison_period, so this is the required average improvement per iteration over the comparison period. Default is 1e-8.max_insufficient_improvements(int): Number of consecutive insufficient improvements before termination (or reset). Default is20 * len(x).comparison_period(int): How many iterations to go back to calculate the improvement. For example 5 would mean that each criterion evaluation is compared to the criterion value from 5 iterations before. Default is 5.
- initial_directions: Literal['coordinate', 'random'] = 'coordinate'¶
Whether to draw the initial directions used to build the first interpolation set as coordinate directions (“coordinate”) or random directions (“random”).
- interpolation_rounding_error: float = 0.1¶
Scaling factor that controls when the interpolation base point is re-centered to reduce roundoff errors.
Internally, all the NAG algorithms store interpolation points with respect to a base point \(x_b\); that is, they store \(\{y_t - x_b\}\), which reduces the risk of roundoff errors. The base point \(x_b\) is shifted to the current iterate \(x_k\) when \(\text{proposed step} \leq \textsf{interpolation\_rounding\_error} \cdot \|x_k - x_b\|\). This is
general.rounding_error_constantin the Py-BOBYQA documentation, from which the default value is taken.
- noise_additive_level: float | None = None¶
Amount of additive noise in the criterion function.
It is used for determining the presence of noise and for the convergence criterion that all evaluations on the interpolation points are within the noise level. 0 means no additive noise. Only additive or multiplicative noise can be specified, not both.
- noise_multiplicative_level: float | None = None¶
Amount of multiplicative noise in the criterion function.
It is used for determining the presence of noise and for the convergence criterion that all evaluations on the interpolation points are within the noise level. 0 means no multiplicative noise. Only additive or multiplicative noise can be specified, not both.
- noise_n_evals_per_point: NonNegativeInt | None = None¶
How often to evaluate the criterion function at each point.
This is only applicable for criterion functions with noise, when averaging multiple evaluations at the same point produces a more accurate value. The solver calls the value positionally as
f(upper_trustregion_radius, lower_trustregion_radius, n_iterations, n_resets)(i.e. with \(\Delta\), \(\rho\), the number of iterations and the number of resets) and expects the number of evaluations as an integer. The default is no averaging, i.e. to evaluate the criterion only once at each point.Warning
Currently, only the default
Noneworks: a callable is rejected by the validation of algorithm options (InvalidAlgoOptionError), and an integer raises aTypeErrorinside the solver because it is not callable.
- random_directions_orthogonal: bool = True¶
Whether to make randomly drawn initial directions orthogonal.
This is only relevant if
initial_directionsis “random”.
- seek_global_optimum: bool = False¶
Whether to apply the heuristic to escape local minima presented in [algo_39].
The heuristic repeatedly restarts the optimization from the best point found so far with an enlarged trust-region radius. It is only a heuristic, so there is no guarantee that the global optimum is found. To use it, both lower and upper bounds must be specified (individual entries may be infinite); otherwise Py-BOBYQA rejects the input and the optimization fails with an error.
Setting this to
Truealso changes the defaults of theuse_resets,max_unsuccessful_resetsandtrust_region_scaling_at_unsuccessful_resetentries oftrustregion_reset_options.
- stopping_max_criterion_evaluations: PositiveInt = 1000000¶
Maximum number of criterion evaluations.
If reached, the optimization stops, but this is not counted as successful convergence.
- threshold_for_safety_step: NonNegativeFloat = 0.5¶
Threshold for when to call the safety step (\(\gamma_s\)).
A safety step is called when \(\text{proposed step} \leq \textsf{threshold\_for\_safety\_step} \cdot \rho_k\), where \(\rho_k\) is the current lower trust-region radius. The default value is taken from Py-BOBYQA.
- trustregion_expansion_factor_successful: NonNegativeFloat = 2.0¶
Ratio by which to expand the upper trust-region radius \(\Delta_k\) in very successful iterations (\(\gamma_{inc}\) in the notation of the paper).
The default value is taken from Py-BOBYQA.
- trustregion_expansion_factor_very_successful: NonNegativeFloat = 4.0¶
Ratio of the proposed step (\(\|s_k\|\)) by which to expand the upper trust-region radius (\(\Delta_k\)) in very successful iterations (\(\overline{\gamma}_{inc}\) in the notation of the paper).
The default value is taken from Py-BOBYQA.
- trustregion_initial_radius: NonNegativeFloat | None = None¶
Initial value of the trust-region radius.
This is
rhobegin the Py-BOBYQA documentation. By default it is set to \(0.1 \max(\|x_0\|_{\infty}, 1)\), as in Py-BOBYQA.
- trustregion_minimum_change_hession_for_underdetermined_interpolation: bool = True¶
Whether to solve the underdetermined quadratic interpolation problem by minimizing the Frobenius norm of the change in the Hessian.
If True (the default, as in Py-BOBYQA and Powell’s original BOBYQA), the quadratic model is chosen such that the Frobenius norm of the change in its Hessian relative to the previous iteration is minimal. If False, the Frobenius norm of the Hessian itself is minimized. This is
interpolation.minimum_change_hessianin the Py-BOBYQA documentation.
- trustregion_n_interpolation_points: NonNegativeInt | None = None¶
The number of interpolation points to use.
This is
nptin the Py-BOBYQA documentation. With \(n\) =len(x), the default is \(2n+1\) if the criterion is not noisy. Otherwise, it is set to \((n+1)(n+2)/2\). Larger values are particularly useful for noisy problems. Py-BOBYQA requires\[n + 1 \leq \textsf{trustregion\_n\_interpolation\_points} \leq (n+1)(n+2)/2.\]
- trustregion_precondition_interpolation: bool = True¶
Whether to scale the interpolation linear system to improve conditioning.
The default value is taken from Py-BOBYQA.
- trustregion_reset_options: dict[str, Any] | None = None¶
Options for resetting the optimization.
Possible entries are:
use_resets(bool): Whether to do resets when the lower trust-region radius (\(\rho_k\)) reaches the stopping criterion (\(\rho_{end}\)), or (optionally) when all interpolation points are within the noise level. The default isTrueif the criterion is noisy orseek_global_optimumisTrue, andFalseelse.minimal_trustregion_radius_tolerance_scaling_at_reset(float): Factor with which the trust-region stopping criterion is multiplied at each reset.reset_type(str): Whether to use “soft” or “hard” resets. The default is “soft”.move_center_at_soft_reset(bool): Whether to move the trust-region center (\(x_k\)) to the best new point evaluated instead of keeping it constant.points_to_replace_at_soft_reset(int): Number of interpolation points to move at each soft reset.reuse_criterion_value_at_hard_reset(bool): Whether or not to recycle the criterion value at the best iterate found when performing a hard reset. This saves one criterion evaluation.max_iterations_without_new_best_after_soft_reset(int): The maximum number of successful steps in a given run where the new criterion value is worse than the best value found in previous runs before terminating. The default isstopping_max_criterion_evaluations.auto_detect(bool): Whether or not to automatically determine when to reset. This is an additional condition and resets can still be triggered by a small upper trust-region radius, etc. There are two criteria used: upper trust-region radius shrinkage (no increases over the history, more decreases than no changes) and changes in the model gradient and Hessian (consistently increasing trend as measured by the slope and correlation coefficient of the line of best fit).auto_detect_history(int): How many iterations of model changes and trust region radii to store.auto_detect_min_jacobian_increase(float): Minimum rate of increase of \(\log(\|g_k - g_{k-1}\|)\) and \(\log(\|H_k - H_{k-1}\|_F)\), i.e. of the changes in the model gradient and Hessian, over past iterations to cause a reset.auto_detect_min_correlations(float): Minimum correlation of the data sets \((k, \log(\|g_k - g_{k-1}\|))\) and \((k, \log(\|H_k - H_{k-1}\|_F))\) required to cause a reset.max_consecutive_unsuccessful_resets(int): Maximum number of consecutive unsuccessful resets allowed (i.e. resets which did not outperform the best known value from earlier runs).max_unsuccessful_resets(int): Number of total unsuccessful resets allowed. The default is 20 ifseek_global_optimumand else unrestricted.trust_region_scaling_at_unsuccessful_reset(float): Factor by which to expand the initial lower trust-region radius (\(\rho_{beg}\)) after unsuccessful resets. The default is 1.1 ifseek_global_optimumelse 1.
- trustregion_shrinking_factor_not_successful: NonNegativeFloat | None = None¶
Ratio by which to shrink the upper trust-region radius when the realized improvement does not match the
trustregion_threshold_successful.This is
tr_radius.gamma_decin the Py-BOBYQA documentation. The default is 0.98 if the criterion is noisy and 0.5 else, as in Py-BOBYQA.
- trustregion_shrinking_factor_lower_radius: NonNegativeFloat | None = None¶
Ratio by which to shrink the lower trust-region radius (\(\rho_k\)) (\(\alpha_1\) in the notation of the paper).
The default is 0.9 if the criterion is noisy and 0.1 else, as in Py-BOBYQA.
- trustregion_shrinking_factor_upper_radius: NonNegativeFloat | None = None¶
Ratio of the current lower trust-region radius (\(\rho_k\)) by which to shrink the upper trust-region radius (\(\Delta_k\)) when the lower one is shrunk (\(\alpha_2\) in the notation of the paper).
The default is 0.95 if the criterion is noisy and 0.5 else, as in Py-BOBYQA.
PYGMO2 Optimizers¶
Please cite [algo_40] in addition to optimagic when using pygmo. optimagic supports the following pygmo2 optimizers.
pygmo_gaco
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pygmo_gaco(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pygmo_gaco",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.pygmo_optimizers.PygmoGaco[source]¶
Minimize a scalar function using the extended ant colony algorithm (GACO).
The version available through pygmo is an extension of the extended ant colony optimization algorithm proposed by [algo_41]. It differs from the original in how two of the three pheromone values (the weights and the standard deviations) are computed.
Ant colony optimization is a class of optimization algorithms modeled on the actions of an ant colony. Artificial “ants” (e.g. simulation agents) locate optimal solutions by moving through a parameter space representing all possible solutions. Real ants lay down pheromones directing each other to resources while exploring their environment. The simulated “ants” similarly record their positions and the quality of their solutions, so that in later simulation iterations more ants locate better solutions.
The extended ant colony algorithm generates future generations of ants by using a multi-kernel gaussian distribution based on three parameters (i.e., pheromone values) which are computed depending on the quality of each previous solution. The solutions are ranked through an oracle penalty method.
Like most pygmo optimizers wrapped by optimagic, this is a global, derivative-free, population based algorithm. It is a good choice for multimodal problems where no derivatives are available and a large budget of function evaluations is affordable. In contrast to most other pygmo algorithms, it supports parallel function evaluation via
n_cores. For smooth problems with only one optimum, local optimizers are much more efficient.The algorithm requires finite bounds on all parameters.
- population_size: int | None = None¶
Size of the population. If None, it is set to
10 * (n_params + 1), but at least 64.
- seed: int | None = None¶
Seed used to sample the initial population and by the pygmo algorithm.
If None, runs are not reproducible.
- discard_start_params: bool = False¶
If True, the start parameters are not guaranteed to be part of the initial population.
This saves one criterion function evaluation that cannot be done in parallel with other evaluations. Default False.
- stopping_maxiter: PositiveInt = 250¶
Number of generations to evolve (the
genparameter in pygmo).
- kernel_size: PositiveInt = 63¶
Number of solutions stored in the solution archive (the
kerparameter in pygmo).It must be at least 2 and not larger than
population_size. The default value is taken from pygmo.
- speed_parameter_q: PositiveFloat = 1.0¶
This parameter manages the convergence speed towards the found minima (the smaller the faster).
In the pygmo documentation it is referred to as \(q\). It must be positive and can be larger than 1. The default is 1.0 until
thresholdis reached. Then it is set to 0.01 automatically. With the defaultthresholdof 1, this happens in the first generation already, sospeed_parameter_qonly has an effect ifthresholdis larger than 1.
- accuracy: PositiveFloat = 0.01¶
Accuracy parameter for maintaining a minimum penalty function’s values distances.
- threshold: PositiveInt = 1¶
When the generation counter reaches the threshold, the convergence speed
speed_parameter_qis set to 0.01 automatically.It must lie between 1 and
stopping_maxiter. To deactivate this effect, set the threshold tostopping_maxiter, which is the largest allowed value.
- speed_of_std_values_convergence: int = 7¶
Parameter that determines the convergence speed of the standard deviations.
This must be an integer (the
n_gen_markparameter in pygmo and pagmo).
- stopping_max_n_without_improvements: PositiveInt = 100000¶
If a positive integer is assigned here, the algorithm counts the runs without improvements; if this number exceeds the given value, the algorithm is stopped (the
impstopparameter in pygmo).
- stopping_maxfun: PositiveInt = 1000¶
Stop after this many consecutive generations without improvement of the best solution found so far (the
evalstopparameter in pygmo).Despite its name, this is not a limit on the number of function evaluations.
- focus: NonNegativeFloat = 0.0¶
This parameter makes the search for the optimum greedier and more focused on local improvements (the higher the greedier).
If the value is very high, the search is more focused around the current best solutions. Values larger than 1 are allowed.
pygmo_bee_colony
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pygmo_bee_colony(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pygmo_bee_colony",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.pygmo_optimizers.PygmoBeeColony[source]¶
Minimize a scalar function using the artificial bee colony algorithm.
The artificial bee colony algorithm (ABC) was originally proposed by [algo_42]. The implemented version of the algorithm is the one proposed in [algo_43].
The algorithm mimics the foraging behavior of a honey bee swarm: employed bees exploit known food sources (candidate solutions), onlooker bees pick promising sources based on their quality, and in each generation the food source with the most unsuccessful trials is abandoned and replaced by a random new one if it could not be improved for
max_n_trialstrials.It is a global, derivative-free, population based algorithm that is suited for multimodal problems where no derivatives are available and many function evaluations are affordable. For smooth problems with only one optimum, local optimizers are much more efficient.
The algorithm requires finite bounds on all parameters.
- stopping_maxiter: PositiveInt = 250¶
Number of generations to evolve (the
genparameter in pygmo).
- seed: int | None = None¶
Seed used to sample the initial population and by the pygmo algorithm.
If None, runs are not reproducible.
- discard_start_params: bool = False¶
If True, the start parameters are not guaranteed to be part of the initial population.
This saves one criterion function evaluation that cannot be done in parallel with other evaluations. Default False.
- max_n_trials: PositiveInt = 1¶
Maximum number of trials for abandoning a food source (the
limitparameter in pygmo).optimagic uses a default of 1, whereas pygmo’s default is 20.
pygmo_de
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pygmo_de(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pygmo_de",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.pygmo_optimizers.PygmoDe[source]¶
Minimize a scalar function using the differential evolution algorithm.
Differential evolution (DE) is a heuristic global optimizer originally presented in [algo_19]. It maintains a population of candidate solutions and creates new candidates by combining existing ones according to a simple mutation and crossover recipe, keeping a new candidate whenever it improves upon the population member it replaces.
DE is derivative-free and copes well with multimodal and non-smooth scalar problems. Like all population based algorithms, it needs many function evaluations, so local optimizers should be preferred for smooth problems with only one optimum.
The algorithm requires finite bounds on all parameters.
- population_size: int | None = None¶
Size of the population. If None, it is set to
10 * (n_params + 1), but at least 10.
- seed: int | None = None¶
Seed used to sample the initial population and by the pygmo algorithm.
If None, runs are not reproducible.
- discard_start_params: bool = False¶
If True, the start parameters are not guaranteed to be part of the initial population.
This saves one criterion function evaluation that cannot be done in parallel with other evaluations. Default False.
- stopping_maxiter: PositiveInt = 250¶
Number of generations to evolve (the
genparameter in pygmo).
- weight_coefficient: NonNegativeFloat = 0.8¶
Weight coefficient, denoted by \(F\) in the differential evolution literature.
It controls the amplification of the differential variation \((x_{r_2, G} - x_{r_3, G})\). The original paper allows values in [0, 2], but the pygmo implementation requires the value to lie in [0, 1]. The default value is taken from pygmo.
- crossover_probability: NonNegativeFloat = 0.9¶
Crossover probability. It must lie in [0, 1]. The default value is taken from pygmo.
- mutation_variant: Literal['best/1/exp', 'rand/1/exp', 'rand-to-best/1/exp', 'best/2/exp', 'rand/2/exp', 'best/1/bin', 'rand/1/bin', 'rand-to-best/1/bin', 'best/2/bin', 'rand/2/bin'] = 'rand/1/exp'¶
Mutation variant used to create a new candidate individual.
The default is “rand/1/exp”. The following variants are available; the corresponding pygmo integer code is given in parentheses for reference, but only the names are accepted:
“best/1/exp” (1)
“rand/1/exp” (2)
“rand-to-best/1/exp” (3)
“best/2/exp” (4)
“rand/2/exp” (5)
“best/1/bin” (6)
“rand/1/bin” (7)
“rand-to-best/1/bin” (8)
“best/2/bin” (9)
“rand/2/bin” (10)
- convergence_criterion_tolerance: NonNegativeFloat = 1e-06¶
Stop when the absolute difference between the best and the worst objective value in the population is smaller than this value (the
ftolparameter in pygmo).The default value is taken from pygmo.
- convergence_relative_params_tolerance: NonNegativeFloat = 1e-05¶
Stop when the sum of absolute differences between the best and the worst parameter vector in the population is smaller than this value (the
xtolparameter in pygmo).In pygmo the default is 1e-6, but optimagic uses its default value of 1e-5.
pygmo_sea
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pygmo_sea(stopping_maxiter=5_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pygmo_sea",
algo_options={"stopping_maxiter": 5_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.pygmo_optimizers.PygmoSea[source]¶
Minimize a scalar function using the (N+1)-ES simple evolutionary algorithm.
This algorithm represents the simplest evolutionary strategy: a population of \(\lambda\) individuals produces one offspring per generation by mutating its best individual uniformly at random within the bounds. Should the offspring be better than the worst individual in the population, it will substitute it. See [algo_44] for a time-complexity analysis of this kind of evolutionary algorithm.
Each generation computes the objective function only once, so progress is slow but the algorithm is extremely simple and robust. It is mainly useful as a baseline for other global, derivative-free optimizers on multimodal problems.
The algorithm requires finite bounds on all parameters.
- population_size: int | None = None¶
Size of the population. If None, it is set to
10 * (n_params + 1), but at least 10.
- seed: int | None = None¶
Seed used to sample the initial population and by the pygmo algorithm.
If None, runs are not reproducible.
- discard_start_params: bool = False¶
If True, the start parameters are not guaranteed to be part of the initial population.
This saves one criterion function evaluation that cannot be done in parallel with other evaluations. Default False.
- stopping_maxiter: PositiveInt = 10000¶
Number of generations to evolve (the
genparameter in pygmo).Each generation computes the objective function once.
pygmo_sga
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pygmo_sga(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pygmo_sga",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.pygmo_optimizers.PygmoSga[source]¶
Minimize a scalar function using a simple genetic algorithm.
A simple genetic algorithm evolves a population of candidate solutions by repeatedly applying selection, crossover, and mutation operators. The pygmo implementation offers several strategies for each of these operators. A detailed description of the algorithm can be found in the pagmo2 documentation. See also [algo_44] for a time-complexity analysis of evolutionary algorithms.
Genetic algorithms are global, derivative-free, population based optimizers that are suited for multimodal problems where no derivatives are available and many function evaluations are affordable. For smooth problems with only one optimum, local optimizers are much more efficient.
The algorithm requires finite bounds on all parameters.
- population_size: int | None = None¶
Size of the population. If None, it is set to
10 * (n_params + 1), but at least 64.
- seed: int | None = None¶
Seed used to sample the initial population and by the pygmo algorithm.
If None, runs are not reproducible.
- discard_start_params: bool = False¶
If True, the start parameters are not guaranteed to be part of the initial population.
This saves one criterion function evaluation that cannot be done in parallel with other evaluations. Default False.
- stopping_maxiter: PositiveInt = 250¶
Number of generations to evolve (the
genparameter in pygmo).
- crossover_probability: NonNegativeFloat = 0.9¶
Crossover probability. It must lie in [0, 1]. The default value is taken from pygmo.
- crossover_strategy: Literal['exponential', 'sbx', 'single', 'binomial'] = 'exponential'¶
The crossover strategy.
One of “exponential”, “binomial”, “single” or “sbx” (simulated binary crossover). Default is “exponential”.
- eta_c: PositiveFloat | None = None¶
Distribution index for “sbx” crossover.
It must lie in [1, 100]. This parameter is ignored (and a warning is raised) if another crossover strategy is selected. If None, pygmo’s default of 1.0 is used.
- mutation_probability: NonNegativeFloat = 0.02¶
Mutation probability. It must lie in [0, 1]. The default value is taken from pygmo.
- mutation_strategy: Literal['uniform', 'polynomial'] = 'polynomial'¶
Mutation strategy. Must be “uniform” or “polynomial”. Default is “polynomial”.
- mutation_polynomial_distribution_index: NonNegativeFloat | None = None¶
Distribution index used by polynomial mutation (part of the
param_mparameter in pygmo).According to the pygmo documentation, it must lie in [1, 100]. It is only used if
mutation_strategyis “polynomial”; otherwise a warning is raised and the value is ignored. If None, 1.0 is used.
- mutation_gaussian_width: NonNegativeFloat | None = None¶
Width of the gaussian used by gaussian mutation (part of the
param_mparameter in pygmo).This option has no effect: “gaussian” is not an allowed
mutation_strategy, so setting this value only raises a warning.
- selection_strategy: Literal['tournament', 'truncated'] = 'tournament'¶
Selection strategy. Must be “tournament” or “truncated”. Default is “tournament”.
pygmo_sade
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pygmo_sade(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pygmo_sade",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.pygmo_optimizers.PygmoSade[source]¶
Minimize a scalar function using self-adaptive differential evolution.
The original differential evolution algorithm (pygmo_de) can be significantly improved by introducing the idea of parameter self-adaptation. Many different proposals have been made to self-adapt both the crossover probability \(CR\) and the weight coefficient \(F\) of the original differential evolution algorithm. pygmo’s implementation supports two different mechanisms. The first one, proposed by [algo_45], does not make use of the differential evolution operators to produce new values for \(F\) and \(CR\) and, strictly speaking, is thus not self-adaptation, but rather parameter control. The resulting differential evolution variant is often referred to as jDE. The second variant is inspired by the ideas introduced by [algo_46] and uses a variation of the selected DE operator to produce new \(CR\) and \(F\) parameters for each individual. This variant is referred to as iDE.
Like plain differential evolution, this is a global, derivative-free, population based algorithm for multimodal problems. The self-adaptation removes the need to tune \(F\) and \(CR\) by hand.
The algorithm requires finite bounds on all parameters.
- population_size: int | None = None¶
Size of the population. If None, it is set to
10 * (n_params + 1), but at least 64.
- seed: int | None = None¶
Seed used to sample the initial population and by the pygmo algorithm.
If None, runs are not reproducible.
- discard_start_params: bool = False¶
If True, the start parameters are not guaranteed to be part of the initial population.
This saves one criterion function evaluation that cannot be done in parallel with other evaluations. Default False.
- jde: bool = True¶
Whether to use the jDE self-adaptation variant ([algo_45]) to control the \(F\) and \(CR\) parameters.
If True, jDE is used, otherwise iDE ([algo_46]).
- stopping_maxiter: PositiveInt = 250¶
Number of generations to evolve (the
genparameter in pygmo).
- mutation_variant: Literal['best/1/exp', 'rand/1/exp', 'rand-to-best/1/exp', 'best/2/exp', 'rand/2/exp', 'best/1/bin', 'rand/1/bin', 'rand-to-best/1/bin', 'best/2/bin', 'rand/2/bin', 'rand/3/exp', 'rand/3/bin', 'best/3/exp', 'best/3/bin', 'rand-to-current/2/exp', 'rand-to-current/2/bin', 'rand-to-best-and-current/2/exp', 'rand-to-best-and-current/2/bin'] = 'rand/1/exp'¶
Mutation variant used to create a new candidate individual.
The default is “rand/1/exp”. The first ten variants are the classical mutation variants introduced in the original DE algorithm; the remaining ones are considered in the work by [algo_46]. The following variants are available; the corresponding pygmo integer code is given in parentheses for reference, but only the names are accepted:
“best/1/exp” (1)
“rand/1/exp” (2)
“rand-to-best/1/exp” (3)
“best/2/exp” (4)
“rand/2/exp” (5)
“best/1/bin” (6)
“rand/1/bin” (7)
“rand-to-best/1/bin” (8)
“best/2/bin” (9)
“rand/2/bin” (10)
“rand/3/exp” (11)
“rand/3/bin” (12)
“best/3/exp” (13)
“best/3/bin” (14)
“rand-to-current/2/exp” (15)
“rand-to-current/2/bin” (16)
“rand-to-best-and-current/2/exp” (17)
“rand-to-best-and-current/2/bin” (18)
- keep_adapted_params: bool = False¶
When True, the adapted parameters \(CR\) and \(F\) are not reset between successive calls to the evolve method (the
memoryparameter in pygmo).Default is False.
- ftol: NonNegativeFloat = 1e-06¶
Stop when the absolute difference between the best and the worst objective value in the population is smaller than this value.
The default value is taken from pygmo.
- xtol: NonNegativeFloat = 1e-06¶
Stop when the sum of absolute differences between the best and the worst parameter vector in the population is smaller than this value.
The default value is taken from pygmo.
pygmo_cmaes
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pygmo_cmaes(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pygmo_cmaes",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.pygmo_optimizers.PygmoCmaes[source]¶
Minimize a scalar function using the covariance matrix evolutionary strategy.
CMA-ES is one of the most successful algorithms, classified as an evolutionary strategy, for derivative-free global optimization. The version supported by optimagic is the version described in [algo_47].
CMA-ES samples new candidate solutions from a multivariate normal distribution whose covariance matrix is adapted based on the success of previous generations. It is a good default choice among the population based pygmo optimizers for continuous problems that are multimodal, non-smooth, or noisy and for which no derivatives are available. Note that the algorithm is not elitist, i.e. the best solution found so far is not guaranteed to be part of the current population.
In contrast to the pygmo version, optimagic always sets
force_boundsto True. This avoids that ill defined parameter values are evaluated, but it interferes with the covariance matrix adaptation and can worsen the performance considerably.The algorithm requires finite bounds on all parameters.
- population_size: int | None = None¶
Size of the population. If None, it is set to
10 * (n_params + 1), but at least 64.
- seed: int | None = None¶
Seed used to sample the initial population and by the pygmo algorithm.
If None, runs are not reproducible.
- discard_start_params: bool = False¶
If True, the start parameters are not guaranteed to be part of the initial population.
This saves one criterion function evaluation that cannot be done in parallel with other evaluations. Default False.
- stopping_maxiter: PositiveInt = 250¶
Number of generations to evolve (the
genparameter in pygmo).
- backward_horizon: NonNegativeFloat | None = None¶
Backward time horizon for the evolution path (
ccin the pygmo documentation).It must lie between 0 and 1. If None, it is determined automatically by pygmo.
- variance_loss_compensation: NonNegativeFloat | None = None¶
Makes partly up for the small variance loss in case the indicator is zero (
csin the pygmo documentation and in the MATLAB code of [algo_47]).It must lie between 0 and 1. If None, it is determined automatically by pygmo.
- learning_rate_rank_one_update: NonNegativeFloat | None = None¶
Learning rate for the rank-one update of the covariance matrix (
c1in the pygmo and pagmo documentation).It must lie between 0 and 1. If None, it is determined automatically by pygmo.
- learning_rate_rank_mu_update: NonNegativeFloat | None = None¶
Learning rate for the rank-mu update of the covariance matrix (
cmuin the pygmo and pagmo documentation).It must lie between 0 and 1. If None, it is determined automatically by pygmo.
- initial_step_size: float = 0.5¶
Initial step size, \(\sigma^0\) in the original paper.
It is relative to the width of the bounds: the initial standard deviation along parameter
iisinitial_step_size * (upper_i - lower_i). The default value is taken from pygmo.
- ftol: NonNegativeFloat = 1e-06¶
Stop when the absolute difference between the best and the worst objective value in the population is smaller than this value.
The default value is taken from pygmo.
- xtol: NonNegativeFloat = 1e-06¶
Stopping tolerance in the parameter space.
The algorithm stops when the sampling distribution has become so narrow that the typical parameter change falls below this value. The default value is taken from pygmo.
pygmo_simulated_annealing
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pygmo_simulated_annealing(start_temperature=5.0),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pygmo_simulated_annealing",
algo_options={"start_temperature": 5.0},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.pygmo_optimizers.PygmoSimulatedAnnealing[source]¶
Minimize a scalar function with the simulated annealing algorithm.
This version of the simulated annealing algorithm is, essentially, an iterative random search procedure with adaptive moves along the coordinate directions. It permits uphill moves under the control of a metropolis criterion, in the hope to avoid the first local minima encountered. This version is the one proposed in [algo_48].
Simulated annealing is a derivative-free global optimizer that is suited for multimodal problems where no derivatives are available. It should not be used for stochastic (noisy) problems.
Note
When selecting the starting and final temperature values it helps to think about the temperature as the deterioration in the objective function value that still has a 37% chance of being accepted.
Apart from the evaluations of the initial population, the criterion function is evaluated
n_temp_adjustments * n_range_adjustments * bin_size * n_paramstimes.The algorithm requires finite bounds on all parameters.
- population_size: int | None = None¶
Size of the initial population.
Simulated annealing is not population based, so this value only determines how many random initial points are evaluated; the annealing then starts from the best of them. If None, it is set to
10 * (n_params + 1), but at least 64.
- seed: int | None = None¶
Seed used to sample the initial population and by the pygmo algorithm.
If None, runs are not reproducible.
- discard_start_params: bool = False¶
If True, the start parameters are not guaranteed to be part of the initial population.
This saves one criterion function evaluation that cannot be done in parallel with other evaluations. Default False.
- start_temperature: PositiveFloat = 10.0¶
Starting temperature. Must be > 0. The default value is taken from pygmo.
- end_temperature: float = 0.01¶
Final temperature.
It must be positive and not larger than
start_temperature. Our default (0.01) is lower than the default in pygmo and pagmo (0.1).
- n_range_adjustments: int = 10¶
Number of adjustments of the search range performed at a constant temperature.
optimagic uses a default of 10, whereas pygmo’s default is 1.
- bin_size: int = 10¶
Number of mutations that are used to compute the acceptance rate.
optimagic uses a default of 10, whereas pygmo’s default is 20.
- start_range: NonNegativeFloat = 1.0¶
Starting range for mutating the decision vector. It must lie in (0, 1].
pygmo_pso
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pygmo_pso(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pygmo_pso",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.pygmo_optimizers.PygmoPso[source]¶
Minimize a scalar function using particle swarm optimization.
Particle swarm optimization (PSO) is a population based algorithm inspired by the foraging behaviour of swarms, originally proposed by [algo_49]. In PSO each point has memory of the position where it achieved the best performance \(x^l_i\) (local memory) and of the best decision vector \(x^g\) in a certain neighbourhood, and uses this information to update its position. For a survey on particle swarm optimization algorithms, see [algo_50].
In the default variant (“canonical_constriction”), each particle updates its velocity and position as
\[v_{i+1} = \omega (v_i + \eta_1 \cdot \mathbf{r}_1 \cdot (x^{l}_i - x_i) + \eta_2 \cdot \mathbf{r}_2 \cdot (x^g - x_i)), \qquad x_{i+1} = x_i + v_{i+1}\]The inertia weight variants (the first four values of
algo_variant) use \(v_{i+1} = \omega v_i + \eta_1 \cdot \mathbf{r}_1 \cdot (x^{l}_i - x_i) + \eta_2 \cdot \mathbf{r}_2 \cdot (x^g - x_i)\), and “fips” uses the best positions of all neighbors.PSO is a global, derivative-free optimizer suited for multimodal problems where no derivatives are available and many function evaluations are affordable. This version updates one particle at a time and should not be used for stochastic problems; see pygmo_pso_gen for a generational variant that supports them and allows parallelization.
The algorithm requires finite bounds on all parameters.
- population_size: int | None = None¶
Size of the population. If None, it is set to
10 * (n_params + 1), but at least 10.
- seed: int | None = None¶
Seed used to sample the initial population and by the pygmo algorithm.
If None, runs are not reproducible.
- discard_start_params: bool = False¶
If True, the start parameters are not guaranteed to be part of the initial population.
This saves one criterion function evaluation that cannot be done in parallel with other evaluations. Default False.
- stopping_maxiter: PositiveInt = 250¶
Number of generations to evolve (the
genparameter in pygmo).
- omega: NonNegativeFloat = 0.7298¶
Depending on the variant chosen, \(\omega\) is the particles’ inertia weight or the constriction coefficient.
It must lie between 0 and 1. The default value is taken from pygmo.
- force_of_previous_best: NonNegativeFloat = 2.05¶
\(\eta_1\) in the equation above.
It is the magnitude of the force, applied to the particle’s velocity, in the direction of its previous best position. It must lie between 0 and 4. The default value is taken from pygmo.
- force_of_best_in_neighborhood: NonNegativeFloat = 2.05¶
\(\eta_2\) in the equation above.
It is the magnitude of the force, applied to the particle’s velocity, in the direction of the best position in its neighborhood. It must lie between 0 and 4. The default value is taken from pygmo.
- max_velocity: NonNegativeFloat = 0.5¶
Maximum allowed particle velocity as fraction of the box bounds.
It must lie in (0, 1]. The default value is taken from pygmo.
- algo_variant: Literal['canonical_inertia', 'social_and_cog_rand', 'all_components_rand', 'one_rand', 'canonical_constriction', 'fips'] = 'canonical_constriction'¶
Algorithm variant to be used:
“canonical_inertia” (1): canonical PSO with inertia weight
“social_and_cog_rand” (2): same social and cognitive random vector
“all_components_rand” (3): same random vector for all components
“one_rand” (4): only one random number per velocity update
“canonical_constriction” (5): canonical PSO with constriction factor
“fips” (6): fully informed particle swarm
The corresponding pygmo integer code is given in parentheses for reference; only the names are accepted.
- neighbor_definition: Literal['gbest', 'lbest', 'Von Neumann', 'Adaptive random'] = 'lbest'¶
Swarm topology that defines each particle’s neighbors.
One of “gbest” (1), “lbest” (2), “Von Neumann” (3) or “Adaptive random” (4). The corresponding pygmo integer code is given in parentheses for reference; only the names are accepted.
- neighbor_param: int | None = None¶
The neighbourhood parameter.
If the “lbest” topology is selected, it represents each particle’s indegree (also outdegree) in the swarm topology. Particles have neighbours up to a radius of
neighbor_param / 2in the ring. If the “Adaptive random” topology is selected, it represents each particle’s maximum outdegree in the swarm topology; the minimum outdegree is 1 (the particle always connects back to itself). If the neighbor definition is “gbest” or “Von Neumann”, this parameter is ignored and a warning is raised if it is set. If None, pygmo’s default of 4 is used.
pygmo_pso_gen
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pygmo_pso_gen(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pygmo_pso_gen",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.pygmo_optimizers.PygmoPsoGen[source]¶
Minimize a scalar function with generational particle swarm optimization.
Particle swarm optimization (generational) is identical to pygmo_pso, but it updates the velocities of all particles before the new particle positions are computed (taking into consideration all updated particle velocities). Each particle is thus evaluated on the same seed within a generation, as opposed to the standard PSO, which evaluates a single particle at a time. This makes the algorithm suitable for pygmo’s stochastic problems, i.e. problems whose random seed pygmo can change. optimagic does not pass such problems to pygmo, so this property is not used.
Because the whole population is evaluated in one batch per generation, the algorithm supports parallel function evaluation via
n_cores.For a survey on particle swarm optimization algorithms, see [algo_50].
In the default variant (“canonical_constriction”), each particle updates its velocity and position as
\[v_{i+1} = \omega (v_i + \eta_1 \cdot \mathbf{r}_1 \cdot (x^{l}_i - x_i) + \eta_2 \cdot \mathbf{r}_2 \cdot (x^g - x_i)), \qquad x_{i+1} = x_i + v_{i+1}\]The inertia weight variants (the first four values of
algo_variant) use \(v_{i+1} = \omega v_i + \eta_1 \cdot \mathbf{r}_1 \cdot (x^{l}_i - x_i) + \eta_2 \cdot \mathbf{r}_2 \cdot (x^g - x_i)\), and “fips” uses the best positions of all neighbors.The algorithm requires finite bounds on all parameters.
- population_size: int | None = None¶
Size of the population. If None, it is set to
10 * (n_params + 1), but at least 10.
- n_cores: PositiveInt = 1¶
Number of cores used for parallel function evaluation.
- seed: int | None = None¶
Seed used to sample the initial population and by the pygmo algorithm.
If None, runs are not reproducible.
- discard_start_params: bool = False¶
If True, the start parameters are not guaranteed to be part of the initial population.
This saves one criterion function evaluation that cannot be done in parallel with other evaluations. Default False.
- stopping_maxiter: PositiveInt = 250¶
Number of generations to evolve (the
genparameter in pygmo).
- omega: NonNegativeFloat = 0.7298¶
Depending on the variant chosen, \(\omega\) is the particles’ inertia weight or the constriction coefficient.
It must lie between 0 and 1. The default value is taken from pygmo.
- force_of_previous_best: NonNegativeFloat = 2.05¶
\(\eta_1\) in the equation above.
It is the magnitude of the force, applied to the particle’s velocity, in the direction of its previous best position. It must lie between 0 and 4. The default value is taken from pygmo.
- force_of_best_in_neighborhood: NonNegativeFloat = 2.05¶
\(\eta_2\) in the equation above.
It is the magnitude of the force, applied to the particle’s velocity, in the direction of the best position in its neighborhood. It must lie between 0 and 4. The default value is taken from pygmo.
- max_velocity: NonNegativeFloat = 0.5¶
Maximum allowed particle velocity as fraction of the box bounds.
It must lie in (0, 1]. The default value is taken from pygmo.
- algo_variant: Literal['canonical_inertia', 'social_and_cog_rand', 'all_components_rand', 'one_rand', 'canonical_constriction', 'fips'] = 'canonical_constriction'¶
Algorithm variant to be used:
“canonical_inertia” (1): canonical PSO with inertia weight
“social_and_cog_rand” (2): same social and cognitive random vector
“all_components_rand” (3): same random vector for all components
“one_rand” (4): only one random number per velocity update
“canonical_constriction” (5): canonical PSO with constriction factor
“fips” (6): fully informed particle swarm
The corresponding pygmo integer code is given in parentheses for reference; only the names are accepted.
- neighbor_definition: Literal['gbest', 'lbest', 'Von Neumann', 'Adaptive random'] = 'lbest'¶
Swarm topology that defines each particle’s neighbors.
One of “gbest” (1), “lbest” (2), “Von Neumann” (3) or “Adaptive random” (4). The corresponding pygmo integer code is given in parentheses for reference; only the names are accepted.
- neighbor_param: int | None = None¶
The neighbourhood parameter.
If the “lbest” topology is selected, it represents each particle’s indegree (also outdegree) in the swarm topology. Particles have neighbours up to a radius of
neighbor_param / 2in the ring. If the “Adaptive random” topology is selected, it represents each particle’s maximum outdegree in the swarm topology; the minimum outdegree is 1 (the particle always connects back to itself). If the neighbor definition is “gbest” or “Von Neumann”, this parameter is ignored and a warning is raised if it is set. If None, pygmo’s default of 4 is used.
pygmo_mbh
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pygmo_mbh(perturbation=0.05),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pygmo_mbh",
algo_options={"perturbation": 0.05},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.pygmo_optimizers.PygmoMbh[source]¶
Minimize a scalar function using generalized monotonic basin hopping.
Monotonic basin hopping, or simply basin hopping, is an algorithm rooted in the idea of mapping the objective function \(f(x_0)\) into the local minimum found when starting a local search from \(x_0\). This simple idea allows a substantial increase of efficiency in solving problems, such as the Lennard-Jones cluster or the MGA-1DSM interplanetary trajectory problem, that are conjectured to have a so-called funnel structure. See [algo_18] for the paper introducing the basin hopping idea for a Lennard-Jones cluster optimization.
pygmo provides an original generalization of this concept resulting in a meta-algorithm that operates on a population: the population is randomly perturbed, the inner algorithm is run on it, and the result is kept only if it improves upon the best known solution. When a population containing a single individual is used, the original method is recovered.
Basin hopping is a good choice for derivative-free problems with many local optima in which good local optima are close to each other (a funnel structure). The algorithm requires finite bounds on all parameters.
- population_size: int | None = None¶
Size of the population. If None, it is set to
10 * (n_params + 1), but at least 250.
- seed: int | None = None¶
Seed used to sample the initial population and by the pygmo algorithm.
If None, runs are not reproducible.
- discard_start_params: bool = False¶
If True, the start parameters are not guaranteed to be part of the initial population.
This saves one criterion function evaluation that cannot be done in parallel with other evaluations. Default False.
- inner_algorithm: PygmoAlgorithm | None = None¶
A pygmo algorithm or a user-defined pygmo algorithm, either C++ or Python, that is used for the inner (local) searches.
If None,
pygmo.compass_search()with pygmo’s default settings is used. Its defaultmax_fevals=1means that each local search is a single compass sweep with at most2 * n_paramsfunction evaluations. Pass a configured algorithm, e.g.pygmo.compass_search(max_fevals=1000), for a more thorough local search.
- stopping_max_inner_runs_without_improvement: PositiveInt = 30¶
Number of consecutive runs of the inner algorithm that need to result in no improvement for the algorithm to stop (the
stopparameter in pygmo).optimagic uses a default of 30, whereas pygmo’s default is 5.
pygmo_xnes
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pygmo_xnes(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pygmo_xnes",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.pygmo_optimizers.PygmoXnes[source]¶
Minimize a scalar function using exponential natural evolution strategies.
Exponential natural evolution strategies (xNES) is an algorithm closely related to CMA-ES and based on the adaptation of a gaussian sampling distribution via the so-called natural gradient. Like CMA-ES, it is based on the idea of sampling new trial vectors from a multivariate distribution and using the new sampled points to update the distribution parameters. Naively, this could be done following the gradient of the expected fitness as approximated by a finite number of sampled points. While this idea offers a powerful lead on algorithmic construction, it has some major drawbacks that are solved in the so-called natural evolution strategies class of algorithms by adopting, instead, the natural gradient. xNES is one of the most performing variants in this class.
See [algo_51] and the pagmo documentation on xNES for details.
Like CMA-ES, xNES is a global, derivative-free, population based optimizer for continuous problems that are multimodal, non-smooth, or noisy. The algorithm is not elitist, i.e. the best solution found so far is not guaranteed to be part of the current population. In contrast to the pygmo version, optimagic always sets
force_boundsto True, so the criterion function is never evaluated outside of the bounds, at the cost of a somewhat worse adaptation of the sampling distribution.The algorithm requires finite bounds on all parameters.
- population_size: float | None = None¶
Size of the population. If None, it is set to
10 * (n_params + 1), but at least 64.
- seed: int | None = None¶
Seed used to sample the initial population and by the pygmo algorithm.
If None, runs are not reproducible.
- discard_start_params: bool = False¶
If True, the start parameters are not guaranteed to be part of the initial population.
This saves one criterion function evaluation that cannot be done in parallel with other evaluations. Default False.
- stopping_maxiter: PositiveInt = 250¶
Number of generations to evolve (the
genparameter in pygmo).
- learning_rate_mean_update: NonNegativeFloat | None = 1.0¶
Learning rate for the mean update (\(\eta_\mu\) in the pygmo documentation).
It must lie in (0, 1]. If None, pygmo uses 1.0, which is also the default.
- learning_rate_step_size_update: NonNegativeFloat | None = None¶
Learning rate for the step-size update (
eta_sigmain the pygmo documentation).It must lie in (0, 1]. If None, it is chosen automatically by pygmo.
- learning_rate_cov_matrix_update: NonNegativeFloat | None = None¶
Learning rate for the covariance matrix update (
eta_bin the pygmo documentation).It must lie in (0, 1]. If None, it is chosen automatically by pygmo.
Share of the given search space that will be initially searched (
sigma0in the pygmo documentation).The width of the initial sampling distribution along dimension
iisinitial_search_share * (upper_bound_i - lower_bound_i). It must lie in (0, 1]. optimagic uses a default of 1, whereas pygmo’s default is 0.5.
- ftol: NonNegativeFloat = 1e-06¶
Stop when the absolute difference between the best and the worst objective value in the population is smaller than this value.
The default value is taken from pygmo.
- xtol: NonNegativeFloat = 1e-06¶
Stopping tolerance in the parameter space.
The algorithm stops when the sampling distribution has become so narrow that the typical parameter change falls below this value. The default value is taken from pygmo.
pygmo_gwo
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pygmo_gwo(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pygmo_gwo",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.pygmo_optimizers.PygmoGwo[source]¶
Minimize a scalar function using the grey wolf optimizer.
The grey wolf optimizer was proposed by [algo_52]. The pygmo implementation that is wrapped by optimagic is based on the pseudo-code provided in that paper. The algorithm mimics the leadership hierarchy and hunting mechanism of grey wolves, with the three best solutions (called alpha, beta, and delta) guiding the movement of the remaining population.
This algorithm is a classic example of a highly criticizable line of research that led in the first decades of our millennium to the development of an entire zoo of metaphors inspiring optimization heuristics. In the opinion of the pagmo developers, they are often but small variations of already existing heuristics rebranded with unnecessary and convoluted biological metaphors. In the case of GWO this is particularly evident as the position update rule is strikingly trivial and can also be easily seen as a product of an evolutionary metaphor or a particle swarm one. Such an update rule is also not particularly effective and results in a rather poor performance most of the time.
The algorithm requires finite bounds on all parameters.
- population_size: int | None = None¶
Size of the population. If None, it is set to
10 * (n_params + 1), but at least 64.
- seed: int | None = None¶
Seed used to sample the initial population and by the pygmo algorithm.
If None, runs are not reproducible.
- discard_start_params: bool = False¶
If True, the start parameters are not guaranteed to be part of the initial population.
This saves one criterion function evaluation that cannot be done in parallel with other evaluations. Default False.
- stopping_maxiter: PositiveInt = 250¶
Number of generations to evolve (the
genparameter in pygmo).
pygmo_compass_search
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pygmo_compass_search(stopping_maxfun=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pygmo_compass_search",
algo_options={"stopping_maxfun": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.pygmo_optimizers.PygmoCompassSearch[source]¶
Minimize a scalar function using compass search.
Compass search is a direct (pattern) search method: at each step, the objective function is evaluated at points obtained by changing one parameter at a time by the current step size (a fraction of the width of the bounds). If an improvement is found, the search moves there; otherwise, the step size is reduced. The algorithm is described in [algo_53].
In contrast to the other pygmo algorithms, compass search is a local, derivative-free optimizer. It is considered slow but reliable and is a reasonable choice for non-differentiable problems where only a local optimum is needed. It should not be used for stochastic problems.
The algorithm requires finite bounds on all parameters.
- population_size: int | None = None¶
Size of the initial population.
Compass search itself is not population based, so this value only determines how many random initial points are evaluated when the population is created; the search then continues from the best of them. If a value is specified, a warning is raised. If None, 100 is used.
- seed: int | None = None¶
Seed used to sample the initial population.
Compass search itself is deterministic.
- discard_start_params: bool = False¶
If True, the start parameters are not guaranteed to be part of the initial population.
This saves one criterion function evaluation that cannot be done in parallel with other evaluations. Default False.
- stopping_maxfun: PositiveInt = 1000¶
Maximum number of function evaluations (the
max_fevalsparameter in pygmo).
- start_range: PositiveFloat = 0.1¶
The start range, as a fraction of the width of the bounds.
Must lie in (0, 1]. The default value is taken from pygmo.
- stop_range: PositiveFloat = 0.01¶
The stop range; the search stops when the range falls below this value.
Must lie in (0, start_range). The default value is taken from pygmo.
- reduction_coeff: PositiveFloat = 0.5¶
The range reduction coefficient by which the range is multiplied when no improvement is found.
Must lie in (0, 1). The default value is taken from pygmo.
pygmo_ihs
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pygmo_ihs(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pygmo_ihs",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.pygmo_optimizers.PygmoIhs[source]¶
Minimize a scalar function using the improved harmony search algorithm.
Improved harmony search (IHS) was introduced by [algo_54]. Harmony search mimics the improvisation process of a music orchestra: new candidate solutions (“harmonies”) are composed by recombining components of the solutions stored in the harmony memory (the population), by adjusting them (“pitch adjustment”), or by drawing random values. In the improved variant, the pitch adjustment rate and the adjustment bandwidth vary over the course of the optimization (linearly and exponentially, respectively).
IHS is a derivative-free global optimizer for multimodal problems. Each generation creates and evaluates exactly one new candidate solution, so progress is slow but steady.
The algorithm requires finite bounds on all parameters.
- population_size: int | None = None¶
Size of the population (the harmony memory).
If None, it is set to
10 * (n_params + 1). If a value is specified, a warning is raised. New candidates draw their components from randomly chosen members of the harmony memory, and the worst member is replaced whenever a better candidate is found.
- seed: int | None = None¶
Seed used to sample the initial population and by the pygmo algorithm.
If None, runs are not reproducible.
- discard_start_params: bool = False¶
If True, the start parameters are not guaranteed to be part of the initial population.
This saves one criterion function evaluation that cannot be done in parallel with other evaluations. Default False.
- stopping_maxiter: PositiveInt = 250¶
Number of generations to evolve (the
genparameter in pygmo).Each generation computes the objective function once.
- choose_from_memory_probability: NonNegativeFloat = 0.85¶
Probability of choosing from memory (similar to a crossover probability; the
phmcrparameter in pygmo).It must lie between 0 and 1. The default value is taken from pygmo.
- min_pitch_adjustment_rate: NonNegativeFloat = 0.35¶
Minimum pitch adjustment rate (similar to a mutation rate; the
ppar_minparameter in pygmo).It must lie between 0 and 1. The default value is taken from pygmo.
- max_pitch_adjustment_rate: NonNegativeFloat = 0.99¶
Maximum pitch adjustment rate (similar to a mutation rate; the
ppar_maxparameter in pygmo).It must lie between 0 and 1 and not be smaller than
min_pitch_adjustment_rate. The default value is taken from pygmo.
- min_distance_bandwidth: PositiveFloat = 1e-05¶
Minimum distance bandwidth (similar to a mutation width; the
bw_minparameter in pygmo).It must be positive. The default value is taken from pygmo.
- max_distance_bandwidth: PositiveFloat = 1.0¶
Maximum distance bandwidth (similar to a mutation width; the
bw_maxparameter in pygmo).It must not be smaller than
min_distance_bandwidth. The default value is taken from pygmo.
pygmo_de1220
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pygmo_de1220(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pygmo_de1220",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.pygmo_optimizers.PygmoDe1220[source]¶
Minimize a scalar function using pygmo’s self-adaptive differential evolution.
de1220, also known as pDE, is pygmo’s own flavor of self-adaptive differential evolution. In addition to self-adapting the crossover probability \(CR\) and the weight coefficient \(F\) with either the jDE ([algo_45]) or the iDE ([algo_46]) mechanism, each individual also carries and adapts the mutation variant that is used to create new candidates. See the pagmo documentation on de1220 for details.
Like the other differential evolution variants, it is a global, derivative-free, population based optimizer for multimodal problems. It is a good choice if you do not want to tune the mutation variant and the control parameters of differential evolution by hand.
The algorithm requires finite bounds on all parameters.
- population_size: int | None = None¶
Size of the population. If None, it is set to
10 * (n_params + 1), but at least 64.
- seed: int | None = None¶
Seed used to sample the initial population and by the pygmo algorithm.
If None, runs are not reproducible.
- discard_start_params: bool = False¶
If True, the start parameters are not guaranteed to be part of the initial population.
This saves one criterion function evaluation that cannot be done in parallel with other evaluations. Default False.
- jde: bool = True¶
Whether to use the jDE self-adaptation variant ([algo_45]) to control the \(F\) and \(CR\) parameters.
If True, jDE is used, otherwise iDE ([algo_46]).
- stopping_maxiter: PositiveInt = 250¶
Number of generations to evolve (the
genparameter in pygmo).
- allowed_variants: List[str] | None = None¶
Mutation variants the self-adaptation is allowed to choose from.
Each variant is given by its name; the corresponding pygmo integer code is shown in parentheses below for reference. The first ten variants are the classical mutation variants introduced in the original DE algorithm; the remaining ones are considered in the work by [algo_46]. If None, the default is [“rand/1/exp”, “rand-to-best/1/exp”, “rand/1/bin”, “rand/2/bin”, “best/3/exp”, “best/3/bin”, “rand-to-current/2/exp”, “rand-to-current/2/bin”]. The following variants are available:
“best/1/exp” (1)
“rand/1/exp” (2)
“rand-to-best/1/exp” (3)
“best/2/exp” (4)
“rand/2/exp” (5)
“best/1/bin” (6)
“rand/1/bin” (7)
“rand-to-best/1/bin” (8)
“best/2/bin” (9)
“rand/2/bin” (10)
“rand/3/exp” (11)
“rand/3/bin” (12)
“best/3/exp” (13)
“best/3/bin” (14)
“rand-to-current/2/exp” (15)
“rand-to-current/2/bin” (16)
“rand-to-best-and-current/2/exp” (17)
“rand-to-best-and-current/2/bin” (18)
- keep_adapted_params: bool = False¶
When True, the adapted parameters \(CR\) and \(F\) and the mutation variant are not reset between successive calls to the evolve method (the
memoryparameter in pygmo).Default is False.
- ftol: NonNegativeFloat = 1e-06¶
Stop when the absolute difference between the best and the worst objective value in the population is smaller than this value.
The default value is taken from pygmo.
- xtol: NonNegativeFloat = 1e-06¶
Stop when the sum of absolute differences between the best and the worst parameter vector in the population is smaller than this value.
The default value is taken from pygmo.
The Interior Point Optimizer (ipopt)¶
optimagic’s support for the Interior Point Optimizer ([algo_55], [algo_56], [algo_57], [algo_58]) is built on cyipopt, a Python wrapper for the Ipopt optimization package.
To use ipopt, you need to have
cyipopt installed
(conda install cyipopt).
ipopt
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.ipopt(stopping_maxiter=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="ipopt",
algo_options={"stopping_maxiter": 1_000},
)
Description and available options:
- class optimagic.optimizers.ipopt.Ipopt[source]¶
Minimize a scalar function using the Interior Point Optimizer (Ipopt).
Ipopt ([algo_57]) is an open-source solver for large-scale smooth nonlinear optimization developed within the COIN-OR project. It implements a primal-dual interior point method with a filter line search ([algo_55], [algo_56]) and, optionally, an adaptive update strategy for the barrier parameter ([algo_58]). optimagic’s support for Ipopt is built on cyipopt, a Python wrapper for the Ipopt optimization package.
Ipopt is a local optimizer for smooth (ideally twice continuously differentiable) scalar objective functions. It supports bounds as well as nonlinear equality and inequality constraints and is designed to scale to very large problems. It requires first derivatives of the objective function and the constraints. optimagic does not pass second derivatives to Ipopt; the Hessian of the Lagrangian is approximated with a limited-memory quasi-Newton method. Ipopt is not suitable for noisy or discontinuous objective functions.
There are two levels of termination criteria. If the usual “desired” tolerances (see
convergence_ftol_rel,dual_inf_toletc.) are satisfied at an iteration, the algorithm immediately terminates with a success message. On the other hand, if the algorithm encountersacceptable_itermany iterations in a row that are considered “acceptable”, it will terminate before the desired convergence tolerance is met. This is useful in cases where the algorithm might not be able to achieve the “desired” level of accuracy.The options are analogous to the ones in the Ipopt options reference, with two exceptions. First, the stopping and convergence criteria follow optimagic’s naming:
convergence_ftol_relis Ipopt’stol,stopping_maxiterismax_iter,stopping_max_wall_time_secondsismax_wall_timeandstopping_max_cpu_timeismax_cpu_time. Second, the linear solver options are bundled into the dictionarylinear_solver_options. Any option that takes “yes” and “no” in the Ipopt documentation can also be passed asTrueandFalse, respectively, and any option that accepts “none” in Ipopt accepts a PythonNone.optimagic passes every option to Ipopt explicitly, including the defaults. Ipopt behavior that depends on an option being unset therefore does not apply; the affected options say so in their descriptions.
The following options are not supported:
num_linear_variables: since optimagic may reparametrize your problem, which changes which parameters Ipopt sees and in which order, we do not support this optiongrad_f_constant,jacobian_approximation,gradient_approximationandfindiff_perturbationthe linear solvers “pardisomkl”, “spral” and “wsmp”
derivative checks
print options.
Note
To use this algorithm you need to have cyipopt installed (
conda install -c conda-forge cyipopt).- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Relative convergence tolerance of the algorithm.
The algorithm terminates successfully if the (scaled) nonlinear programming error becomes smaller than this value and the absolute criteria
dual_inf_tol,constr_viol_tolandcompl_inf_tolare met. This is passed to Ipopt as thetoloption and must be positive; zero raises an error. optimagic’s default (2e-9) is stricter than Ipopt’s own default of 1e-8.
- dual_inf_tol: PositiveFloat = 1.0¶
Desired threshold for the dual infeasibility.
Successful termination requires that the max-norm of the (unscaled) dual infeasibility is less than this threshold.
- constr_viol_tol: PositiveFloat = 0.0001¶
Desired threshold for the constraint and variable bound violation.
Successful termination requires that the max-norm of the (unscaled) constraint violation is less than this threshold. If
bound_relax_factoris not zero, Ipopt relaxes the given variable bounds; the value ofconstr_viol_tolis then used to restrict the absolute amount of this bound relaxation.
- compl_inf_tol: PositiveFloat = 0.0001¶
Desired threshold for the complementarity conditions.
Successful termination requires that the max-norm of the (unscaled) complementarity is less than this threshold.
- s_max: float = 100¶
Advanced feature. Scaling threshold for the NLP error.
See paragraph after Eqn. (6) in [algo_57].
- mu_target: NonNegativeFloat = 0.0¶
Desired value of the complementarity.
Usually, the barrier parameter is driven to zero and the termination test for complementarity is measured with respect to zero complementarity. However, in some cases it might be desirable to have Ipopt solve the barrier problem for a strictly positive value of the barrier parameter. In this case,
mu_targetspecifies the final value of the barrier parameter and the termination tests are then defined with respect to the barrier problem for this value.
- stopping_maxiter: PositiveInt = 1000000¶
Maximum number of iterations.
If the maximum number of iterations is reached, the optimization stops, but we do not count this as successful convergence. One iteration might need several criterion evaluations, e.g. in a line search. This is passed to Ipopt as the
max_iteroption. optimagic’s default (1,000,000) is much larger than Ipopt’s own default of 3000.
- stopping_max_wall_time_seconds: PositiveFloat = 1e+20¶
Maximum number of wall clock seconds Ipopt may use to solve one problem.
If this limit is exceeded during the convergence check, Ipopt terminates with a corresponding message. This is passed to Ipopt as the
max_wall_timeoption.
- stopping_max_cpu_time: PositiveFloat = 1e+20¶
Maximum number of CPU seconds Ipopt may use to solve one problem.
If this limit is exceeded during the convergence check, Ipopt terminates with a corresponding message. This is passed to Ipopt as the
max_cpu_timeoption.
- acceptable_iter: NonNegativeInt = 15¶
Number of successive “acceptable” iterates before termination.
If the algorithm encounters this many successive “acceptable” iterates, it terminates, assuming that the problem has been solved to the best possible accuracy given round-off. If set to zero, this heuristic is disabled.
- acceptable_tol: PositiveFloat = 1e-06¶
“Acceptable” convergence tolerance (relative).
Determines which (scaled) overall optimality error is considered to be “acceptable”. Must be larger than
convergence_ftol_rel.
- acceptable_dual_inf_tol: PositiveFloat = 1e-10¶
“Acceptance” threshold for the dual infeasibility.
“Acceptable” termination requires that the max-norm of the (unscaled) dual infeasibility is less than this threshold; see also
acceptable_tol. Note that optimagic’s default (1e-10) is much stricter than Ipopt’s own default of 1e10. With this default, the “acceptable” termination heuristic effectively never triggers, because its dual infeasibility requirement is far stricter than the one for regular termination (dual_inf_tol); set this option to 1e10 to get Ipopt’s behavior.
- acceptable_constr_viol_tol: PositiveFloat = 0.01¶
“Acceptance” threshold for the constraint violation.
“Acceptable” termination requires that the max-norm of the (unscaled) constraint violation is less than this threshold; see also
acceptable_tol.
- acceptable_compl_inf_tol: PositiveFloat = 0.01¶
“Acceptance” threshold for the complementarity conditions.
“Acceptable” termination requires that the max-norm of the (unscaled) complementarity is less than this threshold; see also
acceptable_tol.
- acceptable_obj_change_tol: PositiveFloat = 1e+20¶
“Acceptance” stopping criterion based on the objective function change.
If the relative change of the objective function (scaled by
max(1, |f(x)|)) is less than this value, this part of the acceptable tolerance termination is satisfied; see alsoacceptable_tol. This is useful for the quasi-Newton option, which has trouble bringing down the dual infeasibility.
- diverging_iterates_tol: PositiveFloat = 1e+20¶
Threshold for the maximal value of the primal iterates.
If any component of the primal iterates exceeds this value in absolute terms, the optimization is aborted with the exit message that the iterates seem to be diverging.
- nlp_lower_bound_inf: float = -1e+19¶
Any bound less or equal to this value will be considered minus infinity (i.e. the variable is treated as not lower bounded).
- nlp_upper_bound_inf: float = 1e+19¶
Any bound greater or equal to this value will be considered plus infinity (i.e. the variable is treated as not upper bounded).
- fixed_variable_treatment: Literal['make_parameter', 'make_parameter_nodual', 'relax_bounds', 'make_constraint'] = 'make_parameter'¶
Determines how fixed variables are handled.
Possible values:
“make_parameter”: remove fixed variables from the optimization variables
“make_parameter_nodual”: as “make_parameter”, but do not compute bound multipliers for fixed variables
“make_constraint”: add equality constraints fixing the variables
“relax_bounds”: relax the fixing bound constraints (according to
bound_relax_factor)
The main difference is that in the “make_constraint” case the starting point still has the fixed variables at their given values, whereas with “make_parameter(_nodual)” the functions are always evaluated with the fixed values for those variables. For all but “make_parameter_nodual”, bound multipliers are computed for the fixed variables.
- dependency_detector: Literal['none', 'mumps', 'wsmp', 'ma28'] | None = None¶
Advanced feature. Which linear solver should be used to detect linearly dependent equality constraints.
None(or “none”) means no check is performed. This feature is experimental and does not work well.
- dependency_detection_with_rhs: YesNoBool = False¶
Advanced feature. Whether the right hand sides of the constraints should be considered in addition to the gradients during dependency detection.
- kappa_d: NonNegativeFloat = 1e-05¶
Advanced feature. Weight for the linear damping term (to handle one-sided bounds).
See Section 3.7 in [algo_57].
- bound_relax_factor: NonNegativeFloat = 1e-08¶
Factor for the initial relaxation of the bounds.
Before the start of the optimization, the bounds given by the user are relaxed by this relative factor. In addition,
constr_viol_tolis used to bound the relaxation by an absolute value. If set to zero, the bound relaxation is disabled. See Eqn. (35) in [algo_57]. Note that the constraint violation reported by Ipopt at the end of the solution process does not include violations of the original (non-relaxed) variable bounds. See alsohonor_original_bounds.
- honor_original_bounds: YesNoBool = False¶
Whether the final point should be projected back into the original bounds.
Ipopt might relax the bounds during the optimization (see
bound_relax_factor). This option determines whether the final point is projected back into the user-provided original bounds after the optimization. Note that violations of constraints and complementarity reported by Ipopt at the end of the solution process are for the non-projected point.
- check_derivatives_for_naninf: YesNoBool = False¶
Whether to check for NaN or Inf in the derivative matrices.
Activating this option will cause an error if an invalid number is detected in the constraint Jacobians or the Lagrangian Hessian. If it is not activated, the test is skipped and the algorithm might proceed with invalid numbers and fail.
- jac_c_constant: YesNoBool = False¶
Whether to assume that all equality constraints are linear.
Activating this option will cause Ipopt to ask for the Jacobian of the equality constraints only once and reuse this information later.
- jac_d_constant: YesNoBool = False¶
Whether to assume that all inequality constraints are linear.
Activating this option will cause Ipopt to ask for the Jacobian of the inequality constraints only once and reuse this information later.
- hessian_constant: YesNoBool = False¶
Whether to assume that the problem is a QP (quadratic objective, linear constraints).
Activating this option will cause Ipopt to ask for the Hessian of the Lagrangian function only once and reuse this information later. This is only relevant for exact Hessians, which optimagic does not provide.
- nlp_scaling_method: Literal['none', 'user-scaling', 'gradient-based', 'equilibration-based'] | None = 'gradient-based'¶
Technique used for scaling the problem internally before it is solved.
Possible values:
Noneor “none”: no problem scaling is performed“user-scaling”: the scaling parameters come from the user
“gradient-based”: scale the problem so that the maximum gradient at the starting point is
nlp_scaling_max_gradient“equilibration-based”: scale the problem so that first derivatives are of order 1 at random points (uses the Harwell routine MC19)
optimagic provides no way to pass user scaling parameters, so apart from
obj_scaling_factor, “user-scaling” amounts to no scaling.
- obj_scaling_factor: float = 1¶
Scaling factor for the objective function.
The scaling is only seen internally by Ipopt, the unscaled objective is reported in the output. If additional scaling parameters are computed (e.g. with user-scaling or gradient-based scaling), both factors are multiplied. A negative value makes Ipopt maximize optimagic’s internal criterion, which optimagic still treats as a minimization; use
om.maximizeto maximize.
- nlp_scaling_max_gradient: PositiveFloat = 100¶
Maximum gradient after NLP scaling.
This is the gradient scaling cut-off. If the maximum gradient is above this value, gradient based scaling is performed, with scaling parameters calculated to scale the maximum gradient back to this value. This is g_max in Section 3.8 of [algo_57]. Only used if
nlp_scaling_methodis “gradient-based”.
- nlp_scaling_obj_target_gradient: NonNegativeFloat = 0.0¶
Advanced feature. Target value for the objective function gradient size.
If a positive number is chosen, the scaling factor for the objective function is computed so that the gradient has the max-norm of the given size at the starting point. This overrides
nlp_scaling_max_gradientfor the objective function.
- nlp_scaling_constr_target_gradient: NonNegativeFloat = 0.0¶
Advanced feature. Target value for the constraint function gradient size.
If a positive number is chosen, the scaling factors for the constraint functions are computed so that the gradient has the max-norm of the given size at the starting point. This overrides
nlp_scaling_max_gradientfor the constraint functions.
- nlp_scaling_min_value: NonNegativeFloat = 1e-08¶
Minimum value of gradient-based scaling values.
This is the lower bound for the scaling factors computed by the gradient-based scaling method. If some derivatives of some functions are huge, the scaling factors will otherwise become very small, and the (unscaled) final constraint violation, for example, might then be significant. Only used if
nlp_scaling_methodis “gradient-based”.
- bound_push: PositiveFloat = 0.01¶
Desired minimum absolute distance from the initial point to the bounds.
Determines how much the initial point might have to be modified in order to be sufficiently inside the bounds (together with
bound_frac). This is kappa_1 in Section 3.6 of [algo_57].
- bound_frac: PositiveFloat = 0.01¶
Desired minimum relative distance from the initial point to the bounds.
Determines how much the initial point might have to be modified in order to be sufficiently inside the bounds (together with
bound_push). This is kappa_2 in Section 3.6 of [algo_57]. The valid range is (0, 0.5].
- slack_bound_push: PositiveFloat = 0.01¶
Desired minimum absolute distance from the initial slack to the bounds.
Determines how much the initial slack variables might have to be modified in order to be sufficiently inside the inequality bounds (together with
slack_bound_frac). This is kappa_1 in Section 3.6 of [algo_57]. In Ipopt, this defaults tobound_push; since optimagic always passes it, it does not follow changes tobound_push.
- slack_bound_frac: PositiveFloat = 0.01¶
Desired minimum relative distance from the initial slack to the bounds.
Determines how much the initial slack variables might have to be modified in order to be sufficiently inside the inequality bounds (together with
slack_bound_push). This is kappa_2 in Section 3.6 of [algo_57]. The valid range is (0, 0.5]. In Ipopt, this defaults tobound_frac; since optimagic always passes it, it does not follow changes tobound_frac.
- constr_mult_init_max: NonNegativeFloat = 1000¶
Maximum allowed least-squares guess of the constraint multipliers.
Determines how large the initial least-squares guesses of the constraint multipliers are allowed to be (in max-norm). If the guess is larger than this value, it is discarded and all constraint multipliers are set to zero. Since optimagic always passes this option, the same value is also used when initializing the restoration phase, where Ipopt’s own default is 0.
- bound_mult_init_val: PositiveFloat = 1¶
Initial value for the bound multipliers.
All dual variables corresponding to bound constraints are initialized to this value.
- bound_mult_init_method: Literal['constant', 'mu-based'] = 'constant'¶
Initialization method for the bound multipliers.
If “constant” is chosen, all bound multipliers are initialized to the value of
bound_mult_init_val. If “mu-based” is chosen, each value is initialized tomu_initdivided by the corresponding slack variable. The latter might be useful if the starting point is close to the optimal solution.
- least_square_init_primal: YesNoBool = False¶
Least-squares initialization of the primal variables.
If enabled, Ipopt ignores the user-provided point and solves a least-squares problem for the primal variables (x and s) to fit the linearized equality and inequality constraints. This might be useful if the user doesn’t know anything about the starting point, or for solving an LP or QP.
- least_square_init_duals: YesNoBool = False¶
Least-squares initialization of all dual variables.
If enabled, Ipopt tries to compute least-squares multipliers, considering all dual variables. If successful, the bound multipliers are possibly corrected to be at least
bound_mult_init_val. This might be useful if the user doesn’t know anything about the starting point, or for solving an LP or QP. This overwrites the optionbound_mult_init_method.
- warm_start_init_point: YesNoBool = False¶
Whether this optimization should use a warm start initialization, where values of the primal and dual variables are given (e.g. from a previous optimization of a related problem).
optimagic only passes the start parameters to Ipopt, so with a warm start all multipliers start at zero (raised to at least
warm_start_mult_bound_push).
- warm_start_same_structure: YesNoBool = False¶
Advanced feature.
Indicates whether a problem with a structure identical to the previous one is to be solved. If enabled, the algorithm assumes that an NLP is now to be solved whose structure is identical to one that was already considered (with the same NLP object).
Warning
optimagic creates a new Ipopt problem for every optimization, so enabling this option makes Ipopt abort with an exception and the optimization fails.
- warm_start_bound_push: PositiveFloat = 0.001¶
Same as
bound_pushfor the warm start initializer.
- warm_start_bound_frac: PositiveFloat = 0.001¶
Same as
bound_fracfor the warm start initializer.The valid range is (0, 0.5].
- warm_start_slack_bound_push: PositiveFloat = 0.001¶
Same as
slack_bound_pushfor the warm start initializer.
- warm_start_slack_bound_frac: PositiveFloat = 0.001¶
Same as
slack_bound_fracfor the warm start initializer.The valid range is (0, 0.5].
- warm_start_mult_bound_push: PositiveFloat = 0.001¶
Same as
bound_pushfor the bound multipliers in the warm start initializer.
- warm_start_mult_init_max: float = 1000000.0¶
Maximum absolute initial value of the constraint and bound multipliers when using a warm start.
- warm_start_entire_iterate: YesNoBool = False¶
Advanced feature. Whether to use the GetWarmStartIterate method in the NLP instead of GetStartingPoint when using a warm start.
The NLP that optimagic passes to Ipopt does not provide a warm start iterate, so Ipopt falls back to GetStartingPoint and this option has no effect.
- option_file_name: str = ''¶
File name of an Ipopt options file.
By default, optimagic passes an empty string, which disables reading of an options file (Ipopt’s own default is “ipopt.opt”). If a name is given, Ipopt reads additional options from that file.
- replace_bounds: YesNoBool = False¶
Advanced feature. Whether all variable bounds should be replaced by inequality constraints.
Ipopt requires this for its inexact algorithm, which optimagic does not expose. For problems with bounds but without nonlinear constraints, enabling this option currently raises an error.
- skip_finalize_solution_call: YesNoBool = False¶
Advanced feature. Whether the call to NLP::FinalizeSolution after the optimization should be suppressed.
Warning
optimagic receives the solution through this call. If it is suppressed, the result reports the start parameters and a meaningless objective value while still claiming success.
- timing_statistics: YesNoBool = False¶
Whether to measure the time spent in the components of Ipopt and the NLP evaluation.
The overall algorithm time is unaffected by this option.
- mu_max_fact: PositiveFloat = 1000¶
Factor for the initialization of the maximum value of the barrier parameter.
In Ipopt, the upper bound on the barrier parameter is computed as the average complementarity at the initial point times the value of this option, unless
mu_maxis set. Since optimagic always passesmu_max, this option currently has no effect. Only used ifmu_strategyis “adaptive”.
- mu_max: PositiveFloat = 100000¶
Maximum value for the barrier parameter.
This option specifies an upper bound on the barrier parameter in the adaptive mu selection mode. If this option is set, it overwrites the effect of
mu_max_fact; optimagic always passes it, somu_max_factis never used. Only used ifmu_strategyis “adaptive”.
- mu_min: PositiveFloat = 1e-11¶
Minimum value for the barrier parameter.
This option specifies the lower bound on the barrier parameter in the adaptive mu selection mode. Ipopt derives a tolerance-dependent value if this option is not set; since optimagic always passes it, the given value is used as is (also in the restoration phase). Only used if
mu_strategyis “adaptive”.
- adaptive_mu_globalization: Literal['obj-constr-filter', 'kkt-error', 'never-monotone-mode'] = 'obj-constr-filter'¶
Globalization strategy for the adaptive mu selection mode.
To achieve global convergence of the adaptive version, the algorithm has to switch to the monotone mode (Fiacco-McCormick approach) when convergence does not seem to appear. This option sets the criterion used to decide when to make this switch. Possible values:
“kkt-error”: nonmonotone decrease of the KKT error
“obj-constr-filter”: two-dimensional filter for objective and constraint violation
“never-monotone-mode”: disables globalization
Only used if
mu_strategyis “adaptive”.
- adaptive_mu_kkterror_red_iters: NonNegativeInt = 4¶
Advanced feature. Maximum number of iterations requiring sufficient progress.
For the “kkt-error” based globalization strategy, sufficient progress must be made for this many iterations. If this number of iterations is exceeded, the globalization strategy switches to the monotone mode.
- adaptive_mu_kkterror_red_fact: PositiveFloat = 0.9999¶
Advanced feature. Sufficient decrease factor for the “kkt-error” globalization strategy.
For the “kkt-error” based globalization strategy, the error must decrease by this factor to be deemed sufficient decrease. The valid range is (0, 1).
- filter_margin_fact: PositiveFloat = 1e-05¶
Advanced feature. Factor determining the width of the margin for the “obj-constr-filter” adaptive globalization strategy.
Sufficient progress for a filter entry is defined as: (new obj) < (filter obj) - filter_margin_fact * (new constr-viol) or (new constr-viol) < (filter constr-viol) - filter_margin_fact * (new constr-viol). The valid range is (0, 1).
- filter_max_margin: PositiveFloat = 1¶
Advanced feature.
Maximum width of the margin in the “obj-constr-filter” adaptive globalization strategy.
- adaptive_mu_restore_previous_iterate: YesNoBool = False¶
Advanced feature. Whether the previous accepted iterate should be restored if the monotone mode is entered.
When the globalization strategy for the adaptive barrier algorithm switches to the monotone mode, it can either start from the most recent iterate (False) or from the last iterate that was accepted (True).
- adaptive_mu_monotone_init_factor: PositiveFloat = 0.8¶
Advanced feature. Determines the initial value of the barrier parameter when switching to the monotone mode.
When the globalization strategy for the adaptive barrier algorithm switches to the monotone mode and
fixed_mu_oracleis chosen as “average_compl”, the barrier parameter is set to the current average complementarity times the value of this option.
- adaptive_mu_kkt_norm_type: Literal['max-norm', '2-norm-squared', '1-norm', '2-norm'] = '2-norm-squared'¶
Advanced feature. Norm used for the KKT error in the adaptive mu globalization strategies.
When computing the KKT error for the globalization strategies, the norm to be used is specified with this option. Note that in Ipopt 3.14 this option is registered but not read; the norm is taken from
quality_function_norm_typeinstead.
- mu_strategy: Literal['monotone', 'adaptive'] = 'monotone'¶
Update strategy for the barrier parameter.
“monotone” uses the monotone (Fiacco-McCormick) strategy; “adaptive” uses the adaptive update strategy from [algo_58]. Ipopt (and cyipopt’s
minimize_ipopt) use “adaptive” if this option is not set and the Hessian is approximated with limited-memory updates; since optimagic always passes this option, its default is “monotone”.
- mu_oracle: Literal['probing', 'quality-function', 'loqo'] = 'quality-function'¶
Oracle for a new barrier parameter in the adaptive strategy.
Determines how a new barrier parameter is computed in each “free-mode” iteration of the adaptive barrier parameter strategy. Possible values:
“probing”: Mehrotra’s probing heuristic
“loqo”: LOQO’s centrality rule
“quality-function”: minimize a quality function
Only used if
mu_strategyis “adaptive”.
- fixed_mu_oracle: Literal['probing', 'loqo', 'quality-function', 'average_compl'] = 'average_compl'¶
Oracle for the barrier parameter when switching to the fixed mode.
Determines how the first value of the barrier parameter should be computed when switching to the “monotone mode” in the adaptive strategy. In addition to the choices for
mu_oracle, “average_compl” bases the value on the current average complementarity. Only used ifmu_strategyis “adaptive”.
- mu_init: PositiveFloat = 0.1¶
Initial value for the barrier parameter.
This option determines the initial value for the barrier parameter mu. It is only relevant in the monotone, Fiacco-McCormick version of the algorithm, i.e. if
mu_strategyis “monotone”.
- barrier_tol_factor: PositiveFloat = 10¶
Factor for mu in the barrier stop test.
The convergence tolerance for each barrier problem in the monotone mode is the value of the barrier parameter times this factor. This option is also used in the adaptive mu strategy during the monotone mode. This is kappa_epsilon in [algo_57].
- mu_linear_decrease_factor: PositiveFloat = 0.2¶
Determines the linear decrease rate of the barrier parameter.
For the Fiacco-McCormick update procedure, the new barrier parameter mu is obtained by taking the minimum of
mu * mu_linear_decrease_factorandmu ** mu_superlinear_decrease_power. This is kappa_mu in [algo_57]. This option is also used in the adaptive mu strategy during the monotone mode. The valid range is (0, 1).
- mu_superlinear_decrease_power: GtOneFloat = 1.5¶
Determines the superlinear decrease rate of the barrier parameter.
For the Fiacco-McCormick update procedure, the new barrier parameter mu is obtained by taking the minimum of
mu * mu_linear_decrease_factorandmu ** mu_superlinear_decrease_power. This is theta_mu in [algo_57]. This option is also used in the adaptive mu strategy during the monotone mode. The valid range is (1, 2).
- mu_allow_fast_monotone_decrease: YesNoBool = True¶
Advanced feature. Allow skipping of the barrier problem if the barrier test is already met.
If False, the algorithm takes at least one iteration per barrier problem, even if the barrier test is already met for the updated barrier parameter.
- tau_min: PositiveFloat = 0.99¶
Advanced feature. Lower bound on the fraction-to-the-boundary parameter tau.
This is tau_min in [algo_57]. This option is also used in the adaptive mu strategy during the monotone mode. The valid range is (0, 1).
- sigma_max: PositiveFloat = 100¶
Advanced feature. Maximum value of the centering parameter.
This is the upper bound for the centering parameter chosen by the quality function based barrier parameter update. Only used if
mu_oracleis “quality-function”.
- sigma_min: NonNegativeFloat = 1e-06¶
Advanced feature. Minimum value of the centering parameter.
This is the lower bound for the centering parameter chosen by the quality function based barrier parameter update. Only used if
mu_oracleis “quality-function”.
- quality_function_norm_type: Literal['max-norm', '2-norm-squared', '1-norm', '2-norm'] = '2-norm-squared'¶
Advanced feature. Norm used for the components of the quality function.
Only used if
mu_oracleis “quality-function”.
- quality_function_centrality: Literal['none', 'reciprocal', 'log', 'cubed-reciprocal'] | None = None¶
Advanced feature. The penalty term for centrality that is included in the quality function.
This determines whether a term is added to the quality function to penalize deviation from centrality with respect to complementarity. The complementarity measure here is the xi in the LOQO update rule. Possible values:
Noneor “none”: no penalty term is added“log”: complementarity times the log of the centrality measure
“reciprocal”: complementarity times the reciprocal of the centrality measure
“cubed-reciprocal”: complementarity times the reciprocal of the centrality measure cubed
Only used if
mu_oracleis “quality-function”.
- quality_function_balancing_term: Literal['none', 'cubic'] | None = None¶
Advanced feature. The balancing term included in the quality function for centrality.
This determines whether a term is added to the quality function that penalizes situations where the complementarity is much smaller than the dual and primal infeasibilities.
None(or “none”) adds no balancing term; “cubic” addsmax(0, max(dual_inf, primal_inf) - compl)**3. Only used ifmu_oracleis “quality-function”.
- quality_function_max_section_steps: NonNegativeInt = 8¶
Maximum number of search steps during the direct search procedure determining the optimal centering parameter.
The golden section search is performed for the quality function based mu oracle. Only used if
mu_oracleis “quality-function”.
- quality_function_section_sigma_tol: NonNegativeFloat = 0.01¶
Advanced feature. Tolerance for the section search procedure determining the optimal centering parameter (in sigma space).
The golden section search is performed for the quality function based mu oracle. Only used if
mu_oracleis “quality-function”. The valid range is [0, 1).
- quality_function_section_qf_tol: NonNegativeFloat = 0.0¶
Advanced feature. Tolerance for the golden section search procedure determining the optimal centering parameter (in the function value space).
Only used if
mu_oracleis “quality-function”. The valid range is [0, 1).
- line_search_method: Literal['filter', 'penalty', 'cg-penalty'] = 'filter'¶
Advanced feature. Globalization method used in the backtracking line search.
Only the “filter” choice is officially supported, but sometimes good results might be obtained with “cg-penalty” (Chen-Goldfarb penalty function) or “penalty” (standard penalty function).
- alpha_red_factor: PositiveFloat = 0.5¶
Advanced feature. Fractional reduction of the trial step size in the backtracking line search.
At every step of the backtracking line search, the trial step size is reduced by this factor. The valid range is (0, 1).
- accept_every_trial_step: YesNoBool = False¶
Always accept the first trial step.
Setting this option to True essentially disables the line search and makes the algorithm take aggressive steps, without global convergence guarantees.
- accept_after_max_steps: Literal[-1] | NonNegativeInt = -1¶
Advanced feature. Accept a trial point after at most this number of steps, even if it does not satisfy the line search conditions.
Setting this to -1 disables this heuristic.
- alpha_for_y: Literal['primal', 'bound-mult', 'min', 'max', 'full', 'min-dual-infeas', 'safer-min-dual-infeas', 'primal-and-full', 'dual-and-full', 'acceptor'] = 'primal'¶
Method to determine the step size for the equality constraint multipliers (alpha_y).
Possible values:
“primal”: use the primal step size
“bound-mult”: use the step size for the bound multipliers (good for LPs)
“min”: use the min of the primal and bound multiplier step sizes
“max”: use the max of the primal and bound multiplier step sizes
“full”: take a full step of size one
“min-dual-infeas”: choose the step size minimizing the new dual infeasibility
“safer-min-dual-infeas”: like “min-dual-infeas”, but safeguarded by “min” and “max”
“primal-and-full”: use the primal step size, and a full step if
delta_x <= alpha_for_y_tol“dual-and-full”: use the dual step size, and a full step if
delta_x <= alpha_for_y_tol“acceptor”: call LSAcceptor to get the step size for y
- alpha_for_y_tol: NonNegativeFloat = 10¶
Tolerance for switching to full equality multiplier steps.
This is only relevant if
alpha_for_yis “primal-and-full” or “dual-and-full”. The step size for the equality constraint multipliers is taken to be one if the max-norm of the primal step is less than this tolerance.
- tiny_step_tol: NonNegativeFloat = 2.22045e-15¶
Advanced feature. Tolerance for detecting numerically insignificant steps.
If the search direction in the primal variables (x and s) is, in relative terms for each component, less than this value, the algorithm accepts the full step without a line search. If this happens repeatedly, the algorithm terminates with a corresponding exit message. The default value is 10 times machine precision.
- tiny_step_y_tol: NonNegativeFloat = 0.01¶
Advanced feature. Tolerance for quitting because of numerically insignificant steps.
If the search direction in the primal variables (x and s) is, in relative terms for each component, repeatedly less than
tiny_step_toland the step in the y variables is smaller than this threshold, the algorithm terminates.
- watchdog_shortened_iter_trigger: NonNegativeInt = 10¶
Number of shortened iterations that trigger the watchdog procedure.
If the number of successive iterations in which the backtracking line search did not accept the first trial point exceeds this number, the watchdog procedure is activated. Choosing 0 disables the watchdog procedure.
- watchdog_trial_iter_max: PositiveInt = 3¶
Maximum number of watchdog iterations.
This option determines the number of trial iterations allowed before the watchdog procedure is aborted and the algorithm returns to the stored point.
- theta_max_fact: PositiveFloat = 10000¶
Advanced feature. Determines the upper bound for the constraint violation in the filter.
The algorithmic parameter theta_max is determined as this value times the maximum of 1 and the constraint violation at the initial point. Any point with a constraint violation larger than theta_max is unacceptable to the filter (see Eqn. (21) in [algo_57]).
- theta_min_fact: PositiveFloat = 0.0001¶
Advanced feature. Determines the constraint violation threshold in the switching rule.
The algorithmic parameter theta_min is determined as this value times the maximum of 1 and the constraint violation at the initial point. The switching rule treats an iteration as an h-type iteration whenever the current constraint violation is larger than theta_min (see paragraph before Eqn. (19) in [algo_57]).
- eta_phi: PositiveFloat = 1e-08¶
Advanced feature. Relaxation factor in the Armijo condition.
See Eqn. (20) in [algo_57]. The valid range is (0, 0.5).
- delta: PositiveFloat = 1¶
Advanced feature. Multiplier for the constraint violation in the switching rule.
See Eqn. (19) in [algo_57].
- s_phi: GtOneFloat = 2.3¶
Advanced feature. Exponent for the linear barrier function model in the switching rule.
See Eqn. (19) in [algo_57].
- s_theta: GtOneFloat = 1.1¶
Advanced feature. Exponent for the current constraint violation in the switching rule.
See Eqn. (19) in [algo_57].
- gamma_phi: PositiveFloat = 1e-08¶
Advanced feature. Relaxation factor in the filter margin for the barrier function.
See Eqn. (18a) in [algo_57]. The valid range is (0, 1).
- gamma_theta: PositiveFloat = 1e-05¶
Advanced feature. Relaxation factor in the filter margin for the constraint violation.
See Eqn. (18b) in [algo_57]. The valid range is (0, 1).
- alpha_min_frac: PositiveFloat = 0.05¶
Advanced feature. Safety factor for the minimal step size (before switching to the restoration phase).
This is gamma_alpha in Eqn. (23) in [algo_57]. The valid range is (0, 1).
- max_soc: NonNegativeInt = 4¶
Maximum number of second order correction trial steps at each iteration.
Choosing 0 disables the second order corrections. This is p^max of Step A-5.9 of Algorithm A in [algo_57].
- kappa_soc: PositiveFloat = 0.99¶
Advanced feature. Factor in the sufficient reduction rule for the second order correction.
This option determines how much a second order correction step must reduce the constraint violation so that further correction steps are attempted. See Step A-5.9 of Algorithm A in [algo_57].
- obj_max_inc: float = 5.0¶
Advanced feature. Upper bound on the acceptable increase of the barrier objective function.
Trial points are rejected if they lead to an increase in the barrier objective function by more than this many orders of magnitude. The valid range is (1, inf).
- max_filter_resets: NonNegativeInt = 5¶
Advanced feature. Maximal allowed number of filter resets.
A positive number enables a heuristic that resets the filter whenever in more than
filter_reset_triggersuccessive iterations the last rejected trial step size was rejected because of the filter. This option determines the maximal number of resets that are allowed to take place.
- filter_reset_trigger: PositiveInt = 5¶
Advanced feature. Number of iterations that trigger the filter reset.
If the filter reset heuristic is active and the last rejected trial step size was rejected because of the filter for this many successive iterations, the filter is reset.
- corrector_type: Literal['none', 'affine', 'primal-dual'] | None = None¶
Advanced feature. The type of corrector steps that should be taken.
If
mu_strategyis “adaptive”, this option determines what kind of corrector steps should be tried. Possible values areNone(or “none”, no corrector), “affine” (corrector step towards mu=0) and “primal-dual” (corrector step towards the current mu). Changing this option is experimental.
- skip_corr_if_neg_curv: YesNoBool = True¶
Advanced feature. Whether to skip the corrector step in negative curvature iterations.
The corrector step is not tried if negative curvature has been encountered during the computation of the search direction in the current iteration. Only used if
mu_strategyis “adaptive”. Changing this option is experimental.
- skip_corr_in_monotone_mode: YesNoBool = True¶
Advanced feature. Whether to skip the corrector step during the monotone barrier parameter mode.
The corrector step is not tried if the algorithm is currently in the monotone mode. Only used if
mu_strategyis “adaptive”. Changing this option is experimental.
- corrector_compl_avrg_red_fact: PositiveFloat = 1¶
Advanced feature. Complementarity tolerance factor for accepting a corrector step.
This option determines the factor by which the complementarity is allowed to increase for a corrector step to be accepted. Changing this option is experimental.
- soc_method: Literal[0, 1] = 0¶
Ways to apply the second order correction.
0 is the method described in [algo_57]; 1 is a modified way which adds alpha on the right hand side of the x and s rows.
- nu_init: PositiveFloat = 1e-06¶
Advanced feature.
Initial value of the penalty parameter in the penalty function based line search.
- nu_inc: PositiveFloat = 0.0001¶
Advanced feature.
Increment of the penalty parameter in the penalty function based line search.
- rho: PositiveFloat = 0.1¶
Advanced feature. Value in the penalty parameter update formula.
The valid range is (0, 1).
- kappa_sigma: PositiveFloat = 10000000000.0¶
Advanced feature. Factor limiting the deviation of the dual variables from their primal estimates.
If the dual variables deviate from their primal estimates, a correction is performed. See Eqn. (16) in [algo_57]. Setting the value to less than 1 disables the correction.
- recalc_y: YesNoBool = False¶
Whether to recalculate the equality and inequality multipliers as least-squares estimates.
This asks the algorithm to recompute the multipliers whenever the current infeasibility is less than
recalc_y_feas_tol. Choosing True might be helpful in the quasi-Newton option, but each recalculation requires an extra factorization of the linear system. Ipopt enables this automatically for limited-memory quasi-Newton approximations if the option is not set; since optimagic always passes it, it is only used if set to True.
- recalc_y_feas_tol: PositiveFloat = 1e-06¶
Feasibility threshold for the recomputation of multipliers.
If
recalc_yis chosen and the current infeasibility is less than this value, the multipliers are recomputed.
- slack_move: NonNegativeFloat = 1.81899e-12¶
Advanced feature. Correction size for very small slacks.
Due to numerical issues or the lack of an interior, the slack variables might become very small. If a slack becomes very small compared to machine precision, the corresponding bound is moved slightly; this parameter determines how large the move should be. The default is mach_eps^(3/4). See also the end of Section 3.5 in [algo_57] (the actual implementation might be somewhat different).
- constraint_violation_norm_type: Literal['1-norm', '2-norm', 'max-norm'] = '1-norm'¶
Advanced feature.
Norm to be used for the constraint violation in the line search.
- mehrotra_algorithm: YesNoBool = False¶
Whether to do Mehrotra’s predictor-corrector algorithm.
If enabled, the line search is disabled and the (unglobalized) adaptive mu strategy is chosen with the “probing” oracle, and affine corrector steps are used without any safeguards. Mehrotra’s predictor-corrector algorithm usually works very well for LPs and convex QPs.
Warning
Ipopt selects these settings only for options that are not set, but optimagic always passes all options. Enabling only this option therefore makes Ipopt abort with “Invalid option encountered”; you also need
mu_strategy="adaptive",mu_oracle="probing",adaptive_mu_globalization="never-monotone-mode"andaccept_every_trial_step=True(withcorrector_type=None). Ipopt’s more aggressive defaults forbound_push,bound_frac,bound_mult_init_val,constr_mult_init_max,alpha_for_yandleast_square_init_primalare not applied either.
- fast_step_computation: YesNoBool = False¶
Whether the linear system should be solved quickly.
If enabled, the algorithm assumes that the linear system that is solved to obtain the search direction is solved sufficiently well. In that case, no residuals are computed to verify the solution and the computation of the search direction is a little faster.
- min_refinement_steps: NonNegativeInt = 1¶
Minimum number of iterative refinement steps per linear system solve.
Iterative refinement (on the full unsymmetric system) is performed for each right hand side; at least this many iterative refinement steps are enforced per right hand side.
- max_refinement_steps: NonNegativeInt = 10¶
Maximum number of iterative refinement steps per linear system solve.
Iterative refinement (on the full unsymmetric system) is performed for each right hand side.
- residual_ratio_max: PositiveFloat = 1e-10¶
Advanced feature. Iterative refinement tolerance.
Iterative refinement is performed until the residual test ratio is less than this tolerance (or until
max_refinement_stepsrefinement steps are performed).
- residual_ratio_singular: PositiveFloat = 1e-05¶
Advanced feature. Threshold for declaring the linear system singular after failed iterative refinement.
If the residual test ratio is larger than this value after failed iterative refinement, the algorithm pretends that the linear system is singular.
- residual_improvement_factor: PositiveFloat = 1¶
Advanced feature. Minimal required reduction of the residual test ratio in iterative refinement.
If the improvement of the residual test ratio made by one iterative refinement step is not better than this factor, iterative refinement is aborted.
- neg_curv_test_tol: NonNegativeFloat = 0¶
Tolerance for the heuristic to ignore wrong inertia.
If nonzero, incorrect inertia in the augmented system is ignored and Ipopt tests if the direction is a direction of positive curvature. This tolerance is alpha_n in [algo_59] and it determines when the direction is considered to be sufficiently positive. A value in the range [1e-12, 1e-11] is recommended.
- neg_curv_test_reg: YesNoBool = True¶
Whether to do the curvature test with the primal regularization (see [algo_59]).
If False, the original Ipopt approach is used, in which the primal regularization is ignored.
- max_hessian_perturbation: PositiveFloat = 1e+20¶
Maximum value of the regularization parameter for handling negative curvature.
To guarantee that the search directions are proper descent directions, Ipopt requires that the inertia of the (augmented) linear system for the step computation has the correct number of negative and positive eigenvalues. This guides the algorithm away from maximizers and makes Ipopt more likely to converge to first order optimal points that are minimizers. If the inertia is not correct, a multiple of the identity matrix is added to the Hessian of the Lagrangian in the augmented system. This parameter gives the maximum value of the regularization parameter; if a regularization of that size is not enough, the algorithm skips this iteration and goes to the restoration phase. This is delta_w^max in [algo_57].
- min_hessian_perturbation: NonNegativeFloat = 1e-20¶
Smallest perturbation of the Hessian block.
The size of the perturbation of the Hessian block is never selected smaller than this value, unless no perturbation is necessary. This is delta_w^min in [algo_57].
- perturb_inc_fact_first: GtOneFloat = 100¶
Increase factor for the x-s perturbation for the very first perturbation.
The factor by which the perturbation is increased when a trial value was not sufficient; this value is used for the computation of the very first perturbation and allows a different value for the first perturbation than that used for the remaining perturbations. This is bar_kappa_w^+ in [algo_57].
- perturb_inc_fact: GtOneFloat = 8¶
Increase factor for the x-s perturbation.
The factor by which the perturbation is increased when a trial value was not sufficient; this value is used for the computation of all perturbations except for the first. This is kappa_w^+ in [algo_57].
- perturb_dec_fact: PositiveFloat = 0.333333¶
Decrease factor for the x-s perturbation.
The factor by which the perturbation is decreased when a trial value is deduced from the size of the most recent successful perturbation. This is kappa_w^- in [algo_57]. The valid range is (0, 1).
- first_hessian_perturbation: PositiveFloat = 0.0001¶
Size of the first x-s perturbation tried.
This is the first value tried for the x-s perturbation in the inertia correction scheme. It is delta_0 in [algo_57].
- jacobian_regularization_value: NonNegativeFloat = 1e-08¶
Size of the regularization for rank-deficient constraint Jacobians.
This is bar_delta_c in [algo_57].
- jacobian_regularization_exponent: NonNegativeFloat = 0.25¶
Advanced feature. Exponent for mu in the regularization for rank-deficient constraint Jacobians.
This is kappa_c in [algo_57].
- perturb_always_cd: YesNoBool = False¶
Advanced feature. Activate the permanent perturbation of the constraint linearization.
Enabling this option leads to using the delta_c and delta_d perturbations for the computation of every search direction. Usually, they are only used when the iteration matrix is singular.
- expect_infeasible_problem: YesNoBool = False¶
Enable heuristics to quickly detect an infeasible problem.
This option activates heuristics that may speed up the infeasibility determination if you expect that there is a good chance for the problem to be infeasible. In the filter line search procedure, the restoration phase is called more quickly than usual. Ipopt additionally enforces more reduction in the constraint violation before the restoration phase is left, but only if
required_infeasibility_reductionis not set, which is never the case in optimagic.
- expect_infeasible_problem_ctol: NonNegativeFloat = 0.001¶
Threshold for disabling the
expect_infeasible_problemoption.If the constraint violation becomes smaller than this threshold, the
expect_infeasible_problemheuristics in the filter line search are disabled. If the problem is square, this option is set to 0.
- expect_infeasible_problem_ytol: PositiveFloat = 100000000.0¶
Multiplier threshold for activating the
expect_infeasible_problemoption.If the max-norm of the constraint multipliers becomes larger than this value and
expect_infeasible_problemis chosen, then the restoration phase is entered.
- start_with_resto: YesNoBool = False¶
Whether to switch to the restoration phase in the first iteration.
Setting this option to True forces the algorithm to switch to the feasibility restoration phase in the first iteration. If the initial point is feasible, the algorithm will abort with a failure.
- soft_resto_pderror_reduction_factor: NonNegativeFloat = 0.9999¶
Required reduction in the primal-dual error in the soft restoration phase.
The soft restoration phase attempts to reduce the primal-dual error with regular steps. If the damped primal-dual step (damped only to satisfy the fraction-to-the-boundary rule) is not decreasing the primal-dual error by at least this factor, then the regular restoration phase is called. Choosing 0 here disables the soft restoration phase.
- max_soft_resto_iters: NonNegativeInt = 10¶
Advanced feature. Maximum number of iterations performed successively in the soft restoration phase.
If the soft restoration phase is performed for more than this many iterations in a row, the regular restoration phase is called.
- required_infeasibility_reduction: NonNegativeFloat = 0.9¶
Required reduction of the infeasibility before leaving the restoration phase.
The restoration phase algorithm is performed until a point is found that is acceptable to the filter and the infeasibility has been reduced by at least the fraction given by this option. The valid range is [0, 1).
- max_resto_iter: NonNegativeInt = 3000000¶
Advanced feature. Maximum number of successive iterations in the restoration phase.
The algorithm terminates with an error message if the number of iterations successively taken in the restoration phase exceeds this number.
- evaluate_orig_obj_at_resto_trial: YesNoBool = True¶
Whether the original objective function should be evaluated at restoration phase trial points.
Enabling this option makes the restoration phase algorithm evaluate the objective function of the original problem at every trial point encountered during the restoration phase, even if this value is not required. This guarantees that the original objective function can be evaluated without error at all accepted iterates; otherwise the algorithm might fail at a point where the restoration phase accepts an iterate that is good for the restoration phase problem but not the original problem. On the other hand, if the evaluation of the original objective is expensive, this might be costly.
- resto_penalty_parameter: PositiveFloat = 1000¶
Advanced feature. Penalty parameter in the restoration phase objective function.
This is the parameter rho in equation (31a) in [algo_57].
- resto_proximity_weight: NonNegativeFloat = 1¶
Advanced feature. Weighting factor for the proximity term in the restoration phase objective.
This determines how the parameter zeta in equation (29a) in [algo_57] is computed. zeta here is this value times the square root of mu, where mu is the current barrier parameter.
- bound_mult_reset_threshold: NonNegativeFloat = 1000¶
Threshold for resetting the bound multipliers after the restoration phase.
After returning from the restoration phase, the bound multipliers are updated with a Newton step for complementarity, where the change in the primal variables during the entire restoration phase is taken to be the corresponding primal Newton step. However, if after the update the largest bound multiplier exceeds this threshold, the multipliers are all reset to 1.
- constr_mult_reset_threshold: NonNegativeFloat = 0¶
Threshold for resetting the equality and inequality multipliers after the restoration phase.
After returning from the restoration phase, the constraint multipliers are recomputed by a least-squares estimate. This option triggers when those least-squares estimates should be ignored.
- resto_failure_feasibility_threshold: NonNegativeFloat | None = None¶
Advanced feature. Threshold for the primal infeasibility to declare failure of the restoration phase.
If the restoration phase is terminated because of the “acceptable” termination criteria and the primal infeasibility is smaller than this value, the restoration phase is declared to have failed. If
None(the default), it is set to100 * convergence_ftol_rel.
- limited_memory_aug_solver: Literal['sherman-morrison', 'extended'] = 'sherman-morrison'¶
Advanced feature. Strategy for solving the augmented system for the low-rank Hessian.
“sherman-morrison” uses the Sherman-Morrison formula; “extended” uses an extended augmented system.
- limited_memory_max_history: NonNegativeInt = 6¶
Maximum size of the history for the limited-memory quasi-Newton Hessian approximation.
This option determines the number of most recent iterations that are taken into account for the limited-memory quasi-Newton approximation.
- limited_memory_update_type: Literal['bfgs', 'sr1'] = 'bfgs'¶
Quasi-Newton update formula for the limited-memory quasi-Newton approximation.
“bfgs” is the BFGS update (with skipping); “sr1” is the SR1 update (not working well).
- limited_memory_initialization: Literal['scalar1', 'scalar2', 'scalar3', 'scalar4', 'constant'] = 'scalar1'¶
Initialization strategy for the limited-memory quasi-Newton approximation.
Determines how the diagonal matrix B_0 as the first term in the limited-memory approximation should be computed. Possible values:
“scalar1”: sigma = s^T y / s^T s
“scalar2”: sigma = y^T y / s^T y
“scalar3”: arithmetic average of scalar1 and scalar2
“scalar4”: geometric average of scalar1 and scalar2
“constant”: sigma =
limited_memory_init_val
- limited_memory_init_val: PositiveFloat = 1¶
Value for B_0 in the low-rank update.
The starting matrix in the low-rank update, B_0, is chosen to be this multiple of the identity in the first iteration (when no updates have been performed yet), and is constantly chosen as this value if
limited_memory_initializationis “constant”.
- limited_memory_init_val_max: PositiveFloat = 100000000.0¶
Upper bound on the value for B_0 in the low-rank update.
- limited_memory_init_val_min: PositiveFloat = 1e-08¶
Lower bound on the value for B_0 in the low-rank update.
- limited_memory_max_skipping: PositiveInt = 2¶
Threshold for successive iterations where the quasi-Newton update is skipped.
If the update is skipped more than this number of successive iterations, the quasi-Newton approximation is reset.
- limited_memory_special_for_resto: YesNoBool = False¶
Whether the quasi-Newton updates should be special during the restoration phase.
Until Nov 2010, Ipopt used a special update during the restoration phase, but it turned out that this does not work well. The new default uses the regular update procedure, which improves results. If for some reason you want to get back to the original update, set this option to True.
- hessian_approximation: Literal['limited-memory', 'exact'] = 'limited-memory'¶
Indicates what Hessian information is to be used.
“limited-memory” performs a limited-memory quasi-Newton approximation of the Hessian of the Lagrangian. “exact” (Ipopt’s own default) uses second derivatives provided by the NLP. Since optimagic does not pass second derivatives to Ipopt, the default is “limited-memory”.
Warning
Do not use “exact”: without second derivatives, Ipopt runs without valid Hessian information and does not raise an error.
- hessian_approximation_space: Literal['nonlinear-variables', 'all-variables'] = 'nonlinear-variables'¶
Advanced feature. Indicates in which subspace the Hessian information is to be approximated.
“nonlinear-variables” approximates only in the space of the nonlinear variables; “all-variables” approximates in the space of all variables (without slacks).
- linear_solver: Literal['mumps', 'ma27', 'ma57', 'ma77', 'ma86', 'ma97', 'pardiso', 'custom'] = 'mumps'¶
Linear solver used for the step computations.
Determines which linear algebra package is used for the solution of the augmented linear system (for obtaining the search directions). The default in optimagic is “mumps” (the MUMPS package that ships with most cyipopt installations); Ipopt’s documented default is “ma27”, which requires the HSL library. The Harwell routines “ma27”, “ma57”, “ma77”, “ma86” and “ma97” as well as “pardiso” are loaded from libraries at runtime and require these to be installed; “custom” selects a custom linear solver (expert use). The Ipopt values “pardisomkl”, “spral” and “wsmp” are not supported.
- linear_solver_options: dict[str, Any] | None = None¶
Dictionary with the linear solver options, possibly including
linear_system_scaling,hsllibandpardisolib.See the Ipopt documentation for details. The linear solver options are not automatically converted to float at the moment.
The Fides Optimizer¶
optimagic supports the
Fides Optimizer. To use Fides, you
need to have the fides package installed
(pip install fides>=0.7.4).
fides
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.fides(hessian_update_strategy="bfgs"),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="fides",
algo_options={"hessian_update_strategy": "bfgs"},
)
Description and available options:
- class optimagic.optimizers.fides.Fides[source]¶
Minimize a scalar function using the Fides trust-region optimizer.
Fides implements an Interior Trust-Region Reflective method for bound-constrained optimization, following the approach of [algo_60] and [algo_16]. Accordingly, Fides is named after the Roman goddess of trust and reliability. The optimizer is taken from the
fidespackage ([algo_61]), which must be installed separately (pip install "fides>=0.7.4").Fides is a gradient-based local optimizer for smooth, differentiable scalar objective functions. It supports lower and upper bounds (including infinite bounds) but no linear or nonlinear constraints. It requires first derivatives; the Hessian is approximated internally using one of several quasi-Newton update strategies, so no user-provided Hessian is needed.
In contrast to many other trust-region methods, Fides can solve the full trust-region subproblem exactly rather than approximately; this is the case for the default
trustregion_subspace_dimension="full". This can yield higher-quality proposal steps at a higher per-iteration cost, which makes Fides especially attractive when the objective function is expensive to evaluate and the cost of solving the trust-region subproblem is negligible in comparison.Note
General linear and nonlinear constraints are not supported by optimagic.
- hessian_update_strategy: HessianUpdateStrategy = 'bfgs'¶
Quasi-Newton strategy used to approximate the Hessian of the objective.
Can be the (case-insensitive) name of a strategy or an instance of
fides.hessian_approximation.HessianApproximation. The available names are:"bfgs": the Broyden-Fletcher-Goldfarb-Shanno update, a rank-2 update that preserves symmetry and positive definiteness. This is the default."dfp": the Davidon-Fletcher-Powell update."sr1": the Symmetric Rank 1 update, described in [algo_62], Chapter 6.2."bb": Broyden’s “bad” method, introduced in [algo_63]."bg": Broyden’s “good” method, introduced in [algo_63].
The general Broyden class update is a convex combination of the BFGS and DFP updates controlled by an interpolation parameter \(\phi\) ([algo_62], Chapter 6.3): \(\phi = 0\) gives BFGS and \(\phi = 1\) gives DFP. For \(\phi \in [0, 1]\) the update preserves symmetry and positive semi-definiteness. It cannot be selected by name because \(\phi\) has no default; instead, create an instance of
fides.hessian_approximation.Broydenwith the desired \(\phi\) and pass it here.The residual-based approximations
FX,SSM,TSSMandGNSBFGSprovided by thefidespackage are not available, because optimagic does not pass least-squares residuals to fides.
- convergence_ftol_abs: NonNegativeFloat = 0¶
Stop when the absolute change in the objective becomes small.
Denoting the absolute criterion tolerance by \(\alpha\) (this parameter) and the relative criterion tolerance by \(\beta\) (
convergence_ftol_rel), Fides stops successfully when\[|f_k - f_{k-1}| < \alpha + \beta \, |f_{k-1}|\]in an iteration in which the trust-region radius was not increased. Here, \(f_k\) is the objective value at the proposed point and \(f_{k-1}\) the one at the current iterate.
This parameter therefore governs convergence on its own only when
convergence_ftol_relis set to 0. Note that optimagic defaults to 0, whereas thefidespackage itself defaults to 1e-8.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Stop when the relative change in the objective becomes small.
This is the relative criterion tolerance \(\beta\) in the joint convergence condition documented under
convergence_ftol_abs. It governs convergence on its own only whenconvergence_ftol_absis set to 0 (as is the default). Note that optimagic defaults to 2e-9, whereas thefidespackage itself defaults to 1e-8.
- convergence_xtol_abs: NonNegativeFloat = 0¶
Stop when the step size becomes small.
The optimization terminates successfully when the norm of the step \(\|x_{k} - x_{k-1}\|\) falls below this tolerance.
- convergence_gtol_abs: NonNegativeFloat = 1e-05¶
Stop when the gradient norm is less than or equal to this tolerance.
Note that optimagic defaults to 1e-5, whereas the
fidespackage itself defaults to 1e-6.
- convergence_gtol_rel: NonNegativeFloat = 1e-08¶
Stop when the gradient norm divided by the absolute function value is less than or equal to this tolerance.
Note that optimagic defaults to 1e-8, whereas the
fidespackage itself defaults to 0, i.e. deactivates this criterion.
- stopping_maxiter: PositiveInt = 1000000¶
Maximum number of iterations.
Note that optimagic defaults to 1,000,000, whereas the
fidespackage itself defaults to 1,000.
- stopping_max_seconds: float = inf¶
Maximum number of wall-clock seconds. Deactivated (infinite) by default.
- trustregion_initial_radius: PositiveFloat = 1.0¶
Initial trust-region radius.
- trustregion_stepback_strategy: Literal['truncate', 'reflect', 'reflect_single', 'mixed'] = 'truncate'¶
Refinement strategy applied when a proposed step reaches a parameter bound.
The available options are:
"truncate": truncate the step at the boundary and re-solve the restricted subproblem. This is optimagic’s default."reflect": recursive reflections at the boundary."reflect_single": a single reflection at the boundary."mixed": mix reflections and truncations.
Note that optimagic defaults to
"truncate", whereas thefidespackage itself defaults to"reflect".
- trustregion_subspace_dimension: Literal['full', '2D', 'scg'] = 'full'¶
Dimension of the subspace in which the trust-region subproblem is solved.
The available options are:
"full": use the full parameter dimensionality. This is optimagic’s default."2D": a two-dimensional Newton/gradient subspace."scg": a conjugate-gradient subspace via Steihaug’s method.
Note that optimagic defaults to
"full", whereas thefidespackage itself defaults to"2D".
- trustregion_max_stepback_fraction: float = 0.95¶
Controls how close steps are allowed to get to the boundary.
It is the maximal fraction of a step to take if the full step would reach a breakpoint (the bound).
- trustregion_decrease_threshold: float = 0.25¶
Threshold for the trust-region ratio at or below which the radius is decreased.
Note that this is not an acceptance threshold: fides accepts every step with a positive trust-region ratio. This is the
muoption of fides; its default is the value used in algorithm 4.1 of [algo_5].
- trustregion_increase_threshold: float = 0.75¶
Threshold for the trust-region ratio at or above which the radius may be increased.
The radius is only increased if, in addition, the norm of the proposed step is at least 90% of the current radius. This is the
etaoption of fides; its default is the value used in algorithm 4.1 of [algo_5].
- trustregion_decrease_factor: float = 0.25¶
Factor by which the trust-region radius is multiplied when it is decreased.
More precisely, the decreased radius is \(\min(\gamma_1 \Delta, \|s\| / 4)\), where \(\gamma_1\) is this factor, \(\Delta\) the current radius and \(s\) the proposed step. This is the
gamma1option of fides; its default is the value used in algorithm 4.1 of [algo_5].
The NLOPT Optimizers (nlopt)¶
optimagic supports the following NLOPT
algorithms. Please add the
appropriate citations in
addition to optimagic when using an NLOPT algorithm. To install nlopt run
conda install nlopt.
PRAXIS, ESCH, ISRES, CRS2-LM, and randomized DIRECT accept a seed option. It must be
an integer between 0 and 2**32 - 1, inclusive. When set, it initializes NLopt’s random
number generator before the optimization. When None, optimagic leaves NLopt’s existing
random state unchanged. The random state is shared by NLopt optimizers on the same
thread in builds with thread-local storage, and may be shared across threads in other
builds. Nested optimizations can therefore change the random stream of an outer
optimization. The deterministic DIRECT variants do not use the seed.
nlopt_bobyqa
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nlopt_bobyqa(stopping_maxfun=10_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nlopt_bobyqa",
algo_options={"stopping_maxfun": 10_000},
)
Description and available options:
- class optimagic.optimizers.nlopt_optimizers.NloptBOBYQA[source]¶
Minimize a scalar function using the BOBYQA algorithm.
BOBYQA (Bound Optimization BY Quadratic Approximation) is a derivative-free local optimizer for bound-constrained problems by M. J. D. Powell [algo_37]. It iteratively constructs a quadratic approximation of the objective function from function values only and minimizes this model in a trust region.
The algorithm is a good choice for smooth scalar problems with a moderate number of parameters when derivatives are not available. Because it relies on a quadratic model, it may perform poorly for objective functions that are not twice-differentiable.
BOBYQA is the successor of Powell’s NEWUOA algorithm (
nlopt_newuoa) and largely supersedes it; in contrast to NEWUOA, it supports bound constraints natively. For noisy or very non-smooth problems, simplex-based methods such asnlopt_neldermeadornlopt_sbplxcan be more robust.The implementation in NLopt [algo_64] is a C translation of Powell’s original Fortran subroutine. In addition, it supports all NLopt stopping criteria and unequal initial step sizes in the different parameters, achieved by internally rescaling the parameters proportional to the initial steps.
- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Stop when an optimization step (or an estimate of the optimum) changes the parameters by less than this value relative to their size.
More precisely, NLopt checks whether the sum of the absolute parameter changes is smaller than this value times the sum of the absolute parameter values. This corresponds to NLopt’s
xtol_relstopping criterion. A value of 0 means that this criterion is disabled.BOBYQA implements this criterion differently: it stops when its trust-region radius falls below this value times the initial trust-region radius.
- convergence_xtol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes every parameter by less than this absolute value.
This corresponds to NLopt’s
xtol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this value multiplied by the absolute value of the function value.
This corresponds to NLopt’s
ftol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_ftol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this absolute value.
This corresponds to NLopt’s
ftol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- stopping_maxfun: PositiveInt = 1000000¶
Maximum number of objective function evaluations.
If reached, the optimization stops, but this is not counted as successful convergence. This corresponds to NLopt’s
maxevalstopping criterion.
nlopt_neldermead
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nlopt_neldermead(stopping_maxfun=10_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nlopt_neldermead",
algo_options={"stopping_maxfun": 10_000},
)
Description and available options:
- class optimagic.optimizers.nlopt_optimizers.NloptNelderMead[source]¶
Minimize a scalar function using the Nelder-Mead simplex algorithm.
The Nelder-Mead algorithm [algo_2] is a derivative-free local optimizer that maintains a simplex of n+1 points in n dimensions. In each iteration, the simplex is updated by reflecting, expanding or contracting it away from the worst point.
The algorithm is simple and only requires function values. It can make progress on noisy or non-smooth problems where model-based methods such as
nlopt_bobyqafail, but it typically needs many function evaluations and is known to fail to converge for some functions. The relatednlopt_sbplxalgorithm applies Nelder-Mead on a sequence of subspaces, is claimed to be more efficient and robust, and is recommended over Nelder-Mead by the NLopt author.The implementation in NLopt [algo_64] differs from the original algorithm in that it explicitly supports bound constraints: whenever a new point would lie outside the bounds, it is moved exactly onto the boundary. This can collapse the simplex into a lower-dimensional subspace.
Unlike the other NLopt algorithms in optimagic, this algorithm has no
convergence_ftol_reloption, i.e. NLopt’s relative tolerance on the function value is disabled.- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Stop when an optimization step (or an estimate of the optimum) changes the parameters by less than this value relative to their size.
More precisely, NLopt checks whether the sum of the absolute parameter changes is smaller than this value times the sum of the absolute parameter values. This corresponds to NLopt’s
xtol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_xtol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes every parameter by less than this absolute value.
This corresponds to NLopt’s
xtol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- convergence_ftol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this absolute value.
This corresponds to NLopt’s
ftol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- stopping_maxfun: PositiveInt = 1000000¶
Maximum number of objective function evaluations.
If reached, the optimization stops, but this is not counted as successful convergence. This corresponds to NLopt’s
maxevalstopping criterion.
nlopt_praxis
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nlopt_praxis(stopping_maxfun=10_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nlopt_praxis",
algo_options={"stopping_maxfun": 10_000},
)
Description and available options:
- class optimagic.optimizers.nlopt_optimizers.NloptPRAXIS[source]¶
Minimize a scalar function using the principal-axis method.
PRAXIS is a derivative-free local optimizer by Richard Brent [algo_65]. It assumes an approximately quadratic form of the objective function and repeatedly updates a set of conjugate search directions (the principal axes) along which one-dimensional minimizations are performed.
The algorithm is not invariant to scaling of the objective function and may fail under certain rank-preserving transformations of the objective (e.g. transformations that lead to a non-quadratic shape of the objective function).
The algorithm is not deterministic because it takes random steps to avoid stagnation; use
seedto make runs reproducible.The implementation in NLopt [algo_64] is based on a C translation of Brent’s original Fortran code. The original algorithm was designed for unconstrained optimization; NLopt emulates bound constraints via a variable transformation. For bound-constrained problems, this method is dominated by algorithms with native bound support such as
nlopt_bobyqaandnlopt_cobyla.- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Stop when an optimization step (or an estimate of the optimum) changes the parameters by less than this value relative to their size.
More precisely, NLopt checks whether the sum of the absolute parameter changes is smaller than this value times the sum of the absolute parameter values. This corresponds to NLopt’s
xtol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_xtol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes every parameter by less than this absolute value.
This corresponds to NLopt’s
xtol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this value multiplied by the absolute value of the function value.
This corresponds to NLopt’s
ftol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_ftol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this absolute value.
This corresponds to NLopt’s
ftol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- stopping_maxfun: PositiveInt = 1000000¶
Maximum number of objective function evaluations.
If reached, the optimization stops, but this is not counted as successful convergence. This corresponds to NLopt’s
maxevalstopping criterion.
- seed: _NloptSeed | None = None¶
Seed for NLopt’s random number generator, between 0 and 2**32 - 1.
If None, NLopt’s current random state is used and results can differ between runs. NLopt’s random state is shared by all NLopt optimizers on the same thread, so nested optimizations can change the random stream of an outer optimization.
nlopt_cobyla
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nlopt_cobyla(stopping_maxfun=10_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nlopt_cobyla",
algo_options={"stopping_maxfun": 10_000},
)
Description and available options:
- class optimagic.optimizers.nlopt_optimizers.NloptCOBYLA[source]¶
Minimize a scalar function using the COBYLA algorithm.
COBYLA (Constrained Optimization BY Linear Approximations) is a derivative-free local optimizer by M. J. D. Powell that supports nonlinear inequality and equality constraints [algo_6].
It constructs successive linear approximations of the objective function and constraints via a simplex of n+1 points (in n dimensions) and optimizes these approximations in a trust region at each step.
Use it for scalar problems without derivatives, in particular when nonlinear constraints are present: it is the only derivative-free local NLopt optimizer in optimagic that supports them (for global derivative-free optimization with nonlinear constraints, see
nlopt_isres). For unconstrained or bound-constrained smooth problems,nlopt_bobyqausually converges faster because it uses quadratic instead of linear approximations.The implementation in NLopt [algo_64] is based on a C translation of Powell’s original Fortran code and differs from the original implementation in a few ways:
It incorporates all of the NLopt termination criteria.
It adds explicit support for bound constraints.
It allows the trust-region radius to increase if the predicted improvement was approximately right and the simplex is satisfactory, which can improve convergence speed.
It pseudo-randomizes the simplex steps, improving robustness by avoiding accidentally taking steps that do not improve conditioning, while preserving the deterministic nature of the algorithm (a deterministic seed is used).
It supports unequal initial step sizes in the different parameters.
Since the underlying code only supports inequality constraints, equality constraints are automatically transformed into pairs of inequality constraints by NLopt.
- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Stop when an optimization step (or an estimate of the optimum) changes the parameters by less than this value relative to their size.
More precisely, NLopt checks whether the sum of the absolute parameter changes is smaller than this value times the sum of the absolute parameter values. This corresponds to NLopt’s
xtol_relstopping criterion. A value of 0 means that this criterion is disabled.COBYLA implements this criterion differently: it stops when its trust-region radius falls below this value times the initial trust-region radius.
- convergence_xtol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes every parameter by less than this absolute value.
This corresponds to NLopt’s
xtol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this value multiplied by the absolute value of the function value.
This corresponds to NLopt’s
ftol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_ftol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this absolute value.
This corresponds to NLopt’s
ftol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- stopping_maxfun: PositiveInt = 1000000¶
Maximum number of objective function evaluations.
If reached, the optimization stops, but this is not counted as successful convergence. This corresponds to NLopt’s
maxevalstopping criterion.
nlopt_sbplx
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nlopt_sbplx(stopping_maxfun=10_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nlopt_sbplx",
algo_options={"stopping_maxfun": 10_000},
)
Description and available options:
- class optimagic.optimizers.nlopt_optimizers.NloptSbplx[source]¶
Minimize a scalar function using the Subplex algorithm.
Sbplx is a re-implementation of Tom Rowan’s Subplex method [algo_66]. Subplex is a variant of the Nelder-Mead algorithm (
nlopt_neldermead) that applies Nelder-Mead on a sequence of subspaces. It is claimed to be more efficient and robust than the original Nelder-Mead algorithm, while retaining its ability to make progress on noisy and non-smooth objective functions.The implementation in NLopt [algo_64] was rewritten from scratch because the license status of Rowan’s original code is unclear. It differs from the original algorithm in that it explicitly supports bound constraints, which gives a big improvement in the case where the optimum lies against one of the bounds.
- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Stop when an optimization step (or an estimate of the optimum) changes the parameters by less than this value relative to their size.
More precisely, NLopt checks whether the sum of the absolute parameter changes is smaller than this value times the sum of the absolute parameter values. This corresponds to NLopt’s
xtol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_xtol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes every parameter by less than this absolute value.
This corresponds to NLopt’s
xtol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this value multiplied by the absolute value of the function value.
This corresponds to NLopt’s
ftol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_ftol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this absolute value.
This corresponds to NLopt’s
ftol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- stopping_maxfun: PositiveInt = 1000000¶
Maximum number of objective function evaluations.
If reached, the optimization stops, but this is not counted as successful convergence. This corresponds to NLopt’s
maxevalstopping criterion.
nlopt_newuoa
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nlopt_newuoa(stopping_maxfun=10_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nlopt_newuoa",
algo_options={"stopping_maxfun": 10_000},
)
Description and available options:
- class optimagic.optimizers.nlopt_optimizers.NloptNEWUOA[source]¶
Minimize a scalar function using the NEWUOA algorithm.
NEWUOA is a derivative-free local optimizer for unconstrained optimization by M. J. D. Powell [algo_67]. Like BOBYQA, it iteratively constructs a quadratic approximation of the objective function from function values only and minimizes this model in a trust region.
Use it for smooth scalar problems when derivatives are not available. NEWUOA is largely superseded by its successor BOBYQA (
nlopt_bobyqa), which supports bound constraints natively and is usually preferable, in particular for bound-constrained problems.The version in NLopt [algo_64] has been extended to support bound constraints via the
LN_NEWUOA_BOUNDvariant, which solves the trust-region subproblems with the MMA algorithm and truncates some steps to the bounds; this may slow down convergence. optimagic usesLN_NEWUOA_BOUNDif at least one finite bound is specified; otherwise, it uses the originalLN_NEWUOAalgorithm for unconstrained optimization.Note
NEWUOA requires the dimension n of the parameter space to be at least 2, i.e. the implementation does not handle one-dimensional optimization problems.
- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Stop when an optimization step (or an estimate of the optimum) changes the parameters by less than this value relative to their size.
More precisely, NLopt checks whether the sum of the absolute parameter changes is smaller than this value times the sum of the absolute parameter values. This corresponds to NLopt’s
xtol_relstopping criterion. A value of 0 means that this criterion is disabled.NEWUOA implements this criterion differently: it stops when its trust-region radius falls below this value times the initial trust-region radius.
- convergence_xtol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes every parameter by less than this absolute value.
This corresponds to NLopt’s
xtol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this value multiplied by the absolute value of the function value.
This corresponds to NLopt’s
ftol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_ftol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this absolute value.
This corresponds to NLopt’s
ftol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- stopping_maxfun: PositiveInt = 1000000¶
Maximum number of objective function evaluations.
If reached, the optimization stops, but this is not counted as successful convergence. This corresponds to NLopt’s
maxevalstopping criterion.
nlopt_tnewton
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nlopt_tnewton(stopping_maxfun=10_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nlopt_tnewton",
algo_options={"stopping_maxfun": 10_000},
)
Description and available options:
- class optimagic.optimizers.nlopt_optimizers.NloptTNewton[source]¶
Minimize a scalar function using a truncated Newton method.
Truncated Newton methods are designed for large-scale smooth optimization problems. Instead of solving the Newton equations exactly, which would require the Hessian matrix, they solve them approximately (hence “truncated” or “inexact”) with a conjugate-gradient iteration that only requires gradient information. A detailed description is given in [algo_9].
Use it for differentiable scalar problems, in particular with many parameters. The algorithm uses gradients; if no
jacorfun_and_jacis provided, optimagic approximates them numerically.The implementation in NLopt [algo_64] is based on a Fortran implementation written by Prof. Ladislav Luksan. NLopt also provides variants of the method that add preconditioning via a low-storage BFGS approximation and steepest-descent restarting; optimagic wraps the plain variant (
LD_TNEWTON) without preconditioning or restarting.In addition to the stopping criteria below, the algorithm stops when the projected gradient becomes smaller than 1e-8 (NLopt’s
tolgparameter, which optimagic does not expose).- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Stop when an optimization step (or an estimate of the optimum) changes the parameters by less than this value relative to their size.
More precisely, NLopt checks whether the sum of the absolute parameter changes is smaller than this value times the sum of the absolute parameter values. This corresponds to NLopt’s
xtol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_xtol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes every parameter by less than this absolute value.
This corresponds to NLopt’s
xtol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this value multiplied by the absolute value of the function value.
This corresponds to NLopt’s
ftol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_ftol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this absolute value.
This corresponds to NLopt’s
ftol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- stopping_maxfun: PositiveInt = 1000000¶
Maximum number of objective function evaluations.
If reached, the optimization stops, but this is not counted as successful convergence. This corresponds to NLopt’s
maxevalstopping criterion.
nlopt_lbfgsb
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nlopt_lbfgsb(stopping_maxfun=10_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nlopt_lbfgsb",
algo_options={"stopping_maxfun": 10_000},
)
Description and available options:
- class optimagic.optimizers.nlopt_optimizers.NloptLBFGSB[source]¶
Minimize a scalar function using the low-storage BFGS algorithm.
L-BFGS is a limited-memory quasi-Newton method. It approximates the inverse Hessian of the objective function from a limited number of stored past gradient and parameter updates and uses this approximation to compute search directions for a line search. Detailed descriptions of the algorithm are given in [algo_68] and [algo_69].
Use it for smooth, differentiable scalar problems, in particular with many parameters: due to the limited-memory Hessian approximation, memory use grows only linearly in the number of parameters. The algorithm uses gradients; if no
jacorfun_and_jacis provided, optimagic approximates them numerically.The implementation in NLopt [algo_64] is based on a Fortran implementation of the low-storage BFGS algorithm written by Prof. Ladislav Luksan. It is a different implementation than the one wrapped by
scipy_lbfgsb, which is based on the original Fortran code by Nocedal and coworkers.In addition to the stopping criteria below, the algorithm stops when the projected gradient becomes smaller than 1e-8 (NLopt’s
tolgparameter, which optimagic does not expose). The number of stored past updates is chosen heuristically by NLopt and cannot be set in optimagic.- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Stop when an optimization step (or an estimate of the optimum) changes the parameters by less than this value relative to their size.
More precisely, NLopt checks whether the sum of the absolute parameter changes is smaller than this value times the sum of the absolute parameter values. This corresponds to NLopt’s
xtol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_xtol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes every parameter by less than this absolute value.
This corresponds to NLopt’s
xtol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this value multiplied by the absolute value of the function value.
This corresponds to NLopt’s
ftol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_ftol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this absolute value.
This corresponds to NLopt’s
ftol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- stopping_maxfun: PositiveInt = 1000000¶
Maximum number of objective function evaluations.
If reached, the optimization stops, but this is not counted as successful convergence. This corresponds to NLopt’s
maxevalstopping criterion.
nlopt_ccsaq
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nlopt_ccsaq(stopping_maxfun=10_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nlopt_ccsaq",
algo_options={"stopping_maxfun": 10_000},
)
Description and available options:
- class optimagic.optimizers.nlopt_optimizers.NloptCCSAQ[source]¶
Minimize a scalar function using the CCSAQ algorithm.
CCSAQ uses the quadratic variant of the conservative convex separable approximation (CCSA) framework described in [algo_70]. It is a gradient-based local optimizer: at each candidate point, an affine approximation of the objective function is constructed from the gradient, plus a separable quadratic penalty term that makes the approximation convex and conservative (an upper bound of the true function). The approximation is then minimized to obtain the next candidate point.
The algorithm is “globally convergent” in the sense that it is guaranteed to converge to a local optimum from any feasible starting point; it does not find the global optimum.
CCSAQ is closely related to
nlopt_mma, which belongs to the same CCSA family but approximates the objective with moving asymptotes instead of a quadratic model. For problems without nonlinear constraints, the NLopt author recommends trying CCSAQ before MMA.Note
The underlying NLopt implementation [algo_64] supports nonlinear inequality constraints, but nonlinear constraints are not supported for this algorithm in optimagic. Use
nlopt_mmaornlopt_slsqpfor nonlinearly constrained problems.- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Stop when an optimization step (or an estimate of the optimum) changes the parameters by less than this value relative to their size.
More precisely, NLopt checks whether the sum of the absolute parameter changes is smaller than this value times the sum of the absolute parameter values. This corresponds to NLopt’s
xtol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_xtol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes every parameter by less than this absolute value.
This corresponds to NLopt’s
xtol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this value multiplied by the absolute value of the function value.
This corresponds to NLopt’s
ftol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_ftol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this absolute value.
This corresponds to NLopt’s
ftol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- stopping_maxfun: PositiveInt = 1000000¶
Maximum number of objective function evaluations.
If reached, the optimization stops, but this is not counted as successful convergence. This corresponds to NLopt’s
maxevalstopping criterion.
nlopt_mma
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nlopt_mma(stopping_maxfun=10_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nlopt_mma",
algo_options={"stopping_maxfun": 10_000},
)
Description and available options:
- class optimagic.optimizers.nlopt_optimizers.NloptMMA[source]¶
Minimize a scalar function using the method of moving asymptotes (MMA).
MMA is a gradient-based local optimizer that was originally developed for structural optimization [algo_71]. The implementation in NLopt [algo_64] is based on the globally convergent variant of the algorithm described in [algo_70].
At each candidate point, a convex and separable approximation of the objective function and constraints is constructed from the gradient and so-called moving asymptotes that are updated across iterations. A quadratic penalty term makes the approximation conservative (an upper bound of the true function). The resulting convex separable subproblem is solved to obtain the next candidate point. The algorithm is “globally convergent” in the sense that it is guaranteed to converge to a local optimum from any feasible starting point; it does not find the global optimum.
Use it for smooth scalar problems with bound and nonlinear constraints when gradients are available. The underlying implementation supports nonlinear inequality constraints, but no equality constraints; optimagic automatically converts equality constraints into pairs of inequality constraints, so both types can be specified. For problems without nonlinear constraints, the NLopt author recommends trying
nlopt_ccsaqfirst.- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Stop when an optimization step (or an estimate of the optimum) changes the parameters by less than this value relative to their size.
More precisely, NLopt checks whether the sum of the absolute parameter changes is smaller than this value times the sum of the absolute parameter values. This corresponds to NLopt’s
xtol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_xtol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes every parameter by less than this absolute value.
This corresponds to NLopt’s
xtol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this value multiplied by the absolute value of the function value.
This corresponds to NLopt’s
ftol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_ftol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this absolute value.
This corresponds to NLopt’s
ftol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- stopping_maxfun: PositiveInt = 1000000¶
Maximum number of objective function evaluations.
If reached, the optimization stops, but this is not counted as successful convergence. This corresponds to NLopt’s
maxevalstopping criterion.
nlopt_var
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nlopt_var(rank_1_update=False),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nlopt_var",
algo_options={"rank_1_update": False},
)
Description and available options:
- class optimagic.optimizers.nlopt_optimizers.NloptVAR[source]¶
Minimize a scalar function using a limited-memory variable-metric method.
The algorithm is a shifted limited-memory variable-metric method by Vlcek and Luksan; a detailed description, including the rank-1 and rank-2 variants, is given in [algo_72]. Like L-BFGS, it approximates the inverse Hessian from a limited number of stored past updates of the gradient. The larger the number of stored updates, the more memory is consumed; this number is chosen heuristically by NLopt and cannot be set in optimagic.
Use it for smooth, differentiable scalar problems, in particular with many parameters. The algorithm uses gradients; if no
jacorfun_and_jacis provided, optimagic approximates them numerically. Depending on therank_1_updateoption, either a rank-1 (LD_VAR1) or a rank-2 (LD_VAR2) update formula for the variable-metric approximation is used.The implementation in NLopt [algo_64] is based on a Fortran implementation written by Prof. Ladislav Luksan. In addition to the stopping criteria below, the algorithm stops when the projected gradient becomes smaller than 1e-8 (NLopt’s
tolgparameter, which optimagic does not expose).- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Stop when an optimization step (or an estimate of the optimum) changes the parameters by less than this value relative to their size.
More precisely, NLopt checks whether the sum of the absolute parameter changes is smaller than this value times the sum of the absolute parameter values. This corresponds to NLopt’s
xtol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_xtol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes every parameter by less than this absolute value.
This corresponds to NLopt’s
xtol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this value multiplied by the absolute value of the function value.
This corresponds to NLopt’s
ftol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_ftol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this absolute value.
This corresponds to NLopt’s
ftol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- stopping_maxfun: PositiveInt = 1000000¶
Maximum number of objective function evaluations.
If reached, the optimization stops, but this is not counted as successful convergence. This corresponds to NLopt’s
maxevalstopping criterion.
nlopt_slsqp
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nlopt_slsqp(stopping_maxfun=10_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nlopt_slsqp",
algo_options={"stopping_maxfun": 10_000},
)
Description and available options:
- class optimagic.optimizers.nlopt_optimizers.NloptSLSQP[source]¶
Minimize a scalar function using the SLSQP algorithm.
SLSQP (Sequential Least Squares Quadratic Programming) is a gradient-based local optimizer for nonlinearly constrained problems. It supports bound constraints as well as nonlinear equality and inequality constraints. The algorithm is a sequential quadratic programming (SQP) method that treats the optimization problem as a sequence of constrained least-squares problems. Despite its name, it is a general nonlinear optimizer for scalar objectives, not a least-squares solver.
The implementation in NLopt [algo_64] is based on the procedure described in [algo_1] and [algo_73].
Note
Because the underlying code uses dense-matrix methods, it requires O(n^2) storage and O(n^3) time in n dimensions, which makes it less practical for problems with more than a few thousand parameters.
- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Stop when an optimization step (or an estimate of the optimum) changes the parameters by less than this value relative to their size.
More precisely, NLopt checks whether the sum of the absolute parameter changes is smaller than this value times the sum of the absolute parameter values. This corresponds to NLopt’s
xtol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_xtol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes every parameter by less than this absolute value.
This corresponds to NLopt’s
xtol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this value multiplied by the absolute value of the function value.
This corresponds to NLopt’s
ftol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_ftol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this absolute value.
This corresponds to NLopt’s
ftol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- stopping_maxfun: PositiveInt = 1000000¶
Maximum number of objective function evaluations.
If reached, the optimization stops, but this is not counted as successful convergence. This corresponds to NLopt’s
maxevalstopping criterion.
nlopt_direct
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nlopt_direct(locally_biased=True),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nlopt_direct",
algo_options={"locally_biased": True},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.nlopt_optimizers.NloptDirect[source]¶
Minimize a scalar function using the DIRECT algorithm.
DIRECT (DIviding RECTangles) is a deterministic derivative-free global optimizer [algo_24]. It systematically divides the bounded search domain into smaller and smaller hyperrectangles and evaluates the objective function at their centers, balancing global exploration and local refinement.
Use it for global optimization of scalar problems with a small number of parameters when no derivatives are available. Finite bounds on all parameters are required. The start parameters are not used; the search starts at the center of the bounds. The basic algorithm is deterministic. The randomized variants are not; use
seedto make runs reproducible.The implementation in NLopt [algo_64] provides several variants that are selected via the
locally_biased,random_searchandunscaled_boundsoptions:The locally biased variant DIRECT_L [algo_25] is more biased towards local search and tends to be more efficient for objective functions without too many local minima.
The randomized variants (only available for the locally biased version) use some randomization to decide which dimension to halve next in the case of near-ties.
By default, NLopt rescales the bounds to a unit hypercube, which gives all dimensions equal weight relative to their bound widths. The unscaled (“NOSCAL”) variants skip this rescaling, which can be better if the search region is long and skinny but the objective function varies at about the same speed in all directions. According to NLopt, the unscaled variants make the most sense for the original (not locally biased) DIRECT algorithm.
The available combinations are DIRECT, DIRECT_L, DIRECT_L_NOSCAL, DIRECT_L_RAND, DIRECT_L_RAND_NOSCAL and DIRECT_NOSCAL. The NLopt author suggests trying the locally biased variant (
locally_biased=True) first.- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Stop when an optimization step (or an estimate of the optimum) changes the parameters by less than this value relative to their size.
More precisely, NLopt checks whether the sum of the absolute parameter changes is smaller than this value times the sum of the absolute parameter values. This corresponds to NLopt’s
xtol_relstopping criterion. A value of 0 means that this criterion is disabled.DIRECT implements this criterion differently: it stops when all hyperrectangles selected for division are smaller than this value times the width of the bounds in every dimension.
- convergence_xtol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes every parameter by less than this absolute value.
This corresponds to NLopt’s
xtol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this value multiplied by the absolute value of the function value.
This corresponds to NLopt’s
ftol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_ftol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this absolute value.
This corresponds to NLopt’s
ftol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- stopping_maxfun: PositiveInt = 1000¶
Maximum number of objective function evaluations.
If reached, the optimization stops, but this is not counted as successful convergence. This corresponds to NLopt’s
maxevalstopping criterion. The optimagic default for global optimizers is much lower than for local optimizers to keep runtimes manageable.
- locally_biased: bool = False¶
Whether the locally biased variant DIRECT_L of the algorithm is used.
The locally biased variant tends to be more efficient for objective functions without too many local minima. See [algo_25] for details.
- random_search: bool = False¶
Whether the randomized variant of the locally biased algorithm is used.
The randomized variant uses some randomization to decide which dimension to halve next in the case of near-ties. It is only available for the locally biased version of the algorithm, i.e. this option requires
locally_biased=True; setting it to True withlocally_biased=Falseraises a ValueError.
- unscaled_bounds: bool = False¶
Whether the “NOSCAL” variant of the algorithm is used, which does not rescale the bounds to a unit hypercube.
Skipping the rescaling can be beneficial if the search region is long and skinny but the objective function varies at about the same speed in all directions.
- seed: _NloptSeed | None = None¶
Seed for NLopt’s random number generator, between 0 and 2**32 - 1.
Only used if
random_search=True. If None, NLopt’s current random state is used and results can differ between runs. NLopt’s random state is shared by all NLopt optimizers on the same thread, so nested optimizations can change the random stream of an outer optimization.NLopt 2.10.1 uses the deterministic implementation for the unscaled randomized variant (
random_search=True, unscaled_bounds=True), so the seed has no effect there.
nlopt_esch
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nlopt_esch(stopping_maxfun=10_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nlopt_esch",
algo_options={"stopping_maxfun": 10_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.nlopt_optimizers.NloptESCH[source]¶
Minimize a scalar function using the ESCH algorithm.
ESCH is an evolutionary algorithm for global optimization developed by Carlos Henrique da Silva Santos [algo_74], [algo_75]. It is a modified evolution strategy [algo_76] that evolves a population of candidate points (40 parents and 60 offspring) via crossover, Cauchy mutation and selection; see also [algo_77].
Use it for global optimization of scalar problems when no derivatives are available. Finite bounds on all parameters are required. The algorithm supports bound constraints only; nonlinear constraints are not supported.
Like most evolutionary algorithms, it typically needs many function evaluations, and there is no guarantee that the global optimum is found within a finite budget. Results differ between runs unless
seedis set.Note
ESCH ignores all
convergence_*criteria; it always runs untilstopping_maxfunis reached.- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Relative tolerance on the parameters (NLopt’s
xtol_rel); ignored by ESCH.NLopt’s ESCH implementation does not check this criterion and only stops when
stopping_maxfunis reached.
- convergence_xtol_abs: NonNegativeFloat = 0¶
Absolute tolerance on the parameters (NLopt’s
xtol_abs); ignored by ESCH.NLopt’s ESCH implementation does not check this criterion and only stops when
stopping_maxfunis reached.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Relative tolerance on the function value (NLopt’s
ftol_rel); ignored by ESCH.NLopt’s ESCH implementation does not check this criterion and only stops when
stopping_maxfunis reached.
- convergence_ftol_abs: NonNegativeFloat = 0¶
Absolute tolerance on the function value (NLopt’s
ftol_abs); ignored by ESCH.NLopt’s ESCH implementation does not check this criterion and only stops when
stopping_maxfunis reached.
- stopping_maxfun: PositiveInt = 1000¶
Maximum number of objective function evaluations.
If reached, the optimization stops, but this is not counted as successful convergence. This corresponds to NLopt’s
maxevalstopping criterion. The optimagic default for global optimizers is much lower than for local optimizers to keep runtimes manageable. Since ESCH ignores all convergence criteria, it always uses the full number of function evaluations.
- seed: _NloptSeed | None = None¶
Seed for NLopt’s random number generator, between 0 and 2**32 - 1.
If None, NLopt’s current random state is used and results can differ between runs. NLopt’s random state is shared by all NLopt optimizers on the same thread, so nested optimizations can change the random stream of an outer optimization.
nlopt_isres
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nlopt_isres(stopping_maxfun=10_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nlopt_isres",
algo_options={"stopping_maxfun": 10_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.nlopt_optimizers.NloptISRES[source]¶
Minimize a scalar function using the ISRES algorithm.
ISRES (Improved Stochastic Ranking Evolution Strategy) is an evolutionary algorithm for nonlinearly constrained global optimization [algo_78]. Its evolution strategy combines a mutation rule (with a log-normal step-size update and exponential smoothing) with differential variation (a Nelder-Mead-like update rule). For constrained problems, individuals are ranked via the stochastic ranking procedure described in [algo_79].
Use it for global optimization of scalar problems when no derivatives are available; it is one of the few global optimizers that supports nonlinear equality and inequality constraints. Finite bounds on all parameters are required. The algorithm has heuristics to escape local optima, but no proof of global convergence is available.
In the implementation in NLopt [algo_64], the population size defaults to 20 * (number of parameters + 1); optimagic does not expose this setting. Results differ between runs unless
seedis set.- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Stop when an optimization step (or an estimate of the optimum) changes the parameters by less than this value relative to their size.
More precisely, NLopt checks whether the sum of the absolute parameter changes is smaller than this value times the sum of the absolute parameter values. This corresponds to NLopt’s
xtol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_xtol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes every parameter by less than this absolute value.
This corresponds to NLopt’s
xtol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this value multiplied by the absolute value of the function value.
This corresponds to NLopt’s
ftol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_ftol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this absolute value.
This corresponds to NLopt’s
ftol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- stopping_maxfun: PositiveInt = 1000¶
Maximum number of objective function evaluations.
If reached, the optimization stops, but this is not counted as successful convergence. This corresponds to NLopt’s
maxevalstopping criterion. The optimagic default for global optimizers is much lower than for local optimizers to keep runtimes manageable.
- seed: _NloptSeed | None = None¶
Seed for NLopt’s random number generator, between 0 and 2**32 - 1.
If None, NLopt’s current random state is used and results can differ between runs. NLopt’s random state is shared by all NLopt optimizers on the same thread, so nested optimizations can change the random stream of an outer optimization.
nlopt_crs2_lm
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nlopt_crs2_lm(population_size=100),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nlopt_crs2_lm",
algo_options={"population_size": 100},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.nlopt_optimizers.NloptCRS2LM[source]¶
Minimize a scalar function using the CRS2_LM algorithm.
CRS2 (Controlled Random Search 2) with local mutation is a derivative-free global optimizer. The CRS class of algorithms, originally described in [algo_80] and [algo_81], starts with a random population of points and evolves these points by heuristic rules; the evolution somewhat resembles a randomized Nelder-Mead algorithm. The implementation in NLopt [algo_64] uses the CRS2 variant with the local mutation modification described in [algo_82].
Use it for global optimization of scalar problems when no derivatives are available. Finite bounds on all parameters are required. Like all stochastic global optimizers, it typically needs many function evaluations and offers no guarantee of finding the global optimum. Results differ between runs unless
seedis set.- convergence_xtol_rel: NonNegativeFloat = 1e-05¶
Stop when an optimization step (or an estimate of the optimum) changes the parameters by less than this value relative to their size.
More precisely, NLopt checks whether the sum of the absolute parameter changes is smaller than this value times the sum of the absolute parameter values. This corresponds to NLopt’s
xtol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_xtol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes every parameter by less than this absolute value.
This corresponds to NLopt’s
xtol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this value multiplied by the absolute value of the function value.
This corresponds to NLopt’s
ftol_relstopping criterion. A value of 0 means that this criterion is disabled.
- convergence_ftol_abs: NonNegativeFloat = 0¶
Stop when an optimization step (or an estimate of the optimum) changes the objective function value by less than this absolute value.
This corresponds to NLopt’s
ftol_absstopping criterion. A value of 0 means that this criterion is disabled, which is the optimagic default.
- stopping_maxfun: PositiveInt = 1000¶
Maximum number of objective function evaluations.
If reached, the optimization stops, but this is not counted as successful convergence. This corresponds to NLopt’s
maxevalstopping criterion. The optimagic default for global optimizers is much lower than for local optimizers to keep runtimes manageable.
- population_size: PositiveInt | None = None¶
Size of the random population of points that is evolved by the algorithm.
If None, the population size is set to 10 * (number of parameters + 1), which is the default of the NLopt implementation. NLopt requires the population size to be at least the number of parameters + 1.
- seed: _NloptSeed | None = None¶
Seed for NLopt’s random number generator, between 0 and 2**32 - 1.
If None, NLopt’s current random state is used and results can differ between runs. NLopt’s random state is shared by all NLopt optimizers on the same thread, so nested optimizations can change the random stream of an outer optimization.
Optimizers from iminuit¶
optimagic supports the IMINUIT MIGRAD Optimizer. To
use MIGRAD, you need to have
the iminuit package installed
(pip install iminuit).
iminuit_migrad
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.iminuit_migrad(stopping_maxfun=10_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="iminuit_migrad",
algo_options={"stopping_maxfun": 10_000},
)
Description and available options:
- class optimagic.optimizers.iminuit_migrad.IminuitMigrad[source]¶
Minimize a scalar differentiable function using the MIGRAD algorithm from iminuit.
This optimizer wraps the MIGRAD algorithm from the iminuit package, which provides a Python interface to the Minuit2 C++ library developed and maintained by CERN.
MIGRAD is a local optimization method in the quasi-Newton family. It iteratively builds an approximation of the inverse Hessian matrix using the DFP variable-metric method to efficiently navigate optimization landscapes.
At each iteration, the algorithm attempts a Newton step, using gradient and Hessian approximations to move toward the function’s minimum. If this step fails to reduce the objective function, MIGRAD conducts a line search along the gradient direction to maintain progress. This continues until the convergence criteria, such as the Estimated Distance to Minimum (EDM) are met, that is, they fall below preset thresholds.
MIGRAD is designed for statistical optimization problems where accurate parameter uncertainty estimates are essential. It excels at maximum-likelihood and least- squares fits common in scientific computing, and is best suited for smooth, differentiable cost functions.
For best performance, supply analytical gradients. Convergence and solution will depend on your starting values. Bound constraints (limits) supported.
Nevergrad Optimizers¶
optimagic supports following algorithms from the
Nevergrad library. To use
these optimizers, you need to have
the nevergrad package installed.
(pip install nevergrad).
Two algorithms from nevergrad are not available in optimagic.
SPSA (Simultaneous Perturbation Stochastic Approximation) - This is WIP in nevergrad
and hence imprecise.
AXP (AX-platform) - Very slow and not recommended.
nevergrad_pso
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nevergrad_pso(stopping_maxfun=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nevergrad_pso",
algo_options={"stopping_maxfun": 1_000},
)
Description and available options:
- class optimagic.optimizers.nevergrad_optimizers.NevergradPSO[source]¶
Minimize a scalar function using the Particle Swarm Optimization algorithm.
The Particle Swarm Optimization algorithm was originally proposed by [algo_49].The implementation in Nevergrad is based on [algo_83].
PSO solves an optimization problem by evolving a swarm of particles (candidate solutions) across the search space. Each particle adjusts its position based on its own experience (cognitive component) and the experiences of its neighbors or the swarm (social component), using velocity updates. The algorithm iteratively guides the swarm toward promising regions of the search space.
- transform: Literal['arctan', 'gaussian', 'identity'] = 'arctan'¶
The transform used to map from PSO optimization space to real space.
- stopping_maxfun: PositiveInt = 1000¶
Maximum number of function evaluations.
- inertia: float = 0.7213475204444817¶
Inertia weight ω.
Controls the influence of a particle’s previous velocity. Must be less than 1 to avoid divergence.
- cognitive: float = 1.1931471805599454¶
Cognitive coefficient \(\phi_p\).
Controls the influence of a particle’s own best known position. Typical values: 1.0 to 3.0.
- social: float = 1.1931471805599454¶
Social coefficient.
Denoted by \(\phi_g\). Controls the influence of the swarm’s best known position. Typical values: 1.0 to 3.0.
- speed_quasi_opp_init: bool = False¶
Whether to apply quasi-opposition initialization to speed.
Default is False.
nevergrad_cmaes
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nevergrad_cmaes(stopping_maxfun=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nevergrad_cmaes",
algo_options={"stopping_maxfun": 1_000},
)
Description and available options:
- class optimagic.optimizers.nevergrad_optimizers.NevergradCMAES[source]¶
Minimize a scalar function using the Covariance Matrix Adaptation Evolution Strategy (CMA-ES) algorithm.
The CMA-ES is a state-of-the-art evolutionary algorithm for difficult non-linear, non-convex, black-box optimization problems in continuous domains. It is typically applied to unconstrained or bounded problems with dimensionality between 3 and 100. CMA-ES adapts a multivariate normal distribution to approximate the objective function’s shape by estimating a positive-definite covariance matrix, akin to the inverse Hessian in convex-quadratic problems, but without requiring derivatives.
This implementation is a python wrapper over the original code.
Original paper can be accessed at cma-es.
- scale: NonNegativeFloat = 1.0¶
Scale of the search.
- elitist: bool = False¶
Whether to switch to elitist mode (also known as (μ,λ)-CMA-ES).
In elitist mode, the best point in the population is always retained.
- diagonal: bool = False¶
Use the diagonal version of CMA, which is more efficient for high-dimensional problems.
- fast_cmaes: bool = False¶
Use the fast CMA-ES implementation.
Cannot be used with diagonal=True. Produces equivalent results and is preferable for high dimensions or when objective function evaluations are fast.
- n_cores: PositiveInt = 1¶
Number of cores to use for parallel function evaluation.
- step_size_adaptive: bool | str = True¶
Whether to adapt the step size.
Can be a boolean or a string specifying the adaptation strategy.
- CSA_dampfac: PositiveFloat = 1.0¶
Damping factor for step size adaptation.
- CMA_dampsvec_fade: PositiveFloat = 0.1¶
Damping rate for step size adaptation.
- CMA_rankone: float = 1.0¶
Multiplier for the rank-one update learning rate of the covariance matrix.
- CMA_mirrormethod: Literal[0, 1, 2] = 2¶
Strategy for mirror sampling.
0: Unconditional, 1: Selective, 2: Selective with delay.
- CMA_const_trace: bool | Literal['arithm', 'geom', 'aeig', 'geig'] = False¶
How to normalize the trace of the covariance matrix.
False: No normalization, True: Normalize to 1. Other options: ‘arithm’, ‘geom’, ‘aeig’, ‘geig’.
- CMA_diagonal: int | bool = False¶
Number of iterations to use diagonal covariance matrix before switching to full matrix.
If False, always use full matrix.
- stopping_maxfun: PositiveInt = 1000¶
Maximum number of function evaluations before termination.
- stopping_maxiter: PositiveInt = 1000000¶
Maximum number of iterations before termination.
- stopping_maxtime: PositiveFloat = inf¶
Maximum time in seconds before termination.
- stopping_cov_mat_cond: NonNegativeFloat = 100000000000000.0¶
Maximum condition number of the covariance matrix before termination.
- convergence_ftol_abs: NonNegativeFloat = 0¶
Absolute tolerance on function value changes for convergence.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Relative tolerance on function value changes for convergence.
- convergence_xtol_abs: NonNegativeFloat = 0¶
Absolute tolerance on parameter changes for convergence.
- convergence_iter_noimprove: PositiveInt | None = None¶
Number of iterations without improvement before termination.
nevergrad_oneplusone
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nevergrad_oneplusone(stopping_maxfun=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nevergrad_oneplusone",
algo_options={"stopping_maxfun": 1_000},
)
Description and available options:
- class optimagic.optimizers.nevergrad_optimizers.NevergradOnePlusOne[source]¶
Minimize a scalar function using the One-Plus-One Evolutionary algorithm.
The One-Plus-One evolutionary algorithm iterates to find a set of parameters that minimizes the loss function. It does this by perturbing, or mutating, the parameters from the last iteration (the parent). If the new (child) parameters yield a better result, the child becomes the new parent whose parameters are perturbed, perhaps more aggressively. If the parent yields a better result, it remains the parent and the next perturbation is less aggressive.
Originally proposed by [algo_84]. The implementation in Nevergrad is based on the one-fifth adaptation rule from [algo_85].
- noise_handling: Literal['random', 'optimistic'] | tuple[Literal['random', 'optimistic'], float] | None = None¶
Method for handling noise.
‘random’ reevaluates a random point, while ‘optimistic’ reevaluates the best optimistic point. A float coefficient can be provided to tune the regularity of these reevaluations.
- mutation: Literal['gaussian', 'cauchy', 'discrete', 'fastga', 'rls', 'doublefastga', 'adaptive', 'coordinatewise_adaptive', 'portfolio', 'discreteBSO', 'lengler', 'lengler2', 'lengler3', 'lenglerhalf', 'lenglerfourth', 'doerr', 'lognormal', 'xlognormal', 'xsmalllognormal', 'tinylognormal', 'smalllognormal', 'biglognormal', 'hugelognormal'] = 'gaussian'¶
Type of mutation to apply.
‘gaussian’ is the default. Other options include ‘cauchy’, ‘discrete’, ‘fastga’, ‘rls’, and ‘portfolio’.
- annealing: Literal['none', 'Exp0.9', 'Exp0.99', 'Exp0.9Auto', 'Lin100.0', 'Lin1.0', 'LinAuto'] | None = None¶
Annealing schedule for mutation amplitude.
Can be ‘none’, exponential (e.g., ‘Exp0.9’), or linear (e.g., ‘Lin100.0’).
- super_radii: bool = False¶
Whether to apply extended radii beyond standard bounds for candidate generation, enabling broader exploration.
- roulette_size: PositiveInt = 64¶
Size of the roulette wheel used for selection, affecting sampling diversity from past candidates.
- antismooth: NonNegativeInt = 4¶
Degree of anti-smoothing to prevent premature convergence by penalizing overly smooth improvements.
- crossover_type: Literal['none', 'rand', 'max', 'min', 'onepoint', 'twopoint'] | None = None¶
Method for genetic crossover.
Options include ‘rand’, ‘onepoint’, and ‘twopoint’.
- tabu_length: NonNegativeInt = 1000¶
Length of the tabu list to prevent revisiting recent candidates and help escape local minima.
- rotation: bool = False¶
Whether to apply rotational transformations to the search space to enhance search performance.
- stopping_maxfun: PositiveInt = 1000¶
Maximum number of function evaluations.
- n_cores: PositiveInt = 1¶
Number of cores to use for parallel computation.
nevergrad_de
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nevergrad_de(population_size="large"),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nevergrad_de",
algo_options={"population_size": "large"},
)
Description and available options:
- class optimagic.optimizers.nevergrad_optimizers.NevergradDifferentialEvolution[source]¶
Minimize a scalar function using the Differential Evolution optimizer.
Differential Evolution is typically used for continuous optimization. It uses differences between points in the population for performing mutations in fruitful directions. It is a kind of covariance adaptation without any explicit covariance, making it very fast in high dimensions.
- initialization: Literal['parametrization', 'LHS', 'QR', 'QO', 'SO'] = 'parametrization'¶
Algorithm for initialization.
‘LHS’ is Latin Hypercube Sampling, ‘QR’ is Quasi-Random.
- recommendation: Literal['pessimistic', 'optimistic', 'mean', 'noisy'] = 'pessimistic'¶
Criterion for selecting the best point to recommend.
- crossover: float | Literal['dimension', 'random', 'onepoint', 'twopoints', 'rotated_twopoints', 'parametrization'] = 0.5¶
Crossover rate or strategy.
Can be a float, ‘dimension’ (1/dim), ‘random’, ‘onepoint’, or ‘twopoints’.
- F1: PositiveFloat = 0.8¶
Differential weight #1 (scaling factor).
- F2: PositiveFloat = 0.8¶
Differential weight #2 (scaling factor).
- population_size: int | Literal['standard', 'dimension', 'large'] = 'standard'¶
Population size.
Can be an integer or a string like ‘standard’, ‘dimension’, or ‘large’ to set it automatically.
- stopping_maxfun: PositiveInt = 1000¶
Maximum number of function evaluations before termination.
- n_cores: PositiveInt = 1¶
Number of cores to use for parallel function evaluation.
nevergrad_bo
Note
Using this optimizer requires the bayes-optim package to be installed as well. This can be done with pip install bayes-optim.
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nevergrad_bo(stopping_maxfun=1_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nevergrad_bo",
algo_options={"stopping_maxfun": 1_000},
)
Description and available options:
- class optimagic.optimizers.nevergrad_optimizers.NevergradBayesOptim[source]¶
Minimize a scalar function using the Bayesian Optimization (BO) algorithm.
This wrapper uses the BO and PCA-BO algorithms from the bayes_optim package [algo_86]. PCA-BO (Principal Component Analysis for Bayesian Optimization) is a dimensionality reduction technique for black-box optimization. It applies PCA to the input space before performing Bayesian optimization, improving efficiency in high dimensions by focusing on directions of greatest variance.
- n_components: NonNegativeFloat = 0.95¶
Number of principal axes, representing the percentage of explained variance (e.g., 0.95 means 95% variance retained).
- prop_doe_factor: NonNegativeFloat | None = 1¶
Percentage of the initial budget used for Design of Experiments (DoE).
- stopping_maxfun: PositiveInt = 1000¶
Maximum number of function evaluations before termination.
- n_cores: PositiveInt = 1¶
Number of cores to use for parallel function evaluation.
nevergrad_emna
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nevergrad_emna(noise_handling=False),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nevergrad_emna",
algo_options={"noise_handling": False},
)
Description and available options:
- class optimagic.optimizers.nevergrad_optimizers.NevergradEMNA[source]¶
Minimize a scalar function using the Estimation of Multivariate Normal Algorithm.
EMNA is a distribution-based evolutionary algorithm that models the search space using a multivariate Gaussian. It learns the full covariance matrix, resulting in a cubic time complexity with respect to each sampling. It is efficient in parallel settings but other methods should be considered first. See [algo_87].
- isotropic: bool = True¶
If True, uses an isotropic (identity covariance) Gaussian.
If False, uses a separable (diagonal covariance) Gaussian.
- noise_handling: bool = True¶
If True, returns the best individual found.
If False (recommended for noisy problems), returns the average of the final population.
- population_size_adaptation: bool = False¶
If True, the population size is adjusted automatically based on the optimization landscape and noise level.
- initial_popsize: int | None = None¶
Initial population size.
Defaults to 4 times the problem dimension.
- stopping_maxfun: PositiveInt = 1000¶
Maximum number of function evaluations before termination.
- n_cores: PositiveInt = 1¶
Number of cores to use for parallel function evaluation.
nevergrad_cga
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nevergrad_cga(stopping_maxfun=10_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nevergrad_cga",
algo_options={"stopping_maxfun": 10_000},
)
Description and available options:
- class optimagic.optimizers.nevergrad_optimizers.NevergradCGA[source]¶
Minimize a scalar function using the Compact Genetic Algorithm.
The Compact Genetic Algorithm (cGA) is a memory-efficient genetic algorithm that represents the population as a probability vector over gene values. It simulates the behavior of a simple GA with uniform crossover by updating probabilities instead of maintaining an explicit population. See [algo_88].
- stopping_maxfun: PositiveInt = 1000¶
Maximum number of function evaluations before termination.
- n_cores: PositiveInt = 1¶
Number of cores to use for parallel function evaluation.
nevergrad_eda
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nevergrad_eda(stopping_maxfun=10_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nevergrad_eda",
algo_options={"stopping_maxfun": 10_000},
)
Description and available options:
- class optimagic.optimizers.nevergrad_optimizers.NevergradEDA[source]¶
Minimize a scalar function using the Estimation of Distribution Algorithm.
Estimation of Distribution Algorithms (EDAs) optimize by building and sampling a probabilistic model of promising solutions. Instead of using traditional variation operators like crossover or mutation, EDAs update a distribution based on selected individuals and sample new candidates from it. Refer to [algo_89].
- stopping_maxfun: PositiveInt = 1000¶
Maximum number of function evaluations before termination.
- n_cores: PositiveInt = 1¶
Number of cores to use for parallel function evaluation.
nevergrad_tbpsa
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nevergrad_tbpsa(noise_handling=False),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nevergrad_tbpsa",
algo_options={"noise_handling": False},
)
Description and available options:
- class optimagic.optimizers.nevergrad_optimizers.NevergradTBPSA[source]¶
Minimize a scalar function using the Test-based Population Size Adaptation algorithm.
TBPSA adapts population size based on fitness trend detection using linear regression. If no significant improvement is found (via hypothesis testing), the population size is increased to improve robustness, making it effective for noisy optimization problems. For more details, refer to [algo_90].
- noise_handling: bool = True¶
If True, returns the best individual.
If False (recommended for noisy problems), returns the average of the final population to reduce noise.
- initial_popsize: int | None = None¶
Initial population size.
If not specified, defaults to 4 times the problem dimension.
- stopping_maxfun: PositiveInt = 1000¶
Maximum number of function evaluations before termination.
- n_cores: PositiveInt = 1¶
Number of cores to use for parallel function evaluation.
nevergrad_randomsearch
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nevergrad_randomsearch(opposition_mode="quasi"),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nevergrad_randomsearch",
algo_options={"opposition_mode": "quasi"},
)
Description and available options:
- class optimagic.optimizers.nevergrad_optimizers.NevergradRandomSearch[source]¶
Minimize a scalar function using the Random Search algorithm.
This is a one-shot optimization method that provides random suggestions and serves as a simple baseline for other optimizers.
- opposition_mode: Literal['opposite', 'quasi'] | None = None¶
Symmetrizes exploration with respect to the center.
‘opposite’ enables full symmetry, while ‘quasi’ applies randomized symmetry.
- sampler: Literal['parametrization', 'gaussian', 'cauchy'] = 'parametrization'¶
The probability distribution for sampling points.
‘gaussian’ and ‘cauchy’ are available alternatives.
- scale: PositiveFloat | Literal['random', 'auto', 'autotune'] = 'auto'¶
Scalar used to multiply suggested point values.
Can be a float or a string for auto-scaling (‘random’, ‘auto’, ‘autotune’).
- recommendation_rule: Literal['average_of_best', 'pessimistic', 'average_of_exp_best'] = 'pessimistic'¶
Specifies how the final recommendation is chosen, e.g., ‘pessimistic’ (default) or ‘average_of_best’.
- stopping_maxfun: PositiveInt = 1000¶
Maximum number of function evaluations before termination.
- n_cores: PositiveInt = 1¶
Number of cores to use for parallel function evaluation.
nevergrad_samplingsearch
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nevergrad_samplingsearch(
sampler="Hammersley",
scrambled=True,
),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nevergrad_samplingsearch",
algo_options={"sampler": "Hammersley", "scrambled": True},
)
Description and available options:
- class optimagic.optimizers.nevergrad_optimizers.NevergradSamplingSearch[source]¶
Minimize a scalar function using SamplingSearch.
This is a one-shot optimization method that is better than random search because it uses low-discrepancy sequences to ensure more uniform coverage of the search space. It is recommended to use “Hammersley” as the sampler if the budget is known, and to set scrambled=True in high dimensions.
- sampler: Literal['Halton', 'LHS', 'Hammersley'] = 'Halton'¶
Choice of the low-discrepancy sampler used for generating points.
‘LHS’ is Latin Hypercube Sampling.
- scrambled: bool = False¶
If True, adds scrambling to the search sequence, which is highly recommended for high-dimensional problems.
- middle_point: bool = False¶
If True, the first suggested point is the zero vector, useful for initializing at the center of the search space.
- cauchy: bool = False¶
If True, uses the inverse Cauchy distribution instead of Gaussian when projecting samples to a real-valued space.
- scale: bool | NonNegativeFloat = 1.0¶
A float multiplier to scale all generated points.
- rescaled: bool = False¶
If True, rescales the sampling pattern to ensure better coverage of the boundaries.
- recommendation_rule: Literal['average_of_best', 'pessimistic'] = 'pessimistic'¶
How the final recommendation is chosen.
‘pessimistic’ is the default.
- stopping_maxfun: PositiveInt = 1000¶
Maximum number of function evaluations before termination.
- n_cores: PositiveInt = 1¶
Number of cores to use for parallel function evaluation.
nevergrad_ngopt
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nevergrad_ngopt(optimizer="NGOptRW"),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nevergrad_ngopt",
algo_options={"optimizer": "NGOptRW"},
)
Description and available options:
- class optimagic.optimizers.nevergrad_optimizers.NevergradNGOpt[source]¶
Minimize a scalar function using a Meta Optimizer from Nevergrad.
These are meta-optimizers that intelligently combine multiple different optimization algorithms to solve a problem. The specific portfolio of optimizers can be selected via the optimizer parameter.
- optimizer: Literal['NGOpt', 'NGOpt4', 'NGOpt8', 'NGOpt10', 'NGOpt12', 'NGOpt13', 'NGOpt14', 'NGOpt15', 'NGOpt16', 'NGOpt21', 'NGOpt36', 'NGOpt38', 'NGOpt39', 'NGOptRW', 'NGOptF', 'NGOptF2', 'NGOptF3', 'NGOptF5', 'NgIoh2', 'NgIoh3', 'NgIoh4', 'NgIoh5', 'NgIoh6', 'NgIoh7', 'NgIoh11', 'NgIoh14', 'NgIoh13', 'NgIoh15', 'NgIoh12', 'NgIoh16', 'NgIoh17', 'NgIoh21', 'NgIoh20', 'NgIoh19', 'NgIoh18', 'NgIoh10', 'NgIoh9', 'NgIoh8', 'NgIoh12b', 'NgIoh13b', 'NgIoh14b', 'NgIoh15b', 'NgDS', 'NgDS2', 'NGDSRW', 'NGO', 'NgIohRW2', 'NgIohTuned', 'CSEC', 'CSEC10', 'CSEC11', 'Wiz'] = 'NGOpt'¶
The specific Nevergrad meta-optimizer to use.
Each option is a portfolio of different algorithms.
- stopping_maxfun: PositiveInt = 1000¶
Maximum number of function evaluations before termination.
- n_cores: PositiveInt = 1¶
Number of cores to use for parallel function evaluation.
nevergrad_meta
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.nevergrad_meta(optimizer="BFGSCMAPlus"),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="nevergrad_meta",
algo_options={"optimizer": "BFGSCMAPlus"},
)
Description and available options:
- class optimagic.optimizers.nevergrad_optimizers.NevergradMeta[source]¶
Minimize a scalar function using a Meta Optimizer from Nevergrad.
This algorithm utilizes a combination of local and global optimizers to find the best solution. The specific portfolio of optimizers can be selected via the optimizer parameter.
- optimizer: Literal['MultiBFGSPlus', 'LogMultiBFGSPlus', 'SqrtMultiBFGSPlus', 'MultiCobylaPlus', 'MultiSQPPlus', 'BFGSCMAPlus', 'LogBFGSCMAPlus', 'SqrtBFGSCMAPlus', 'SQPCMAPlus', 'LogSQPCMAPlus', 'SqrtSQPCMAPlus', 'MultiBFGS', 'LogMultiBFGS', 'SqrtMultiBFGS', 'MultiCobyla', 'ForceMultiCobyla', 'MultiSQP', 'BFGSCMA', 'LogBFGSCMA', 'SqrtBFGSCMA', 'SQPCMA', 'LogSQPCMA', 'SqrtSQPCMA', 'FSQPCMA', 'F2SQPCMA', 'F3SQPCMA', 'MultiDiscrete', 'CMandAS2', 'CMandAS3', 'MetaCMA', 'CMA', 'PCEDA', 'MPCEDA', 'MEDA', 'NoisyBandit', 'Shiwa', 'Carola3'] = 'Shiwa'¶
The specific Nevergrad meta-optimizer to use.
Each option is a portfolio of different local and global algorithms.
- stopping_maxfun: PositiveInt = 1000¶
Maximum number of function evaluations before termination.
- n_cores: PositiveInt = 1¶
Number of cores to use for parallel function evaluation.
Bayesian Optimization¶
We wrap the
BayesianOptimization
package. To use it, you need to have
bayesian-optimization installed.
Note: This optimizer requires bayesian_optimization > 2.0.0 to be installed which is
incompatible with nevergrad > 1.0.3.
bayes_opt
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.bayes_opt(stopping_maxiter=50),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="bayes_opt",
algo_options={"stopping_maxiter": 50},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.bayesian_optimizer.BayesOpt[source]¶
Minimize a scalar function using Bayesian Optimization with Gaussian Process.
This optimizer wraps the BayesianOptimization package [algo_91], which implements a surrogate model-based global optimization algorithm. It works by constructing a posterior distribution over the objective function via a Gaussian process that best approximates it. Instead of directly optimizing the expensive original function, it uses a proxy optimization problem by finding the maximum of an acquisition function, which is computationally cheaper than evaluating the original function.
The algorithm starts by sampling a few initial points (init_points) to gather observations of the objective function. These observations are used to fit a Gaussian process surrogate model that learns about the function’s behavior. The optimizer then uses an acquisition function to iteratively select promising new points to evaluate, updates its model, and this continues for stopping_maxiter iterations.
This optimizer is well-suited for expensive functions where each evaluation is costly (simulations, experiments, model training), black-box optimization where gradients are unavailable, and problems with a limited evaluation budget.
Default parameter values match those of the underlying BayesianOptimization package where appropriate. Nonlinear constraints are currently not supported.
- init_points: PositiveInt = 5¶
Number of random points sampled before optimization.
More points improve initial GP fit but increase evaluation cost. Default = 5.
- stopping_maxiter: PositiveInt = 25¶
Number of Bayesian optimization iterations to perform after initial exploration.
- verbose: Literal[0, 1, 2] = 0¶
Verbosity level (0 for silent, 1 for brief, 2 for detailed output).
- kappa: NonNegativeFloat = 2.576¶
Exploration-exploitation trade-off parameter for Upper Confidence Bound acquisition.
Controls the balance between exploration and exploitation when using the Upper Confidence Bound (UCB) acquisition function. Higher values favor exploration over exploitation . This parameter is only used when the acquisition function is “ucb” or “upper_confidence_bound”. The default value of 2.576 corresponds to a 99% confidence interval.
- xi: PositiveFloat = 0.01¶
Exploration-exploitation trade-off parameter for Expected/Probability of Improvement.
Controls the balance between exploration and exploitation for Expected Improvement (EI) and Probability of Improvement (POI) acquisition functions. Higher values favor exploration over exploitation . This parameter is only used when the acquisition function is “ei”, “expected_improvement”, “poi”, or “probability_of_improvement”. The default value is 0.01.
- exploration_decay: UnitIntervalFloat | None = None¶
Rate at which exploration decays over time during optimization.
If specified, the exploration parameters (kappa or xi) are multiplied by this factor after each iteration, gradually shifting from exploration to exploitation. Must be between 0 and 1 (range: (0, 1]) If None, no decay is applied and exploration remains constant.
- exploration_decay_delay: NonNegativeInt | None = None¶
Number of iterations to delay before applying exploration decay.
If specified, exploration decay only begins after this many iterations have completed. If None, decay is applied from the first iteration.
- acquisition_function: str | AcquisitionFunction | Type[AcquisitionFunction] | None = None¶
Strategy for selecting the next evaluation point during optimization.
The acquisition function determines how to balance exploration and exploitation when selecting the next point to evaluate. Supported options:
- String: “ucb”/”upper_confidence_bound”, “ei”/”expected_improvement”,
“poi”/”probability_of_improvement”
AcquisitionFunction instance: Pre-configured acquisition function object
AcquisitionFunction class: Class that will be instantiated with default parameters
None: Uses package default (UCB for unconstrained, EI for constrained problems)
- enable_sdr: bool = False¶
Enable Sequential Domain Reduction (SDR).
When True, the search domain is iteratively shrunk around promising regions using SDR parameters (sdr_gamma_osc, sdr_gamma_pan, sdr_eta, sdr_minimum_window).
- sdr_gamma_osc: float = 0.7¶
Oscillation shrinkage parameter for SDR.
Controls how aggressively the search space shrinks in oscillating fashion. Only used when enable_sdr is True. Typical range: [0.5, 0.7]. Default = 0.7.
- sdr_gamma_pan: float = 1.0¶
Panning parameter for SDR.
Controls the panning behavior during domain reduction. Only used when enable_sdr is True. Typical value: 1.0. Default = 1.0.
- sdr_minimum_window: NonNegativeFloat = 0.0¶
Minimum window size for Sequential Domain Reduction.
Only used when enable_sdr is True. Default = 0.0.
Gradient Free Optimizers¶
Optimizers from the gradient_free_optimizers package are available in optimagic. To use it, you need to have gradient_free_optimizers installed.
gfo_hillclimbing
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.gfo_hillclimbing(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="gfo_hillclimbing",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.gfo_optimizers.GFOHillClimbing[source]¶
Minimize a scalar function using the HillClimbing algorithm.
This algorithm is a Python implementation of the HillClimbing algorithm through the gradient_free_optimizers package.
Hill climbing is a local search algorithm suited for exploring combinatorial search spaces.
“It starts at an initial point, which is the best point chosen from n_init initialization runs, and continues to move to positions within its neighbourhood with a better solution. It has no method against getting stuck in local optima.
- epsilon: PositiveFloat = 0.03¶
The step-size of the hill climbing algorithm. If step_size is too large the newly selected positions will be at the edge of the search space.
If its value is very low it might not find new positions.
- distribution: Literal['normal', 'laplace', 'logistic', 'gumbel'] = 'normal'¶
The mathematical distribution the algorithm draws samples from.
All available distributions are taken from the numpy-package.
- n_neighbours: PositiveInt = 3¶
The number of positions the algorithm explores from its current postion before setting its current position to the best of those neighbour positions.
If the value of n_neighbours is large the hill-climbing-based algorithm will take a lot of time to choose the next position to move to, but the choice will probably be a good one. It might be a prudent approach to increase n_neighbours of the search- space has a lot of dimensions, because there are more possible directions to move to.
- caching = True¶
Whether to cache evaluated param and function values in a dictionary for lookup.
- convergence_ftol_abs = 0¶
Converge if the absolute change in the objective function is less than this value.
- convergence_ftol_rel = None¶
Converge if the relative change in the objective function is less than this value.
- convergence_iter_noimprove = 1000000¶
Number of iterations without improvement before termination.
- convergence_target_value = None¶
“Stop the optimization if the objective function is less than this value.
- extra_start_params = None¶
List of additional start points for the optimization run.
In case of population based optimizers, the initial_population can be provided via extra_start_params
- n_grid_points = 201¶
Number of grid points per dimension.
If an integer is provided, it will be used for all dimensions.
- n_init = 20¶
Number of initialization steps to run.
Accordingly, N//2 positions will be initialized in a grid like pattern and remaining initialized at the vertices and randomly in the search space.
- rand_rest_p = 0¶
Probability for the optimization algorithm to jump to a random position in an iteration step.
- seed = None¶
Random seed for reproducibility.
- stopping_maxiter = 1000000¶
Maximum number of iterations.
- stopping_maxtime = None¶
Maximum time in seconds before termination.
- verbosity = False¶
Determines what part of the optimization information will be printed.
- warm_start = None¶
Pandas dataframe that contains score and paramter information that will be automatically loaded into the memory.
example:
score x1 x2 x… 0.756 0.1 0.2 … 0.823 0.3 0.1 … … … … … … … … …
gfo_stochastichillclimbing
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.gfo_stochastichillclimbing(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="gfo_stochastichillclimbing",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.gfo_optimizers.GFOStochasticHillClimbing[source]¶
Minimize a scalar function using the Stochastic Hill Climbing algorithm.
This algorithm is a Python implementation of the StochasticHillClimbing algorithm through the gradient_free_optimizers package.
Stochastic hill climbing extends the normal hill climbing by accepting worse positions with a probability p_accept as a next position helping against getting stuck in local optima.
- epsilon: PositiveFloat = 0.03¶
The step-size of the hill climbing algorithm. If step_size is too large the newly selected positions will be at the edge of the search space.
If its value is very low it might not find new positions.
- distribution: Literal['normal', 'laplace', 'logistic', 'gumbel'] = 'normal'¶
The mathematical distribution the algorithm draws samples from.
All available distributions are taken from the numpy-package.
- n_neighbours: PositiveInt = 3¶
The number of positions the algorithm explores from its current postion before setting its current position to the best of those neighbour positions.
If the value of n_neighbours is large the hill-climbing-based algorithm will take a lot of time to choose the next position to move to, but the choice will probably be a good one. It might be a prudent approach to increase n_neighbours of the search- space has a lot of dimensions, because there are more possible directions to move to.
- p_accept: UnitIntervalFloat = 0.5¶
The probability factor used in the equation to calculate if a worse position is accepted as the new position.
If the new score is not better than the previous one the algorithm accepts worse positions with probability p_accept.
\[score_{normalized} = norm * \frac{score_{current} - score_{new}} {score_{current} + score_{new}}\]\[p = \exp^{-score_{normalized}}\]If p is less than p_accept the new position gets accepted anyways.
- caching = True¶
Whether to cache evaluated param and function values in a dictionary for lookup.
- convergence_ftol_abs = 0¶
Converge if the absolute change in the objective function is less than this value.
- convergence_ftol_rel = None¶
Converge if the relative change in the objective function is less than this value.
- convergence_iter_noimprove = 1000000¶
Number of iterations without improvement before termination.
- convergence_target_value = None¶
“Stop the optimization if the objective function is less than this value.
- extra_start_params = None¶
List of additional start points for the optimization run.
In case of population based optimizers, the initial_population can be provided via extra_start_params
- n_grid_points = 201¶
Number of grid points per dimension.
If an integer is provided, it will be used for all dimensions.
- n_init = 20¶
Number of initialization steps to run.
Accordingly, N//2 positions will be initialized in a grid like pattern and remaining initialized at the vertices and randomly in the search space.
- rand_rest_p = 0¶
Probability for the optimization algorithm to jump to a random position in an iteration step.
- seed = None¶
Random seed for reproducibility.
- stopping_maxiter = 1000000¶
Maximum number of iterations.
- stopping_maxtime = None¶
Maximum time in seconds before termination.
- verbosity = False¶
Determines what part of the optimization information will be printed.
- warm_start = None¶
Pandas dataframe that contains score and paramter information that will be automatically loaded into the memory.
example:
score x1 x2 x… 0.756 0.1 0.2 … 0.823 0.3 0.1 … … … … … … … … …
gfo_repulsinghillclimbing
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.gfo_repulsinghillclimbing(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="gfo_repulsinghillclimbing",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.gfo_optimizers.GFORepulsingHillClimbing[source]¶
Minimize a scalar function using the Repulsing Hill Climbing algorithm.
This algorithm is a Python implementation of the Repulsing Hill Climbing algorithm through the gradient_free_optimizers package.
The algorithm inherits from the Hill climbing which is a local search algorithm but always activates its methods to escape local optima.
- epsilon: PositiveFloat = 0.03¶
The step-size of the hill climbing algorithm. If step_size is too large the newly selected positions will be at the edge of the search space.
If its value is very low it might not find new positions.
- distribution: Literal['normal', 'laplace', 'logistic', 'gumbel'] = 'normal'¶
The mathematical distribution the algorithm draws samples from.
All available distributions are taken from the numpy-package.
- n_neighbours: PositiveInt = 3¶
The number of positions the algorithm explores from its current position before setting its current position to the best of those neighbour positions.
- repulsion_factor: PositiveFloat = 5¶
The algorithm increases the step size by multiplying it with the repulsion_factor for the next iteration. This way the algorithm escapes the region that does not offer better positions.
\[\epsilon = \epsilon * {repulsion factor}\]
- caching = True¶
Whether to cache evaluated param and function values in a dictionary for lookup.
- convergence_ftol_abs = 0¶
Converge if the absolute change in the objective function is less than this value.
- convergence_ftol_rel = None¶
Converge if the relative change in the objective function is less than this value.
- convergence_iter_noimprove = 1000000¶
Number of iterations without improvement before termination.
- convergence_target_value = None¶
“Stop the optimization if the objective function is less than this value.
- extra_start_params = None¶
List of additional start points for the optimization run.
In case of population based optimizers, the initial_population can be provided via extra_start_params
- n_grid_points = 201¶
Number of grid points per dimension.
If an integer is provided, it will be used for all dimensions.
- n_init = 20¶
Number of initialization steps to run.
Accordingly, N//2 positions will be initialized in a grid like pattern and remaining initialized at the vertices and randomly in the search space.
- rand_rest_p = 0¶
Probability for the optimization algorithm to jump to a random position in an iteration step.
- seed = None¶
Random seed for reproducibility.
- stopping_maxiter = 1000000¶
Maximum number of iterations.
- stopping_maxtime = None¶
Maximum time in seconds before termination.
- verbosity = False¶
Determines what part of the optimization information will be printed.
- warm_start = None¶
Pandas dataframe that contains score and paramter information that will be automatically loaded into the memory.
example:
score x1 x2 x… 0.756 0.1 0.2 … 0.823 0.3 0.1 … … … … … … … … …
gfo_simulatedannealing
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.gfo_simulatedannealing(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="gfo_simulatedannealing",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.gfo_optimizers.GFOSimulatedAnnealing[source]¶
Minimize a scalar function using the Simulated Annealing algorithm.
This algorithm is a Python implementation of Simulated Annealing through the gradient_free_optimizers package.
Simulated annealing chooses its next possible position similar to hill climbing, but it accepts worse results with a probability that decreases with time. It simulates a temperature that decreases with each iteration, similar to a material cooling down.
- epsilon: PositiveFloat = 0.03¶
The step-size of the algorithm.
If step_size is too large the newly selected positions will be at the edge of the search space. If its value is very low it might not find new positions.
- distribution: Literal['normal', 'laplace', 'logistic', 'gumbel'] = 'normal'¶
The mathematical distribution the algorithm draws samples from.
All available distributions are taken from the numpy-package.
- n_neighbours: PositiveInt = 3¶
The number of positions the algorithm explores from its current position before setting its current position to the best of those neighbour positions.
- start_temp: PositiveFloat = 1¶
The start_temp is a factor for the probability p of accepting a worse position.
\[p = \exp^{-\frac{score_{normalized}}{temp}}\]
- annealing_rate: PositiveFloat = 0.97¶
Rate at which the temperatur-value of the algorithm decreases. An annealing rate above 1 increases the temperature over time.
\[start\_temp \leftarrow start\_temp * annealing\_rate\]
- caching = True¶
Whether to cache evaluated param and function values in a dictionary for lookup.
- convergence_ftol_abs = 0¶
Converge if the absolute change in the objective function is less than this value.
- convergence_ftol_rel = None¶
Converge if the relative change in the objective function is less than this value.
- convergence_iter_noimprove = 1000000¶
Number of iterations without improvement before termination.
- convergence_target_value = None¶
“Stop the optimization if the objective function is less than this value.
- extra_start_params = None¶
List of additional start points for the optimization run.
In case of population based optimizers, the initial_population can be provided via extra_start_params
- n_grid_points = 201¶
Number of grid points per dimension.
If an integer is provided, it will be used for all dimensions.
- n_init = 20¶
Number of initialization steps to run.
Accordingly, N//2 positions will be initialized in a grid like pattern and remaining initialized at the vertices and randomly in the search space.
- rand_rest_p = 0¶
Probability for the optimization algorithm to jump to a random position in an iteration step.
- seed = None¶
Random seed for reproducibility.
- stopping_maxiter = 1000000¶
Maximum number of iterations.
- stopping_maxtime = None¶
Maximum time in seconds before termination.
- verbosity = False¶
Determines what part of the optimization information will be printed.
- warm_start = None¶
Pandas dataframe that contains score and paramter information that will be automatically loaded into the memory.
example:
score x1 x2 x… 0.756 0.1 0.2 … 0.823 0.3 0.1 … … … … … … … … …
gfo_downhillsimplex
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.gfo_downhillsimplex(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="gfo_downhillsimplex",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.gfo_optimizers.GFODownhillSimplex[source]¶
Minimize a scalar function using the Downhill Simplex algorithm.
This algorithm is a Python implementation of the Downhill Simplex algorithm through the gradient_free_optimizers package.
The Downhill simplex or Nelder mead algorithm works by grouping number of dimensions + 1 positions into a simplex, which can explore the search-space by changing shape. The simplex changes shape by reflecting, expanding, contracting or shrinking via the alpha, gamma, beta or sigma parameters. It needs at least number of dimensions + 1 initial positions to form a simplex in the search-space and the movement of the positions in the simplex are affected by each other.
- simplex_reflection: PositiveFloat = 1¶
The reflection parameter of the simplex algorithm.
- simplex_expansion: PositiveFloat = 2¶
The expansion parameter of the simplex algorithm.
- simplex_contraction: PositiveFloat = 0.5¶
The contraction parameter of the simplex algorithm.
- simplex_shrinking: PositiveFloat = 0.5¶
The shrinking parameter of the simplex algorithm.
- caching = True¶
Whether to cache evaluated param and function values in a dictionary for lookup.
- convergence_ftol_abs = 0¶
Converge if the absolute change in the objective function is less than this value.
- convergence_ftol_rel = None¶
Converge if the relative change in the objective function is less than this value.
- convergence_iter_noimprove = 1000000¶
Number of iterations without improvement before termination.
- convergence_target_value = None¶
“Stop the optimization if the objective function is less than this value.
- extra_start_params = None¶
List of additional start points for the optimization run.
In case of population based optimizers, the initial_population can be provided via extra_start_params
- n_grid_points = 201¶
Number of grid points per dimension.
If an integer is provided, it will be used for all dimensions.
- n_init = 20¶
Number of initialization steps to run.
Accordingly, N//2 positions will be initialized in a grid like pattern and remaining initialized at the vertices and randomly in the search space.
- rand_rest_p = 0¶
Probability for the optimization algorithm to jump to a random position in an iteration step.
- seed = None¶
Random seed for reproducibility.
- stopping_maxiter = 1000000¶
Maximum number of iterations.
- stopping_maxtime = None¶
Maximum time in seconds before termination.
- verbosity = False¶
Determines what part of the optimization information will be printed.
- warm_start = None¶
Pandas dataframe that contains score and paramter information that will be automatically loaded into the memory.
example:
score x1 x2 x… 0.756 0.1 0.2 … 0.823 0.3 0.1 … … … … … … … … …
gfo_powells_method
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.gfo_powells_method(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="gfo_powells_method",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.gfo_optimizers.GFOPowellsMethod[source]¶
Minimize a scalar function using Powell’s Method.
This algorithm is a Python implementation of the Powell’s Method algorithm through the gradient_free_optimizers package.
This powell’s method implementation works by optimizing each search space dimension at a time with the hill climbing algorithm. It works by setting the search space range for all dimensions except one to a single value. The hill climbing algorithms searches the best position within this dimension. After iters_p_dim iterations the next dimension is searched, while the search space range from the previously searched dimension is set to the best position, This way the algorithm finds new best positions one dimension at a time.
- iters_p_dim: PositiveInt = 10¶
Number of iterations the algorithm will let the hill-climbing algorithm search to find the best position before it changes to the next dimension of the search space.
Typical range: 5 to 15.
- caching = True¶
Whether to cache evaluated param and function values in a dictionary for lookup.
- convergence_ftol_abs = 0¶
Converge if the absolute change in the objective function is less than this value.
- convergence_ftol_rel = None¶
Converge if the relative change in the objective function is less than this value.
- convergence_iter_noimprove = 1000000¶
Number of iterations without improvement before termination.
- convergence_target_value = None¶
“Stop the optimization if the objective function is less than this value.
- extra_start_params = None¶
List of additional start points for the optimization run.
In case of population based optimizers, the initial_population can be provided via extra_start_params
- n_grid_points = 201¶
Number of grid points per dimension.
If an integer is provided, it will be used for all dimensions.
- n_init = 20¶
Number of initialization steps to run.
Accordingly, N//2 positions will be initialized in a grid like pattern and remaining initialized at the vertices and randomly in the search space.
- rand_rest_p = 0¶
Probability for the optimization algorithm to jump to a random position in an iteration step.
- seed = None¶
Random seed for reproducibility.
- stopping_maxiter = 1000000¶
Maximum number of iterations.
- stopping_maxtime = None¶
Maximum time in seconds before termination.
- verbosity = False¶
Determines what part of the optimization information will be printed.
- warm_start = None¶
Pandas dataframe that contains score and paramter information that will be automatically loaded into the memory.
example:
score x1 x2 x… 0.756 0.1 0.2 … 0.823 0.3 0.1 … … … … … … … … …
gfo_pso
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.gfo_pso(stopping_maxiter=1_000),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="gfo_pso",
algo_options={"stopping_maxiter": 1_000},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.gfo_optimizers.GFOParticleSwarmOptimization[source]¶
Minimize a scalar function using the Particle Swarm Optimization algorithm.
This algorithm is a Python implementation of the Particle Swarm Optimization algorithm through the gradient_free_optimizers package.
Particle Swarm Optimization is a global population based algorithm.
The algorithm simulates a swarm of particles which move according to their own inertia across the search space. Each particle adjusts its position based on its own experience (cognitive weight) and the experiences of its neighbors or the swarm (social weight), using velocity updates. The algorithm iteratively guides the swarm toward promising regions of the search space.
The velocity of a particle is calculated by the following equation:
\[\begin{split}v_{n+1} = \\omega \\cdot v_n + c_k \\cdot r_1 \\cdot (p_{best}-p_n) + c_s \\cdot r_2 \\cdot (g_{best} - p_n)\end{split}\]- population_size: PositiveInt | None = None¶
Size of the population.
- caching = True¶
Whether to cache evaluated param and function values in a dictionary for lookup.
- convergence_ftol_abs = 0¶
Converge if the absolute change in the objective function is less than this value.
- convergence_ftol_rel = None¶
Converge if the relative change in the objective function is less than this value.
- convergence_iter_noimprove = 1000000¶
Number of iterations without improvement before termination.
- convergence_target_value = None¶
“Stop the optimization if the objective function is less than this value.
- extra_start_params = None¶
List of additional start points for the optimization run.
In case of population based optimizers, the initial_population can be provided via extra_start_params
- n_grid_points = 201¶
Number of grid points per dimension.
If an integer is provided, it will be used for all dimensions.
- n_init = 20¶
Number of initialization steps to run.
Accordingly, N//2 positions will be initialized in a grid like pattern and remaining initialized at the vertices and randomly in the search space.
- rand_rest_p = 0¶
Probability for the optimization algorithm to jump to a random position in an iteration step.
- seed = None¶
Random seed for reproducibility.
- stopping_maxiter = 1000000¶
Maximum number of iterations.
- stopping_maxtime = None¶
Maximum time in seconds before termination.
- verbosity = False¶
Determines what part of the optimization information will be printed.
- warm_start = None¶
Pandas dataframe that contains score and paramter information that will be automatically loaded into the memory.
example:
score x1 x2 x… 0.756 0.1 0.2 … 0.823 0.3 0.1 … … … … … … … … …
- inertia: NonNegativeFloat = 0.7213475204444817¶
The inertia of the movement of the individual particles in the population.
- cognitive_weight: NonNegativeFloat = 1.1931471805599454¶
A factor of the movement towards the personal best position of the individual particles in the population.
- social_weight: NonNegativeFloat = 1.1931471805599454¶
A factor of the movement towards the global best position of the individual particles in the population.
gfo_parallel_tempering
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.gfo_parallel_tempering(
population_size=15,
n_iter_swap=5,
),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="gfo_parallel_tempering",
algo_options={"population_size": 15, "n_iter_swap": 5},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.gfo_optimizers.GFOParallelTempering[source]¶
Minimize a scalar function using the Parallel Tempering algorithm.
This algorithm is a Python implementation of the Parallel Tempering algorithm through the gradient_free_optimizers package.
Parallel Tempering is a global optimization algorithm that is inspired by metallurgical annealing. It runs multiple optimizer instances at different “starting temperatures” in parallel. Periodically, swaps between these runs are attempted. Swaps between optimization runs at different temperatures allow the optimizer to overcome local optima.
The probability of swapping temperatures for any combination of optimizer instances is given by.
\[\begin{split}p = \\min \\left( 1, \\exp\\left[{(\\text{score}_i- \\text{score}_j)\\left(\\frac{1}{T_i}-\\frac{1}{T_j}\\right)}\\right] \\right)\end{split}\]- caching = True¶
Whether to cache evaluated param and function values in a dictionary for lookup.
- convergence_ftol_abs = 0¶
Converge if the absolute change in the objective function is less than this value.
- convergence_ftol_rel = None¶
Converge if the relative change in the objective function is less than this value.
- convergence_iter_noimprove = 1000000¶
Number of iterations without improvement before termination.
- convergence_target_value = None¶
“Stop the optimization if the objective function is less than this value.
- extra_start_params = None¶
List of additional start points for the optimization run.
In case of population based optimizers, the initial_population can be provided via extra_start_params
- n_grid_points = 201¶
Number of grid points per dimension.
If an integer is provided, it will be used for all dimensions.
- n_init = 20¶
Number of initialization steps to run.
Accordingly, N//2 positions will be initialized in a grid like pattern and remaining initialized at the vertices and randomly in the search space.
- rand_rest_p = 0¶
Probability for the optimization algorithm to jump to a random position in an iteration step.
- seed = None¶
Random seed for reproducibility.
- stopping_maxiter = 1000000¶
Maximum number of iterations.
- stopping_maxtime = None¶
Maximum time in seconds before termination.
- verbosity = False¶
Determines what part of the optimization information will be printed.
- warm_start = None¶
Pandas dataframe that contains score and paramter information that will be automatically loaded into the memory.
example:
score x1 x2 x… 0.756 0.1 0.2 … 0.823 0.3 0.1 … … … … … … … … …
- population_size: PositiveInt | None = None¶
Size of the population.
- n_iter_swap: PositiveInt = 10¶
The number of iterations the algorithm performs before switching temperatures of the individual optimizers in the population.
gfo_spiral_optimization
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.gfo_spiral_optimization(
population_size=15,
decay_rate=0.95,
),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="gfo_spiral_optimization",
algo_options={"population_size": 15, "decay_rate": 0.95},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.gfo_optimizers.GFOSpiralOptimization[source]¶
Minimize a scalar function using the Spiral Optimization algorithm.
This algorithm is a Python implementation of the Spiral Optimization algorithm through the gradient_free_optimizers package.
Spiral Optimization is a population-based algorithm, in which a number of particles move in a spiral-like pattern to explore the search space and converge to the best known position as the spiral decays.
The position of each particle is updated according to the following equation:
\[\begin{split}x_i (k+1) = x^* (k) + r(k) \\cdot R(\\theta) \\cdot (x_i(k)- x^*(k))\end{split}\]- where:
k = k-th iteration
x_i(k) = current position.
x*(k) = center position (known best position of all particles)
r(k) = decay rate ,
R = rotation matrix.
and rotation matrix R is given by
\[\begin{split}R(\\theta) = \\begin{bmatrix} 0^{\\top}_{n-1} & -1 \\\\ I_{n-1} & 0_{n-1} \\end{bmatrix}\end{split}\]- caching = True¶
Whether to cache evaluated param and function values in a dictionary for lookup.
- convergence_ftol_abs = 0¶
Converge if the absolute change in the objective function is less than this value.
- convergence_ftol_rel = None¶
Converge if the relative change in the objective function is less than this value.
- convergence_iter_noimprove = 1000000¶
Number of iterations without improvement before termination.
- convergence_target_value = None¶
“Stop the optimization if the objective function is less than this value.
- extra_start_params = None¶
List of additional start points for the optimization run.
In case of population based optimizers, the initial_population can be provided via extra_start_params
- n_grid_points = 201¶
Number of grid points per dimension.
If an integer is provided, it will be used for all dimensions.
- n_init = 20¶
Number of initialization steps to run.
Accordingly, N//2 positions will be initialized in a grid like pattern and remaining initialized at the vertices and randomly in the search space.
- rand_rest_p = 0¶
Probability for the optimization algorithm to jump to a random position in an iteration step.
- seed = None¶
Random seed for reproducibility.
- stopping_maxiter = 1000000¶
Maximum number of iterations.
- stopping_maxtime = None¶
Maximum time in seconds before termination.
- verbosity = False¶
Determines what part of the optimization information will be printed.
- warm_start = None¶
Pandas dataframe that contains score and paramter information that will be automatically loaded into the memory.
example:
score x1 x2 x… 0.756 0.1 0.2 … 0.823 0.3 0.1 … … … … … … … … …
- population_size: PositiveInt | None = None¶
Size of the population.
- decay_rate: NonNegativeFloat = 0.99¶
The decay rate r is a factor, by which the radius of the spiral movement of the particles decays during their spiral movement.
Lower values accelerate the convergence of the particles to the best known position, while values above 1 eventually lead to a movement where the particles spiral away from each other. Typical range: 0.85 to 1.15.
gfo_genetic_algorithm
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.gfo_genetic_algorithm(
population_size=20,
mutation_rate=0.6,
),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="gfo_genetic_algorithm",
algo_options={"population_size": 20, "mutation_rate": 0.6},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.gfo_optimizers.GFOGeneticAlgorithm[source]¶
Minimize a scalar function using the Genetic Algorithm.
This algorithm is a Python implementation of the Genetic Algorithm through the gradient_free_optimizers package.
The Genetic Algorithm is an evolutionary algorithm inspired by the process of natural selection. It evolves a population of candidate solutions over generations using mechanisms like selection, crossover, and mutation of genes(bits) to find the best solution.
- caching = True¶
Whether to cache evaluated param and function values in a dictionary for lookup.
- convergence_ftol_abs = 0¶
Converge if the absolute change in the objective function is less than this value.
- convergence_ftol_rel = None¶
Converge if the relative change in the objective function is less than this value.
- convergence_iter_noimprove = 1000000¶
Number of iterations without improvement before termination.
- convergence_target_value = None¶
“Stop the optimization if the objective function is less than this value.
- extra_start_params = None¶
List of additional start points for the optimization run.
In case of population based optimizers, the initial_population can be provided via extra_start_params
- n_grid_points = 201¶
Number of grid points per dimension.
If an integer is provided, it will be used for all dimensions.
- n_init = 20¶
Number of initialization steps to run.
Accordingly, N//2 positions will be initialized in a grid like pattern and remaining initialized at the vertices and randomly in the search space.
- rand_rest_p = 0¶
Probability for the optimization algorithm to jump to a random position in an iteration step.
- seed = None¶
Random seed for reproducibility.
- stopping_maxiter = 1000000¶
Maximum number of iterations.
- stopping_maxtime = None¶
Maximum time in seconds before termination.
- verbosity = False¶
Determines what part of the optimization information will be printed.
- warm_start = None¶
Pandas dataframe that contains score and paramter information that will be automatically loaded into the memory.
example:
score x1 x2 x… 0.756 0.1 0.2 … 0.823 0.3 0.1 … … … … … … … … …
- population_size: PositiveInt | None = None¶
Size of the population.
- mutation_rate: UnitIntervalFloat = 0.5¶
Probability of a mutation event occurring in an individual of the population. Mutation helps in maintaining genetic diversity within the population and prevents the algorithm from getting stuck in local optima. Bits are randomly altered with.
\[\begin{split}x'_i = \begin{cases} x_i & \text{if } \text{rand} > p_m \\ 1 - x_i & \text{if } \text{rand} \leq p_m \end{cases}\end{split}\]where p_m is mutation_rate.
- crossover_rate: UnitIntervalFloat = 0.5¶
Probability of a crossover event occurring between two parents. A higher crossover rate increases the diversity of the offspring, which can help in exploring the search space more effectively. Crossover happens with.
\[\begin{split}u_{i,j}^{(g)} = \begin{cases} v_{i,j}^{(g)} & \text{if } \text{rand}_j \leq C_r \text{ or } j = j_{\text{rand}} \\ x_{i,j}^{(g)} & \text{otherwise} \end{cases}\end{split}\]where C_r is crossover_rate .
- n_parents: PositiveInt = 2¶
The number of parents selected from the current population to participate in the crossover process to produce offspring.
By default, pairs of parents are selected to generate new offspring.
- n_offsprings: PositiveInt = 10¶
The number of offsprings generated in each generation through the processes of crossover and mutation.
Typically, the number of offspring is equal to the population size, ensuring that the population size remains constant over generations.
gfo_evolution_strategy
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.gfo_evolution_strategy(
population_size=15,
crossover_rate=0.4,
),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="gfo_evolution_strategy",
algo_options={"population_size": 15, "crossover_rate": 0.4},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.gfo_optimizers.GFOEvolutionStrategy[source]¶
Minimize a scalar function using the Evolution Strategy algorithm.
This algorithm is a Python implementation of the Evolution Strategy algorithm through the gradient_free_optimizers package.
Evolution Strategy is a evolutionary algorithm inspired by natural evolution and work by iteratively improving a population of candidate solutions through mutation, crossover, and selection. A population of parents generates offspring, and only the fittest individuals from both parents and offspring are selected to form the next generation.
The algorithm uses both mutation and crossover to create new candidate solutions. The choice between mutation and crossover is determined probabilistically based on their respective rates in the following way.
\[\begin{split}\\text{total\\_rate} = \\text{mutation\\_rate} + \\text{crossover\\_rate}\end{split}\]\[\begin{split}R = \\text{random\\_float} (0 ... \\text{total\\_rate})\end{split}\]if R <= mutation-rate: do mutation else: do crossover
- caching = True¶
Whether to cache evaluated param and function values in a dictionary for lookup.
- convergence_ftol_abs = 0¶
Converge if the absolute change in the objective function is less than this value.
- convergence_ftol_rel = None¶
Converge if the relative change in the objective function is less than this value.
- convergence_iter_noimprove = 1000000¶
Number of iterations without improvement before termination.
- convergence_target_value = None¶
“Stop the optimization if the objective function is less than this value.
- extra_start_params = None¶
List of additional start points for the optimization run.
In case of population based optimizers, the initial_population can be provided via extra_start_params
- n_grid_points = 201¶
Number of grid points per dimension.
If an integer is provided, it will be used for all dimensions.
- n_init = 20¶
Number of initialization steps to run.
Accordingly, N//2 positions will be initialized in a grid like pattern and remaining initialized at the vertices and randomly in the search space.
- rand_rest_p = 0¶
Probability for the optimization algorithm to jump to a random position in an iteration step.
- seed = None¶
Random seed for reproducibility.
- stopping_maxtime = None¶
Maximum time in seconds before termination.
- verbosity = False¶
Determines what part of the optimization information will be printed.
- warm_start = None¶
Pandas dataframe that contains score and paramter information that will be automatically loaded into the memory.
example:
score x1 x2 x… 0.756 0.1 0.2 … 0.823 0.3 0.1 … … … … … … … … …
- population_size: PositiveInt | None = None¶
Size of the population.
- stopping_maxiter: PositiveInt = 1000¶
Maximum number of iterations.
- mutation_rate: UnitIntervalFloat = 0.7¶
Probability of a mutation event occurring in an individual.
- crossover_rate: UnitIntervalFloat = 0.3¶
Probability of an individual to perform a crossover with the best individual in the population.
gfo_differential_evolution
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.gfo_differential_evolution(
population_size=20,
mutation_rate=0.8,
),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="gfo_differential_evolution",
algo_options={"population_size": 20, "mutation_rate": 0.8},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.gfo_optimizers.GFODifferentialEvolution[source]¶
Minimize a scalar function using the Differential Evolution algorithm.
This algorithm is a Python implementation of the Differential Evolution algorithm through the gradient_free_optimizers package.
Differential Evolution is a population-based optimization algorithm that creates iteratively improves a population of candidate solutions by combining and perturbing them based on their differences. It creates new positions in the search space by adding the weighted difference between two individuals in the population to a third individual creating trial solutions that are evaluated for their fitness and if a trial solution is better than the target it replaces, ensures continual improvement.
A new trial solution is generated according to:
\[\begin{split}x_{trial} = x_{r1} + F \\cdot (x_{r2} - x_{r3})\end{split}\]where \(r1, r2, r3\) are random individuals from the population, and \(F\) is the differential weight or mutation_rate.
- caching = True¶
Whether to cache evaluated param and function values in a dictionary for lookup.
- convergence_ftol_abs = 0¶
Converge if the absolute change in the objective function is less than this value.
- convergence_ftol_rel = None¶
Converge if the relative change in the objective function is less than this value.
- convergence_iter_noimprove = 1000000¶
Number of iterations without improvement before termination.
- convergence_target_value = None¶
“Stop the optimization if the objective function is less than this value.
- extra_start_params = None¶
List of additional start points for the optimization run.
In case of population based optimizers, the initial_population can be provided via extra_start_params
- n_grid_points = 201¶
Number of grid points per dimension.
If an integer is provided, it will be used for all dimensions.
- n_init = 20¶
Number of initialization steps to run.
Accordingly, N//2 positions will be initialized in a grid like pattern and remaining initialized at the vertices and randomly in the search space.
- rand_rest_p = 0¶
Probability for the optimization algorithm to jump to a random position in an iteration step.
- seed = None¶
Random seed for reproducibility.
- stopping_maxiter = 1000000¶
Maximum number of iterations.
- stopping_maxtime = None¶
Maximum time in seconds before termination.
- verbosity = False¶
Determines what part of the optimization information will be printed.
- warm_start = None¶
Pandas dataframe that contains score and paramter information that will be automatically loaded into the memory.
example:
score x1 x2 x… 0.756 0.1 0.2 … 0.823 0.3 0.1 … … … … … … … … …
- population_size: PositiveInt | None = None¶
Size of the population.
- mutation_rate: UnitIntervalFloat = 0.9¶
Probability of a mutation event occurring in an individual.
The mutation rate influences the algorithm’s ability to explore the search space. A higher value of mutation_rate also called the differential weight F increases the diversity of the mutant individuals, leading to broader exploration, while a lower value encourages convergence by making smaller adjustments.
\[\mathbf{v}_{i,G+1} = \mathbf{x}_{r1,G} + F \cdot (\mathbf{x}_{r2,G} - \mathbf{x}_{r3,G})\]
- crossover_rate: UnitIntervalFloat = 0.9¶
Probability of a crossover event occurring between two parents. It determines how much of the trial vector inherits its components from the mutant individual versus the target individual. A high crossover rate means that more components will come from the mutant individual, promoting exploration of new solutions. Conversely, a low crossover rate results in more components being taken from the target individual, which can help maintain existing solutions and refine them.
\[\begin{split}u_{i,j,G+1} = \begin{cases} v_{i,j,G+1} & \text{if } \text{rand}_j(0,1) \leq CR \text{ or } j = j_{\text{rand}} \\ x_{i,j,G} & \text{otherwise} \end{cases}\end{split}\]
Pygad Optimizer¶
We wrap the pygad optimizer. To use it you need to have pygad installed.
pygad
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pygad(num_generations=100),
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pygad",
algo_options={"num_generations": 100},
bounds=om.Bounds(lower=np.full(3, -5.0), upper=np.full(3, 5.0)),
)
Description and available options:
- class optimagic.optimizers.pygad_optimizer.Pygad[source]¶
Minimize a scalar function using the PyGAD genetic algorithm.
This optimizer wraps the PyGAD genetic algorithm package [algo_92], a population-based evolutionary method for global optimization. It maintains a population of candidate solutions and evolves them over generations using biologically inspired operations: selection (choosing parents based on fitness), crossover (combining genes from parents), and mutation (introducing random variations).
The algorithm is well-suited for global optimization problems with multiple local optima, black-box optimization where gradients are unavailable or difficult to compute.
All variables must have finite bounds. Parallel fitness evaluation is supported via batch processing.
For more details, see the PyGAD documentation.
- population_size: PositiveInt | None = None¶
Number of solutions in each generation.
Larger populations explore the search space more thoroughly but require more fitness evaluations per generation. If None, optimagic sets this to
max(10, 10 * (problem_dimension + 1)).
- num_parents_mating: PositiveInt | None = 10¶
Number of parents selected for mating in each generation.
Higher values can speed up convergence but may risk premature convergence. If None, defaults to
max(2, population_size // 2).
- num_generations: PositiveInt | None = 50¶
Number of generations to evolve the population.
- stopping_maxiter: PositiveInt = 1000000¶
Maximum number of iterations (generations) to run.
This corresponds to PyGAD’s num_generations parameter.
- initial_population: list[PyTree] | None = None¶
Optional initial population as a list of parameter PyTrees.
If None, the population is initialized randomly within parameter bounds.
- parent_selection_type: Literal['sss', 'rws', 'sus', 'rank', 'random', 'tournament'] | ParentSelectionFunction = 'sss'¶
Parent selection strategy used to choose parents for crossover.
Available methods:
"sss": Steady-State Selection (selects the best individuals to continue)"rws": Roulette Wheel Selection (probabilistic, fitness-proportional)"sus": Stochastic Universal Sampling (even sampling across population)"rank": Rank Selection (selects based on rank order)"random": Random Selection"tournament": Tournament Selection (best from K randomly chosen individuals)
Alternatively, provide a custom function with signature
(fitness, num_parents, ga_instance) -> tuple[NDArray, NDArray].
- keep_parents: int = -1¶
Number of best parents to keep in the next generation.
Only used if
keep_elitism = 0. Values:-1: Keep all parents in the next generation (default)0: Keep no parents in the next generationPositive integer: Keep the specified number of best parents
- keep_elitism: int = 1¶
Number of elite (best) solutions preserved each generation.
Range: 0 to population_size. If greater than 0, takes precedence over
keep_parents. When 0, elitism is disabled andkeep_parentscontrols parent retention.
- K_tournament: PositiveInt = 3¶
Tournament size for parent selection when
parent_selection_type="tournament".
- crossover_type: Literal['single_point', 'two_points', 'uniform', 'scattered'] | CrossoverFunction | None = 'single_point'¶
Crossover operator for generating offspring.
Available methods:
"single_point": Single-point crossover"two_points": Two-point crossover"uniform": Uniform crossover (randomly mixes genes)"scattered": Scattered crossover (random mask)
Or provide a custom function with signature
(parents, offspring_size, ga_instance) -> NDArray.
- crossover_probability: ProbabilityFloat | None = None¶
Probability of applying crossover to selected parents.
Range [0, 1]. If None, uses PyGAD’s default.
- mutation: Literal['random', 'swap', 'inversion', 'scramble', 'adaptive'] | type[_BuiltinMutation] | _BuiltinMutation | MutationFunction | None = 'random'¶
Mutation operator for introducing genetic diversity.
Available options:
String values for default configurations:
"random": Random mutation with default parameters"swap": Swap mutation with default parameters"inversion": Inversion mutation with default parameters"scramble": Scramble mutation with default parameters"adaptive": Adaptive random mutation with default parameters
Mutation classes for default configurations:
Any mutation class (e.g.,
RandomMutation,SwapMutation,AdaptiveMutation, etc.)All classes can be used without parameters for default behavior
Configured mutation instances:
Any mutation instance (e.g.,
RandomMutation(...),SwapMutation(), etc.)All mutation classes inherit from
_BuiltinMutation
Custom function:
Custom function with signature
(offspring, ga_instance) -> NDArray
Disable mutation:
Noneto disable mutation
- gene_constraint: list[GeneConstraintFunction | None] | None = None¶
Optional list of per-gene constraint functions.
Each with signature
(solution, values) -> list[float] | NDArray.
- sample_size: PositiveInt = 100¶
Number of values to sample when enforcing uniqueness or gene constraints.
- batch_size: PositiveInt | None = None¶
Number of solutions to evaluate in parallel batches.
If None and
n_cores > 1, automatically set ton_cores.
- convergence_target_value: PositiveFloat | None = None¶
Target value for early stopping.
Default: None.
- convergence_generations_noimprove: PositiveInt | None = None¶
Maximum generations without fitness improvement before stopping.
Default: None.
- n_cores: PositiveInt = 1¶
Number of CPU cores for parallel fitness evaluation.
PySwarms Optimizers¶
optimagic supports the following continuous algorithms from the
PySwarms library: (GlobalBestPSO,
LocalBestPSO, GeneralOptimizerPSO). To use these optimizers, you need to have
the pyswarms package installed.
(pip install pyswarms).
pyswarms_global_best
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pyswarms_global_best(n_particles=50),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pyswarms_global_best",
algo_options={"n_particles": 50},
)
Description and available options:
- class optimagic.optimizers.pyswarms_optimizers.PySwarmsGlobalBestPSO[source]¶
Minimize a scalar function using Global Best Particle Swarm Optimization.
A population-based stochastic, global optimization optimization algorithm that simulates the social behavior of bird flocking or fish schooling. Particles (candidate solutions) move through the search space, adjusting their positions based on their own experience (cognitive component) and the experience of their neighbors or the entire swarm (social component).
This implementation uses a star topology where all particles are connected to each other, making each particle aware of the global best solution found by the entire swarm.
The position update follows:
\[x_{i}(t+1) = x_{i}(t) + v_{i}(t+1)\]The velocity update follows:
\[v_{ij}(t+1) = w \cdot v_{ij}(t) + c_1 r_{1j}(t)[y_{ij}(t) - x_{ij}(t)] + c_2 r_{2j}(t)[\hat{y}_j(t) - x_{ij}(t)]\]- Where:
\(w\): inertia weight controlling momentum
\(c_1\): cognitive parameter for attraction to personal best
\(c_2\): social parameter for attraction to global best
\(r_{1j}, r_{2j}\): random numbers in [0,1]
\(y_{ij}(t)\): personal best position of particle i
\(\hat{y}_j(t)\): global best position
This algorithm is an adaptation of the original Particle Swarm Optimization method by [algo_49]
- boundary_strategy = 'periodic'¶
Strategy for handling out-of-bounds particles.
Available options: periodic (default), reflective, shrink, random, intermediate.
- center_init = 1.0¶
Scaling factor for initial particle positions.
- cognitive_parameter = 0.5¶
Cognitive parameter (c1) - attraction to personal best.
- convergence_ftol_iter = 1¶
Number of iterations to check for convergence.
- convergence_ftol_rel = 0¶
Stop when relative change in objective function is less than this value.
- inertia_weight = 0.9¶
Inertia weight (w) - momentum control.
- initial_positions = None¶
Option to set the initial particle positions.
If None, positions are generated randomly within the given bounds, or within [0, 1] if bounds are not specified.
- n_cores = 1¶
Number of cores for parallel evaluation.
- n_particles = 10¶
Number of particles in the swarm.
- oh_strategy = None¶
Dictionary of strategies for time-varying options.
- seed = None¶
Random seed for initial positions.
For full reproducibility, set a global seed with np.random.seed().
- social_parameter = 0.3¶
Social parameter (c2) - attraction to neighborhood/global best.
- stopping_maxiter = 1000¶
Maximum number of iterations.
- velocity_clamp_max = None¶
Maximum velocity limit for particles.
- velocity_clamp_min = None¶
Minimum velocity limit for particles.
- velocity_strategy = 'unmodified'¶
Strategy for handling out-of-bounds velocities.
Available options: unmodified (default), adjust, invert, zero.
- verbose = False¶
Enable or disable the logs and progress bar.
pyswarms_local_best
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pyswarms_local_best(n_particles=50),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pyswarms_local_best",
algo_options={"n_particles": 50},
)
Description and available options:
- class optimagic.optimizers.pyswarms_optimizers.PySwarmsLocalBestPSO[source]¶
Minimize a scalar function using Local Best Particle Swarm Optimization.
A variant of PSO that uses local neighborhoods instead of a single global best. Each particle is influenced only by the best position found within its local neighborhood, which is determined by the k-nearest neighbors using distance metrics.
This approach uses a ring topology where particles are connected to their local neighbors, making each particle aware of only the best solution found within its neighborhood.
The position update follows:
\[x_{i}(t+1) = x_{i}(t) + v_{i}(t+1)\]The velocity update follows:
\[v_{ij}(t+1) = w \cdot v_{ij}(t) + c_1 r_{1j}(t)[y_{ij}(t) - x_{ij}(t)] + c_2 r_{2j}(t)[\hat{y}_{lj}(t) - x_{ij}(t)]\]- Where:
\(w\): inertia weight controlling momentum
\(c_1\): cognitive parameter for attraction to personal best
\(c_2\): social parameter for attraction to local best
\(r_{1j}, r_{2j}\): random numbers in [0,1]
\(y_{ij}(t)\): personal best position of particle i
\(\hat{y}_{lj}(t)\): local best position in particle i’s neighborhood
The algorithm is based on the original Particle Swarm Optimization method by [algo_49] and the local best concept introduced in [algo_93].
- boundary_strategy = 'periodic'¶
Strategy for handling out-of-bounds particles.
Available options: periodic (default), reflective, shrink, random, intermediate.
- center_init = 1.0¶
Scaling factor for initial particle positions.
- cognitive_parameter = 0.5¶
Cognitive parameter (c1) - attraction to personal best.
- convergence_ftol_iter = 1¶
Number of iterations to check for convergence.
- convergence_ftol_rel = 0¶
Stop when relative change in objective function is less than this value.
- inertia_weight = 0.9¶
Inertia weight (w) - momentum control.
- initial_positions = None¶
Option to set the initial particle positions.
If None, positions are generated randomly within the given bounds, or within [0, 1] if bounds are not specified.
- n_cores = 1¶
Number of cores for parallel evaluation.
- n_particles = 10¶
Number of particles in the swarm.
- oh_strategy = None¶
Dictionary of strategies for time-varying options.
- seed = None¶
Random seed for initial positions.
For full reproducibility, set a global seed with np.random.seed().
- social_parameter = 0.3¶
Social parameter (c2) - attraction to neighborhood/global best.
- stopping_maxiter = 1000¶
Maximum number of iterations.
- velocity_clamp_max = None¶
Maximum velocity limit for particles.
- velocity_clamp_min = None¶
Minimum velocity limit for particles.
- velocity_strategy = 'unmodified'¶
Strategy for handling out-of-bounds velocities.
Available options: unmodified (default), adjust, invert, zero.
- verbose = False¶
Enable or disable the logs and progress bar.
- topology: RingTopology = RingTopology(k_neighbors=3, p_norm=2, static=False)¶
Configuration for the Ring topology.
This algorithm uses a fixed ring topology where particles are connected to their local neighbors. This parameter allows customization of the number of neighbors, distance metric, and whether the topology remains static throughout optimization.
pyswarms_general
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.pyswarms_general(n_particles=50, topology="star"),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="pyswarms_general",
algo_options={"n_particles": 50, "topology": "star"},
)
Description and available options:
- class optimagic.optimizers.pyswarms_optimizers.PySwarmsGeneralPSO[source]¶
Minimize a scalar function using General Particle Swarm Optimization with custom topologies.
A flexible PSO implementation that allows selection of different neighborhood topologies, providing control over the balance between exploration and exploitation. The topology determines how particles communicate and share information, directly affecting the algorithm’s search behavior.
The position update follows:
\[x_{i}(t+1) = x_{i}(t) + v_{i}(t+1)\]The velocity update follows:
\[v_{ij}(t+1) = w \cdot v_{ij}(t) + c_1 r_{1j}(t)[y_{ij}(t) - x_{ij}(t)] + c_2 r_{2j}(t)[\hat{y}_{nj}(t) - x_{ij}(t)]\]- Where:
\(w\): inertia weight controlling momentum
\(c_1\): cognitive parameter for attraction to personal best
\(c_2\): social parameter for attraction to neighborhood best
\(r_{1j}, r_{2j}\): random numbers in [0,1]
\(y_{ij}(t)\): personal best position of particle i
\(\hat{y}_{nj}(t)\): neighborhood best position
This algorithm is based on the original Particle Swarm Optimization method by [algo_49] with configurable topology structures. For topology references, see [algo_94, algo_95].
- boundary_strategy = 'periodic'¶
Strategy for handling out-of-bounds particles.
Available options: periodic (default), reflective, shrink, random, intermediate.
- center_init = 1.0¶
Scaling factor for initial particle positions.
- cognitive_parameter = 0.5¶
Cognitive parameter (c1) - attraction to personal best.
- convergence_ftol_iter = 1¶
Number of iterations to check for convergence.
- convergence_ftol_rel = 0¶
Stop when relative change in objective function is less than this value.
- inertia_weight = 0.9¶
Inertia weight (w) - momentum control.
- initial_positions = None¶
Option to set the initial particle positions.
If None, positions are generated randomly within the given bounds, or within [0, 1] if bounds are not specified.
- n_cores = 1¶
Number of cores for parallel evaluation.
- n_particles = 10¶
Number of particles in the swarm.
- oh_strategy = None¶
Dictionary of strategies for time-varying options.
- seed = None¶
Random seed for initial positions.
For full reproducibility, set a global seed with np.random.seed().
- social_parameter = 0.3¶
Social parameter (c2) - attraction to neighborhood/global best.
- stopping_maxiter = 1000¶
Maximum number of iterations.
- velocity_clamp_max = None¶
Maximum velocity limit for particles.
- velocity_clamp_min = None¶
Minimum velocity limit for particles.
- velocity_strategy = 'unmodified'¶
Strategy for handling out-of-bounds velocities.
Available options: unmodified (default), adjust, invert, zero.
- verbose = False¶
Enable or disable the logs and progress bar.
- topology: Literal['star', 'ring', 'vonneumann', 'random', 'pyramid'] | Topology = 'star'¶
Topology structure for particle communication.
The topology can be specified in two ways:
By name (string): e.g.,
"star","ring". This uses the default parameter values for that topology.By dataclass instance: e.g.,
RingTopology(k_neighbors=5, p_norm=1). This allows for detailed configuration of topology-specific parameters.
Available topologies:
StarTopology,RingTopology,VonNeumannTopology,RandomTopology,PyramidTopology.
The Tranquilo Optimizer¶
optimagic supports tranquilo, a
trust-region optimizer for noisy and/or computationally expensive black-box problems
that was developed by the optimagic developers. To use it, you need to have the
tranquilo package (version 0.1.0 or newer) installed, e.g. via pip install tranquilo
or conda install -c conda-forge tranquilo. tranquilo is the scalar version of the
algorithm; tranquilo_ls exploits the least-squares structure of the objective function
and should be preferred whenever your objective function can be expressed as a sum of
squared residuals.
tranquilo
How to use this algorithm:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.tranquilo(stopping_maxfun=5_000),
)
or using the string interface:
import numpy as np
import optimagic as om
om.minimize(
fun=lambda x: x @ x,
params=np.array([1.0, 2.0, 3.0]),
algorithm="tranquilo",
algo_options={"stopping_maxfun": 5_000},
)
Description and available options:
- class optimagic.optimizers.tranquilo.Tranquilo[source]¶
Minimize a scalar function using the tranquilo algorithm.
Tranquilo, short for “TrustRegion Adaptive Noise robust QUadratIc or Linear approximation Optimizer”, is a trust-region optimizer for derivative-free optimization that was developed by the optimagic developers ([algo_96]). It is designed for black-box problems whose objective function is computationally expensive, noisy, or both, as they arise, for example, when structural econometric models are estimated via the method of simulated moments.
This is the scalar version of tranquilo. If your objective function has a least-squares structure, use
tranquilo_lsinstead, which exploits that structure and typically needs far fewer function evaluations.tranquilo is a local optimizer that does not require derivatives. It supports bound constraints, but no linear or nonlinear constraints. In each iteration it fits a quadratic surrogate model to a sample of evaluated points, minimizes the surrogate model within the current trust region to obtain a candidate point, and accepts the candidate if it improves the objective function. The ratio of the actual to the predicted improvement is used to adjust the trust-region radius. For background on derivative-free trust-region methods, see [algo_97].
Two features distinguish tranquilo from most other derivative-free trust-region optimizers:
Parallelization: If
n_coresis larger than one, new sample points are evaluated in parallel batches of sizebatch_size. Withacceptance_decider="classic_line_search", spare evaluations in a batch are additionally used for a parallel line search and speculative sampling, which keep all cores busy even in steps of the algorithm that are inherently sequential. The parallel version thereby aims to minimize the number of evaluation batches rather than the number of function evaluations.Noise handling: If
noisy=True, tranquilo adaptively determines how often the objective function must be evaluated (and averaged) at each point in order to keep making progress. The user does not have to provide any information about the amount or type of noise in the objective function.
All components of the algorithm (sampling of new points, filtering of existing points, fitting of surrogate models, solving of the trust-region subproblem, and the acceptance decision) are exchangeable and configurable via options. The default values were selected based on extensive benchmarking and rarely need to be adjusted. In benchmarks on noise-free problems without parallelization, the scalar version of tranquilo is competitive with, but slightly slower than, established derivative-free optimizers such as
nlopt_bobyqa. The noise handling and the parallelization were developed and benchmarked for the least-squares version. In tranquilo 0.1.1, both are experimental for the scalar version, and tranquilo warns that they are likely to give very suboptimal results.Note
This algorithm requires the tranquilo package (version 0.1.0 or newer) to be installed. You can install it with
pip install tranquiloorconda install -c conda-forge tranquilo.- functype: Literal['scalar'] = 'scalar'¶
The type of the objective function.
For this algorithm it is always “scalar”. Use
tranquilo_lsfor problems with least-squares structure.
- noisy: bool = False¶
Whether the objective function is noisy, i.e. whether repeated evaluations at the same parameter vector return different values.
If True, tranquilo activates its adaptive noise handling: the number of evaluations per sample point starts at
noise_adaptation_options.min_n_evals(1 by default) and is adjusted over the course of the optimization such that just enough noise is averaged out to keep making progress. Moreover, the acceptance decision for candidate points is then based on a statistical power analysis, and the number of evaluations at the start parameters defaults to 5.
- disable_convergence: bool = False¶
If True, the optimization is terminated only by the stopping criteria (
stopping_maxfunandstopping_maxiter), never because a convergence criterion is satisfied.This is mostly useful for benchmarking.
- convergence_ftol_abs: NonNegativeFloat = 0.0¶
Converge if the absolute change in the objective function value between two accepted iterations is less than this value. More formally, this is expressed as
\[|f^k - f^{k+1}| \leq \textsf{convergence\_ftol\_abs}.\]With the default of 0.0, this criterion only triggers if the change is exactly zero. Use
disable_convergence=Trueto switch off all convergence criteria.
- convergence_gtol_abs: NonNegativeFloat = 0.0¶
Converge if the norm of the gradient of the surrogate model is at most this value.
Since tranquilo never evaluates derivatives of the objective function, the gradient of the fitted surrogate model is used instead of the true gradient. In tranquilo 0.1.1, this is the Euclidean norm of the model’s linear terms, i.e. of its gradient at the center of the trust region in which it was fitted (the previously accepted point, or the center of the box if bounds are binding), in coordinates scaled by the trust-region radius. It thus equals the norm of the model gradient multiplied by the trust-region radius.
With the default of 0.0, this criterion only triggers if this norm is exactly zero.
- convergence_xtol_abs: NonNegativeFloat = 0.0¶
Converge if the Euclidean distance between the accepted parameter vectors of two consecutive iterations is less than this value. More formally, this is expressed as
\[\lVert x^k - x^{k+1} \rVert \leq \textsf{convergence\_xtol\_abs}.\]With the default of 0.0, this criterion only triggers if the change is exactly zero.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Converge if the relative change in the objective function value between two accepted iterations is less than this value. More formally, this is expressed as
\[\frac{|f^k - f^{k+1}|}{\max\{|f^k|, 1\}} \leq \textsf{convergence\_ftol\_rel}.\]
- convergence_gtol_rel: NonNegativeFloat = 1e-08¶
Converge if the norm of the gradient of the surrogate model, divided by its maximum with 1, is at most this value. Denoting the radius-scaled model gradient that is described under
convergence_gtol_absby \(g^k\), this is expressed as\[\frac{\lVert g^k \rVert}{\max\{\lVert g^k \rVert, 1\}} \leq \textsf{convergence\_gtol\_rel}.\]
- convergence_xtol_rel: NonNegativeFloat = 1e-08¶
Converge if the relative change of the accepted parameter vectors between two consecutive iterations is less than this value. More formally, this is expressed as
\[\left\lVert \frac{x^k - x^{k+1}}{\max\{|x^k|, 1\}} \right\rVert \leq \textsf{convergence\_xtol\_rel},\]where the division and the maximum are taken element-wise.
- convergence_min_trust_region_radius: NonNegativeFloat = 0.0¶
Minimal trust-region radius for convergence.
In tranquilo 0.1.1, this option has no effect. The trust-region radius is bounded below by
radius_options.min_radius(1e-6 by default).
- stopping_maxfun: PositiveInt = 2000¶
Maximum number of objective function evaluations before termination.
Repeated evaluations at the same point (as used for noisy problems) count towards this limit. The limit is checked at the end of each iteration, so it can be exceeded by the evaluations of the last iteration.
- stopping_maxiter: PositiveInt = 200¶
Maximum number of iterations (trust-region steps) before termination.
- stopping_maxtime: NonNegativeFloat = inf¶
Maximum running time in seconds before termination.
In tranquilo 0.1.1, this option has no effect.
- batch_evaluator: Literal['joblib', 'pathos'] = 'joblib'¶
Batch evaluator that is used to parallelize evaluations of the objective function.
This option is not passed on to tranquilo; parallel function evaluations always use the “joblib” batch evaluator. See Batch evaluators for details.
- n_cores: PositiveInt = 1¶
Number of cores used to evaluate the objective function in parallel.
If larger than one, tranquilo evaluates new sample points in parallel batches. A parallel line search and speculative sampling are only used with
acceptance_decider="classic_line_search".
- batch_size: PositiveInt | None = None¶
Number of points that are evaluated in each batch of parallel function evaluations.
Must be at least as large as
n_cores, to which it defaults.
- sample_size: PositiveInt | None = None¶
Target number of evaluated points in the trust region on which the surrogate model is fitted.
By default, the sample size is \(2 n + 1\), where \(n\) is the dimension of the problem.
- model_type: Literal['quadratic', 'linear'] | None = None¶
Type of surrogate model that is fitted in each iteration.
In tranquilo 0.1.1, the scalar version only supports “quadratic”, which is also the default; “linear” raises a
NotImplementedError.
- search_radius_factor: PositiveFloat | None = None¶
Factor by which the trust-region radius is multiplied to obtain the region in which existing evaluation points are searched for reuse in the surrogate model.
Reusing existing points saves function evaluations. The default is 4.25 for the scalar version and 5.0 for the least-squares version of tranquilo.
- n_evals_per_point: NonNegativeInt | None = None¶
Initial number of times the objective function is evaluated (and averaged) at each sample point.
For noisy problems, the default is
noise_adaptation_options.min_n_evals(1 by default), and the number of evaluations per point is adaptively adjusted over the course of the optimization. For non-noisy problems, the default is 1 and the number is not adjusted.
- n_evals_at_start: NonNegativeInt | None = None¶
Number of objective function evaluations at the start parameters.
The default is 5 for noisy problems and 1 otherwise. Multiple evaluations at the start parameters guarantee that enough evaluations are available to estimate the variance of the noise in the objective function.
- seed: int | None = 925408¶
Seed for the random number generators used to sample new points and to simulate noise during the noise adaptation.
In tranquilo 0.1.1, the seed must be an integer; None raises a
TypeError.
- radius_options: RadiusOptions | None = None¶
Advanced options for the management of the trust-region radius, e.g. the initial, minimal and maximal radius as well as expansion and shrinking factors.
Pass a dict with a subset of the fields of
tranquilo.options.RadiusOptionsor an instance of it; see the tranquilo package for details. The default initial radius is 0.1 times the largest absolute value of the start parameters, so pass a positiveinitial_radiusif all start parameters are zero.
- stagnation_options: StagnationOptions | None = None¶
Advanced options that determine how the algorithm reacts if it stagnates, i.e. if a proposed step is very small relative to the trust-region radius.
Pass a dict with a subset of the fields of
tranquilo.options.StagnationOptionsor an instance of it; see the tranquilo package for details. Fields that are not passed in a dict keep their defaults, which depend onnoisyandbatch_size.
- noise_adaptation_options: NoiseAdaptationOptions | None = None¶
Advanced options that govern how the number of evaluations per point is adapted for noisy problems, e.g. the minimal and maximal number of evaluations per point.
Pass an instance of
tranquilo.options.NoiseAdaptationOptions; see the tranquilo package for details.
- sampler: Literal['optimal_hull', 'random_hull', 'random_interior'] | Callable = 'optimal_hull'¶
Method used to sample new points within the trust region.
“optimal_hull” (the default) places new points on the hull of the trust region such that the minimal distance between all points (including existing ones) is approximately maximized. “random_hull” and “random_interior” sample random points on the hull or in the interior of the trust region. A custom sampling function can be passed as a callable.
- sampler_options: SamplerOptions | None = None¶
Advanced options for the sampler.
Pass an instance of
tranquilo.options.SamplerOptions; see the tranquilo package for details.
- sample_filter: Literal['discard_all', 'keep_all', 'clustering', 'drop_excess'] | Callable | None = None¶
Method used to select which of the existing evaluation points inside the search region are used to fit the surrogate model.
“keep_all” keeps all points, “discard_all” keeps only the trust-region center, “drop_excess” keeps at most
n_max_factor(3 by default) times the target sample size and drops excess points, starting with points outside the trust region and then points that are close to other points, and “clustering” keeps only one point per cluster of nearby points. The default is “drop_excess” ifbatch_sizeis larger than one and “keep_all” otherwise. A custom filter function can be passed as a callable.
- sample_filter_options: FilterOptions | None = None¶
Advanced options for the sample filter.
Pass an instance of
tranquilo.options.FilterOptions; see the tranquilo package for details.
- model_fitter: Literal['ols', 'ridge', 'powell', 'tranquilo'] | Callable | None = None¶
Method used to fit the surrogate model to the sample of evaluated points.
“ols” uses ordinary least-squares regression, “ridge” uses ridge regression, “powell” switches between ordinary least squares and a minimal-Frobenius-norm- of-Hessian fit depending on the sample size, following ideas from [algo_67], and “tranquilo” is a variant of “ols” that penalizes the linear terms of the model less strongly when the fitting problem is underdetermined. By default, “ols” is used if the sample size is large enough to identify all model parameters and “tranquilo” otherwise. A custom fitting function can be passed as a callable.
- model_fitter_options: FitterOptions | None = None¶
Advanced options for the model fitter, e.g. penalty terms for ridge regression.
Pass an instance of
tranquilo.options.FitterOptions; see the tranquilo package for details.
- cube_subsolver: Literal['bntr', 'bntr_fast', 'fallback_cube', 'fallback_multistart'] | Callable = 'bntr_fast'¶
Solver for the trust-region subproblem if the trust region is a cube, which is the case whenever bounds are binding.
“bntr” and “bntr_fast” implement a bounded Newton trust-region algorithm, where “bntr_fast” (the default) is a numba-accelerated version of “bntr”. “fallback_cube” and “fallback_multistart” are robust fallback solvers based on SciPy’s L-BFGS-B, where the multistart version restarts the solver from multiple starting points. A custom subsolver can be passed as a callable.
- sphere_subsolver: Literal['gqtpar', 'gqtpar_fast', 'fallback_reparametrized', 'fallback_inscribed_cube', 'fallback_norm_constraint'] | Callable = 'gqtpar_fast'¶
Solver for the trust-region subproblem if the trust region is a sphere, which is the case when no bounds are binding.
“gqtpar” and “gqtpar_fast” solve the subproblem almost exactly with the method of [algo_34], where “gqtpar_fast” (the default) is a numba-accelerated version of “gqtpar”. The “fallback_*” solvers are robust but less precise alternatives based on general-purpose optimizers. A custom subsolver can be passed as a callable.
- retry_subproblem_with_fallback: bool = True¶
Whether to retry solving the trust-region subproblem with a fallback solver if the main subsolver raises an exception.
- subsolver_options: SubsolverOptions | None = None¶
Advanced options for the trust-region subproblem solvers, e.g. the maximum number of iterations and gradient tolerances.
Pass an instance of
tranquilo.options.SubsolverOptions; see the tranquilo package for details.
- acceptance_decider: Literal['classic', 'naive_noisy', 'classic_line_search', 'noisy'] | Callable | None = None¶
Method used to decide whether a candidate point is accepted as the new trust-region center.
“classic” evaluates the candidate point once and accepts it if it improves on the current point. “classic_line_search” does the same if
batch_sizeis one; otherwise, it uses the spare evaluations of the batch for a line search along the step (if the candidate lies on the border of the trust region) and for speculative sampling of points around the candidate, and accepts the best of these points if it improves on the current point. “naive_noisy” averages a fixed number of evaluations (10) at the candidate point. “noisy” uses a statistical power analysis to determine how many evaluations at the candidate and the current point are needed to decide which one is better. The default is “noisy” for noisy problems and “classic” otherwise. A custom acceptance function can be passed as a callable.
- acceptance_decider_options: AcceptanceOptions | None = None¶
Advanced options for the acceptance decider, e.g. the confidence and power levels of the power analysis for noisy problems.
Pass an instance of
tranquilo.options.AcceptanceOptions; see the tranquilo package for details.
- variance_estimator: Literal['classic'] | Callable = 'classic'¶
Method used to estimate the variance of the noise in the objective function for noisy problems.
The “classic” estimator uses existing repeated function evaluations at points in a neighborhood of the current trust region and treats the noise variance as locally constant. A custom estimation function can be passed as a callable.
- variance_estimator_options: VarianceEstimatorOptions | None = None¶
Advanced options for the variance estimator, e.g. the minimal number of evaluations per point used in the estimation.
Pass an instance of
tranquilo.options.VarianceEstimatorOptions; see the tranquilo package for details.
- infinity_handler: Literal['relative'] | Callable = 'relative'¶
Method used to replace infinite and NaN function values before fitting the surrogate model.
The “relative” method replaces infinite and NaN values with a penalty value that is derived from the range of the finite values in the sample. A custom function can be passed as a callable.
tranquilo_ls
How to use this algorithm:
import numpy as np
import optimagic as om
@om.mark.least_squares
def fun(x):
return x
om.minimize(
fun=fun,
params=np.array([1.0, 2.0, 3.0]),
algorithm=om.algos.tranquilo_ls(stopping_maxfun=5_000),
)
or using the string interface:
import numpy as np
import optimagic as om
@om.mark.least_squares
def fun(x):
return x
om.minimize(
fun=fun,
params=np.array([1.0, 2.0, 3.0]),
algorithm="tranquilo_ls",
algo_options={"stopping_maxfun": 5_000},
)
Description and available options:
- class optimagic.optimizers.tranquilo.TranquiloLS[source]¶
Minimize a least-squares problem using the tranquilo algorithm.
Tranquilo, short for “TrustRegion Adaptive Noise robust QUadratIc or Linear approximation Optimizer”, is a trust-region optimizer for derivative-free optimization that was developed by the optimagic developers ([algo_96]). It is designed for black-box problems whose objective function is computationally expensive, noisy, or both, as they arise, for example, when structural econometric models are estimated via the method of simulated moments.
This is the least-squares version of tranquilo. It minimizes objective functions of the form \(f(x) = \sum_j r_j(x)^2\), where the user provides the vector of residuals \(r(x)\). Instead of fitting one surrogate model for the objective function, it fits a surrogate model for each residual and aggregates them into a model of the objective function. Exploiting the least-squares structure in this way is very efficient: as few as \(n + 1\) function evaluations (where \(n\) is the number of parameters) can be enough to build a useful surrogate model. Use this version whenever your objective function can be expressed as a sum of squares, e.g. in nonlinear regression or method of simulated moments estimation; use the scalar version (
tranquilo) otherwise.tranquilo_ls is a local optimizer that does not require derivatives. It supports bound constraints, but no linear or nonlinear constraints. In each iteration it fits surrogate models to a sample of evaluated points, minimizes the aggregated surrogate model within the current trust region to obtain a candidate point, and accepts the candidate if it improves the objective function. The ratio of the actual to the predicted improvement is used to adjust the trust-region radius. For background on derivative-free trust-region methods, see [algo_97].
Two features distinguish tranquilo from most other derivative-free trust-region optimizers:
Parallelization: If
n_coresis larger than one, new sample points are evaluated in parallel batches of sizebatch_size. Withacceptance_decider="classic_line_search", spare evaluations in a batch are additionally used for a parallel line search and speculative sampling, which keep all cores busy even in steps of the algorithm that are inherently sequential. The parallel version thereby aims to minimize the number of evaluation batches rather than the number of function evaluations.Noise handling: If
noisy=True, tranquilo adaptively determines how often the objective function must be evaluated (and averaged) at each point in order to keep making progress. The user does not have to provide any information about the amount or type of noise in the objective function.
All components of the algorithm (sampling of new points, filtering of existing points, fitting of surrogate models, solving of the trust-region subproblem, and the acceptance decision) are exchangeable and configurable via options. The default values were selected based on extensive benchmarking and rarely need to be adjusted. In benchmarks on noise-free problems without parallelization, tranquilo_ls is slightly slower than DFO-LS ([algo_38]) and faster than POUNDERS ([algo_32]). With two or more cores, it is considerably faster than DFO-LS, and in noisy settings it outperforms all benchmarked configurations of DFO-LS. In tranquilo 0.1.1, combining
noisy=Truewithn_coreslarger than one is experimental.Note
This algorithm requires the tranquilo package (version 0.1.0 or newer) to be installed. You can install it with
pip install tranquiloorconda install -c conda-forge tranquilo.- noisy: bool = False¶
Whether the residual functions are noisy, i.e. whether repeated evaluations at the same parameter vector return different values.
If True, tranquilo activates its adaptive noise handling: the number of evaluations per sample point starts at
noise_adaptation_options.min_n_evals(1 by default) and is adjusted over the course of the optimization such that just enough noise is averaged out to keep making progress. Moreover, the acceptance decision for candidate points is then based on a statistical power analysis, and the number of evaluations at the start parameters defaults to 5.
- disable_convergence: bool = False¶
If True, the optimization is terminated only by the stopping criteria (
stopping_maxfunandstopping_maxiter), never because a convergence criterion is satisfied.This is mostly useful for benchmarking.
- convergence_ftol_abs: NonNegativeFloat = 0.0¶
Converge if the absolute change in the objective function value between two accepted iterations is less than this value. More formally, this is expressed as
\[|f^k - f^{k+1}| \leq \textsf{convergence\_ftol\_abs}.\]With the default of 0.0, this criterion only triggers if the change is exactly zero. Use
disable_convergence=Trueto switch off all convergence criteria.
- convergence_gtol_abs: NonNegativeFloat = 0.0¶
Converge if the norm of the gradient of the surrogate model is at most this value.
Since tranquilo never evaluates derivatives of the objective function, the gradient of the fitted surrogate model is used instead of the true gradient. In tranquilo 0.1.1, this is the Euclidean norm of the model’s linear terms, i.e. of its gradient at the center of the trust region in which it was fitted (the previously accepted point, or the center of the box if bounds are binding), in coordinates scaled by the trust-region radius. It thus equals the norm of the model gradient multiplied by the trust-region radius.
With the default of 0.0, this criterion only triggers if this norm is exactly zero.
- convergence_xtol_abs: NonNegativeFloat = 0.0¶
Converge if the Euclidean distance between the accepted parameter vectors of two consecutive iterations is less than this value. More formally, this is expressed as
\[\lVert x^k - x^{k+1} \rVert \leq \textsf{convergence\_xtol\_abs}.\]With the default of 0.0, this criterion only triggers if the change is exactly zero.
- convergence_ftol_rel: NonNegativeFloat = 2e-09¶
Converge if the relative change in the objective function value between two accepted iterations is less than this value. More formally, this is expressed as
\[\frac{|f^k - f^{k+1}|}{\max\{|f^k|, 1\}} \leq \textsf{convergence\_ftol\_rel}.\]
- convergence_gtol_rel: NonNegativeFloat = 1e-08¶
Converge if the norm of the gradient of the surrogate model, divided by its maximum with 1, is at most this value. Denoting the radius-scaled model gradient that is described under
convergence_gtol_absby \(g^k\), this is expressed as\[\frac{\lVert g^k \rVert}{\max\{\lVert g^k \rVert, 1\}} \leq \textsf{convergence\_gtol\_rel}.\]
- convergence_xtol_rel: NonNegativeFloat = 1e-08¶
Converge if the relative change of the accepted parameter vectors between two consecutive iterations is less than this value. More formally, this is expressed as
\[\left\lVert \frac{x^k - x^{k+1}}{\max\{|x^k|, 1\}} \right\rVert \leq \textsf{convergence\_xtol\_rel},\]where the division and the maximum are taken element-wise.
- convergence_min_trust_region_radius: NonNegativeFloat = 0.0¶
Minimal trust-region radius for convergence.
In tranquilo 0.1.1, this option has no effect. The trust-region radius is bounded below by
radius_options.min_radius(1e-6 by default).
- stopping_maxfun: PositiveInt = 2000¶
Maximum number of objective function evaluations before termination.
Repeated evaluations at the same point (as used for noisy problems) count towards this limit. The limit is checked at the end of each iteration, so it can be exceeded by the evaluations of the last iteration.
- stopping_maxiter: PositiveInt = 200¶
Maximum number of iterations (trust-region steps) before termination.
- stopping_maxtime: NonNegativeFloat = inf¶
Maximum running time in seconds before termination.
In tranquilo 0.1.1, this option has no effect.
- batch_evaluator: Literal['joblib', 'pathos'] = 'joblib'¶
Batch evaluator that is used to parallelize evaluations of the objective function.
This option is not passed on to tranquilo; parallel function evaluations always use the “joblib” batch evaluator. See Batch evaluators for details.
- n_cores: PositiveInt = 1¶
Number of cores used to evaluate the objective function in parallel.
If larger than one, tranquilo evaluates new sample points in parallel batches. A parallel line search and speculative sampling are only used with
acceptance_decider="classic_line_search".
- batch_size: PositiveInt | None = None¶
Number of points that are evaluated in each batch of parallel function evaluations.
Must be at least as large as
n_cores, to which it defaults.
- sample_size: PositiveInt | None = None¶
Target number of evaluated points in the trust region on which the surrogate models are fitted.
By default, the sample size is \(n + 1\) if the problem is noisy or
batch_sizeis larger than one, and \(n + 2\) otherwise, where \(n\) is the dimension of the problem.
- model_type: Literal['quadratic', 'linear'] | None = None¶
Type of surrogate model that is fitted to each residual in every iteration.
In tranquilo 0.1.1, the least-squares version only supports “linear”, which is also the default; “quadratic” raises a
NotImplementedError. The residual models are aggregated into a quadratic model of the objective function, so even with linear residual models the algorithm has curvature information.
- search_radius_factor: PositiveFloat | None = None¶
Factor by which the trust-region radius is multiplied to obtain the region in which existing evaluation points are searched for reuse in the surrogate model.
Reusing existing points saves function evaluations. The default is 5.0 for the least-squares version and 4.25 for the scalar version of tranquilo.
- n_evals_per_point: NonNegativeInt | None = None¶
Initial number of times the objective function is evaluated (and averaged) at each sample point.
For noisy problems, the default is
noise_adaptation_options.min_n_evals(1 by default), and the number of evaluations per point is adaptively adjusted over the course of the optimization. For non-noisy problems, the default is 1 and the number is not adjusted.
- n_evals_at_start: NonNegativeInt | None = None¶
Number of objective function evaluations at the start parameters.
The default is 5 for noisy problems and 1 otherwise. Multiple evaluations at the start parameters guarantee that enough evaluations are available to estimate the variance of the noise in the objective function.
- seed: int | None = 925408¶
Seed for the random number generators used to sample new points and to simulate noise during the noise adaptation.
In tranquilo 0.1.1, the seed must be an integer; None raises a
TypeError.
- radius_options: RadiusOptions | None = None¶
Advanced options for the management of the trust-region radius, e.g. the initial, minimal and maximal radius as well as expansion and shrinking factors.
Pass a dict with a subset of the fields of
tranquilo.options.RadiusOptionsor an instance of it; see the tranquilo package for details. The default initial radius is 0.1 times the largest absolute value of the start parameters, so pass a positiveinitial_radiusif all start parameters are zero.
- stagnation_options: StagnationOptions | None = None¶
Advanced options that determine how the algorithm reacts if it stagnates, i.e. if a proposed step is very small relative to the trust-region radius.
Pass a dict with a subset of the fields of
tranquilo.options.StagnationOptionsor an instance of it; see the tranquilo package for details. Fields that are not passed in a dict keep their defaults, which depend onnoisyandbatch_size.
- noise_adaptation_options: NoiseAdaptationOptions | None = None¶
Advanced options that govern how the number of evaluations per point is adapted for noisy problems, e.g. the minimal and maximal number of evaluations per point.
Pass an instance of
tranquilo.options.NoiseAdaptationOptions; see the tranquilo package for details.
- sampler: Literal['optimal_hull', 'random_hull', 'random_interior'] | Callable = 'optimal_hull'¶
Method used to sample new points within the trust region.
“optimal_hull” (the default) places new points on the hull of the trust region such that the minimal distance between all points (including existing ones) is approximately maximized. “random_hull” and “random_interior” sample random points on the hull or in the interior of the trust region. A custom sampling function can be passed as a callable.
- sampler_options: SamplerOptions | None = None¶
Advanced options for the sampler.
Pass an instance of
tranquilo.options.SamplerOptions; see the tranquilo package for details.
- sample_filter: Literal['discard_all', 'keep_all', 'clustering', 'drop_excess'] | Callable | None = None¶
Method used to select which of the existing evaluation points inside the search region are used to fit the surrogate models.
“keep_all” keeps all points, “discard_all” keeps only the trust-region center, “drop_excess” keeps at most
n_max_factor(3 by default) times the target sample size and drops excess points, starting with points outside the trust region and then points that are close to other points, and “clustering” keeps only one point per cluster of nearby points. The default is “drop_excess” ifbatch_sizeis larger than one and “keep_all” otherwise. A custom filter function can be passed as a callable.
- sample_filter_options: FilterOptions | None = None¶
Advanced options for the sample filter.
Pass an instance of
tranquilo.options.FilterOptions; see the tranquilo package for details.
- model_fitter: Literal['ols', 'ridge', 'powell', 'tranquilo'] | Callable | None = None¶
Method used to fit the surrogate models to the sample of evaluated points.
“ols” uses ordinary least-squares regression, “ridge” uses ridge regression, “powell” switches between ordinary least squares and a minimal-Frobenius-norm- of-Hessian fit depending on the sample size, following ideas from [algo_67], and “tranquilo” is a variant of “ols” that penalizes the linear terms of the model less strongly when the fitting problem is underdetermined. For the least-squares version, whose residual models are linear, the default is “ols”. A custom fitting function can be passed as a callable.
- model_fitter_options: FitterOptions | None = None¶
Advanced options for the model fitter, e.g. penalty terms for ridge regression.
Pass an instance of
tranquilo.options.FitterOptions; see the tranquilo package for details.
- cube_subsolver: Literal['bntr', 'bntr_fast', 'fallback_cube', 'fallback_multistart'] | Callable = 'bntr_fast'¶
Solver for the trust-region subproblem if the trust region is a cube, which is the case whenever bounds are binding.
“bntr” and “bntr_fast” implement a bounded Newton trust-region algorithm, where “bntr_fast” (the default) is a numba-accelerated version of “bntr”. “fallback_cube” and “fallback_multistart” are robust fallback solvers based on SciPy’s L-BFGS-B, where the multistart version restarts the solver from multiple starting points. A custom subsolver can be passed as a callable.
- sphere_subsolver: Literal['gqtpar', 'gqtpar_fast', 'fallback_reparametrized', 'fallback_inscribed_cube', 'fallback_norm_constraint'] | Callable = 'gqtpar_fast'¶
Solver for the trust-region subproblem if the trust region is a sphere, which is the case when no bounds are binding.
“gqtpar” and “gqtpar_fast” solve the subproblem almost exactly with the method of [algo_34], where “gqtpar_fast” (the default) is a numba-accelerated version of “gqtpar”. The “fallback_*” solvers are robust but less precise alternatives based on general-purpose optimizers. A custom subsolver can be passed as a callable.
- retry_subproblem_with_fallback: bool = True¶
Whether to retry solving the trust-region subproblem with a fallback solver if the main subsolver raises an exception.
- subsolver_options: SubsolverOptions | None = None¶
Advanced options for the trust-region subproblem solvers, e.g. the maximum number of iterations and gradient tolerances.
Pass an instance of
tranquilo.options.SubsolverOptions; see the tranquilo package for details.
- acceptance_decider: Literal['classic', 'naive_noisy', 'classic_line_search', 'noisy'] | Callable | None = None¶
Method used to decide whether a candidate point is accepted as the new trust-region center.
“classic” evaluates the candidate point once and accepts it if it improves on the current point. “classic_line_search” does the same if
batch_sizeis one; otherwise, it uses the spare evaluations of the batch for a line search along the step (if the candidate lies on the border of the trust region) and for speculative sampling of points around the candidate, and accepts the best of these points if it improves on the current point. “naive_noisy” averages a fixed number of evaluations (10) at the candidate point. “noisy” uses a statistical power analysis to determine how many evaluations at the candidate and the current point are needed to decide which one is better. The default is “noisy” for noisy problems and “classic” otherwise. A custom acceptance function can be passed as a callable.
- acceptance_decider_options: AcceptanceOptions | None = None¶
Advanced options for the acceptance decider, e.g. the confidence and power levels of the power analysis for noisy problems.
Pass an instance of
tranquilo.options.AcceptanceOptions; see the tranquilo package for details.
- variance_estimator: Literal['classic'] | Callable = 'classic'¶
Method used to estimate the variance of the noise in the objective function for noisy problems.
The “classic” estimator uses existing repeated function evaluations at points in a neighborhood of the current trust region and treats the noise variance as locally constant. A custom estimation function can be passed as a callable.
- variance_estimator_options: VarianceEstimatorOptions | None = None¶
Advanced options for the variance estimator, e.g. the minimal number of evaluations per point used in the estimation.
Pass an instance of
tranquilo.options.VarianceEstimatorOptions; see the tranquilo package for details.
- infinity_handler: Literal['relative'] | Callable = 'relative'¶
Method used to replace infinite and NaN function values before fitting the surrogate models.
The “relative” method replaces infinite and NaN values with a penalty value that is derived from the range of the finite values in the sample. A custom function can be passed as a callable.
References¶
Dieter Kraft. A software package for sequential quadratic programming. Technical Report, DLR German Aerospace Center – Institute for Flight Mechanics, Köln, Germany, 1988. URL: http://degenerateconic.com/wp-content/uploads/2018/03/DFVLR_FB_88_28.pdf.
J Nelder and R Mead. A simplex method for function minimization. The Computer Journal, 7:308–313, 1965.
Fuchang Gao and Lixing Han. Implementing the nelder-mead simplex algorithm with adaptive parameters. Computational Optimization and Applications, 51(1):259–277, 2012.
M. J. D. Powell. An efficient method for finding the minimum of a function of several variables without calculating derivatives. The Computer Journal, 7(2):155–162, 1964. doi:10.1093/comjnl/7.2.155.
Jorge Nocedal and Stephen Wright. Numerical optimization. Springer Science & Business Media, 2006.
M Powell. A direct search optimization method that models the objective and constraint functions by linear interpolation, pages 51–67. Kluwer Academic, Dordrecht, 1994.
Michael JD Powell. Direct search algorithms for optimization calculations. Acta numerica, pages 287–336, 1998.
Michael JD Powell. A view of algorithms for optimization without derivatives. Mathematics Today-Bulletin of the Institute of Mathematics and its Applications, 43(5):170–174, 2007.
R Dembo and T Steihaug. Truncated-Newton algorithms for large-scale unconstrained optimization. Math. Programming, 26:190–212, 1983. doi:10.1007/BF02592055.
Stephen G. Nash. Newton-type minimization via the lanczos method. SIAM Journal on Numerical Analysis, 21(4):770–788, 1984. doi:10.1137/0721052.
Marucha Lalee, Jorge Nocedal, and Todd Plantenga. On the implementation of an algorithm for large-scale equality constrained optimization. SIAM Journal on Optimization, 8(3):682–706, 1998.
AR Conn, NI Gould, and PL Toint. Nonlinear equations and nonlinear fitting. In Trust region methods, volume 1, pages 749–774. Siam, 2000.
Richard H Byrd, Mary E Hribar, and Jorge Nocedal. An interior point algorithm for large-scale nonlinear programming. SIAM Journal on Optimization, 9(4):877–900, 1999.
C. Voglis and I. E. Lagaris. A rectangular trust region dogleg approach for unconstrained and bound constrained nonlinear optimization. In WSEAS International Conference on Applied Mathematics. Corfu, Greece, 2004. URL: https://www.cs.uoi.gr/~lagaris/papers/PREPRINTS/dogbox.pdf.
Mary Ann Branch, Thomas F. Coleman, and Yuying Li. A subspace, interior, and conjugate gradient method for large-scale bound-constrained minimization problems. SIAM Journal on Scientific Computing, 21(1):1–23, 1999. doi:10.1137/S1064827595289108.
Thomas F. Coleman and Yuying Li. An interior trust region approach for nonlinear minimization subject to bounds. SIAM Journal on Optimization, 6(2):418–445, may 1996. doi:10.1137/0806023.
Jorge J. Moré. The levenberg-marquardt algorithm: implementation and theory. In G. A. Watson, editor, Numerical Analysis, volume 630 of Lecture Notes in Mathematics, pages 105–116. Springer, 1978. doi:10.1007/BFb0067700.
David J. Wales and Jonathan P. K. Doye. Global optimization by basin-hopping and the lowest energy structures of lennard-jones clusters containing up to 110 atoms. The Journal of Physical Chemistry A, 101(28):5111–5116, jul 1997.
Rainer Storn and Kenneth Price. Differential evolution – a simple and efficient heuristic for global optimization over continuous spaces. Journal of Global Optimization, 11(4):341–359, 1997. URL: https://link.springer.com/article/10.1023/A:1008202821328.
Stefan C. Endres, Carl Sandrock, and Walter W. Focke. A simplicial homology algorithm for Lipschitz optimisation. Journal of Global Optimization, 72(2):181–217, 2018. doi:10.1007/s10898-018-0645-y.
Constantino Tsallis. Possible generalization of Boltzmann-Gibbs statistics. Journal of Statistical Physics, 52(1-2):479–487, 1988. doi:10.1007/BF01016429.
Constantino Tsallis and Daniel A. Stariolo. Generalized simulated annealing. Physica A: Statistical Mechanics and its Applications, 233(1-2):395–406, 1996. doi:10.1016/S0378-4371(96)00271-3.
Y. Xiang, D. Y. Sun, W. Fan, and X. G. Gong. Generalized simulated annealing algorithm and its application to the Thomson model. Physics Letters A, 233(3):216–220, 1997. doi:10.1016/S0375-9601(97)00474-X.
D Jones, C Perttunen, and B Stuckmann. Lipschitzian optimization without the lipschitz constant. J. Optimization Theory and Applications, 79:157, 1993.
J Gablonsky and C Kelley. A locally-biased form of the direct algorithm. J. Global Optimization, 21(1):27–37, 2001.
Ernst R. Berndt, Bronwyn Hall, Robert Hall, and Jerry Hausman. Estimation and inference in nonlinear structural models. Annals of Economic and Social Measurement, pages 653–665, 1974.
Halbert White. Maximum likelihood estimation of misspecified models. Econometrica, 50(1):1–25, 1982.
Donghoon Lee and Matthew Wiswall. A parallel implementation of the simplex function minimization routine. Computational Economics, 30(2):171–187, 2007. doi:10.1007/s10614-007-9094-2.
John C. Nash. Compact Numerical Methods for Computers: Linear Algebra and Function Minimisation. Adam Hilger, Bristol, 2nd edition, 1990.
Ravi Varadhan and Hans W. Borchers. Dfoptim: derivative-free optimization. 2016. R package version 2016.7-1. URL: https://CRAN.R-project.org/package=dfoptim.
Simon Wessing. Proper initialization is crucial for the nelder–mead simplex search. Optimization Letters, 13:847–856, 2019. doi:10.1007/s11590-018-1284-4.
Stefan M. Wild. Solving derivative-free nonlinear least squares problems with pounders. Technical Report, Argonne National Laboratory, 2015. URL: https://doi.org/10.1137/1.9781611974683.ch40.
S Benson, LC McInnes, JJ Moré, T Munson, and J Sarich. Tao user manual (revision 3.7). Technical Report, Technical Report ANL/MCS-TM-322, Argonne National Laboratory, 2017. URL: http://web.mit.edu/tao-petsc_v3.7/tao_manual.pdf.
Jorge J. Moré and Danny C. Sorensen. Computing a trust region step. Siam Journal on Scientific and Statistical Computing, 4:553–572, 1983.
Stefan M. Wild. MNH: A derivative-free optimization algorithm using minimal norm Hessians. In Tenth Copper Mountain Conference on Iterative Methods. April 2008. URL: http://grandmaster.colorado.edu/~copper/2008/SCWinners/Wild.pdf.
Coralia Cartis, Jan Fiala, Benjamin Marteau, and Lindon Roberts. Improving the flexibility and robustness of model-based derivative-free optimization solvers. 2018. arXiv:1804.00154.
Michael JD Powell. The bobyqa algorithm for bound constrained optimization without derivatives. Cambridge NA Report NA2009/06, University of Cambridge, Cambridge, pages 26–46, 2009.
Coralia Cartis, Jan Fiala, Benjamin Marteau, and Lindon Roberts. Improving the flexibility and robustness of model-based derivative-free optimization solvers. 2018. arXiv:1804.00154.
Coralia Cartis, Lindon Roberts, and Oliver Sheridan-Methven. Escaping local minima with derivative-free methods: a numerical investigation. 2018. arXiv:1812.11343.
Francesco Biscani and Dario Izzo. A parallel global multiobjective framework for optimization: pagmo. Journal of Open Source Software, 5(53):2338, 2020. URL: https://doi.org/10.21105/joss.02338, doi:10.21105/joss.02338.
Martin Schlüter, Jose A. Egea, and Julio R. Banga. Extended ant colony optimization for non-convex mixed integer nonlinear programming. Computers & Operations Research, 36(7):2217–2229, jul 2009. doi:10.1016/j.cor.2008.08.015.
Dervis Karaboga and Bahriye Basturk. A powerful and efficient algorithm for numerical function optimization: artificial bee colony (ABC) algorithm. Journal of Global Optimization, 39(3):459–471, apr 2007. doi:10.1007/s10898-007-9149-x.
Marjan Mernik, Shih-Hsi Liu, Dervis Karaboga, and Matej Črepinšek. On clarifying misconceptions when comparing variants of the artificial bee colony algorithm by offering a new implementation. Information Sciences, 291:115–127, jan 2015. doi:10.1016/j.ins.2014.08.040.
Pietro S. Oliveto, Jun He, and Xin Yao. Time complexity of evolutionary algorithms for combinatorial optimization: a decade of results. International Journal of Automation and Computing, 4(3):281–293, jul 2007. doi:10.1007/s11633-007-0281-3.
Janez Brest, Sao Greiner, Borko Boskovic, Marjan Mernik, and Viljem Zumer. Self-adapting control parameters in differential evolution: a comparative study on numerical benchmark problems. IEEE Transactions on Evolutionary Computation, 10(6):646–657, 2006. doi:10.1109/TEVC.2006.872133.
Saber M. Elsayed, Ruhul A. Sarker, and Daryl L. Essam. Differential evolution with multiple strategies for solving cec2011 real-world numerical optimization problems. In 2011 IEEE Congress of Evolutionary Computation (CEC), 1041–1048. 2011. doi:10.1109/CEC.2011.5949732.
Nikolaus Hansen. The CMA evolution strategy: a comparing review. In Towards a New Evolutionary Computation, pages 75–102. Springer Berlin Heidelberg, 2006. doi:10.1007/3-540-32494-1_4.
A. Corana, M. Marchesi, C. Martini, and S. Ridella. Minimizing multimodal functions of continuous variables with the “simulated annealing” algorithm—corrigenda for this article is available here. ACM Trans. Math. Softw., 13(3):262–280, September 1987. URL: https://doi.org/10.1145/29380.29864, doi:10.1145/29380.29864.
J. Kennedy and R. Eberhart. Particle swarm optimization. In Proceedings of ICNN'95 - International Conference on Neural Networks, volume 4, 1942–1948 vol.4. 1995. doi:10.1109/ICNN.1995.488968.
Riccardo Poli, James Kennedy, and Tim Blackwell. Particle swarm optimization. Swarm Intelligence, 1(1):33–57, aug 2007. doi:10.1007/s11721-007-0002-0.
Tobias Glasmachers, Tom Schaul, Sun Yi, Daan Wierstra, and Jürgen Schmidhuber. Exponential natural evolution strategies. In Proceedings of the 12th annual conference on Genetic and evolutionary computation - GECCO \textquotesingle 10. ACM Press, 2010. doi:10.1145/1830483.1830557.
Seyedali Mirjalili, Seyed Mohammad Mirjalili, and Andrew Lewis. Grey wolf optimizer. Advances in Engineering Software, 69:46–61, mar 2014. doi:10.1016/j.advengsoft.2013.12.007.
Tamara G. Kolda, Robert Michael Lewis, and Virginia Torczon. Optimization by direct search: new perspectives on some classical and modern methods. SIAM Review, 45(3):385–482, jan 2003. doi:10.1137/s003614450242889.
M. Mahdavi, M. Fesanghary, and E. Damangir. An improved harmony search algorithm for solving optimization problems. Applied Mathematics and Computation, 188(2):1567–1579, may 2007. doi:10.1016/j.amc.2006.11.033.
Andreas Wächter and Lorenz T. Biegler. Line search filter methods for nonlinear programming: local convergence. SIAM Journal on Optimization, 16(1):32–48, jan 2005. doi:10.1137/s1052623403426544.
Andreas Wächter and Lorenz T. Biegler. Line search filter methods for nonlinear programming: motivation and global convergence. SIAM Journal on Optimization, 16(1):1–31, jan 2005. doi:10.1137/s1052623403426556.
Andreas Wächter and Lorenz T. Biegler. On the implementation of an interior-point filter line-search algorithm for large-scale nonlinear programming. Mathematical Programming, 106(1):25–57, apr 2005. doi:10.1007/s10107-004-0559-y.
Jorge Nocedal, Andreas Wächter, and Richard A. Waltz. Adaptive barrier update strategies for nonlinear interior methods. SIAM Journal on Optimization, 19(4):1674–1693, jan 2009. doi:10.1137/060649513.
Nai-Yuan Chiang and Victor M. Zavala. An inertia-free filter line-search algorithm for large-scale nonlinear programming. Computational Optimization and Applications, 64(2):327–354, 2016. doi:10.1007/s10589-015-9820-y.
Thomas F. Coleman and Yuying Li. On the convergence of interior-reflective newton methods for nonlinear minimization subject to bounds. Mathematcial Programming, 67(1-3):189–224, oct 1994. doi:10.1007/bf01582221.
Fabian Fröhlich and Peter K. Sorger. Fides: reliable trust-region optimization for parameter estimation of ordinary differential equation models. PLOS Computational Biology, 18(7):e1010322, jul 2022. doi:10.1371/journal.pcbi.1010322.
Jorge Nocedal and Stephen J. Wright, editors. Numerical Optimization. Springer-Verlag, 1999. doi:10.1007/b98874.
C. G. Broyden. A class of methods for solving nonlinear simultaneous equations. Mathematics of Computation, 19(92):577–577, 1965.
Steven G. Johnson. The nlopt nonlinear-optimization package. 2007. URL: https://github.com/stevengj/nlopt.
Richard Brent. Algorithms for minimization without derivatives. 1972.
T Rowan. Functional stability analysis of numerical algorithms. 1990.
M Powell. The newuoa software for unconstrained optimization without derivatives. In Proc. 40th Workshop on Large Scale Nonlinear Optimization. Erice, Italy, 2004.
J. Nocedal. Updating quasi-newton matrices with limited storage. Math. Comput, 35:773–782, 1980.
J Nocedal ; D and J Liu. On the limited memory bfgs method for large scale optimization. Math. Comput, 35:503–528, 1989.
Krister Svanberg. A class of globally convergent optimization methods based on conservative convex separable approximations. SIAM J. Optim, 12(2):555–573, 2002.
Krister Svanberg. The method of moving asymptotes—a new method for structural optimization. International Journal for Numerical Methods in Engineering, 24(2):359–373, 1987. doi:10.1002/nme.1620240207.
J Vlcek and L Luksan. Shifted limited-memory variable metric methods for large-scale unconstrained minimization. J. Computational Appl. Math, 186:365–390, 2006.
Dieter Kraft. Algorithm 733: tomp-fortran modules for optimal control calculations. ACM Transactions on Mathematical Software, 20(3):262–281, 1994.
C. H. da Silva Santos, M. S. Gonçalves, and H. E. Hernández-Figueroa. Designing novel photonic devices by bio-inspired computing. IEEE Photonics Technology Letters, 22(15):1177–1179, 2010.
C. H. da Silva Santos. Parallel and bio-inspired computing applied to analyze microwave and photonic metamaterial structures. 2010.
H.-G Beyer and H.-P Schwefel. Evolution strategies: a comprehensive introduction. Journal Natural Computing, 1(1):3–52, 2002.
W. Vent. Rechenberg, ingo, evolutionsstrategie — optimierung technischer systeme nach prinzipien der biologischen evolution. 170 s. mit 36 abb. frommann-holzboog-verlag. stuttgart 1973. broschiert. Feddes Repertorium, 86(5):337–337, 1975.
Thomas Philip Runarsson and Xin Yao. Search biases in constrained evolutionary optimization. IEEE Trans. on Systems, Man, and Cybernetics Part C: Applications and Reviews, 35(2):233–243, 2005.
Thomas P. Runarsson and Xin Yao. Stochastic ranking for constrained evolutionary optimization. IEEE Trans. Evolutionary Computation, 4(3):284–294, 2000.
W Price. A controlled random search procedure for global optimization, pages 71–84. Volume 2. North-Holland Press, Amsterdam, 1978.
W Price. Global optimization by controlled random search. J. Optim. Theory Appl, 40(3):333–348, 1983.
P Kaelo and M Ali. Some variants of the controlled random search algorithm for global optimization. J. Optim. Theory Appl, 130(2):253–264, 2006.
Mauricio Zambrano-Bigiarini, Maurice Clerc, and Rodrigo Rojas. Standard particle swarm optimisation 2011 at cec-2013: a baseline for future pso improvements. In 2013 IEEE Congress on Evolutionary Computation, 2337–2344. 2013. doi:10.1109/CEC.2013.6557848.
Ingo Rechenberg. Evolutionsstrategie: Optimierung technischer Systeme nach Prinzipien der biologischen Evolution. Frommann-Holzboog Verlag, Stuttgart, 1973. [Evolution Strategy: Optimization of Technical Systems According to the Principles of Biological Evolution]. URL: https://gwern.net/doc/reinforcement-learning/exploration/1973-rechenberg.pdf.
M. Schumer and K. Steiglitz. Adaptive step size random search. IEEE Transactions on Automatic Control, 13(3):270–276, 1968. doi:10.1109/TAC.1968.1098903.
Elena Raponi, Hao Wang, Mariusz Bujny, Simonetta Boria, and Carola Doerr. High dimensional bayesian optimization assisted by principal component analysis. In Parallel Problem Solving from Nature – PPSN XVI: 16th International Conference, PPSN 2020, Leiden, The Netherlands, September 5-9, 2020, Proceedings, Part I, 169–183. Berlin, Heidelberg, 2020. Springer-Verlag. URL: https://doi.org/10.1007/978-3-030-58112-1_12, doi:10.1007/978-3-030-58112-1_12.
Pedro Larranaga and Jose Lozano. Estimation of Distribution Algorithms: A New Tool for Evolutionary Computation. Springer, 01 2002. ISBN 9781461356042. doi:10.1007/978-1-4615-1539-5.
G.R. Harik, F.G. Lobo, and D.E. Goldberg. The compact genetic algorithm. IEEE Transactions on Evolutionary Computation, 3(4):287–297, 1999. doi:10.1109/4235.797971.
Martin S. Krejca and Carsten Witt. Theory of estimation-of-distribution algorithms. 2018. URL: https://arxiv.org/abs/1806.05392, arXiv:1806.05392.
Michael Hellwig and Hans-Georg Beyer. Evolution under strong noise: a self-adaptive evolution strategy can reach the lower performance bound - the pccmsa-es. In Parallel Problem Solving from Nature – PPSN XIII, volume 9921. 09 2016. doi:10.1007/978-3-319-45823-6_3.
Fernando Nogueira. Bayesian Optimization: open source constrained global optimization tool for Python. 2014–. URL: https://github.com/bayesian-optimization/BayesianOptimization.
Ahmed Fawzy Gad. Pygad: an intuitive genetic algorithm python library. Multimedia Tools and Applications, pages 1–14, 2023.
R. Eberhart and J. Kennedy. A new optimizer using particle swarm theory. In MHS'95. Proceedings of the Sixth International Symposium on Micro Machine and Human Science, 39–43. 1995. doi:10.1109/MHS.1995.494215.
James Lane, Andries Engelbrecht, and James Gain. Particle swarm optimization with spatially meaningful neighbours. In 2008 IEEE Swarm Intelligence Symposium, volume, 1–8. 2008. doi:10.1109/SIS.2008.4668281.
Qingjian Ni and Jianming Deng. A new logistic dynamic particle swarm optimization algorithm based on random topology. The Scientific World Journal, 2013(1):409167, 2013. URL: https://onlinelibrary.wiley.com/doi/abs/10.1155/2013/409167, arXiv:https://onlinelibrary.wiley.com/doi/pdf/10.1155/2013/409167, doi:https://doi.org/10.1155/2013/409167.
Janoś Gabler, Sebastian Gsell, Tim Mensinger, and Mariam Petrosyan. Tranquilo: an optimizer for the method of simulated moments. Discussion Paper 522, CRC TR 224, University of Bonn and University of Mannheim, 2024. URL: https://www.crctr224.de/research/discussion-papers/archive/dp522.
Andrew R. Conn, Katya Scheinberg, and Luis N. Vicente. Introduction to Derivative-Free Optimization. Society for Industrial and Applied Mathematics, 2009. URL: https://epubs.siam.org/doi/abs/10.1137/1.9780898718768, doi:10.1137/1.9780898718768.