Python 带区间Gurobi约束的图着色
我正在尝试使用networkx和gurobi修复图形着色问题的一些约束。每一个我∈ 五、 我们定义以下一组区间。每个间隔[l,u]∈ Ii表示与顶点i相关的边集的最小颜色l和最大颜色u的可能对。另外,对于每个k∈K,表示顶点i的区间集∈ 包括颜色k的V: 以下是我编写的所有代码:Python 带区间Gurobi约束的图着色,python,networkx,graph-theory,gurobi,Python,Networkx,Graph Theory,Gurobi,我正在尝试使用networkx和gurobi修复图形着色问题的一些约束。每一个我∈ 五、 我们定义以下一组区间。每个间隔[l,u]∈ Ii表示与顶点i相关的边集的最小颜色l和最大颜色u的可能对。另外,对于每个k∈K,表示顶点i的区间集∈ 包括颜色k的V: 以下是我编写的所有代码: import networkx as nx import gurobi as gb from itertools import combinations, chain import pygraphviz as pyg
import networkx as nx
import gurobi as gb
from itertools import combinations, chain
import pygraphviz as pygv
import os
import matplotlib.pyplot as plt
from IPython.display import SVG, display
创建图形,添加节点和边以及两个列表
G = nx.Graph()
G.add_nodes_from ([0,1,2,3,4])
G.add_edge(0,1)
G.add_edge(0,2)
G.add_edge(0,3)
G.add_edge(0,4)
G.add_edge(1,2)
G.add_edge(1,3)
G.add_edge(2,4)
G.add_edge(3,4)
U = list(G.nodes)
K = G.number_of_edges()
Z = []
创建带有颜色的列表。我们假设K={0,1,…,K− 1} 和K≤ |E|
def nrofCol():
Z.clear()
z = 0
while z < K - 1:
Z.append(z)
z = z+1
return Z
Z = nrofCol()
Z
我将是一个元组列表
I = []
for z in Z:
for u in range (z, len(Z)):
I.append(tuple((z, u)))
向每个边添加颜色属性
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
并使用Gurobi将变量添加到模型中:
制约因素包括:
约束2a-确保每条边只采用一种颜色
for u,v in G.edges():
mdic.addConstr(x.sum(u,v) == 1, name='one_color')
mdic.update()
2b-为每个顶点恰好选择一个间隔(从一组合格间隔中)
for u in U:
mdic.addConstr(y.sum(u) == 1, name='used')
mdic.update()
2c-确保不仅相邻边采用不同的颜色,而且关联到顶点的边也采用该顶点所选间隔中包含的颜色集中的颜色
for u in U:
for z in Z:
mdic.addConstr((x.sum(u,'*',z) + x.sum('*',u,z)) <= y.sum(u,I), name='different_colors')
mdic.update()
使用此代码,该模型是不可行的。我知道变量x和约束2a的定义是正确的。我不确定变量y、其他约束和目标函数。如何更改此设置?应分别为每个节点定义间隔列表
i[i]
:
I = []
for i in G.nodes():
Ii = []
for z in Z:
for u in range (z, len(Z)):
if u - z >= G.degree(i) - 1:
Ii.append(tuple((z, u)))
I.apppend(Ii)
然后必须将I
的用法更改为以下内容:
indices2 = []
for i in G.nodes():
for interval in I[i]:
indices2.append(tuple((i,interval)))
变量y
现在只能创建一次:
y = mdic.addVars(indices2, vtype = gb.GRB.BINARY)
约束2c也必须更改,因为在屏幕截图中,右和仅在I
的子集上迭代:
for u in U:
for z in Z:
y_sum = 0
for z1,z2 in I[u]:
if z1 <= z and z <= z2:
y_sum += y[u,(z1,z2)]
mdic.addConstr((x.sum(u,'*',z) + x.sum('*',u,z)) <= y_sum, name='different_colors')
对于u中的u:
对于z中的z:
y_和=0
对于I[u]中的z1,z2:
如果z1模型仍然不可行。可能约束2c有错误,可能y(u,I)不起作用。目标函数也是如此。我怎样才能修好它@Cepheus@Mike约束2c也必须更改。但是我没有检查目标函数,因为它不应该影响可行性。
indices2 = []
for i in G.nodes():
for interval in I[i]:
indices2.append(tuple((i,interval)))
y = mdic.addVars(indices2, vtype = gb.GRB.BINARY)
for u in U:
for z in Z:
y_sum = 0
for z1,z2 in I[u]:
if z1 <= z and z <= z2:
y_sum += y[u,(z1,z2)]
mdic.addConstr((x.sum(u,'*',z) + x.sum('*',u,z)) <= y_sum, name='different_colors')