Creating variables using JuMP

I am trying to define variables corresponding to nodes in a lattice consisting of one root node and two other time steps with two nodes each. I have defined a 2D list with all the nodes which I want to use for the indexing of my variables:

nodes = [["T=0: N=1"], ["T=1: N=1", "T=1: N=2"], ["T=2: N=1", "T=2: N=2"]]

I want to create the variables in the following way:

for i in range(1, length(time_steps)-1)
    q = @variable(model, 0 <= q[time_steps[i], time_steps[i+1]])
end

I understand that it is not possible to add new variables to an existing container as done here, but I have not found a good way of achieving what I want. I appreciate any guidance you may have in this matter.

How about this (basically define the indices beforehand):

using JuMP

model = Model()

# key: time step, value: node
nodes = Dict(1 => [1], 2 => [2, 3], 3 => [4, 5])

# construct indices
indices = [(i, j) for t in 1:length(nodes) - 1 for i in nodes[t] for j in nodes[t + 1]]

@variable(model, q[indices] >= 0)
2 Likes

I don’t really understand how nodes is related to time_steps.

But there are many options. @math_opt’s is a good one. Here is another:

arcs = [0 => 1, 1=> 1, 1 => 2, 2 => 1, 2 => 2]
model = Model()
@variable(model, q[T in 0:2, N in 1:2; (T => N) in arcs] >= 0)

It really depends on: what do you want to do with q once it is constructed?

If you find yourself struggled to wrangle variables into appropriate forms for constraints and expressions, it usually means that you could use a different data structure that was more appropriate.

1 Like

Thank you! I managed to define the variables in the wanted string format when I used dictionaries.

1 Like