Python 如何构造以文件名作为输入的函数?
为了解决最大流问题,我必须定义一个函数,该函数将写入弧的文件名及其容量作为输入,我必须构建和求解模型,打印变量,并构建一个图形,其中只有弧的值不同于零。 这就是我试图运行的代码Python 如何构造以文件名作为输入的函数?,python,function,networkx,gurobi,max-flow,Python,Function,Networkx,Gurobi,Max Flow,为了解决最大流问题,我必须定义一个函数,该函数将写入弧的文件名及其容量作为输入,我必须构建和求解模型,打印变量,并构建一个图形,其中只有弧的值不同于零。 这就是我试图运行的代码 def maxflow(filename): G = nx.read_edgelist("filename",nodetype=int,create_using=nx.DiGraph()) # Identify the sink and the source nodes source=min
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)
对于这些数据,所有的东西都写在代码里
希望你们中有人能帮助我!提前谢谢。您只需更改一行,使用
G=nx.read\u edgelist(filename,nodetype=int,create\u using=nx.DiGraph())
而不是
G=nx.read\u edgelist(“filename”,nodetype=int,create\u使用=nx.DiGraph())
背景
当前,您使用的是文本
“filename”
而不是变量filename
不要在变量名周围加引号<代码>“文件名”应该是filename
什么是!cat maxflow.lp
应该怎么做?我认为这不是一个有效的python命令。什么是nx
和GP
?那些是模块吗?请您将这些代码添加到您的问题中。非常感谢!现在它运行正常了!非常感谢:)我刚才看到您稍后也使用了“/filename”
,您可能还想更改它
maxflow ("edge_list_max_flow2.txt")