Skip to content

Commit fccd349

Browse files
fixed user trace! overload compat. Both x and user records now saved
1 parent 9c5070b commit fccd349

File tree

2 files changed

+32
-3
lines changed

2 files changed

+32
-3
lines changed

lib/OptimizationEvolutionary/src/OptimizationEvolutionary.jl

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,30 @@ 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+
# function Evolutionary.trace!(record::Dict{String, Any}, objfun, state, population,
15+
# method::Evolutionary.AbstractOptimizer, options)
16+
# record["x"] = population
17+
# end
18+
19+
# Overload the trace! function to add the population to the trace prior to calling any user-defined trace! method
20+
function Evolutionary.trace!(tr, iteration, objfun, state, population, method::Evolutionary.AbstractOptimizer, options, curr_time=time())
21+
dt = Dict{String,Any}()
22+
dt["time"] = curr_time
23+
24+
# record `x` to store the population. Needed for constructing OptimizationState.
25+
dt["x"] = population
26+
27+
# set additional trace value
28+
Evolutionary.trace!(dt, objfun, state, population, method, options)
29+
Evolutionary.update!(tr,
30+
state,
31+
iteration,
32+
Evolutionary.value(state),
33+
dt,
34+
options.store_trace,
35+
options.show_trace,
36+
options.show_every,
37+
options.callback)
1738
end
1839

1940
function __map_optimizer_args(cache::OptimizationCache,

lib/OptimizationEvolutionary/test/runtests.jl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,12 @@ Random.seed!(1234)
4545

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

0 commit comments

Comments
 (0)