Skip to content

Commit 5fc0378

Browse files
Merge pull request #702 from jonathanfischer97/fix_trace!
fixed user `trace!` overload compat. Both `x` and user records now saved
2 parents fedb001 + cf6caa2 commit 5fc0378

File tree

2 files changed

+30
-5
lines changed

2 files changed

+30
-5
lines changed

lib/OptimizationEvolutionary/src/OptimizationEvolutionary.jl

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,25 @@ SciMLBase.supports_opt_cache_interface(opt::Evolutionary.AbstractOptimizer) = tr
1111
decompose_trace(trace::Evolutionary.OptimizationTrace) = last(trace)
1212
decompose_trace(trace::Evolutionary.OptimizationTraceRecord) = trace
1313

14-
function Evolutionary.trace!(record::Dict{String, Any}, objfun, state, population,
15-
method::Evolutionary.AbstractOptimizer, options)
16-
record["x"] = population
14+
# Overload the trace! function to add the population to the trace prior to calling any user-defined trace! method
15+
function Evolutionary.trace!(tr, iteration, objfun, state, population, method::Evolutionary.AbstractOptimizer, options, curr_time=time())
16+
dt = Dict{String,Any}()
17+
dt["time"] = curr_time
18+
19+
# record `x` to store the population. Needed for constructing OptimizationState.
20+
dt["x"] = population
21+
22+
# set additional trace value
23+
Evolutionary.trace!(dt, objfun, state, population, method, options)
24+
Evolutionary.update!(tr,
25+
state,
26+
iteration,
27+
Evolutionary.value(state),
28+
dt,
29+
options.store_trace,
30+
options.show_trace,
31+
options.show_every,
32+
options.callback)
1733
end
1834

1935
function __map_optimizer_args(cache::OptimizationCache,

lib/OptimizationEvolutionary/test/runtests.jl

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,17 @@ Random.seed!(1234)
4141
end
4242
return false
4343
end
44-
sol = solve(prob, CMAES= 40, λ = 100), callback = cb, maxiters = 100)
44+
solve(prob, CMAES= 40, λ = 100), callback = cb, maxiters = 100)
4545

46+
# Test compatibility of user overload of trace!
47+
function Evolutionary.trace!(record::Dict{String, Any}, objfun, state, population, method::CMAES, options)
48+
# record fittest individual
49+
record["TESTVAL"] = state.fittest
50+
end
51+
4652
#test that `store_trace=true` works now. Threw ""type Array has no field value" before.
47-
solve(prob, CMAES= 40, λ = 100), store_trace = true)
53+
sol = solve(prob, CMAES= 40, λ = 100), store_trace = true)
54+
55+
# Make sure that both the user's trace record value, as well as `x` are stored in the trace.
56+
@test haskey(sol.original.trace[end].metadata, "TESTVAL") && haskey(sol.original.trace[end].metadata, "x")
4857
end

0 commit comments

Comments
 (0)