Iterate over a SparseAxisArray container to retrieve variable values and index (jump 0.18+)

I wish to iterate over the variables contained in a JuMP.SparseAxisArray so that I can write out variable values using JuMP.value(var), where var is an entry in the array.

I would also like to obtain the value of the index of the variable. So far I’ve tried var.index and JuMP.index(var) just return an integer, rather than the index set I defined using the @variable macro.

1 Like

You can do it as follows:

julia> using JuMP

julia> model = Model();

julia> @variable(model, x[i=1:2, 1:i])
JuMP.Containers.SparseAxisArray{VariableRef,2,Tuple{Any,Any}} with 3 entries:
  [2, 2]  =  x[2,2]
  [1, 1]  =  x[1,1]
  [2, 1]  =  x[2,1]

julia> for var in x
           @show JuMP.index(var)
       end
JuMP.index(var) = MathOptInterface.VariableIndex(3)
JuMP.index(var) = MathOptInterface.VariableIndex(1)
JuMP.index(var) = MathOptInterface.VariableIndex(2)

I have the same question. Before update my JuMP version I was able to sweep the index of my variable easily, like:

for  key in (sort!(collect(keys(var)))) 

but I cannot find another way to do it in JuMP 0.9. That’s really bad because my whole set of variables is multi-index (like, [“id”,“region”,“city”] and it’s very important to me be able to sweep the index in many parts of my code.