NLopt optimization with inequality constraint where objective function is undefined outside of the constraint


I would like to do nonlinear optimization with inequality constraint by NLopt, in which my objective function is not defined when the constraint is not satisfied. I’m using LN_COBYLA because I cannot compute the derivative.
However, the solver sometimes try to evaluate the objective function outside of the constraint and, as a consequence, the solver fails.

The minimal example below shows the problem.
I know I can impose a bounds constraint for this simple example but not in general.

Is there any way to search values only inside of the constraint? (What I can come up with is to let the objective function return huge value when undefined, although I don’t think it’s a beautiful solution.)

Thank you.

Example: \min x_1+x_2 subject to x_1\geq0 and x_2\geq0 but x_1+x_2 is undefined for x_1<0 or x_2<0

using NLopt
function obj(x, grad)
    if any(x .<0)
        println("negative element")
        return error("undefined")
        return x[1]+x[2]
function myconstraint(result, x, grad)
    result .= -x
opt = Opt(:LN_COBYLA, 2)
min_objective!(opt, obj)
inequality_constraint!(opt, myconstraint, [0, 0])

optimize(opt, [0.001, 0.001])


[-0.000320083, 0.000507602]
(0.000585786437626905, [0.000292893, 0.000292893], :FORCED_STOP)

Do a domain transformation, such as using x^2 or exp(x) as the input, so that way it is defined on the full real lined.


For general nonlinear constraints, NLopt makes no guarantee that it will only evaluate points inside the feasible set (i.e. satisfying the constraints).

However, for a constraint like x₁ ≥ 0, you should instead specify the constraint as a bound constraint via opt.lower_bounds = ... Not only is this much more efficient, but also NLopt guarantees that it will never evaluate a point outside of the bound constraints.


Thank you both,

It’s good to know there is no way to force the solver to use a value satisfying the constraint.

I’ll think about change of variables so that I can use box constraints, although I’m not sure if I can.