Gurobi/Python:通过addVars 添加二进制变量

Gurobi/Python: Adding Binary Variables through addVars

我有这些套装:

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] }

我想编写一个代码来添加图中所示的下一个变量

我的试用期如下

z = m.addVars(R,Cr[r] for r in R,Cr[r] for r in R,vtype=GRB.BINARY)

当我尝试打印 z 时,出现此错误:生成器表达式必须加括号

您可以在 Gurobi 的 tupledict 上使用 update() 来迭代添加变量块:

z = gp.tupledict()

for r in R:
    z.update(m.addVars(Cr[r], Cr[r], vtype=GRB.BINARY))

这将导致这些变量:

{(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>}

gurobipy.Model.addVars() 的第一个参数要么是一些可迭代对象(如 R 或 C),要么是生成器表达式;生成器表达式必须用括号括起来。所以你的代码应该是:

z = m.addVars(((i,j) for r in R for i in Cr[r] for j in Cr[r]),
              vtype=GRB.BINARY, name='z')

或者,您可以按如下方式使用 Python itertools package

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')

我更喜欢第一种语法,但我怀疑 itertools 对于大型数据集可能更快。