Efficient way to get the JuMP.value of all variables in a JuMP.Model?

Do you just want to get the variable values that are registered in object_dictionary(model)?

So something like the following:

d = Dict(
    k => value.(v) for 
    (k, v) in object_dictionary(model) if v isa AbstractArray{VariableRef}
)

You approach is very slow because it doesn’t short-circuit if the key is already found. Do something like:

function get_results_dict(m::JuMP.Model)
    av = JuMP.all_variables(m);
    d = Dict()
    for v in av
        # special handling of time series, sub-indices, etc.
        # e.g. a variable could have three sub-indices in a JuMP.Containers
        v = string(v) # e.g.  "x[a,2,3]"
        k = Symbol(v[1:prevind(v, findfirst('[', v))[1]]) # :x
        if !haskey(d, k)
            vm = value.(m[k])
            d[k] = vm.data
        end
        #  e.g. typeof(vm) is JuMP.Containers.SparseAxisArray{Float64, 3, Tuple{SubString{String}, Int64, Int64}}
    end
    return d
end
1 Like