To solve a max flow problem, I have to define a function that takes as input the name of a file where there are written the arcs and their capacities, I have to build and solve the model, print variables and construct a graph with only the arcs that at the end have value different from zero. This is the code I'm trying to run
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)
So that at the end I can call the function where I put my text file
maxflow ("edge_list_max_flow2.txt")
and have for this data all the things written in the code.
Hope someone of you will help me! Thank you in advance.
You only need to change one line, use
G = nx.read_edgelist(filename,nodetype=int,create_using=nx.DiGraph())
instead of
G = nx.read_edgelist("filename",nodetype=int,create_using=nx.DiGraph())
Currently you are using the literal "filename"
instead of using the variable filename
.