'Transportation problem on python using networkx when total node demand is not zero
There are 6 nodes with negative and positive demands. I need to calculate the best variant to satisfy as much consumers as I can. I'm trying to solve it using networkx python library:
import networkx as nx
G = nx.DiGraph()
G.add_node("1", demand=15)
G.add_node("2", demand=25)
G.add_node("3", demand=60)
G.add_node("4", demand=-55)
G.add_node("5", demand=-35)
G.add_node("6", demand=-40)
G.add_edge("1", "2", weight=2)
G.add_edge("1", "3", weight=1)
G.add_edge("1", "6", weight=3)
G.add_edge("2", "6", weight=4)
G.add_edge("2", "3", weight=5)
G.add_edge("3", "4", weight=3)
G.add_edge("4", "5", weight=6)
G.add_edge("5", "6", weight=2)
flowCost = nx.min_cost_flow_cost(G)
print(flowCost)
But as I understand the problem is that summary of my negative and positive demands is not zero and I get error:
networkx.exception.NetworkXUnfeasible: total node demand is not zero
So is there some solution for this problem? Maybe it's better to use some different library?
Solution 1:[1]
Try to add this code:
G.add_node("7", demand = 30)
G.add_edge("4", "7", weight = 7)
G.add_edge("5", "7", weight = 7)
G.add_edge("6", "7", weight = 7)
Solution 2:[2]
To make the network feasible, the total demand must be zero.
Here is the correct code:
import networkx as nx
G = nx.DiGraph()
G.add_node("1", demand=15)
G.add_node("2", demand=25)
G.add_node("3", demand=60)
G.add_node("4", demand=-45)
G.add_node("5", demand=-25)
G.add_node("6", demand=-30)
G.add_edge("1", "2", weight=2)
G.add_edge("1", "3", weight=1)
G.add_edge("1", "6", weight=3)
G.add_edge("2", "6", weight=4)
G.add_edge("2", "3", weight=5)
G.add_edge("3", "4", weight=3)
G.add_edge("4", "5", weight=6)
G.add_edge("5", "6", weight=2)
flowCost = nx.min_cost_flow_cost(G)
print(flowCost)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Elvis |
| Solution 2 | Mohammad Rahmani |

