如何构造一个以文件名作为输入的函数?

How to construct a function that takes as input the name of a file?

为了解决最大流量问题,我必须定义一个函数,该函数将写入弧及其容量的文件的名称作为输入,我必须构建和求解模型,打印变量并构造仅包含末尾值不为零的弧的图。 这是我正在尝试 运行

的代码
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")

并拥有代码中编写的所有内容。

希望有人能帮助我!提前谢谢你。

只需要换一行,使用

G = nx.read_edgelist(filename,nodetype=int,create_using=nx.DiGraph())

而不是

G = nx.read_edgelist("filename",nodetype=int,create_using=nx.DiGraph())

背景

目前您正在使用文字 "filename" 而不是使用变量 filename.