Skip to content

Commit a394b3a

Browse files
committed
demo and test callback
1 parent c41258f commit a394b3a

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

test/dummy_solver.jl

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ function SolverCore.solve!(
8686
end
8787

8888
iter = 0
89+
set_iter!(stats, iter)
8990
ϵd = atol + rtol * norm(dual)
9091
ϵp = atol
9192

@@ -94,8 +95,9 @@ function SolverCore.solve!(
9495
verbose && @info log_row(Any[iter, fx, norm(cx), norm(dual), elapsed_time, 'c'])
9596
solved = norm(dual) < ϵd && norm(cx) < ϵp
9697
tired = neval_obj(nlp) + neval_cons(nlp) > max_eval || elapsed_time > max_time
98+
user = false
9799

98-
while !(solved || tired)
100+
while !(solved || tired || user)
99101
# assume the model returns a dense Hessian in column-major order
100102
# NB: hess_coord!() only returns values in the lower triangle
101103
hess_coord!(nlp, x, y, view(hval, 1:nnzh))
@@ -122,6 +124,9 @@ function SolverCore.solve!(
122124
Wxy = reshape_array(wval, (nvar + ncon, nvar + ncon))
123125
Hxy = reshape_array(hval, (nvar, nvar))
124126
Wxy[1:nvar, 1:nvar] .= Hxy
127+
for i = 1:nvar
128+
Wxy[i, i] += sqrt(eps(T))
129+
end
125130
if ncon > 0
126131
Wxy[(nvar + 1):(nvar + ncon), 1:nvar] .= Jx
127132
end
@@ -146,11 +151,21 @@ function SolverCore.solve!(
146151
mul!(dual, Jx', y, one(T), one(T))
147152
end
148153
elapsed_time = time() - start_time
149-
solved = norm(dual) < ϵd && norm(cx) < ϵp
154+
set_time!(stats, elapsed_time)
155+
presid = norm(cx)
156+
dresid = norm(dual)
157+
set_residuals!(stats, presid, dresid)
158+
solved = dresid < ϵd && presid < ϵp
150159
tired = neval_obj(nlp) + neval_cons(nlp) > max_eval || elapsed_time > max_time
151160

152161
iter += 1
153162
fx = obj(nlp, x)
163+
set_iter!(stats, iter)
164+
set_objective!(stats, fx)
165+
166+
callback(nlp, solver, stats)
167+
user = stats.status == :user
168+
154169
verbose && @info log_row(Any[iter, fx, norm(cx), norm(dual), elapsed_time, 'd'])
155170
end
156171

test/runtests.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,4 @@ include("dummy_solver.jl")
1111

1212
include("test_logging.jl")
1313
include("test_stats.jl")
14+
include("test_callback.jl")

test/test_callback.jl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
@testset "test callback" begin
2+
nlp =
3+
ADNLPModel(x -> dot(x, x) / 2, ones(2), x -> [sum(x .^ 3) - 1], [0.0], [0.0], name = "linquad")
4+
callback(nlp, solver, stats) = begin
5+
if stats.iter 3
6+
set_status!(stats, :user)
7+
end
8+
end
9+
stats = dummy_solver(nlp, max_eval = 20, callback = callback)
10+
@test stats.iter == 3
11+
end

0 commit comments

Comments
 (0)