Slicing a sparse variable created from list of tuples

Hi everyone,

I would like to do slicing on a sparse variable created from a list of tuples.

In the next example (extracted from documentation), the same variable is created in two different ways. While it is possible to do slicing on x1, it is not on x2.

N = 10
S = [(1, 1, 1), (N, N, N)]

model = Model(Gurobi.Optimizer)

@variable(model, x1[i=1:N, j=1:N, k=1:N; (i, j, k) in S])
@variable(model, x2[S])

x1[1,:,:], x2[1,:,:]

I get MethodError: no method matching one(::Colon)

Is there any way to create a sparse variable from a list of tuples and afterward be able to do slicing?

Thanks!

No. The key is to look at what is actually created:

julia> using JuMP

julia> N = 10
10

julia> S = [(1, 1, 1), (N, N, N)]
2-element Vector{Tuple{Int64, Int64, Int64}}:
 (1, 1, 1)
 (10, 10, 10)

julia> model = Model()
A JuMP Model
Feasibility problem with:
Variables: 0
Model mode: AUTOMATIC
CachingOptimizer state: NO_OPTIMIZER
Solver name: No optimizer attached.

julia> @variable(model, x1[i=1:N, j=1:N, k=1:N; (i, j, k) in S])
JuMP.Containers.SparseAxisArray{VariableRef, 3, Tuple{Int64, Int64, Int64}} with 2 entries:
  [1, 1, 1   ]  =  x1[1,1,1]
  [10, 10, 10]  =  x1[10,10,10]

julia> @variable(model, x2[S])
1-dimensional DenseAxisArray{VariableRef,1,...} with index sets:
    Dimension 1, [(1, 1, 1), (10, 10, 10)]
And data, a 2-element Vector{VariableRef}:
 x2[(1, 1, 1)]
 x2[(10, 10, 10)]
  • x1 is a JuMP.Containers.SparseAxisArray, with three dimensions and two non-zero keys.
  • x2 is a JuMP.Containers.DenseAxisArray, with one dimension containing S.

So you can’t even index into x2 with three arguments:

julia> x2[1, 1, 1]
ERROR: KeyError: key 1 not found

What you could do is something like this:

julia> x2[[s for s in S if s[1] == 1]]
1-dimensional DenseAxisArray{VariableRef,1,...} with index sets:
    Dimension 1, [(1, 1, 1)]
And data, a 1-element Vector{VariableRef}:
 x2[(1, 1, 1)]