我正在尝试使用networkx创建具有与边缘关联的颜色的图形。每个边缘应具有所有颜色,但只能选择一种。
Z = [0, 1, 2, 3, 4, 5, 6]
for colored_arc in ((u,v,z) for u,v in G.edges() for z in Z):
G[colored_arc[0]][colored_arc[1]][colored_arc[2]] = colored_arc
其中u,v是节点,z是颜色。这是结果
for u,v in G.edges():
for z in Z:
print(G[u][v][z])
(1, 2, 0)
(1, 2, 1)
(1, 2, 2)
(1, 2, 3)
(1, 2, 4)
(1, 2, 5)
(1, 2, 6)
.....
现在我正在创建一个二进制变量(使用gurobi),其中1是与每个边缘的正确颜色关联的值,所有其他颜色的值为0。
mdic = gb.Model()
for u,v in G.edges():
for z in Z:
x = mdic.addVars(obj=[G[u][v][z]], ub = 1.0, vtype=gb.GRB.BINARY, name='x')
但这是错误:
IndexError Traceback (most recent call last)
<ipython-input-24-be25e6af1ffe> in <module>()
5 for u,v in G.edges():
6 for z in Z:
----> 7 x = mdic.addVars(obj=[G[u][v][z]], ub = 1.0, vtype=gb.GRB.BINARY, name='x')
8
9 # decision variables s i and S i for i ∈ V to represent the minimum and maximum color in the set of colors
model.pxi in gurobipy.Model.addVars (../../src/python/gurobipy.c:80144)()
model.pxi in gurobipy.__listify.__init__ (../../src/python/gurobipy.c:50924)()
IndexError: list index out of range
答案 0 :(得分:0)
使用mdic.addVar(...)
代替mdic.addVars(...)
创建单个决策变量。
函数addVars
需要根据http://www.gurobi.com/documentation/8.0/refman/py_model_addvars.html列出的索引,您没有提供。因此,您得到了IndexError
。
您可以在优化模型后将变量存储在列表中以获取其值。
# n: number of nodes
x = [[[None] * len(Z)] * (n+1)] * (n+1)
for u,v in G.edges():
for z in Z:
x[u][v][z] = mdic.addVar(vtype = gb.GRB.BINARY)
mdic.update()
# add constraints using the variables in x...
# add objective function...
mdic.optimize()
# get results using x[u][v][z].getAttr(GRB.Attr.x)
indices = []
for u,v in G.edges():
for z in Z:
indices.append((u,v,z))
x = mdic.addVars(indices, vtype = gb.GRB.BINARY)