How to evaluate a JuMP model given a candidate solution?

Supposing I have built an optimization model in JuMP, how can I evaluate its objective with a candidate solution? This solution may be obtained manually or from other tools. That is, how to get objective(x) if I have a tentative value of x.

The feasibility of a solution (point) can be checked with primal_feasibility_report, but how to get the corresponding objective value?

3 Likes

You can fix the variables in the model and solve it ( Variables · JuMP)

1 Like

Another option is this

julia> model = Model();

julia> @variable(model, x)
x

julia> @objective(model, Min, 2x^2 + x + 0.5)
2 x² + x + 0.5

julia> f = objective_function(model)
2 x² + x + 0.5

julia> point = Dict(x => 2.0)
Dict{VariableRef, Float64} with 1 entry:
  x => 2.0

julia> value(f, x -> point[x])
10.5
6 Likes

But fixing the variables changes the original model construction code, right? Supposing we are given a built model, can we easily evaluate its objective at a given point without modifying model? That is, I want something like primal_feasibility_report.

Yes, fixing will modify the bounds. You’re looking for my answer above.

Yes, it worked. Thanks.

I have provided some comments for your code for others who are interested.

# the model
model = Model();
@variable(model, x)
@variable(model, 0 <= y[1:3] <= 10)
@objective(model, Min, 2x^2 + x + y[1] * y[2] + y[3])

# get the objective
fobj = objective_function(model) 
# `fobj` is a JuMP expression and we can use `value` to evaluate it
# the second parameter `var_value` is a `Function` that returns the value 
# of a variable `v` when called by `var_value(v)`

# need to give the value for each variable in a container
point = Dict(x => 2.0, y[1] => 1.2, y[2] => 10.0, y[3] => -1.3)
# note that no constraints are checked; `var_value` is given as a Lambda function
value(fobj, v -> point[v])
4 Likes