Skip to content

Commit

Permalink
Remove chk from optimize to allow failures to return to the user (#221)
Browse files Browse the repository at this point in the history
Co-authored-by: Vaibhavdixit02 <[email protected]>
  • Loading branch information
odow and Vaibhavdixit02 authored Aug 16, 2024
1 parent b860c0c commit ed16344
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/NLopt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -890,8 +890,17 @@ function optimize!(o::Opt, x::Vector{Cdouble})
x,
opt_f,
)
chk(o, ret)
return (opt_f[1], x, Symbol(ret))
# We do not need to check the value of `ret`, except if it is a FORCED_STOP
# with a Julia-related exception from a callback
if ret == FORCED_STOP
global nlopt_exception
e = nlopt_exception
nlopt_exception = nothing
if e !== nothing && !(e isa ForcedStop)
throw(e)
end
end
return opt_f[1], x, Symbol(ret)
end

function optimize(o::Opt, x::AbstractVector{<:Real})
Expand Down
27 changes: 27 additions & 0 deletions test/C_API.jl
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,33 @@ function test_tutorial()
return
end

# It's not obvious why this test returns FAILURE. If it breaks in future, look
# for something else.
function test_return_FAILURE_from_optimize()
function objective_fn(x, grad)
if length(grad) > 0
grad[1] = -2 * (1 - x[1]) - 400 * x[1] * (x[2] - x[1]^2)
grad[2] = 200 * (x[2] - x[1]^2)
end
return (1 - x[1])^2 + 100 * (x[2] - x[1]^2)^2
end
function eq_constraint_fn(h, x, J)
if length(J) > 0
J[1, 1] = 2x[1]
J[2, 1] = 2x[2]
end
h[1] = x[1]^2 + x[2]^2 - 1.0
return
end
opt = Opt(:AUGLAG, 2)
opt.local_optimizer = Opt(:LD_LBFGS, 2)
opt.min_objective = objective_fn
equality_constraint!(opt, eq_constraint_fn, [1e-8])
_, _, ret = optimize(opt, [0.5, 0.5])
@test ret == :FAILURE
return
end

end # module

TestCAPI.runtests()

0 comments on commit ed16344

Please sign in to comment.