【发布时间】:2021-07-22 21:24:54
【问题描述】:
为了解决最大流量问题,我必须定义一个函数,该函数将写入弧及其容量的文件的名称作为输入,我必须构建和求解模型、打印变量并构建图形只有最后值不为零的弧。 这是我要运行的代码
def maxflow(filename):
G = nx.read_edgelist("filename",nodetype=int,create_using=nx.DiGraph())
# Identify the sink and the source nodes
source=min(G.nodes)
print(f"Source={source}")
sink=max(G.nodes)
print(f"Sink={sink}")
m = gp.Model("maxflow")
# Create variables
x = m.addVars(G.edges(), vtype=GRB.CONTINUOUS, name="x")
v = m.addVar(vtype=GRB.CONTINUOUS, name="v")
# Update new variables
m.update()
print(x)
print(v)
# Set objective
# Set the direction
m.modelSense = GRB.MAXIMIZE
#Add to the model
m.setObjective( v )
# Capacity constraints: x_ij <= C_ij
for e in G.edges():
print(f"--{e}--")
constr = x[e]
print(f"Adding Capacity constraints to edge {e}: {constr} with capacity {G[e[0]][e[1]]['capacity']}")
# Finally we add it to the model
m.addConstr( constr, GRB.LESS_EQUAL, G[e[0]][e[1]]["capacity"], f"C{e[0]},{e[1]}" )
m.addConstr(x.sum(source,'*') == v, name=f"Source{source}")
m.addConstr(x.sum('*', sink) == v, name=f"Sink{sink}")
for n in G.nodes():
if n != source and n != sink:
m.addConstr(x.sum(n,'*') - x.sum('*',n) == 0.0, name=f"N{n}")
m.write("maxflow.lp")
!cat maxflow.lp
m.optimize()
# Print solution
if m.status == GRB.status.OPTIMAL:
print(f"Optimal solution\nObj: {m.objVal}")
for var in m.getVars():
print(f"Variable name: {var.varName}. Value: {var.x}")
# Construct graph with only arcs that have some flow
for var in m.getVars():
G = nx.read_edgelist("./filename",nodetype=int,create_using=nx.DiGraph())
if var.x==0.0:
stringa=str(var.varName)
s = stringa.replace ("x", "")
y=literal_eval(s)
G.remove_edge(y[0],y[1])
nx.draw(G, with_labels=True)
这样最后我可以调用放置文本文件的函数
maxflow ("edge_list_max_flow2.txt")
并为这些数据编写代码中的所有内容。
希望你们中的某个人能帮助我!提前谢谢你。
【问题讨论】:
-
不要在变量名两边加上引号。
"filename"应该是filename -
!cat maxflow.lp应该做什么?我不认为这是一个有效的 python 命令。nx和GP是什么?是那些模块吗?您能否将这些代码部分添加到您的问题中。 -
非常感谢!现在它可以正常运行了!
标签: python function networkx gurobi max-flow