4

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

tofri
  • 43
  • 5
  • 2
    I ensure you won't get answers unless you put what you have tried. Put a reproducible and minimal example of what you want to do and the expected result, as detailed and straightforward as possible. – Shayan Dec 01 '22 at 18:20
  • thanks for the hint. I edited the post and hope the example makes the problem clear – tofri Dec 01 '22 at 18:59
  • is my answer exactly what you wanted or were you looking for something different? – Przemyslaw Szufel Dec 01 '22 at 22:50

2 Answers2

3

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]
Oscar Dowson
  • 2,395
  • 1
  • 5
  • 13
0

JuMP supports dense arrays with custom indexing.

julia> indices = [Symbol.(:a, 1:2);Symbol.(:b, 1:3)];

julia> @variable(m, x[indices], Bin)
1-dimensional DenseAxisArray{VariableRef,1,...} with index sets:
    Dimension 1, [:a1, :a2, :b1, :b2, :b3]
And data, a 5-element Vector{VariableRef}:
 x[a1]
 x[a2]
 x[b1]
 x[b2]
 x[b3]

Przemyslaw Szufel
  • 40,002
  • 3
  • 32
  • 62
  • Thanks for your answer! unfortunately it is not exactly what I am looking for. But Oscar Dowson (post above) presented the solution I was looking for – tofri Dec 02 '22 at 15:39