Reputation: 81
I have these sets:
R = [1,2,3,4]
C = [10,11,12,13,14,15,16,17,18,19,20,21]
Cr = {1: C[0:3], 2 : C[3:6],3: C[6:9], 4: C[9:12] }
I want to write a code for adding the next variable shown in the image
My trial is as next
z = m.addVars(R,Cr[r] for r in R,Cr[r] for r in R,vtype=GRB.BINARY)
When I tried to print z, I got this error: Generator expression must be parenthesized
Upvotes: 0
Views: 492
Reputation: 5653
The first arguments to gurobipy.Model.addVars() are either some iterables (like R or C) or a generator expression; the generator expression must be parenthesized. So your code should be:
z = m.addVars(((i,j) for r in R for i in Cr[r] for j in Cr[r]),
vtype=GRB.BINARY, name='z')
Alternately, you could use the Python itertools package as follows:
import itertools as it
z = m.addVars(it.chain.from_iterable(map(lambda x: it.product(x, repeat=2), Cr.values())),
vtype=GRB.BINARY, name='z')
I prefer the first syntax but I suspect that itertools may be faster for large data sets.
Upvotes: 2
Reputation: 6716
You can use update()
on Gurobi's tupledict to iteratively add the blocks of variables:
z = gp.tupledict()
for r in R:
z.update(m.addVars(Cr[r], Cr[r], vtype=GRB.BINARY))
This will result in these variables:
{(10, 10): <gurobi.Var C0>,
(10, 11): <gurobi.Var C1>,
(10, 12): <gurobi.Var C2>,
(11, 10): <gurobi.Var C3>,
(11, 11): <gurobi.Var C4>,
(11, 12): <gurobi.Var C5>,
(12, 10): <gurobi.Var C6>,
(12, 11): <gurobi.Var C7>,
(12, 12): <gurobi.Var C8>,
(13, 13): <gurobi.Var C9>,
(13, 14): <gurobi.Var C10>,
(13, 15): <gurobi.Var C11>,
(14, 13): <gurobi.Var C12>,
(14, 14): <gurobi.Var C13>,
(14, 15): <gurobi.Var C14>,
(15, 13): <gurobi.Var C15>,
(15, 14): <gurobi.Var C16>,
(15, 15): <gurobi.Var C17>,
(16, 16): <gurobi.Var C18>,
(16, 17): <gurobi.Var C19>,
(16, 18): <gurobi.Var C20>,
(17, 16): <gurobi.Var C21>,
(17, 17): <gurobi.Var C22>,
(17, 18): <gurobi.Var C23>,
(18, 16): <gurobi.Var C24>,
(18, 17): <gurobi.Var C25>,
(18, 18): <gurobi.Var C26>,
(19, 19): <gurobi.Var C27>,
(19, 20): <gurobi.Var C28>,
(19, 21): <gurobi.Var C29>,
(20, 19): <gurobi.Var C30>,
(20, 20): <gurobi.Var C31>,
(20, 21): <gurobi.Var C32>,
(21, 19): <gurobi.Var C33>,
(21, 20): <gurobi.Var C34>,
(21, 21): <gurobi.Var C35>}
Upvotes: 1