Skip to content

Commit

Permalink
Catch InterruptException and handle as ForcedStop (#245)
Browse files Browse the repository at this point in the history
  • Loading branch information
odow authored Sep 10, 2024
1 parent 8107a84 commit 1699685
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/NLopt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,8 @@ end
function _catch_forced_stop(o::Opt, e)
if e isa ForcedStop
setfield!(o, :exception, e)
elseif e isa InterruptException
setfield!(o, :exception, ForcedStop())
else
setfield!(o, :exception, CapturedException(e, catch_backtrace()))
end
Expand Down
22 changes: 22 additions & 0 deletions test/C_API.jl
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,28 @@ function test_vector_forced_stop()
return
end

function test_vector_interrupt_exception()
function my_objective_fn(x::Vector, grad::Vector)
if length(grad) > 0
grad[1] = 0
grad[2] = 0.5 / sqrt(x[2])
end
return sqrt(x[2])
end
function my_constraint_fn(ret, x::Vector, grad::Matrix)
throw(NLopt.InterruptException())
return
end
opt = Opt(:LD_MMA, 2)
lower_bounds!(opt, [-Inf, 0.0])
xtol_rel!(opt, 1e-4)
min_objective!(opt, my_objective_fn)
inequality_constraint!(opt, my_constraint_fn, [1e-8, 1e-8])
min_f, min_x, ret = optimize(opt, [1.234, 5.678])
@test ret == :FORCED_STOP
return
end

function test_max_objective()
opt = Opt(:LD_MMA, 2)
function objective_fn(x, grad)
Expand Down

0 comments on commit 1699685

Please sign in to comment.