Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove chk from optimize to allow failures to return to the user #221

Merged
merged 2 commits into from
Aug 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
Loading