def test_negative_selfloops(self): """Negative selfloops should cause an exception if uncapacitated and always be saturated otherwise. """ G = nx.DiGraph() G.add_edge(1, 1, weight=-1) assert_raises(nx.NetworkXUnbounded, nx.network_simplex, G) assert_raises(nx.NetworkXUnbounded, nx.capacity_scaling, G) G[1][1]['capacity'] = 2 flowCost, H = nx.network_simplex(G) assert_equal(flowCost, -2) assert_equal(H, {1: {1: 2}}) flowCost, H = nx.capacity_scaling(G) assert_equal(flowCost, -2) assert_equal(H, {1: {1: 2}}) G = nx.MultiDiGraph() G.add_edge(1, 1, 'x', weight=-1) G.add_edge(1, 1, 'y', weight=1) assert_raises(nx.NetworkXUnbounded, nx.network_simplex, G) assert_raises(nx.NetworkXUnbounded, nx.capacity_scaling, G) G[1][1]['x']['capacity'] = 2 flowCost, H = nx.network_simplex(G) assert_equal(flowCost, -2) assert_equal(H, {1: {1: {'x': 2, 'y': 0}}}) flowCost, H = nx.capacity_scaling(G) assert_equal(flowCost, -2) assert_equal(H, {1: {1: {'x': 2, 'y': 0}}})
def test_negative_selfloops(self): """Negative selfloops should cause an exception if uncapacitated and always be saturated otherwise. """ G = nx.DiGraph() G.add_edge(1, 1, weight=-1) pytest.raises(nx.NetworkXUnbounded, nx.network_simplex, G) pytest.raises(nx.NetworkXUnbounded, nx.capacity_scaling, G) G[1][1]["capacity"] = 2 flowCost, H = nx.network_simplex(G) assert flowCost == -2 assert H == {1: {1: 2}} flowCost, H = nx.capacity_scaling(G) assert flowCost == -2 assert H == {1: {1: 2}} G = nx.MultiDiGraph() G.add_edge(1, 1, "x", weight=-1) G.add_edge(1, 1, "y", weight=1) pytest.raises(nx.NetworkXUnbounded, nx.network_simplex, G) pytest.raises(nx.NetworkXUnbounded, nx.capacity_scaling, G) G[1][1]["x"]["capacity"] = 2 flowCost, H = nx.network_simplex(G) assert flowCost == -2 assert H == {1: {1: {"x": 2, "y": 0}}} flowCost, H = nx.capacity_scaling(G) assert flowCost == -2 assert H == {1: {1: {"x": 2, "y": 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)
def monroescore_flowbased(profile, committee): """Returns Monroe score of a given committee. Uses a flow-based algorithm that works even if committeesize does not divide the number of voters""" G = nx.DiGraph() committeesize = len(committee) # the lower bound of the size of districts lower_bound = len(profile) // committeesize # number of voters that will be contribute to the excess # of the lower bounds of districts overflow = len(profile) - committeesize * lower_bound # add a sink node for the overflow G.add_node('sink', demand=overflow) for i in committee: G.add_node(i, demand=lower_bound) G.add_edge(i, 'sink', weight=0, capacity=1) for i, vote in enumerate(profile): voter_name = 'v' + str(i) G.add_node(voter_name, demand=-1) for cand in committee: if cand in vote: G.add_edge(voter_name, cand, weight=0, capacity=1) else: G.add_edge(voter_name, cand, weight=1, capacity=1) # compute the minimal cost assignment of voters to candidates, # i.e. the unrepresented voters, and subtract it from the total number # of voters return len(profile) - nx.capacity_scaling(G)[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 flow == soln assert 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 flowCost == -410 assert flow['t']['s'] == 5 del flow['t']['s'] assert flow == soln assert nx.cost_of_flow(G, flow, weight='cost') == 90
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
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
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
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_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 flow == soln assert 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 flowCost == -410 assert flow["t"]["s"] == 5 del flow["t"]["s"] assert flow == soln assert nx.cost_of_flow(G, flow, weight="cost") == 90
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)
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)
def test_multidigraph(self): """Raise an exception for multidigraph.""" G = nx.MultiDiGraph() G.add_weighted_edges_from([(1, 2, 1), (2, 3, 2)], weight='capacity') assert_raises(nx.NetworkXError, nx.network_simplex, G) flowCost, H = nx.capacity_scaling(G) assert_equal(flowCost, 0) assert_equal(H, {1: {2: {0: 0}}, 2: {3: {0: 0}}, 3: {}})
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 test_multidigraph(self): """Multidigraphs are acceptable.""" G = nx.MultiDiGraph() G.add_weighted_edges_from([(1, 2, 1), (2, 3, 2)], weight='capacity') flowCost, H = nx.network_simplex(G) assert_equal(flowCost, 0) assert_equal(H, {1: {2: {0: 0}}, 2: {3: {0: 0}}, 3: {}}) flowCost, H = nx.capacity_scaling(G) assert_equal(flowCost, 0) assert_equal(H, {1: {2: {0: 0}}, 2: {3: {0: 0}}, 3: {}})
def test5(): G = nx.DiGraph() G.add_node("a", demand=-14) G.add_node("d", demand=14) 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, flowDict = nx.capacity_scaling(G) print(flowCost) print(flowDict)
def createFlow(F, source, destiny, flow, flows, id): env = Environment(loader=FileSystemLoader(os.path.join('.', 'templates'))) template = env.get_template('commands-template.txt') currentSourceCapacity = F.node[source]['demand'] currentDestinyCapacity = F.node[destiny]['demand'] F.node[source]['demand'] = currentSourceCapacity+(-flow) F.node[destiny]['demand'] = currentDestinyCapacity+(flow) flowCost, flowDict = nx.capacity_scaling(F, capacity='current_capacity') #print(flowDict) for i in flowDict: for j in flowDict[i]: currentCapacityij = F.edge[i][j]['current_capacity'] F.edge[i][j]['current_capacity'] = currentCapacityij-flowDict[i][j] F.node[source]['demand'] = 0 F.node[destiny]['demand'] = 0 currentSourceCapacity2 = F.node[destiny]['demand'] currentDestinyCapacity2 = F.node[source]['demand'] F.node[source]['demand'] = currentSourceCapacity2+(flow) F.node[destiny]['demand'] = currentDestinyCapacity2+(-flow) flowCost2, flowDict2 = nx.capacity_scaling(F, capacity='current_capacity') #print(flowDict2) for i in flowDict2: for j in flowDict2[i]: currentCapacityij = F.edge[i][j]['current_capacity'] F.edge[i][j]['current_capacity'] = currentCapacityij-flowDict2[i][j] F.node[source]['demand'] = 0 F.node[destiny]['demand'] = 0 for i in flowDict: if F.node[i]['isHost'] != 1: pathGo = [0] * F.node[i]['numPorts'] pathBack = [0] * F.node[i]['numPorts'] for j in flowDict[i]: pathGo[F.edge[i][j]['porigem']] = flowDict[i][j] pathBack[F.edge[i][j]['porigem']] = flowDict2[i][j] arq = open("util/"+str(i)+"-commands.txt", 'w') arq.write(template.render(source_ip=F.node[source]['ip'], destination_ip=F.node[destiny]['ip'], numP = F.node[i]['numPorts'], listPath=pathGo)+"\n" ) arq.write(template.render(source_ip=F.node[destiny]['ip'], destination_ip=F.node[source]['ip'], numP = F.node[i]['numPorts'], listPath=pathBack)) arq.close() flows[id] = flowDict flows[id+1] = flowDict2 return F, flows
def createFlow(F, source, destiny, flow, flows, id): env = Environment(loader=FileSystemLoader(os.path.join('.', 'templates'))) template1 = env.get_template('s1_commands-template.txt') template2 = env.get_template('s5_commands-template.txt') arq1 = open("util/s1_commands.txt", "w") arq2 = open("util/s5_commands.txt", "w") currentSourceCapacity = F.node[source]['demand'] currentDestinyCapacity = F.node[destiny]['demand'] F.node[source]['demand'] = currentSourceCapacity + (-flow) F.node[destiny]['demand'] = currentDestinyCapacity + (flow) flowCost, flowDict = nx.capacity_scaling(F, capacity='current_capacity') print(flowDict) for i in flowDict: for j in flowDict[i]: currentCapacityij = F.edge[i][j]['current_capacity'] currentCapacityji = F.edge[j][i]['current_capacity'] F.edge[i][j][ 'current_capacity'] = currentCapacityij - flowDict[i][j] F.edge[j][i][ 'current_capacity'] = currentCapacityji - flowDict[i][j] arq1.write( template1.render( source_ip=F.node[source]['ip'], destination_ip=F.node[destiny]['ip'], first=format( F.edge[2][3]['capacity'] - F.edge[2][3]['current_capacity'], '08b'), second=format( F.edge[2][4]['capacity'] - F.edge[2][4]['current_capacity'], '08b'), third=format( F.edge[2][5]['capacity'] - F.edge[2][5]['current_capacity'], '08b'))) arq2.write( template2.render( source_ip=F.node[destiny]['ip'], destination_ip=F.node[source]['ip'], first=format( F.edge[2][3]['capacity'] - F.edge[2][3]['current_capacity'], '08b'), second=format( F.edge[2][4]['capacity'] - F.edge[2][4]['current_capacity'], '08b'), third=format( F.edge[2][5]['capacity'] - F.edge[2][5]['current_capacity'], '08b'))) flows[id] = flowDict F.node[source]['demand'] = 0 F.node[destiny]['demand'] = 0 arq1.close() arq2.close() return F, flows
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)
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 nx.min_cost_flow_cost(G) == min_cost flowCost, H = nx.capacity_scaling(G) assert flowCost == -2 assert H == {"a": {"b": 1}, "b": {"a": 1}} assert nx.cost_of_flow(G, H) == -2
def test_bone_shaped(self): # From #1283 G = nx.DiGraph() G.add_node(0, demand=-4) G.add_node(1, demand=2) G.add_node(2, demand=2) G.add_node(3, demand=4) G.add_node(4, demand=-2) G.add_node(5, demand=-2) G.add_edge(0, 1, capacity=4) G.add_edge(0, 2, capacity=4) G.add_edge(4, 3, capacity=4) G.add_edge(5, 3, capacity=4) G.add_edge(0, 3, capacity=0) flowCost, H = nx.network_simplex(G) assert_equal(flowCost, 0) assert_equal(H, { 0: { 1: 2, 2: 2, 3: 0 }, 1: {}, 2: {}, 3: {}, 4: { 3: 2 }, 5: { 3: 2 } }) flowCost, H = nx.capacity_scaling(G) assert_equal(flowCost, 0) assert_equal(H, { 0: { 1: 2, 2: 2, 3: 0 }, 1: {}, 2: {}, 3: {}, 4: { 3: 2 }, 5: { 3: 2 } })
def capacity_scaling(self): import networkx as nx self.dataframe_edge['flow'] = 0 self.cost, self.flow = nx.capacity_scaling(self.DiGraph, demand='val', capacity='capacity', weight='cost') for fnode, dli in self.flow.items(): for tnode, edge_flow in dli.items(): if edge_flow != 0: self.dataframe_edge.loc[(fnode, tnode), 'flow'] = edge_flow
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
def monroescore_flowbased(profile, committee): """ Return Monroe score of a given committee. Uses a flow-based algorithm that works even if `committeesize` does not divide the number of voters. Slower than monroescore_matching(). Parameters ---------- profile : abcvoting.preferences.Profile A profile. committee : set A committee. Returns ------- int The Monroe score. """ graph = nx.DiGraph() committeesize = len(committee) # the lower bound of the size of districts lower_bound = len(profile) // committeesize # number of voters that will be contribute to the excess # of the lower bounds of districts overflow = len(profile) - committeesize * lower_bound # add a sink node for the overflow graph.add_node("sink", demand=overflow) for i in committee: graph.add_node(i, demand=lower_bound) graph.add_edge(i, "sink", weight=0, capacity=1) for i, voter in enumerate(profile): voter_name = "v" + str(i) graph.add_node(voter_name, demand=-1) for cand in committee: if cand in voter.approved: graph.add_edge(voter_name, cand, weight=0, capacity=1) else: graph.add_edge(voter_name, cand, weight=1, capacity=1) # compute the minimal cost assignment of voters to candidates, # i.e. the unrepresented voters, and subtract it from the total number # of voters return len(profile) - nx.capacity_scaling(graph)[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
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)
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)
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 4 == flow assert 23 == nx.cost_of_flow(G, sol, weight=1) assert sol["s"] == {"a": 2, "b": 2} assert sol["a"] == {"b": 1, "t": 1} assert sol["b"] == {"a": 0, "t": 3} assert 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 4 == flow assert sol["t"]["s"] == 4 assert flowCost == -377 del sol["t"]["s"] assert sol["s"] == {"a": 2, "b": 2} assert sol["a"] == {"b": 1, "t": 1} assert sol["b"] == {"a": 0, "t": 3} assert sol["t"] == {} assert nx.cost_of_flow(G, sol, weight=1) == 23
def map_requests(self, requests, osts): totalDemand = sum([req.numStripes for req in requests]) stripeSize = requests[0].stripeSize currStripeCount = requests[0].numStripes G = nx.DiGraph() G.add_node('source', demand=-totalDemand) G.add_node('sink', demand=totalDemand) doneFlag = False while not doneFlag and len(requests) > 0: for req in requests: G.add_edge('source', req.name, weight=0, capacity=req.numStripes) for ost in osts: G.add_edge(req.name, ost.name, weight=ost.cost_to_reach(), capacity=1) for ost in osts: G.add_edge(ost.name, 'sink', weight=ost.cost(), capacity=ost.capacity(stripeSize)) try: flowCost, flowDict = nx.capacity_scaling(G) doneFlag = True except: requests = requests[:-1] doneFlag = False if doneFlag: ostWeights = flowDict['req0'] ostNames = [] for ost, weight in ostWeights.iteritems(): if weight > 0: ostNames.append(ost) return tuple([ostNames, flowCost]) else: ostNames = [ ost.name for ost in random.sample(osts, currStripeCount) ] return tuple([ostNames, 0])
def Wasserstein(h1, h2, M): """ Compute the Wasserstein distance between the two histograms h1 and h2 using distance matrix M """ d = len(h1) # Build the graph for max flow G = nx.DiGraph() # add d nodes for each histrogam # (d+1) source, (d+2) target for i in range(d): G.add_node(i, demand=-h1[i]) G.add_node(d + i, demand=+h2[i]) # Add all edges for i in range(d): for j in range(d): G.add_edge(i, d + j, weight=M[i][j], capacity=min(h1[i], h2[j])) #flowCost, flowDict = nx.capacity_scaling(G, heap=nx.utils.heaps.PairingHeap) flowCost, flowDict = nx.capacity_scaling(G, heap=nx.utils.heaps.BinaryHeap) #flowCost, flowDict = nx.network_simplex(G) return flowCost
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
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)
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
def calc_save_min_cost_flow(): G = nx.DiGraph() G.add_node("O", demand=-N) G.add_node("D", demand=N) for node_id, goal_id in edges.observed_goal.items(): G.add_node("G%d"%goal_id, demand=0) G.add_edge("G%d"%goal_id, "D", weight=0, capacity=edges.goal_capa[goal_id]) for ped in pedestrians[:N]: G.add_node("P%d"%ped.idx, demand=0) G.add_edge("O", "P%d"%ped.idx, weight=0, capacity=1) for node_id, goal_id in edges.observed_goal.items(): dist = edges.DistanceMatrix[edges.observed_goal[ped.destination], goal_id] w = int(dist/ped.speed) # print(ped.idx, ped.destination, goal_id, dist, w) G.add_edge("P%d"%ped.idx, "G%d"%goal_id, weight=int(dist/ped.speed), capacity=1) flowCost, flowDict = nx.capacity_scaling(G, demand="demand", capacity="capacity", weight="weight") pd.to_pickle(flowDict, "flowDict.pickle") pd.to_pickle(flowCost, "flowCost.pickle")
def test_bone_shaped(self): # From #1283 G = nx.DiGraph() G.add_node(0, demand=-4) G.add_node(1, demand=2) G.add_node(2, demand=2) G.add_node(3, demand=4) G.add_node(4, demand=-2) G.add_node(5, demand=-2) G.add_edge(0, 1, capacity=4) G.add_edge(0, 2, capacity=4) G.add_edge(4, 3, capacity=4) G.add_edge(5, 3, capacity=4) G.add_edge(0, 3, capacity=0) flowCost, H = nx.network_simplex(G) assert_equal(flowCost, 0) assert_equal( H, {0: {1: 2, 2: 2, 3: 0}, 1: {}, 2: {}, 3: {}, 4: {3: 2}, 5: {3: 2}}) flowCost, H = nx.capacity_scaling(G) assert_equal(flowCost, 0) assert_equal( H, {0: {1: 2, 2: 2, 3: 0}, 1: {}, 2: {}, 3: {}, 4: {3: 2}, 5: {3: 2}})
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)
import networkx as nx INF = float('inf') def inputNodes(): print "Please input the number of nodes: " number = int(raw_input()) for i in xrange(0, number): print "Please input the name of Node ", i node, inputDemand = raw_input().strip().split(" ") G.add_node(node, demand=int(inputDemand)) while True: try: print "Please input the cost of nodes (Stop with EOF): " node1, node2, cost = raw_input().strip().split(" ") G.add_edge(node2, node1, weight=float(cost), capacity=INF) except EOFError: break return G G = nx.DiGraph() G = inputNodes() flowCost, flowDict = nx.capacity_scaling(G) print flowCost print flowDict
import networkx G = networkx.DiGraph() G.add_node('Beach', demand=-5) G.add_node('High Ground', demand=5) G.add_edge('Beach', 'Seatown', weight=3, capacity=6) G.add_edge('Beach', 'River Valley', weight=5, capacity=4) G.add_edge('Seatown', 'High Ground', weight=5, capacity=6) G.add_edge('River Valley', 'High Ground', weight=10, capacity=2) flow_cost, flow_dict = networkx.capacity_scaling(G) print("Total cost to satisfy these demands: ", flow_cost)