Exemplo n.º 1
0
    def test_max_flow_min_cost(self):
        G = nx.DiGraph()
        G.add_edge('s', 'a', bandwidth=6)
        G.add_edge('s', 'c', bandwidth=10, cost=10)
        G.add_edge('a', 'b', cost=6)
        G.add_edge('b', 'd', bandwidth=8, cost=7)
        G.add_edge('c', 'd', cost=10)
        G.add_edge('d', 't', bandwidth=5, cost=5)
        soln = {'s': {'a': 5, 'c': 0},
                'a': {'b': 5},
                'b': {'d': 5},
                'c': {'d': 0},
                'd': {'t': 5},
                't': {}}
        flow = nx.max_flow_min_cost(G, 's', 't', capacity='bandwidth',
                                    weight='cost')
        assert_equal(flow, soln)
        assert_equal(nx.cost_of_flow(G, flow, weight='cost'), 90)

        G.add_edge('t', 's', cost=-100)
        flowCost, flow = nx.capacity_scaling(G, capacity='bandwidth',
                                             weight='cost')
        G.remove_edge('t', 's')
        assert_equal(flowCost, -410)
        assert_equal(flow['t']['s'], 5)
        del flow['t']['s']
        assert_equal(flow, soln)
        assert_equal(nx.cost_of_flow(G, flow, weight='cost'), 90)
Exemplo n.º 2
0
    def test_digraph1(self):
        # From Bradley, S. P., Hax, A. C. and Magnanti, T. L. Applied
        # Mathematical Programming. Addison-Wesley, 1977.
        G = nx.DiGraph()
        G.add_node(1, demand=-20)
        G.add_node(4, demand=5)
        G.add_node(5, demand=15)
        G.add_edges_from([(1, 2, {'capacity': 15, 'weight': 4}),
                          (1, 3, {'capacity': 8, 'weight': 4}),
                          (2, 3, {'weight': 2}),
                          (2, 4, {'capacity': 4, 'weight': 2}),
                          (2, 5, {'capacity': 10, 'weight': 6}),
                          (3, 4, {'capacity': 15, 'weight': 1}),
                          (3, 5, {'capacity': 5, 'weight': 3}),
                          (4, 5, {'weight': 2}),
                          (5, 3, {'capacity': 4, 'weight': 1})])
        flowCost, H = nx.network_simplex(G)
        soln = {1: {2: 12, 3: 8},
                2: {3: 8, 4: 4, 5: 0},
                3: {4: 11, 5: 5},
                4: {5: 10},
                5: {3: 0}}
        assert_equal(flowCost, 150)
        assert_equal(nx.min_cost_flow_cost(G), 150)
        assert_equal(H, soln)
        assert_equal(nx.min_cost_flow(G), soln)
        assert_equal(nx.cost_of_flow(G, H), 150)

        flowCost, H = nx.capacity_scaling(G)
        assert_equal(flowCost, 150)
        assert_equal(H, soln)
        assert_equal(nx.cost_of_flow(G, H), 150)
Exemplo n.º 3
0
    def test_zero_capacity_edges(self):
        """Address issue raised in ticket #617 by arv."""
        G = nx.DiGraph()
        G.add_edges_from([(1, 2, {'capacity': 1, 'weight': 1}),
                          (1, 5, {'capacity': 1, 'weight': 1}),
                          (2, 3, {'capacity': 0, 'weight': 1}),
                          (2, 5, {'capacity': 1, 'weight': 1}),
                          (5, 3, {'capacity': 2, 'weight': 1}),
                          (5, 4, {'capacity': 0, 'weight': 1}),
                          (3, 4, {'capacity': 2, 'weight': 1})])
        G.nodes[1]['demand'] = -1
        G.nodes[2]['demand'] = -1
        G.nodes[4]['demand'] = 2

        flowCost, H = nx.network_simplex(G)
        soln = {1: {2: 0, 5: 1},
                2: {3: 0, 5: 1},
                3: {4: 2},
                4: {},
                5: {3: 2, 4: 0}}
        assert_equal(flowCost, 6)
        assert_equal(nx.min_cost_flow_cost(G), 6)
        assert_equal(H, soln)
        assert_equal(nx.min_cost_flow(G), soln)
        assert_equal(nx.cost_of_flow(G, H), 6)

        flowCost, H = nx.capacity_scaling(G)
        assert_equal(flowCost, 6)
        assert_equal(H, soln)
        assert_equal(nx.cost_of_flow(G, H), 6)
Exemplo n.º 4
0
    def test_digon(self):
        """Check if digons are handled properly. Taken from ticket
        #618 by arv."""
        nodes = [(1, {}),
                 (2, {'demand': -4}),
                 (3, {'demand': 4}),
                 ]
        edges = [(1, 2, {'capacity': 3, 'weight': 600000}),
                 (2, 1, {'capacity': 2, 'weight': 0}),
                 (2, 3, {'capacity': 5, 'weight': 714285}),
                 (3, 2, {'capacity': 2, 'weight': 0}),
                 ]
        G = nx.DiGraph(edges)
        G.add_nodes_from(nodes)
        flowCost, H = nx.network_simplex(G)
        soln = {1: {2: 0},
                2: {1: 0, 3: 4},
                3: {2: 0}}
        assert_equal(flowCost, 2857140)
        assert_equal(nx.min_cost_flow_cost(G), 2857140)
        assert_equal(H, soln)
        assert_equal(nx.min_cost_flow(G), soln)
        assert_equal(nx.cost_of_flow(G, H), 2857140)

        flowCost, H = nx.capacity_scaling(G)
        assert_equal(flowCost, 2857140)
        assert_equal(H, soln)
        assert_equal(nx.cost_of_flow(G, H), 2857140)
Exemplo n.º 5
0
 def test_large(self):
     fname = os.path.join(os.path.dirname(__file__), 'netgen-2.gpickle.bz2')
     G = nx.read_gpickle(fname)
     flowCost, flowDict = nx.network_simplex(G)
     assert_equal(6749969302, flowCost)
     assert_equal(6749969302, nx.cost_of_flow(G, flowDict))
     flowCost, flowDict = nx.capacity_scaling(G)
     assert_equal(6749969302, flowCost)
     assert_equal(6749969302, nx.cost_of_flow(G, flowDict))
def optimal_procurement(supply_cost, x_max, demand_quantity, holding_cost, backlogging_cost, xh_0=0, xh_n=0):
    """Calculates optimal procurement planning.

    Arguments:
    supply_cost -- Supply cost at each time period
    x_max -- Maximum supply quantity at each time period.
    demand_quantity -- Demand quantity at each time period
    holding_cost -- Holding cost.
    backlogging_cost -- Backlogging cost.
    xh_0 -- Initial inventory.
    x_hn -- Final inventory target.
    """

    G = nx.DiGraph()
    n = len(supply_cost)
    for t in range(n):
        G.add_edge("source", t, {'capacity': x_max[t], 'weight': supply_cost[t]})
        G.add_edge(t, "sink", {'capacity': demand_quantity[t], 'weight': 0})
        G.add_edge(t, t + 1, {'capacity': np.inf, 'weight': holding_cost})
        G.add_edge(t + 1, t, {'capacity': np.inf, 'weight': backlogging_cost})

    G.add_edge("source", -1, {'capacity': xh_0, 'weight': 0})
    G.add_edge(-1, 0, {'capacity': xh_0, 'weight': 0})

    G.add_edge(n, "sink", {'capacity': xh_n, 'weight': 0})

    mincost_flow = nx.max_flow_min_cost(G, "source", "sink")
    cost = nx.cost_of_flow(G, mincost_flow)
    return cost, np.array([mincost_flow['source'][t] for t in range(n)])
Exemplo n.º 7
0
    def test_transshipment(self):
        G = nx.DiGraph()
        G.add_node('a', demand=1)
        G.add_node('b', demand=-2)
        G.add_node('c', demand=-2)
        G.add_node('d', demand=3)
        G.add_node('e', demand=-4)
        G.add_node('f', demand=-4)
        G.add_node('g', demand=3)
        G.add_node('h', demand=2)
        G.add_node('r', demand=3)
        G.add_edge('a', 'c', weight=3)
        G.add_edge('r', 'a', weight=2)
        G.add_edge('b', 'a', weight=9)
        G.add_edge('r', 'c', weight=0)
        G.add_edge('b', 'r', weight=-6)
        G.add_edge('c', 'd', weight=5)
        G.add_edge('e', 'r', weight=4)
        G.add_edge('e', 'f', weight=3)
        G.add_edge('h', 'b', weight=4)
        G.add_edge('f', 'd', weight=7)
        G.add_edge('f', 'h', weight=12)
        G.add_edge('g', 'd', weight=12)
        G.add_edge('f', 'g', weight=-1)
        G.add_edge('h', 'g', weight=-10)
        flowCost, H = nx.network_simplex(G)
        soln = {'a': {'c': 0},
                'b': {'a': 0, 'r': 2},
                'c': {'d': 3},
                'd': {},
                'e': {'r': 3, 'f': 1},
                'f': {'d': 0, 'g': 3, 'h': 2},
                'g': {'d': 0},
                'h': {'b': 0, 'g': 0},
                'r': {'a': 1, 'c': 1}}
        assert_equal(flowCost, 41)
        assert_equal(nx.min_cost_flow_cost(G), 41)
        assert_equal(H, soln)
        assert_equal(nx.min_cost_flow(G), soln)
        assert_equal(nx.cost_of_flow(G, H), 41)

        flowCost, H = nx.capacity_scaling(G)
        assert_equal(flowCost, 41)
        assert_equal(nx.cost_of_flow(G, H), 41)
        assert_equal(H, soln)
Exemplo n.º 8
0
    def test_digraph3(self):
        """Combinatorial Optimization: Algorithms and Complexity,
        Papadimitriou Steiglitz at page 140 has an example, 7.1, but that
        admits multiple solutions, so I alter it a bit. From ticket #430
        by mfrasca."""

        G = nx.DiGraph()
        G.add_edge('s', 'a')
        G['s']['a'].update({0: 2, 1: 4})
        G.add_edge('s', 'b')
        G['s']['b'].update({0: 2, 1: 1})
        G.add_edge('a', 'b')
        G['a']['b'].update({0: 5, 1: 2})
        G.add_edge('a', 't')
        G['a']['t'].update({0: 1, 1: 5})
        G.add_edge('b', 'a')
        G['b']['a'].update({0: 1, 1: 3})
        G.add_edge('b', 't')
        G['b']['t'].update({0: 3, 1: 2})

        "PS.ex.7.1: testing main function"
        sol = nx.max_flow_min_cost(G, 's', 't', capacity=0, weight=1)
        flow = sum(v for v in sol['s'].values())
        assert_equal(4, flow)
        assert_equal(23, nx.cost_of_flow(G, sol, weight=1))
        assert_equal(sol['s'], {'a': 2, 'b': 2})
        assert_equal(sol['a'], {'b': 1, 't': 1})
        assert_equal(sol['b'], {'a': 0, 't': 3})
        assert_equal(sol['t'], {})

        G.add_edge('t', 's')
        G['t']['s'].update({1: -100})
        flowCost, sol = nx.capacity_scaling(G, capacity=0, weight=1)
        G.remove_edge('t', 's')
        flow = sum(v for v in sol['s'].values())
        assert_equal(4, flow)
        assert_equal(sol['t']['s'], 4)
        assert_equal(flowCost, -377)
        del sol['t']['s']
        assert_equal(sol['s'], {'a': 2, 'b': 2})
        assert_equal(sol['a'], {'b': 1, 't': 1})
        assert_equal(sol['b'], {'a': 0, 't': 3})
        assert_equal(sol['t'], {})
        assert_equal(nx.cost_of_flow(G, sol, weight=1), 23)
Exemplo n.º 9
0
def pr345():
    G = nx.DiGraph()
    n = len(data)
    for i in range(n): 
        G.add_edge('s', 'A'+str(i), weight=0, capacity=1)
        G.add_edge('B'+str(i), 't', weight=0, capacity=1)
    for i in range(n):
        for j in range(n):
            G.add_edge('A'+str(i), 'B'+str(j), weight=-data[i][j], capacity=1)
    flow = nx.max_flow_min_cost(G, 's', 't')
    return -nx.cost_of_flow(G, flow)
Exemplo n.º 10
0
    def test_finite_capacity_neg_digon(self):
        """The digon should receive the maximum amount of flow it can handle.
        Taken from ticket #749 by @chuongdo."""
        G = nx.DiGraph()
        G.add_edge('a', 'b', capacity=1, weight=-1)
        G.add_edge('b', 'a', capacity=1, weight=-1)
        min_cost = -2
        assert_equal(nx.min_cost_flow_cost(G), min_cost)

        flowCost, H = nx.capacity_scaling(G)
        assert_equal(flowCost, -2)
        assert_equal(H, {'a': {'b': 1}, 'b': {'a': 1}})
        assert_equal(nx.cost_of_flow(G, H), -2)
Exemplo n.º 11
0
    def test_simple_digraph(self):
        G = nx.DiGraph()
        G.add_node('a', demand=-5)
        G.add_node('d', demand=5)
        G.add_edge('a', 'b', weight=3, capacity=4)
        G.add_edge('a', 'c', weight=6, capacity=10)
        G.add_edge('b', 'd', weight=1, capacity=9)
        G.add_edge('c', 'd', weight=2, capacity=5)
        flowCost, H = nx.network_simplex(G)
        soln = {'a': {'b': 4, 'c': 1},
                'b': {'d': 4},
                'c': {'d': 1},
                'd': {}}
        assert_equal(flowCost, 24)
        assert_equal(nx.min_cost_flow_cost(G), 24)
        assert_equal(H, soln)
        assert_equal(nx.min_cost_flow(G), soln)
        assert_equal(nx.cost_of_flow(G, H), 24)

        flowCost, H = nx.capacity_scaling(G)
        assert_equal(flowCost, 24)
        assert_equal(nx.cost_of_flow(G, H), 24)
        assert_equal(H, soln)
Exemplo n.º 12
0
    def test_simple_digraph(self):
        G = nx.DiGraph()
        G.add_node('a', demand=-5)
        G.add_node('d', demand=5)
        G.add_edge('a', 'b', weight=3, capacity=4)
        G.add_edge('a', 'c', weight=6, capacity=10)
        G.add_edge('b', 'd', weight=1, capacity=9)
        G.add_edge('c', 'd', weight=2, capacity=5)
        flowCost, H = nx.network_simplex(G)
        soln = {'a': {'b': 4, 'c': 1},
                'b': {'d': 4},
                'c': {'d': 1},
                'd': {}}
        assert flowCost == 24
        assert nx.min_cost_flow_cost(G) == 24
        assert H == soln
        assert nx.min_cost_flow(G) == soln
        assert nx.cost_of_flow(G, H) == 24

        flowCost, H = nx.capacity_scaling(G)
        assert flowCost == 24
        assert nx.cost_of_flow(G, H) == 24
        assert H == soln
Exemplo n.º 13
0
    def test_digraph3(self):
        """Combinatorial Optimization: Algorithms and Complexity,
        Papadimitriou Steiglitz at page 140 has an example, 7.1, but that
        admits multiple solutions, so I alter it a bit. From ticket #430
        by mfrasca."""

        G = nx.DiGraph()
        G.add_edge('s', 'a', {0: 2, 1: 4})
        G.add_edge('s', 'b', {0: 2, 1: 1})
        G.add_edge('a', 'b', {0: 5, 1: 2})
        G.add_edge('a', 't', {0: 1, 1: 5})
        G.add_edge('b', 'a', {0: 1, 1: 3})
        G.add_edge('b', 't', {0: 3, 1: 2})

        "PS.ex.7.1: testing main function"
        sol = nx.max_flow_min_cost(G, 's', 't', capacity=0, weight=1)
        flow = sum(v for v in sol['s'].values())
        assert_equal(4, flow)
        assert_equal(23, nx.cost_of_flow(G, sol, weight=1))
        assert_equal(sol['s'], {'a': 2, 'b': 2})
        assert_equal(sol['a'], {'b': 1, 't': 1})
        assert_equal(sol['b'], {'a': 0, 't': 3})
        assert_equal(sol['t'], {})

        G.add_edge('t', 's', {1: -100})
        flowCost, sol = nx.capacity_scaling(G, capacity=0, weight=1)
        G.remove_edge('t', 's')
        flow = sum(v for v in sol['s'].values())
        assert_equal(4, flow)
        assert_equal(sol['t']['s'], 4)
        assert_equal(flowCost, -377)
        del sol['t']['s']
        assert_equal(sol['s'], {'a': 2, 'b': 2})
        assert_equal(sol['a'], {'b': 1, 't': 1})
        assert_equal(sol['b'], {'a': 0, 't': 3})
        assert_equal(sol['t'], {})
        assert_equal(nx.cost_of_flow(G, sol, weight=1), 23)
Exemplo n.º 14
0
def tst():
    G = nx.DiGraph()
    edges = [(0, 1, {'capacity': 5, 'weight': 1}),
            (0, 2, {'capacity': 3, 'weight': 0.5}),
            (0, 3, {'capacity': 1, 'weight': 1}),
            (4, 6, {'capacity': 4, 'weight': 1}),
            (5, 6, {'capacity': 5, 'weight': 1}),
            (1, 4, {'capacity': np.inf, 'weight': 1}),
            (2, 4, {'capacity': np.inf, 'weight': 1}),
            (3, 5, {'capacity': np.inf, 'weight': 1})
        ]
    G.add_edges_from(edges)
    mincostflow = nx.max_flow_min_cost(G,0,6)
    mincost=nx.cost_of_flow(G,mincostflow)
    max_flow=nx.maximum_flow_value(G, 0, 6)
Exemplo n.º 15
0
    def test_digon(self):
        """Check if digons are handled properly. Taken from ticket
        #618 by arv."""
        nodes = [(1, {}), (2, {"demand": -4}), (3, {"demand": 4})]
        edges = [
            (1, 2, {"capacity": 3, "weight": 600000}),
            (2, 1, {"capacity": 2, "weight": 0}),
            (2, 3, {"capacity": 5, "weight": 714285}),
            (3, 2, {"capacity": 2, "weight": 0}),
        ]
        G = nx.DiGraph(edges)
        G.add_nodes_from(nodes)
        flowCost, H = nx.network_simplex(G)
        soln = {1: {2: 0}, 2: {1: 0, 3: 4}, 3: {2: 0}}
        assert flowCost == 2857140
        assert nx.min_cost_flow_cost(G) == 2857140
        assert H == soln
        assert nx.min_cost_flow(G) == soln
        assert nx.cost_of_flow(G, H) == 2857140

        flowCost, H = nx.capacity_scaling(G)
        assert flowCost == 2857140
        assert H == soln
        assert nx.cost_of_flow(G, H) == 2857140
Exemplo n.º 16
0
 def test_simple_digraph(self):
     G = nx.DiGraph()
     G.add_node('a', demand=-5)
     G.add_node('d', demand=5)
     G.add_edge('a', 'b', weight=3, capacity=4)
     G.add_edge('a', 'c', weight=6, capacity=10)
     G.add_edge('b', 'd', weight=1, capacity=9)
     G.add_edge('c', 'd', weight=2, capacity=5)
     flowCost, H = nx.network_simplex(G)
     soln = {'a': {'b': 4, 'c': 1}, 'b': {'d': 4}, 'c': {'d': 1}, 'd': {}}
     assert_equal(flowCost, 24)
     assert_equal(nx.min_cost_flow_cost(G), 24)
     assert_equal(H, soln)
     assert_equal(nx.min_cost_flow(G), soln)
     assert_equal(nx.cost_of_flow(G, H), 24)
Exemplo n.º 17
0
 def test_max_flow_min_cost(self):
     G = nx.DiGraph()
     G.add_edge('s', 'a', bandwidth = 6)
     G.add_edge('s', 'c', bandwidth = 10, cost = 10)
     G.add_edge('a', 'b', cost = 6)
     G.add_edge('b', 'd', bandwidth = 8, cost = 7)
     G.add_edge('c', 'd', cost = 10)
     G.add_edge('d', 't', bandwidth = 5, cost = 5)
     soln = {'s': {'a': 5, 'c': 0},
             'a': {'b': 5},
             'b': {'d': 5},
             'c': {'d': 0},
             'd': {'t': 5},
             't': {}}
     flow = nx.max_flow_min_cost(G, 's', 't', capacity = 'bandwidth',
                                 weight = 'cost')
     assert_equal(flow, soln)
     assert_equal(nx.cost_of_flow(G, flow, weight = 'cost'), 90)
Exemplo n.º 18
0
 def test_max_flow_min_cost(self):
     G = nx.DiGraph()
     G.add_edge('s', 'a', bandwidth = 6)
     G.add_edge('s', 'c', bandwidth = 10, cost = 10)
     G.add_edge('a', 'b', cost = 6)
     G.add_edge('b', 'd', bandwidth = 8, cost = 7)
     G.add_edge('c', 'd', cost = 10)
     G.add_edge('d', 't', bandwidth = 5, cost = 5)
     soln = {'s': {'a': 5, 'c': 0},
             'a': {'b': 5},
             'b': {'d': 5},
             'c': {'d': 0},
             'd': {'t': 5},
             't': {}}
     flow = nx.max_flow_min_cost(G, 's', 't', capacity = 'bandwidth',
                                 weight = 'cost')
     assert_equal(flow, soln)
     assert_equal(nx.cost_of_flow(G, flow, weight = 'cost'), 90)
Exemplo n.º 19
0
def buildGraph(inputData):
    """

    :param inputData:
    """
    sellerArray, customerArray, costMatrix = inputData
    G = nx.Graph()
    for i in range(1, len(sellerArray) + 1):
        for j in range(1, 1 + len(customerArray)):
            G.add_edge(i, j + len(sellerArray), capacity=inf, weight=int(costMatrix[i - 1][j - 1]))
        G.add_edge(0, i, {'capacity': sellerArray[i - 1], 'weight': int(0)})
    sum = len(sellerArray) + len(customerArray) + 1
    for j in range(len(customerArray)):
        G.add_edge(len(sellerArray) + j + 1, sum, capacity=customerArray[j - 1], weight=0)
        #minCostFlow = nx.max_flow_min_cost(G)
    c1 = 25000 / len(sellerArray)
    c2 = 25000 / len(customerArray)
    pos = {0: (15000.0, -12000.0), len(sellerArray) + len(customerArray) + 1: (15000.0, 12000.0)}
    for i in range(0, len(sellerArray)):
        pos[i + 1] = (i * c1, -7500.0)
    for n in range(len(sellerArray), len(sellerArray) + len(customerArray)):
        pos[n + 1] = ((n - len(sellerArray)) * c2, 7500.0)
        colors = [d['weight'] for (u, v, d) in G.edges(data=True)]
    flow = nx.max_flow_min_cost(G, 0, len(sellerArray) + len(customerArray) + 1)
    costOfFlow = nx.cost_of_flow(G, flow)
    print("Cost: " + str(costOfFlow))
    newEdgeList = []
    for k, v in flow.items():
        for i, j in v.items():
            if G.has_edge(k, i) and j > 0:
                newEdgeList.append([k, i])

    edge_labels = {}
    for u, v, d in G.edges(data=True):
        if flow[u][v] > 0:
            edge_labels[(u, v,)] = str(flow[u][v]) + "/" + str(d['weight'])
    print(costOfFlow, flow)
    nx.draw_networkx(G, pos, edgelist=newEdgeList, node_shape='o', node_color='#A0CBE2', edge_labels=edge_labels,
                     width=1.5, alpha=1,
                     edge_cmap=P.cm.ma,
                     with_labels=True)
    nx.draw_networkx_edge_labels(G, pos, edge_labels, label_pos=0.7, font_size=8)
    P.show()
Exemplo n.º 20
0
 def set_flow(self):
     try:
         self.flow = nx.max_flow_min_cost(self, self.source, self.sink)
         self.flow_cost = nx.cost_of_flow(self, self.flow)
         self.max_flow = nx.maximum_flow(self, self.source, self.sink)[0]
     except nx.NetworkXUnfeasible:
         print 'Allocation satisfying the lower bounds is not possible.'
         print 'Try reducing lower bounds.'
         sys.exit(1)
     except nx.NetworkXError:
         print "The input graph is not directed or not connected."
         print "Please check the data:"
         print "e.g. if all the choices on the level 1 list are" \
               " included in the level 2 list and same for levels 2, 3."
         sys.exit(1)
     except nx.NetworkXUnbounded:
         print "Allocation is not possible because some upper capacity" \
               "bounds at level 1 have not been set up. Please check " \
               "the data."
         sys.exit(1)
Exemplo n.º 21
0
    def test_digraph2(self):
        # Example from ticket #430 from mfrasca. Original source:
        # http://www.cs.princeton.edu/courses/archive/spr03/cs226/lectures/mincost.4up.pdf, slide 11.
        G = nx.DiGraph()
        G.add_edge("s", 1, capacity=12)
        G.add_edge("s", 2, capacity=6)
        G.add_edge("s", 3, capacity=14)
        G.add_edge(1, 2, capacity=11, weight=4)
        G.add_edge(2, 3, capacity=9, weight=6)
        G.add_edge(1, 4, capacity=5, weight=5)
        G.add_edge(1, 5, capacity=2, weight=12)
        G.add_edge(2, 5, capacity=4, weight=4)
        G.add_edge(2, 6, capacity=2, weight=6)
        G.add_edge(3, 6, capacity=31, weight=3)
        G.add_edge(4, 5, capacity=18, weight=4)
        G.add_edge(5, 6, capacity=9, weight=5)
        G.add_edge(4, "t", capacity=3)
        G.add_edge(5, "t", capacity=7)
        G.add_edge(6, "t", capacity=22)
        flow = nx.max_flow_min_cost(G, "s", "t")
        soln = {
            1: {2: 6, 4: 5, 5: 1},
            2: {3: 6, 5: 4, 6: 2},
            3: {6: 20},
            4: {5: 2, "t": 3},
            5: {6: 0, "t": 7},
            6: {"t": 22},
            "s": {1: 12, 2: 6, 3: 14},
            "t": {},
        }
        assert flow == soln

        G.add_edge("t", "s", weight=-100)
        flowCost, flow = nx.capacity_scaling(G)
        G.remove_edge("t", "s")
        assert flow["t"]["s"] == 32
        assert flowCost == -3007
        del flow["t"]["s"]
        assert flow == soln
        assert nx.cost_of_flow(G, flow) == 193
Exemplo n.º 22
0
 def test_transshipment(self):
     G = nx.DiGraph()
     G.add_node('a', demand = 1)
     G.add_node('b', demand = -2)
     G.add_node('c', demand = -2)
     G.add_node('d', demand = 3)
     G.add_node('e', demand = -4)
     G.add_node('f', demand = -4)
     G.add_node('g', demand = 3)
     G.add_node('h', demand = 2)
     G.add_node('r', demand = 3)
     G.add_edge('a', 'c', weight = 3)
     G.add_edge('r', 'a', weight = 2)
     G.add_edge('b', 'a', weight = 9)
     G.add_edge('r', 'c', weight = 0)
     G.add_edge('b', 'r', weight = -6)
     G.add_edge('c', 'd', weight = 5)
     G.add_edge('e', 'r', weight = 4)
     G.add_edge('e', 'f', weight = 3)
     G.add_edge('h', 'b', weight = 4)
     G.add_edge('f', 'd', weight = 7)
     G.add_edge('f', 'h', weight = 12)
     G.add_edge('g', 'd', weight = 12)
     G.add_edge('f', 'g', weight = -1)
     G.add_edge('h', 'g', weight = -10)
     flowCost, H = nx.network_simplex(G)
     soln = {'a': {'c': 0},
             'b': {'a': 0, 'r': 2},
             'c': {'d': 3},
             'd': {},
             'e': {'r': 3, 'f': 1},
             'f': {'d': 0, 'g': 3, 'h': 2},
             'g': {'d': 0},
             'h': {'b': 0, 'g': 0},
             'r': {'a': 1, 'c': 1}}
     assert_equal(flowCost, 41)
     assert_equal(nx.min_cost_flow_cost(G), 41)
     assert_equal(H, soln)
     assert_equal(nx.min_cost_flow(G), soln)
     assert_equal(nx.cost_of_flow(G, H), 41)
Exemplo n.º 23
0
 def test_digon(self):
     """Check if digons are handled properly. Taken from ticket
     #618 by arv."""
     nodes = [
         (1, {}),
         (2, {
             'demand': -4
         }),
         (3, {
             'demand': 4
         }),
     ]
     edges = [
         (1, 2, {
             'capacity': 3,
             'weight': 600000
         }),
         (2, 1, {
             'capacity': 2,
             'weight': 0
         }),
         (2, 3, {
             'capacity': 5,
             'weight': 714285
         }),
         (3, 2, {
             'capacity': 2,
             'weight': 0
         }),
     ]
     G = nx.DiGraph(edges)
     G.add_nodes_from(nodes)
     flowCost, H = nx.network_simplex(G)
     soln = {1: {2: 0}, 2: {1: 0, 3: 4}, 3: {2: 0}}
     assert_equal(flowCost, 2857140)
     assert_equal(nx.min_cost_flow_cost(G), 2857140)
     assert_equal(H, soln)
     assert_equal(nx.min_cost_flow(G), soln)
     assert_equal(nx.cost_of_flow(G, H), 2857140)
def optimal_procurement(supply_cost,
                        x_max,
                        demand_quantity,
                        holding_cost,
                        backlogging_cost,
                        xh_0=0,
                        xh_n=0):
    """Calculates optimal procurement planning.

    Arguments:
    supply_cost -- Supply cost at each time period
    x_max -- Maximum supply quantity at each time period.
    demand_quantity -- Demand quantity at each time period
    holding_cost -- Holding cost.
    backlogging_cost -- Backlogging cost.
    xh_0 -- Initial inventory.
    x_hn -- Final inventory target.
    """

    G = nx.DiGraph()
    n = len(supply_cost)
    for t in range(n):
        G.add_edge("source", t, {
            'capacity': x_max[t],
            'weight': supply_cost[t]
        })
        G.add_edge(t, "sink", {'capacity': demand_quantity[t], 'weight': 0})
        G.add_edge(t, t + 1, {'capacity': np.inf, 'weight': holding_cost})
        G.add_edge(t + 1, t, {'capacity': np.inf, 'weight': backlogging_cost})

    G.add_edge("source", -1, {'capacity': xh_0, 'weight': 0})
    G.add_edge(-1, 0, {'capacity': xh_0, 'weight': 0})

    G.add_edge(n, "sink", {'capacity': xh_n, 'weight': 0})

    mincost_flow = nx.max_flow_min_cost(G, "source", "sink")
    cost = nx.cost_of_flow(G, mincost_flow)
    return cost, np.array([mincost_flow['source'][t] for t in range(n)])
Exemplo n.º 25
0
    def test_digraph2(self):
        # Example from ticket #430 from mfrasca. Original source:
        # http://www.cs.princeton.edu/courses/archive/spr03/cs226/lectures/mincost.4up.pdf, slide 11.
        G = nx.DiGraph()
        G.add_edge('s', 1, capacity=12)
        G.add_edge('s', 2, capacity=6)
        G.add_edge('s', 3, capacity=14)
        G.add_edge(1, 2, capacity=11, weight=4)
        G.add_edge(2, 3, capacity=9, weight=6)
        G.add_edge(1, 4, capacity=5, weight=5)
        G.add_edge(1, 5, capacity=2, weight=12)
        G.add_edge(2, 5, capacity=4, weight=4)
        G.add_edge(2, 6, capacity=2, weight=6)
        G.add_edge(3, 6, capacity=31, weight=3)
        G.add_edge(4, 5, capacity=18, weight=4)
        G.add_edge(5, 6, capacity=9, weight=5)
        G.add_edge(4, 't', capacity=3)
        G.add_edge(5, 't', capacity=7)
        G.add_edge(6, 't', capacity=22)
        flow = nx.max_flow_min_cost(G, 's', 't')
        soln = {1: {2: 6, 4: 5, 5: 1},
                2: {3: 6, 5: 4, 6: 2},
                3: {6: 20},
                4: {5: 2, 't': 3},
                5: {6: 0, 't': 7},
                6: {'t': 22},
                's': {1: 12, 2: 6, 3: 14},
                't': {}}
        assert_equal(flow, soln)

        G.add_edge('t', 's', weight=-100)
        flowCost, flow = nx.capacity_scaling(G)
        G.remove_edge('t', 's')
        assert_equal(flow['t']['s'], 32)
        assert_equal(flowCost, -3007)
        del flow['t']['s']
        assert_equal(flow, soln)
        assert_equal(nx.cost_of_flow(G, flow), 193)
Exemplo n.º 26
0
    def test_digraph2(self):
        # Example from ticket #430 from mfrasca. Original source:
        # http://www.cs.princeton.edu/courses/archive/spr03/cs226/lectures/mincost.4up.pdf, slide 11.
        G = nx.DiGraph()
        G.add_edge('s', 1, capacity=12)
        G.add_edge('s', 2, capacity=6)
        G.add_edge('s', 3, capacity=14)
        G.add_edge(1, 2, capacity=11, weight=4)
        G.add_edge(2, 3, capacity=9, weight=6)
        G.add_edge(1, 4, capacity=5, weight=5)
        G.add_edge(1, 5, capacity=2, weight=12)
        G.add_edge(2, 5, capacity=4, weight=4)
        G.add_edge(2, 6, capacity=2, weight=6)
        G.add_edge(3, 6, capacity=31, weight=3)
        G.add_edge(4, 5, capacity=18, weight=4)
        G.add_edge(5, 6, capacity=9, weight=5)
        G.add_edge(4, 't', capacity=3)
        G.add_edge(5, 't', capacity=7)
        G.add_edge(6, 't', capacity=22)
        flow = nx.max_flow_min_cost(G, 's', 't')
        soln = {1: {2: 6, 4: 5, 5: 1},
                2: {3: 6, 5: 4, 6: 2},
                3: {6: 20},
                4: {5: 2, 't': 3},
                5: {6: 0, 't': 7},
                6: {'t': 22},
                's': {1: 12, 2: 6, 3: 14},
                't': {}}
        assert_equal(flow, soln)

        G.add_edge('t', 's', weight=-100)
        flowCost, flow = nx.capacity_scaling(G)
        G.remove_edge('t', 's')
        assert_equal(flow['t']['s'], 32)
        assert_equal(flowCost, -3007)
        del flow['t']['s']
        assert_equal(flow, soln)
        assert_equal(nx.cost_of_flow(G, flow), 193)
Exemplo n.º 27
0
def end2end_evaluation_matching(groundtruth, result):  # Jaccard Similarity
    n = len(groundtruth)
    m = len(result)
    G = nx.DiGraph()
    S = n + m
    T = n + m + 1
    C = 1e8
    for i in range(n):
        for j in range(m):
            s1 = groundtruth[i]
            s2 = result[j]
            s12 = set(s1) & set(s2)
            weight = len(s12) / (len(s1) + len(s2) - len(s12))
            weight = int(weight * C)
            if weight > 0:
                G.add_edge(i, n + j, capacity=1, weight=-weight)
    for i in range(n):
        G.add_edge(S, i, capacity=1, weight=0)
    for i in range(m):
        G.add_edge(i + n, T, capacity=1, weight=0)
    mincostFlow = nx.algorithms.max_flow_min_cost(G, S, T)
    mincost = nx.cost_of_flow(G, mincostFlow) / C
    return -mincost / m
Exemplo n.º 28
0
def main(departure_locations, meeting_options, departure_date):
    G = nx.DiGraph()
    G = create_graph(departure_locations, meeting_options, departure_date)
    flow_dict = nx.max_flow_min_cost(G, 'SOURCE', 'DEST')

    print(flow_dict)
    mincost = nx.cost_of_flow(G, flow_dict)
    print(mincost)

    pairs = []

    for u in flow_dict.keys():
        for v in (flow_dict[u]).keys():
            if int(flow_dict[u][v]) > 0:
                print(u, v, flow_dict[u][v])
                pairs.append((u, v))

    max_people = 0
    best_loc = ''
    for pair in pairs:
        if pair[1] == 'DEST':
            if int(flow_dict[pair[0]][pair[1]]) > max_people:
                best_loc = pair[0]
                max_people = int(flow_dict[pair[0]][pair[1]])

    print('Best location is ', best_loc)

    response = amadeus.reference_data.locations.get(subType='AIRPORT',
                                                    keyword=best_loc)
    city_name = response.data[0]["address"]["cityName"]
    state_name = response.data[0]["address"]["stateCode"]

    location = city_name + ', ' + state_name
    print('My location is ', location)

    return location, mincost
Exemplo n.º 29
0
import networkx as nx

sread = lambda: sys.stdin.read()

n, m = map(int, input().split())
A = sread().split()

G = nx.DiGraph()
supply = sum([x.count("o") for x in A])

sink = n * m + 1

G.add_node(sink, demand=supply)

for i in range(n):
    for j in range(m):
        if A[i][j] == '#':
            continue
        G.add_edge(i * m + j, sink, capacity=1)
        if A[i][j] == 'o':
            G.add_node(i * m + j, demand=-1)
        if i + 1 < n and A[i + 1][j] != '#':
            G.add_edge(i * m + j, (i + 1) * m + j, weight=-1)
        if j + 1 < m and A[i][j + 1] != '#':
            G.add_edge(i * m + j, i * m + j + 1, weight=-1)

flowDict = nx.min_cost_flow(G)
flowCost = nx.cost_of_flow(G, flowDict)

print(-flowCost)
Exemplo n.º 30
0
    }),
    ('B', '2', {
        'capacity': 7,
        'weight': 22
    }),
    ('B', '3', {
        'capacity': 7,
        'weight': 20
    }),
    ('1', 't', {
        'capacity': 4,
        'weight': 0
    }),
    ('2', 't', {
        'capacity': 5,
        'weight': 0
    }),
    ('3', 't', {
        'capacity': 6,
        'weight': 0
    }),
])
mincostFlow = nx.max_flow_min_cost(G, 's', 't')
print(mincostFlow)
mincost = nx.cost_of_flow(G, mincostFlow)
print('最小费用:', mincost)
mincostFlowValue = (sum(
    (mincostFlow[u]['t'] for u in G.predecessors('t'))) - sum(
        (mincostFlow['t'][v] for v in G.successors('t'))))
print('最大流:', mincostFlowValue)
Exemplo n.º 31
0
offset = 50
supply = n * k

G.add_node(source, demand=-supply)
G.add_node(sink, demand=supply)
G.add_edge(source, sink, capacity=supply, weight=0)

X = [i for i in range(n)]
Y = [i + offset for i in range(n)]

for x in X:
    G.add_edge(source, x, capacity=k, weight=0)
for y in Y:
    G.add_edge(y, sink, capacity=k, weight=0)
for x in X:
    for y in Y:
        G.add_edge(x, y, capacity=1, weight=-A[x][y - offset])

flow_dict = nx.min_cost_flow(G)
flow_cost = nx.cost_of_flow(G, flow_dict)

grid = [["." for _ in range(n)] for _ in range(n)]
for x in X:
    for y in Y:
        if flow_dict[x][y]:
            grid[x][y - offset] = "X"

print(-flow_cost)
for row in grid:
    print("".join(row))
Exemplo n.º 32
0
    def test_digraph1(self):
        # From Bradley, S. P., Hax, A. C. and Magnanti, T. L. Applied
        # Mathematical Programming. Addison-Wesley, 1977.
        G = nx.DiGraph()
        G.add_node(1, demand=-20)
        G.add_node(4, demand=5)
        G.add_node(5, demand=15)
        G.add_edges_from([(1, 2, {
            'capacity': 15,
            'weight': 4
        }), (1, 3, {
            'capacity': 8,
            'weight': 4
        }), (2, 3, {
            'weight': 2
        }), (2, 4, {
            'capacity': 4,
            'weight': 2
        }), (2, 5, {
            'capacity': 10,
            'weight': 6
        }), (3, 4, {
            'capacity': 15,
            'weight': 1
        }), (3, 5, {
            'capacity': 5,
            'weight': 3
        }), (4, 5, {
            'weight': 2
        }), (5, 3, {
            'capacity': 4,
            'weight': 1
        })])
        flowCost, H = nx.network_simplex(G)
        soln = {
            1: {
                2: 12,
                3: 8
            },
            2: {
                3: 8,
                4: 4,
                5: 0
            },
            3: {
                4: 11,
                5: 5
            },
            4: {
                5: 10
            },
            5: {
                3: 0
            }
        }
        assert_equal(flowCost, 150)
        assert_equal(nx.min_cost_flow_cost(G), 150)
        assert_equal(H, soln)
        assert_equal(nx.min_cost_flow(G), soln)
        assert_equal(nx.cost_of_flow(G, H), 150)

        flowCost, H = nx.capacity_scaling(G)
        assert_equal(flowCost, 150)
        assert_equal(H, soln)
        assert_equal(nx.cost_of_flow(G, H), 150)
    def test_transshipment(self):
        G = nx.DiGraph()
        G.add_node("a", demand=1)
        G.add_node("b", demand=-2)
        G.add_node("c", demand=-2)
        G.add_node("d", demand=3)
        G.add_node("e", demand=-4)
        G.add_node("f", demand=-4)
        G.add_node("g", demand=3)
        G.add_node("h", demand=2)
        G.add_node("r", demand=3)
        G.add_edge("a", "c", weight=3)
        G.add_edge("r", "a", weight=2)
        G.add_edge("b", "a", weight=9)
        G.add_edge("r", "c", weight=0)
        G.add_edge("b", "r", weight=-6)
        G.add_edge("c", "d", weight=5)
        G.add_edge("e", "r", weight=4)
        G.add_edge("e", "f", weight=3)
        G.add_edge("h", "b", weight=4)
        G.add_edge("f", "d", weight=7)
        G.add_edge("f", "h", weight=12)
        G.add_edge("g", "d", weight=12)
        G.add_edge("f", "g", weight=-1)
        G.add_edge("h", "g", weight=-10)
        flowCost, H = nx.network_simplex(G)
        soln = {
            "a": {
                "c": 0
            },
            "b": {
                "a": 0,
                "r": 2
            },
            "c": {
                "d": 3
            },
            "d": {},
            "e": {
                "r": 3,
                "f": 1
            },
            "f": {
                "d": 0,
                "g": 3,
                "h": 2
            },
            "g": {
                "d": 0
            },
            "h": {
                "b": 0,
                "g": 0
            },
            "r": {
                "a": 1,
                "c": 1
            },
        }
        assert flowCost == 41
        assert nx.min_cost_flow_cost(G) == 41
        assert H == soln
        assert nx.min_cost_flow(G) == soln
        assert nx.cost_of_flow(G, H) == 41

        flowCost, H = nx.capacity_scaling(G)
        assert flowCost == 41
        assert nx.cost_of_flow(G, H) == 41
        assert H == soln
Exemplo n.º 34
0
    def test_transshipment(self):
        G = nx.DiGraph()
        G.add_node('a', demand=1)
        G.add_node('b', demand=-2)
        G.add_node('c', demand=-2)
        G.add_node('d', demand=3)
        G.add_node('e', demand=-4)
        G.add_node('f', demand=-4)
        G.add_node('g', demand=3)
        G.add_node('h', demand=2)
        G.add_node('r', demand=3)
        G.add_edge('a', 'c', weight=3)
        G.add_edge('r', 'a', weight=2)
        G.add_edge('b', 'a', weight=9)
        G.add_edge('r', 'c', weight=0)
        G.add_edge('b', 'r', weight=-6)
        G.add_edge('c', 'd', weight=5)
        G.add_edge('e', 'r', weight=4)
        G.add_edge('e', 'f', weight=3)
        G.add_edge('h', 'b', weight=4)
        G.add_edge('f', 'd', weight=7)
        G.add_edge('f', 'h', weight=12)
        G.add_edge('g', 'd', weight=12)
        G.add_edge('f', 'g', weight=-1)
        G.add_edge('h', 'g', weight=-10)
        flowCost, H = nx.network_simplex(G)
        soln = {
            'a': {
                'c': 0
            },
            'b': {
                'a': 0,
                'r': 2
            },
            'c': {
                'd': 3
            },
            'd': {},
            'e': {
                'r': 3,
                'f': 1
            },
            'f': {
                'd': 0,
                'g': 3,
                'h': 2
            },
            'g': {
                'd': 0
            },
            'h': {
                'b': 0,
                'g': 0
            },
            'r': {
                'a': 1,
                'c': 1
            }
        }
        assert flowCost == 41
        assert nx.min_cost_flow_cost(G) == 41
        assert H == soln
        assert nx.min_cost_flow(G) == soln
        assert nx.cost_of_flow(G, H) == 41

        flowCost, H = nx.capacity_scaling(G)
        assert flowCost == 41
        assert nx.cost_of_flow(G, H) == 41
        assert H == soln
Exemplo n.º 35
0
def buildGraph(inputData):
    """

    :param inputData:
    """
    sellerArray, customerArray, costMatrix = inputData
    G = nx.Graph()
    for i in range(1, len(sellerArray) + 1):
        for j in range(1, 1 + len(customerArray)):
            G.add_edge(i,
                       j + len(sellerArray),
                       capacity=inf,
                       weight=int(costMatrix[i - 1][j - 1]))
        G.add_edge(0, i, {'capacity': sellerArray[i - 1], 'weight': int(0)})
    sum = len(sellerArray) + len(customerArray) + 1
    for j in range(len(customerArray)):
        G.add_edge(len(sellerArray) + j + 1,
                   sum,
                   capacity=customerArray[j - 1],
                   weight=0)
        #minCostFlow = nx.max_flow_min_cost(G)
    c1 = 25000 / len(sellerArray)
    c2 = 25000 / len(customerArray)
    pos = {
        0: (15000.0, -12000.0),
        len(sellerArray) + len(customerArray) + 1: (15000.0, 12000.0)
    }
    for i in range(0, len(sellerArray)):
        pos[i + 1] = (i * c1, -7500.0)
    for n in range(len(sellerArray), len(sellerArray) + len(customerArray)):
        pos[n + 1] = ((n - len(sellerArray)) * c2, 7500.0)
        colors = [d['weight'] for (u, v, d) in G.edges(data=True)]
    flow = nx.max_flow_min_cost(G, 0,
                                len(sellerArray) + len(customerArray) + 1)
    costOfFlow = nx.cost_of_flow(G, flow)
    print("Cost: " + str(costOfFlow))
    newEdgeList = []
    for k, v in flow.items():
        for i, j in v.items():
            if G.has_edge(k, i) and j > 0:
                newEdgeList.append([k, i])

    edge_labels = {}
    for u, v, d in G.edges(data=True):
        if flow[u][v] > 0:
            edge_labels[(
                u,
                v,
            )] = str(flow[u][v]) + "/" + str(d['weight'])
    print(costOfFlow, flow)
    nx.draw_networkx(G,
                     pos,
                     edgelist=newEdgeList,
                     node_shape='o',
                     node_color='#A0CBE2',
                     edge_labels=edge_labels,
                     width=1.5,
                     alpha=1,
                     edge_cmap=P.cm.ma,
                     with_labels=True)
    nx.draw_networkx_edge_labels(G,
                                 pos,
                                 edge_labels,
                                 label_pos=0.7,
                                 font_size=8)
    P.show()
Exemplo n.º 36
0
def min_cost_flow_error_metric(
    w_learned, w_gt, error_mat, use_int=True, significant_figures=5
):
    """Minimum Cost Flow error metric proposed by us
    
    Reference for min cost flow solver: https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.flow.min_cost_flow.html?highlight=min_cost_flow
    
    Args:
        w1 (1D float array): Weights of the learned models
        w2 (1D float array): Weights of the ground-truth models
        error_mat (2D float array: error_mat[i, j] is the error for the learned model i wrt
            true model j
        
        use_int (bool): If true, convert parameters to integers using significant_figures
            to avoid floating point rounding errors that can prevent convergence.
        significant_figures (int): The solver for the underlying min cost flow network
            problem may not converge for certain floating point weights and capacities.
            A solution is to convert weights and capacities to integers by scaling them
            by a large constant. This achieves convergence at the cost of some accuracy.
            This arguments sets the significant figures (the order of magnitude used for
            the integer scaling). Values too large may lead to float overflow.
    
    Returns:
        (float): The Minimum cost flow error metric
        (dict): Flow dictionary describing how the score is computed
    """

    scale = 10 ** significant_figures if use_int else 1.0
    error_mat = np.array(error_mat) * scale
    w_learned = np.array(w_learned) * scale
    w_gt = np.array(w_gt) * scale

    # Convert edge values to integers to ensure convergence
    if use_int:
        error_mat = error_mat.astype(np.uint64)
        w_learned = w_learned.astype(np.uint64)
        w_gt = w_gt.astype(np.uint64)

        # Compensate for rounding errors
        w_learned_sum, w_gt_sum = w_learned.sum(), w_gt.sum()
        if w_learned_sum < w_gt_sum:
            w_learned[0] += w_gt_sum - w_learned_sum
        else:
            w_gt[0] += w_learned_sum - w_gt_sum

    start_demand = -1.0 * w_learned.sum()
    terminal_demand = 1.0 * w_gt.sum()
    dense_edge_capacities = 1.0 * w_learned.sum()

    lnames = ["l%d" % (i) for i in range(len(w_learned))]
    gnames = ["g%d" % (j) for j in range(len(w_gt))]

    G = nx.DiGraph()
    G.add_node("s", demand=start_demand)
    G.add_node("t", demand=terminal_demand)

    for i in range(len(w_learned)):
        G.add_edge("s", lnames[i], weight=0, capacity=w_learned[i])
    for j in range(len(w_gt)):
        G.add_edge(gnames[j], "t", weight=0, capacity=w_gt[j])

    for i in range(len(w_learned)):
        for j in range(len(w_gt)):
            G.add_edge(
                lnames[i],
                gnames[j],
                weight=error_mat[i][j],
                capacity=dense_edge_capacities,
            )

    flow_dict = nx.min_cost_flow(G)

    if use_int:
        # Scale flowdict back to floating point
        for n2, d in flow_dict.items():
            for n2 in d:
                d[n2] /= scale

    cost = nx.cost_of_flow(G, flow_dict) / scale
    return cost, flow_dict
Exemplo n.º 37
0
def compute_optimal_transport(S,
                              T,
                              underlying_distance=ell2,
                              S_weights=None,
                              T_weights=None):
    """
    input:
    S and T should each be a list of numpy vectors, all unique (no repeats! If you want a point to appear more than once, just increase its weight)
    S_weights should be a list of positive integers of length len(S). Ditto T_weights. If you're not sure, just use the default. The weight is the "number of times" that a point appears, i.e. the mass of the distribution at that point.
    underlying_distance should be a function taking two numpy vectors and returning their distance -- this should be the underlying distance for the purposes of the EMD definition you'd like to use. If you're not sure, just use the default ell2
    Idea for making this more efficient: instead of applying the underlying_distance function to each pair by itself, run something like scipy.spatial.distance.pdist to compute them all at the same time. Might be more efficient.
    """
    dim = len(S[0])
    for v in S:
        assert len(v) == dim, "the input vectors are of varying sizes"
    for u in T:
        assert len(u) == dim, "the input vectors are of varying sizes"
    # assert that the input vectors are unique
    assert len(set(map(tuple, S))) == len(
        S
    ), "a vector appears in S more than once. Please use the S_weights parameter instead "
    assert len(set(map(tuple, T))) == len(
        T
    ), "a vector appears in T more than once. Please use the T_weights parameter instead "

    if S_weights is None:
        S_weights = [1.0] * len(S)
    total_S_weight = sum(S_weights)
    if T_weights is None:
        T_weights = [1.0] * len(T)
    total_T_weight = sum(T_weights)

    # now let's build the distance matrix:
    dist_matrix = []
    for v in S:
        temp = []
        for u in T:
            temp.append(underlying_distance(v, u))
        dist_matrix.append(temp)

    # now let's define the graph:
    # (documentation: https://networkx.github.io/documentation/networkx-1.9/tutorial/tutorial.html )
    # Note that we set all capacities to be integers in order to make the algorithms happy,
    # but we'll then need to divide the final cost by total_S_weight*total_T_weight so that the result is indifferent
    # to the cardinalities and weights of the point-sets.

    G = nx.DiGraph()
    G.add_node("src")
    G.add_node("sink")
    for i in range(len(S)):
        vtx_name = ("S", i)
        G.add_node(vtx_name)
        G.add_edge("src",
                   vtx_name,
                   capacity=total_T_weight * S_weights[i],
                   weight=0)
    for j in range(len(T)):
        vtx_name = ("T", j)
        G.add_node(vtx_name)
        G.add_edge(vtx_name,
                   "sink",
                   capacity=total_S_weight * T_weights[j],
                   weight=0)
    for i in range(len(S)):
        for j in range(len(T)):
            G.add_edge(("S", i), ("T", j),
                       weight=dist_matrix[i][j])  # infinite capacity edge

    # now run the flow algorithm:
    # (documentation: https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.flow.max_flow_min_cost.html )

    mincostFlow_unnormalized = nx.max_flow_min_cost(G, "src", "sink")
    # sanity check -- check that indeed total_S_weight*total_T_weight units of flow have gone through
    amount_of_flow_unnormalized = sum(
        [mincostFlow_unnormalized[v]["sink"] for v in G.predecessors("sink")])
    assert amount_of_flow_unnormalized == total_S_weight * total_T_weight

    # calculate normalized cost of flow:
    mincost_unnormalized = nx.cost_of_flow(G, mincostFlow_unnormalized)
    mincost_normalized = mincost_unnormalized / (total_S_weight *
                                                 total_T_weight)

    # Now remove the source and sink, replace vertex names by their corresponding vectors, and renormalize
    resulting_flow = dict()
    for i in range(len(S)):
        source_vec = tuple(S[i])
        source_vec_weight = S_weights[i]
        outgoing_from_source_vec = mincostFlow_unnormalized[("S", i)]
        result_for_source_vec = dict()
        for u in outgoing_from_source_vec.keys():
            target_vec = tuple(T[u[1]])
            target_vec_weight = T_weights[u[1]]
            flow_amount = outgoing_from_source_vec[u]
            if flow_amount > 0:
                result_for_source_vec[
                    target_vec] = flow_amount / total_T_weight
        resulting_flow[source_vec] = result_for_source_vec

    return resulting_flow, mincost_normalized
    def test_zero_capacity_edges(self):
        """Address issue raised in ticket #617 by arv."""
        G = nx.DiGraph()
        G.add_edges_from([
            (1, 2, {
                "capacity": 1,
                "weight": 1
            }),
            (1, 5, {
                "capacity": 1,
                "weight": 1
            }),
            (2, 3, {
                "capacity": 0,
                "weight": 1
            }),
            (2, 5, {
                "capacity": 1,
                "weight": 1
            }),
            (5, 3, {
                "capacity": 2,
                "weight": 1
            }),
            (5, 4, {
                "capacity": 0,
                "weight": 1
            }),
            (3, 4, {
                "capacity": 2,
                "weight": 1
            }),
        ])
        G.nodes[1]["demand"] = -1
        G.nodes[2]["demand"] = -1
        G.nodes[4]["demand"] = 2

        flowCost, H = nx.network_simplex(G)
        soln = {
            1: {
                2: 0,
                5: 1
            },
            2: {
                3: 0,
                5: 1
            },
            3: {
                4: 2
            },
            4: {},
            5: {
                3: 2,
                4: 0
            }
        }
        assert flowCost == 6
        assert nx.min_cost_flow_cost(G) == 6
        assert H == soln
        assert nx.min_cost_flow(G) == soln
        assert nx.cost_of_flow(G, H) == 6

        flowCost, H = nx.capacity_scaling(G)
        assert flowCost == 6
        assert H == soln
        assert nx.cost_of_flow(G, H) == 6
Exemplo n.º 39
0
def test_large():
    fname = os.path.join(os.path.dirname(__file__), "netgen-2.gpickle.bz2")
    G = nx.read_gpickle(fname)
    flowCost, flowDict = nx.network_simplex(G)
    assert 6749969302 == flowCost
    assert 6749969302 == nx.cost_of_flow(G, flowDict)
Exemplo n.º 40
0
"""
DESTINO EN PAISES BAJOS (NLD)
"""

G.add_edge('SGP','NLD', capacity = 5600, weight=6)


"""
DESTINO EN PAISES BAJOS (NLD)
"""
G.add_edge('SGP','NLD', capacity = 5600)

"""
COMANDOS DE ALGORITMOS
"""
max_flujo, flujo = nx.maximum_flow(G, 'CHN', 'USA')
print(max_flujo)
#print(flujo)

min_flow = nx.min_cost_flow(G)
min_flow_value = nx.cost_of_flow(G, min_flow)
#print(min_flow)
print(min_flow_value)

"""
COMANDO DIBUJO
"""
nx.draw(G, with_labels = True, nodelist =['AUS','BRA','CAN','CHN','DEU','ESP','FRA','GBR','HKG','ITA','JPN','KOR','MEX','MYS','NLD','SGP','USA'], node_color = ['#1F78B4', '#1F78B4', '#1F78B4', '#DB1B11', '#1F78B4','#1F78B4','#1F78B4','#1F78B4','#1F78B4','#1F78B4','#1F78B4','#1F78B4','#1F78B4','#1F78B4','#1F78B4','#1F78B4','#24DB11'], node_size = 500, font_size = 10, pos = nx.shell_layout(G,[['AUS','BRA','CAN','DEU','ESP','FRA','GBR','HKG','ITA','JPN','KOR','MEX','MYS','NLD','SGP'],['USA','CHN']]))
plt.show()
    def test_digraph1(self):
        # From Bradley, S. P., Hax, A. C. and Magnanti, T. L. Applied
        # Mathematical Programming. Addison-Wesley, 1977.
        G = nx.DiGraph()
        G.add_node(1, demand=-20)
        G.add_node(4, demand=5)
        G.add_node(5, demand=15)
        G.add_edges_from([
            (1, 2, {
                "capacity": 15,
                "weight": 4
            }),
            (1, 3, {
                "capacity": 8,
                "weight": 4
            }),
            (2, 3, {
                "weight": 2
            }),
            (2, 4, {
                "capacity": 4,
                "weight": 2
            }),
            (2, 5, {
                "capacity": 10,
                "weight": 6
            }),
            (3, 4, {
                "capacity": 15,
                "weight": 1
            }),
            (3, 5, {
                "capacity": 5,
                "weight": 3
            }),
            (4, 5, {
                "weight": 2
            }),
            (5, 3, {
                "capacity": 4,
                "weight": 1
            }),
        ])
        flowCost, H = nx.network_simplex(G)
        soln = {
            1: {
                2: 12,
                3: 8
            },
            2: {
                3: 8,
                4: 4,
                5: 0
            },
            3: {
                4: 11,
                5: 5
            },
            4: {
                5: 10
            },
            5: {
                3: 0
            },
        }
        assert flowCost == 150
        assert nx.min_cost_flow_cost(G) == 150
        assert H == soln
        assert nx.min_cost_flow(G) == soln
        assert nx.cost_of_flow(G, H) == 150

        flowCost, H = nx.capacity_scaling(G)
        assert flowCost == 150
        assert H == soln
        assert nx.cost_of_flow(G, H) == 150