Min Cost Flow Slotting › Visualizing Minimum Cost flow
Michael BrenndoerferSeptember 1, 20257 min read
Machine Learning from ScratchAll chapters Part 9 of 9Optimization
Min Cost Flow Slotting › Visualizing Minimum Cost flowOne section · Sections in this chapter3 / 8 ↓
Sections in this chapter8
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
Let's create visualizations to understand how the Minimum Cost flow problem works in practice. We'll start by setting up the necessary libraries and creating a simple example.
Out[4]:
Visualization
Now let's solve this network using OR-Tools and visualize the optimal flow:
In[5]:
Codefrom ortools.graph.python import min_cost_flow
def solve_mcf_ortools(G):
"""solve the MCF problem using OR-Tools"""
# Create the solver
solver = min_cost_flow.SimpleMinCostFlow()
# Extract network data
start_nodes = []
end_nodes = []
capacities = []
unit_costs = []
supplies = []
# Add edges
for u, v in G.edges():
start_nodes.append(u)
end_nodes.append(v)
capacities.append(G[u][v]["capacity"])
unit_costs.append(G[u][v]["cost"])
# Add supplies
for node in G.nodes():
supplies.append(G.nodes[node]["supply"])
# Add arcs to the solver
for i in range(len(start_nodes)):
solver.add_arc_with_capacity_and_unit_cost(
start_nodes[i], end_nodes[i], capacities[i], unit_costs[i]
)
# Add node supplies
for i in range(len(supplies)):
solver.set_node_supply(i, supplies[i])
# solve
status = solver.solve()
if status == solver.OPTIMAL:
print(f"Minimum cost: {solver.optimal_cost()}")
print("\nOptimal flow:")
print("Arc flow / capacity Cost")
flows = {}
for i in range(solver.num_arcs()):
tail = solver.tail(i)
head = solver.head(i)
flow = solver.flow(i)
capacity = solver.capacity(i)
cost = solver.flow(i) * solver.unit_cost(i)
flows[(tail, head)] = flow
print(f"{tail} -> {head} {flow} / {capacity} {cost}")
return flows, solver.optimal_cost()
else:
print("No optimal solution found")
return None, None
# solve the problem
flows, total_cost = solve_mcf_ortools(G)Out[5]:
ConsoleMinimum cost: 60 Optimal flow: Arc flow / capacity Cost 0 -> 1 10 / 15 40 0 -> 2 0 / 8 0 1 -> 3 10 / 10 20 1 -> 2 0 / 5 0 2 -> 3 0 / 12 0
Out[6]:
Visualization