optimizationindexingjuliajulia-jump

Optimisation Variable with two indices and different index length in JULIA JUMP


I want to solve an optimization problem in Julia. I am trying to define a binary variable x_{r,i} Thereby, the length of the sets of both indices is not the same.

Let's say there is r_a and r_b, but for r_a there are i_1 and i_2 whereas for r_b there are i_1, i_2 and i_3 so in the end I want to get X_a_1, X_a_2 and X_b_1, X_b_2, X_b_3

The set of indices i varies for different indices r.

Is there any way to define variable x with these indices in Julia?

This is what I tried:

R=["a","b"]
I=Dict("a" => [1,2],"b"=>[1,2,3])

m = Model(CPLEX.Optimizer)

@variables m begin
    X[R,[I]], Bin 
end


Solution

  • You were on the right track. Create a SparseAxisArray:

    julia> R = ["a", "b"]
    2-element Vector{String}:
     "a"
     "b"
    
    julia> I = Dict("a" => [1, 2], "b" => [1, 2, 3])
    Dict{String, Vector{Int64}} with 2 entries:
      "b" => [1, 2, 3]
      "a" => [1, 2]
    
    julia> model = Model();
    
    julia> @variable(model, x[r in R, i in I[r]])
    JuMP.Containers.SparseAxisArray{VariableRef, 2, Tuple{String, Int64}} with 5 entries:
      [a, 1]  =  x[a,1]
      [a, 2]  =  x[a,2]
      [b, 1]  =  x[b,1]
      [b, 2]  =  x[b,2]
      [b, 3]  =  x[b,3]