Skip to content

Commit ed16344

Browse files
odowVaibhavdixit02
andauthored
Remove chk from optimize to allow failures to return to the user (#221)
Co-authored-by: Vaibhavdixit02 <[email protected]>
1 parent b860c0c commit ed16344

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

src/NLopt.jl

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -890,8 +890,17 @@ function optimize!(o::Opt, x::Vector{Cdouble})
890890
x,
891891
opt_f,
892892
)
893-
chk(o, ret)
894-
return (opt_f[1], x, Symbol(ret))
893+
# We do not need to check the value of `ret`, except if it is a FORCED_STOP
894+
# with a Julia-related exception from a callback
895+
if ret == FORCED_STOP
896+
global nlopt_exception
897+
e = nlopt_exception
898+
nlopt_exception = nothing
899+
if e !== nothing && !(e isa ForcedStop)
900+
throw(e)
901+
end
902+
end
903+
return opt_f[1], x, Symbol(ret)
895904
end
896905

897906
function optimize(o::Opt, x::AbstractVector{<:Real})

test/C_API.jl

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,33 @@ function test_tutorial()
181181
return
182182
end
183183

184+
# It's not obvious why this test returns FAILURE. If it breaks in future, look
185+
# for something else.
186+
function test_return_FAILURE_from_optimize()
187+
function objective_fn(x, grad)
188+
if length(grad) > 0
189+
grad[1] = -2 * (1 - x[1]) - 400 * x[1] * (x[2] - x[1]^2)
190+
grad[2] = 200 * (x[2] - x[1]^2)
191+
end
192+
return (1 - x[1])^2 + 100 * (x[2] - x[1]^2)^2
193+
end
194+
function eq_constraint_fn(h, x, J)
195+
if length(J) > 0
196+
J[1, 1] = 2x[1]
197+
J[2, 1] = 2x[2]
198+
end
199+
h[1] = x[1]^2 + x[2]^2 - 1.0
200+
return
201+
end
202+
opt = Opt(:AUGLAG, 2)
203+
opt.local_optimizer = Opt(:LD_LBFGS, 2)
204+
opt.min_objective = objective_fn
205+
equality_constraint!(opt, eq_constraint_fn, [1e-8])
206+
_, _, ret = optimize(opt, [0.5, 0.5])
207+
@test ret == :FAILURE
208+
return
209+
end
210+
184211
end # module
185212

186213
TestCAPI.runtests()

0 commit comments

Comments
 (0)