Automatically use getvalue() for all variables in model - JuMP

After solving my JuMP model, I would like to use getvalue() on all variables in my model in an automated way. Say I have the following example problem:

using JuMP
using Clp
@objective(m,Max,sum(x[i] + 2*y[i] for i=1:3))

I could then do the following in order to obtain the optimal values of the variables:

x_res = getvalue(x)
y_res = getvalue(y)

How could I do this in an automated fashion, looping through all variables that the JuMP model contains and saving them similarly to the example above?
Is there a list/dictionary associated with a JuMP model that contains all the variables, that I could then loop through?
Thank you already in advance

As of JuMP v0.18 (the current version), this trick won’t apply to the future JuMP v0.19 version, you can have the list of variables of a model m using

Variable.(m, 1:m.numCols)
1 Like

JuMP stores a dictionary of the named objects, so you can go

x_res = getvalue(m[:x])

However, this won’t work if you have anonymous variables, or two variables with the same name.

Is it sufficient to go

variables = [:x, :y]
variablevalues = Dict()
for v in variables
    variablevalues[v] = getvalue(m[v])

variablevalues[:x][2] # 3


variables = [x, y]
variablevalues = Dict()
for v in variables
    variablevalues[v] = getvalue(m, v)

variablevalues[x][2] # 3
1 Like

Thank you. For future reference, how would this look like in v0.19?

In JuMP master, you can currently do

using MathOptInterface
const MOI = MathOptInterface
vars = JuMP.Variable(m, MOI.get(m.moibackend, MOI.ListOfVariableIndices()))

but we might have a nicer syntax on JuMP v0.19 like MOI.get(m, MOI.ListOfVariableIndices()) to get the list of variables.

1 Like