def find_unmatch_nodes(G): match=[] nodes = G.nodes() g = nx.DiGraph() gg = nx.DiGraph() p0 =['+'+str(i) for i in nodes] m0 = ['-'+str(i) for i in nodes] for ed in G.edges(): ed1,ed2 = ed g.add_edge('+'+str(ed1),'-'+str(ed2),capacity=1.0) source = 'source' sink = 'sink' for i in p0: #~ print p0 g.add_edge(source,i,capacity=1.0) for i in m0: g.add_edge(i,sink,capacity=1.0) flow,F = nx.ford_fulkerson(g,source,sink) for i in F: if i not in [sink,source]: for j in F[i]: if j not in [sink,source]: #~ print i,j,F[i][j] if F[i][j] > 0: match.append(int(j[1:])) #~ print len(set(match)) unmatch = set(nodes) unmatch = unmatch - set(match) #~ print unmatch return unmatch
def test_optional_capacity(self): # Test optional capacity parameter. G = nx.DiGraph() G.add_edge('x','a', spam = 3.0) G.add_edge('x','b', spam = 1.0) G.add_edge('a','c', spam = 3.0) G.add_edge('b','c', spam = 5.0) G.add_edge('b','d', spam = 4.0) G.add_edge('d','e', spam = 2.0) G.add_edge('c','y', spam = 2.0) G.add_edge('e','y', spam = 3.0) solnFlows = {'x': {'a': 2.0, 'b': 1.0}, 'a': {'c': 2.0}, 'b': {'c': 0, 'd': 1.0}, 'c': {'y': 2.0}, 'd': {'e': 1.0}, 'e': {'y': 1.0}, 'y': {}} solnValue = 3.0 s = 'x' t = 'y' flowValue, flowDict = nx.ford_fulkerson(G, s, t, capacity = 'spam') assert_equal(flowValue, solnValue) assert_equal(flowDict, solnFlows) assert_equal(nx.min_cut(G, s, t, capacity = 'spam'), solnValue) assert_equal(nx.max_flow(G, s, t, capacity = 'spam'), solnValue) assert_equal(nx.ford_fulkerson_flow(G, s, t, capacity = 'spam'), solnFlows)
def compare_flows(G, s, t, H, solnValue): output = nx.ford_fulkerson(G, s, t) flows = [edge[2]['flow'] for edge in output[1].edges(data = True)] solnFlows = [H[u][v]['flow'] for (u, v) in output[1].edges()] assert_equal((output[0], flows), (solnValue, solnFlows))
def test_gl1(self): G = read_graph('gl1') s = 1 t = len(G) validate_flows(G, s, t, 156545, *nx.ford_fulkerson(G, s, t)) validate_flows(G, s, t, 156545, nx.preflow_push_value(G, s, t), nx.preflow_push_flow(G, s, t))
def test_gw1(self): G = read_graph('gw1') s = 1 t = len(G) validate_flows(G, s, t, 1202018, *nx.ford_fulkerson(G, s, t)) validate_flows(G, s, t, 1202018, nx.preflow_push_value(G, s, t), nx.preflow_push_flow(G, s, t))
def test_complete_graph(self): N = 50 G = nx.complete_graph(N) for (u, v) in G.edges(): G[u][v]['capacity'] = 5 assert_equal(nx.ford_fulkerson(G, 1, 2)[0], 5 * (N - 1)) assert_equal(nx.preflow_push(G, 1, 2)[0], 5 * (N - 1))
def test_wlm3(self): G = read_graph('wlm3') s = 1 t = len(G) validate_flows(G, s, t, 11875108, *nx.ford_fulkerson(G, s, t)) validate_flows(G, s, t, 11875108, nx.preflow_push_value(G, s, t), nx.preflow_push_flow(G, s, t))
def mincut(edges): G = nx.DiGraph() for i in range(n): G.add_node(i) for i, j, cap in edges: if abs(cap - 1.0) <= 1e-9: cap = 1.0 G.add_edge(i, j, capacity=cap) source = 0 min_flow = None edges_min_flow = None sink_min_flow = None for sink in range(1, n): flow, F = nx.ford_fulkerson(G, source, sink) if sink_min_flow is None or flow < min_flow: sink_min_flow = sink min_flow = flow edges_min_flow = F.copy() residual_edges = [] for i, j, edge_capacity in edges: edge_flow = edges_min_flow[i][j] if abs(edge_capacity - edge_flow) > 1e-9: residual_edges.append((i, j)) source_component = dfs(residual_edges, source) #print 'MinFlow:', min_flow #print 'Component MinFlow:', source_component return source_component, min_flow
def compare_flows(G, s, t, solnFlows, solnValue): flowValue, flowDict = nx.ford_fulkerson(G, s, t) assert_equal(flowValue, solnValue) assert_equal(flowDict, solnFlows) assert_equal(nx.min_cut(G, s, t), solnValue) assert_equal(nx.max_flow(G, s, t), solnValue) assert_equal(nx.ford_fulkerson_flow(G, s, t), solnFlows)
def test_dimacs_digraph1(self): #AK generator, small graph #http://www.avglab.com/andrew/CATS/gens/ak/ [G,s,t] = nx.read_dimacs("networkx/algorithms/flow/tests/dimacs_digraph1") value = nx.ford_fulkerson(G,s,t)[0] compare_value_flows_vanilla_push_relabel(G,s,t,value) compare_value_flows_relabel_to_front(G,s,t,value) compare_value_flows_highest_label(G,s,t,value)
def get_max_flow_values(G, use_node_capacities=True, use_node_demands=False): ''' This runs a ford-fulkerson maximum flow algrothim over the provided network and assigns the resulting flows to each edge. The flows for each node are also calcualted and assigned. ''' print G.edges() #print G.edges() if use_node_capacities == True: G = convert_topo(G) print G.edges() exit() #check for supply and demand nodes. Needs to be at least one of each. #if more than one need to create a super source/sink(demand) nodes. G, supply_nodes, demand_nodes, added_nodes, added_edges = check_for_demand_supply_nodes( G) #get supply node and demand node supply_nd, demand_nd = get_check_supply_demand_nodes( G, supply_nodes, demand_nodes, added_nodes) if use_node_capacities == True and use_node_demands == False: #this returns the maximum flow and the flow on each edge by node #first check a path is possible - ford-fulkerson would just return 0 otherwise path = nx.has_path(G, supply_nd, demand_nd) if path == False: raise error_classes.GeneralError( 'No path exists between the supply node (node %s) and the demand node (node %s).' % (supply_nd, demand_nd)) max_flow, edge_flows = nx.ford_fulkerson(G, supply_nd, demand_nd, 'flow_capacity') elif use_node_capacities == True and use_node_demands == True: #returns the flow on each edge given capacities and demands #the sum of the demand needs to equal the sum of the supply (indicated by a negative demand value) edge_flows = nx.min_cost_flow(G, 'demand', 'flow_capacity', 'weight') elif use_node_capacities == False and use_node_demands == True: #returns the flow on each edge given demands (capacities should be set at 9999999 (a very high number)) edge_flows = nx.min_cost_flow(G, 'demand', 'flow_capacity', 'weight') #assign flows to nodes and edges G = assign_edge_node_flows(G, edge_flows) #before running any analysis, need to remove the added nodes and edges - the super source/demand if used G = remove_added_nodes_edges(G, added_edges, added_nodes) node_flow_max, edge_flow_max = get_max_flows(G) return G, { 'max_flow': max_flow, 'max_node_flow': node_flow_max, 'max_edge_flow': edge_flow_max }
def compare_flows(G, s, t, solnFlows, solnValue, capacity = 'capacity'): flowValue, flowDict = nx.ford_fulkerson(G, s, t, capacity) assert_equal(flowValue, solnValue) assert_equal(flowDict, solnFlows) flowValue, flowDict = nx.preflow_push(G, s, t, capacity) assert_equal(flowValue, solnValue) validate_flows(G, s, t, flowDict, solnValue, capacity) assert_equal(nx.min_cut(G, s, t, capacity), solnValue) assert_equal(nx.max_flow(G, s, t, capacity), solnValue) assert_equal(nx.ford_fulkerson_flow(G, s, t, capacity), solnFlows)
def test_pyramid(self): N = 10 # N = 100 # this gives a graph with 5051 nodes G = gen_pyramid(N) assert_almost_equal(nx.ford_fulkerson(G, (0, 0), 't')[0], 1.) assert_almost_equal(nx.preflow_push(G, (0, 0), 't')[0], 1.) assert_almost_equal(nx.shortest_augmenting_path( G, (0, 0), 't', two_phase=False)[0], 1.) assert_almost_equal(nx.shortest_augmenting_path( G, (0, 0), 't', two_phase=True)[0], 1.)
def test_complete_graph(self): N = 50 G = nx.complete_graph(N) for (u, v) in G.edges(): G[u][v]['capacity'] = 5 assert_equal(nx.ford_fulkerson(G, 1, 2)[0], 5 * (N - 1)) assert_equal(nx.preflow_push(G, 1, 2)[0], 5 * (N - 1)) assert_equal(nx.shortest_augmenting_path(G, 1, 2, two_phase=False)[0], 5 * (N - 1)) assert_equal(nx.shortest_augmenting_path(G, 1, 2, two_phase=True)[0], 5 * (N - 1))
def test_digraph_infcap_path(self): # Graph with infinite capacity (s, t)-path G = nx.DiGraph() G.add_edge('s', 'a') G.add_edge('s', 'b', capacity = 30) G.add_edge('a', 'c') G.add_edge('b', 'c', capacity = 12) G.add_edge('a', 't', capacity = 60) G.add_edge('c', 't') assert_equal(nx.ford_fulkerson(G, 's', 't'), None)
def test_gl1(self): G = read_graph('gl1') s = 1 t = len(G) validate_flows(G, s, t, 156545, *nx.ford_fulkerson(G, s, t)) validate_flows(G, s, t, 156545, nx.preflow_push_value(G, s, t), nx.preflow_push_flow(G, s, t)) validate_flows( G, s, t, 156545, nx.shortest_augmenting_path_value(G, s, t, two_phase=False), nx.shortest_augmenting_path_flow(G, s, t, two_phase=False)) validate_flows(G, s, t, 156545, nx.shortest_augmenting_path_value(G, s, t, two_phase=True), nx.shortest_augmenting_path_flow(G, s, t, two_phase=True))
def test_wlm3(self): G = read_graph('wlm3') s = 1 t = len(G) validate_flows(G, s, t, 11875108, *nx.ford_fulkerson(G, s, t)) validate_flows(G, s, t, 11875108, nx.preflow_push_value(G, s, t), nx.preflow_push_flow(G, s, t)) validate_flows( G, s, t, 11875108, nx.shortest_augmenting_path_value(G, s, t, two_phase=False), nx.shortest_augmenting_path_flow(G, s, t, two_phase=False)) validate_flows( G, s, t, 11875108, nx.shortest_augmenting_path_value(G, s, t, two_phase=True), nx.shortest_augmenting_path_flow(G, s, t, two_phase=True))
def improve(G, A, score, weights): part_num = -numpy.ones((G.shape[0], )) aug_G = augmented_graph(G, A, score, weights=weights) flow, F = nx.ford_fulkerson(aug_G, 's', 't') for u, v in min_cut(aug_G, F): if not isinstance(u, str): part_num[u] = 1 if not isinstance(v, str): part_num[v] = 1 P1 = numpy.where(part_num == 1)[0] P2 = numpy.where(part_num == -1)[0] return P1, P2
def improve(G, A, score, weights) : part_num = -numpy.ones((G.shape[0],)) aug_G = augmented_graph(G,A,score,weights=weights) flow,F = nx.ford_fulkerson(aug_G, 's', 't') for u,v in min_cut(aug_G,F) : if not isinstance(u,str) : part_num[u] = 1 if not isinstance(v,str) : part_num[v] = 1 P1 = numpy.where(part_num==1)[0] P2 = numpy.where(part_num==-1)[0] return P1,P2
def min_path_max_flow(G, s, t): """ Valor del flow maximal del camino minimo desde s a t. Devuelve el flow y el path minimo: return (flow, path) """ #Tiene el orden inverso al nuestro, algunos casos no van a dar bien path = nx.shortest_path(G, s, t) if len(path) == 2: flow = G.get_edge_data(0, 1)["weight"] else: spath = nx.subgraph(G, path) flow, _ = nx.ford_fulkerson(spath, s, t, capacity='weight') return flow, path
def test_optional_capacity(self): # Test optional capacity parameter. G = nx.DiGraph() G.add_edge('x', 'a', spam=3.0) G.add_edge('x', 'b', spam=1.0) G.add_edge('a', 'c', spam=3.0) G.add_edge('b', 'c', spam=5.0) G.add_edge('b', 'd', spam=4.0) G.add_edge('d', 'e', spam=2.0) G.add_edge('c', 'y', spam=2.0) G.add_edge('e', 'y', spam=3.0) solnFlows = { 'x': { 'a': 2.0, 'b': 1.0 }, 'a': { 'c': 2.0 }, 'b': { 'c': 0, 'd': 1.0 }, 'c': { 'y': 2.0 }, 'd': { 'e': 1.0 }, 'e': { 'y': 1.0 }, 'y': {} } solnValue = 3.0 s = 'x' t = 'y' flowValue, flowDict = nx.ford_fulkerson(G, s, t, capacity='spam') assert_equal(flowValue, solnValue) assert_equal(flowDict, solnFlows) assert_equal(nx.min_cut(G, s, t, capacity='spam'), solnValue) assert_equal(nx.max_flow(G, s, t, capacity='spam'), solnValue) assert_equal(nx.ford_fulkerson_flow(G, s, t, capacity='spam'), solnFlows)
def find_mincut_part(G,origin,terminus): """ Find the vertices on the origin side of a mincut of G separating origin from terminus. """ try: # old version of networkx flow_rate, flow_dict=nx.ford_fulkerson(G,origin,terminus) except AttributeError: # new version of networkx flow_value, flow_dict = nx.maximum_flow(G, origin, terminus,flow_func=ford_fulkerson) newverts=set([origin]) verts=set([]) while newverts: thisvert=newverts.pop() verts.add(thisvert) for e in G.out_edges_iter(thisvert, data=True): if e[2]['capacity']>flow_dict[e[0]][e[1]] and e[1] not in verts: newverts.add(e[1]) return verts
def compare_flows(G, s, t, solnFlows, solnValue, capacity = 'capacity'): flowValue, flowDict = nx.ford_fulkerson(G, s, t, capacity) assert_equal(flowValue, solnValue) assert_equal(flowDict, solnFlows) flowValue, flowDict = nx.preflow_push(G, s, t, capacity) assert_equal(flowValue, solnValue) validate_flows(G, s, t, flowDict, solnValue, capacity) flowValue, flowDict = nx.shortest_augmenting_path(G, s, t, capacity, two_phase=False) assert_equal(flowValue, solnValue) validate_flows(G, s, t, flowDict, solnValue, capacity) flowValue, flowDict = nx.shortest_augmenting_path(G, s, t, capacity, two_phase=True) assert_equal(flowValue, solnValue) validate_flows(G, s, t, flowDict, solnValue, capacity) assert_equal(nx.min_cut(G, s, t, capacity), solnValue) assert_equal(nx.max_flow(G, s, t, capacity), solnValue) assert_equal(nx.ford_fulkerson_flow(G, s, t, capacity), solnFlows)
def strength_of_vote_management(self, voter_profile): # Initialize the graph weights for pattern in self.pattern_nodes: self.vote_management_graph["source"][pattern]['capacity'] = voter_profile[pattern] for i in range(self.required_winners): if pattern[i] == 1: self.vote_management_graph[pattern][i]['capacity'] = voter_profile[pattern] # Iterate towards the limit r = [(float(sum(voter_profile.values())) - voter_profile[tuple([PREFERRED_MORE] * self.required_winners)]) / self.required_winners] while len(r) < 2 or r[-2] - r[-1] > STRENGTH_TOLERANCE: for i in range(self.required_winners): self.vote_management_graph[i]["sink"]['capacity'] = r[-1] max_flow = nx.ford_fulkerson(self.vote_management_graph, "source", "sink") sink_sum = sum(v for k, v in max_flow[1].iteritems() if k[1] == "sink") r.append(sink_sum / self.required_winners) # We expect strengths to be above a specified threshold if sink_sum < STRENGTH_THRESHOLD: return 0 # Return the final max flow return round(r[-1], 9)
def compare_flows(G, s, t, solnFlows, solnValue, capacity='capacity'): flowValue, flowDict = nx.ford_fulkerson(G, s, t, capacity) assert_equal(flowValue, solnValue) assert_equal(flowDict, solnFlows) flowValue, flowDict = nx.preflow_push(G, s, t, capacity) assert_equal(flowValue, solnValue) validate_flows(G, s, t, flowDict, solnValue, capacity) flowValue, flowDict = nx.shortest_augmenting_path(G, s, t, capacity, two_phase=False) assert_equal(flowValue, solnValue) validate_flows(G, s, t, flowDict, solnValue, capacity) flowValue, flowDict = nx.shortest_augmenting_path(G, s, t, capacity, two_phase=True) assert_equal(flowValue, solnValue) validate_flows(G, s, t, flowDict, solnValue, capacity) assert_equal(nx.min_cut(G, s, t, capacity), solnValue) assert_equal(nx.max_flow(G, s, t, capacity), solnValue) assert_equal(nx.ford_fulkerson_flow(G, s, t, capacity), solnFlows)
def test_pyramid(self): N = 10 # N = 100 # this gives a graph with 5051 nodes G = gen_pyramid(N) assert_almost_equal(nx.ford_fulkerson(G, (0, 0), 't')[0], 1.)
def main(argv): file1 = argv[1] file2 = argv[2] file3 = argv[3] network = nx.read_dot(file1) #print(network) file2 = open(file2,'r') rawNodeCaps = file2.readlines() nodeCaps={} for line in rawNodeCaps: splitLine = line.split() nodeCaps[str(splitLine[0])]= int(splitLine[1]) airTrafficGraph = nx.DiGraph() airTrafficGraph = nx.DiGraph(name='AirTraffic') airTrafficGraph.add_nodes_from(network) edgelist = [] edgetuples = network.edges() for edgetuple in edgetuples: tmplist =[] tmplist.append(edgetuple[0]) tmplist.append(edgetuple[1]) edgelist.append(tmplist) for edge in edgelist: edge.append({"capacity":int(network[edge[0]][edge[1]][0]['label'])}) #edge.append({"label":int(network[edge[0]][edge[1]][0]['label'])}) airTrafficGraph.add_edges_from(edgelist) ## print(network.edges()) #print(airgraph.edges()) traffic = nx.read_dot(file3) #print(traffic) airTrafficGraph.add_nodes_from(traffic) edgelist = [] edgetuples = traffic.edges() for edgetuple in edgetuples: tmplist =[] tmplist.append(edgetuple[0]) tmplist.append(edgetuple[1]) edgelist.append(tmplist) for edge in edgelist: edge.append({"capacity":int(traffic[edge[0]][edge[1]][0]['label'])}) #edge.append({"label":int(network[edge[0]][edge[1]][0]['label'])}) airTrafficGraph.add_edges_from(edgelist) airTrafficGraph=removeAntiParallelEdges(airTrafficGraph) airTrafficGraph=removeCapConstraint(airTrafficGraph,nodeCaps) #network=SingleSourceSink(airTrafficGraph, traffic) plotGraph(airTrafficGraph) '''netout = nx.write_dot(airTrafficGraph, "./airgraphout.dot") file4 = open("./airgraphout.dot",'r') newnet= nx.read_dot(file4) print(newnet.to_directed())''' flow, F =nx.ford_fulkerson(airTrafficGraph, 'S','T') #print(flow) for thing in F: print thing, F[thing] #print(network) #unwindFlow(network,airTrafficGraph,F) ## print nodeCaps ## print (multiEdgeNodes) ## print(network.nodes()) ## print("~~~~~~~~~~~~~~~~~~~") ## print(network["newnode1"]["JFK"][0]['label']) ## print(network.edges()) ## print(nodeCaps) ## print(traffic) file2.close()
#then add them to the whole list global people people.append(person_parameter) return G people = [] #empty list for people issues = [] #empty list for issues count1 = 0 count2 = 0 G = create_graph() #test case, as required part(e) G = g_prime(G, people, issues) G = g_hat(G, people, issues) print("Total Demand on People Nodes: ", count1) print("Total Demand on Issues Nodes: ", count2) R = nx.ford_fulkerson(G, 'source', 'sink') print("Max Flow: ", R[0]) print("\n") if count1 != count2: print("The Two Demands are not Equal") print("Hence, may not be feasible survey") #Fourth Problem import networkx as nx def createGraph(G): #adding an edge also adds the node G.add_edge('Spider', 'A', weight=1.0) G.add_edge('Spider', 'H', weight=1.0)
''' >>> import networkx as nx >>> G = nx.DiGraph() >>> G.add_edge('x','a', capacity=3.0) >>> G.add_edge('x','b', capacity=1.0) >>> G.add_edge('a','c', capacity=3.0) >>> G.add_edge('b','c', capacity=5.0) >>> G.add_edge('b','d', capacity=4.0) >>> G.add_edge('d','e', capacity=2.0) >>> G.add_edge('c','y', capacity=2.0) >>> G.add_edge('e','y', capacity=3.0) >>> flow, F = nx.ford_fulkerson(G, 'x', 'y') >>> flow 3.0 ''' import networkx as nx G = nx.DiGraph() G.add_edge('x', 'a', capacity=3.0) G.add_edge('x', 'b', capacity=1.0) G.add_edge('a', 'c', capacity=3.0) G.add_edge('b', 'c', capacity=5.0) G.add_edge('b', 'd', capacity=4.0) G.add_edge('d', 'e', capacity=2.0) G.add_edge('c', 'y', capacity=2.0) G.add_edge('e', 'y', capacity=3.0) flow, F = nx.ford_fulkerson(G, 'x', 'y') print(flow) print(F)
def minimum_st_edge_cut(G, s, t, capacity='capacity'): """Returns the edges of the cut-set of a minimum (s, t)-cut. We use the max-flow min-cut theorem, i.e., the capacity of a minimum capacity cut is equal to the flow value of a maximum flow. Parameters ---------- G : NetworkX graph Edges of the graph are expected to have an attribute called 'capacity'. If this attribute is not present, the edge is considered to have infinite capacity. s : node Source node for the flow. t : node Sink node for the flow. capacity: string Edges of the graph G are expected to have an attribute capacity that indicates how much flow the edge can support. If this attribute is not present, the edge is considered to have infinite capacity. Default value: 'capacity'. Returns ------- cutset : set Set of edges that, if removed from the graph, will disconnect it Raises ------ NetworkXUnbounded If the graph has a path of infinite capacity, all cuts have infinite capacity and the function raises a NetworkXError. Examples -------- >>> G = nx.DiGraph() >>> G.add_edge('x','a', capacity = 3.0) >>> G.add_edge('x','b', capacity = 1.0) >>> G.add_edge('a','c', capacity = 3.0) >>> G.add_edge('b','c', capacity = 5.0) >>> G.add_edge('b','d', capacity = 4.0) >>> G.add_edge('d','e', capacity = 2.0) >>> G.add_edge('c','y', capacity = 2.0) >>> G.add_edge('e','y', capacity = 3.0) >>> sorted(nx.minimum_edge_cut(G, 'x', 'y')) [('c', 'y'), ('x', 'b')] >>> nx.minimum_cut_value(G, 'x', 'y') 3.0 """ try: H = nx.ford_fulkerson(G, s, t, capacity=capacity) cutset = set() # Compute reachable nodes from source in the residual network reachable = set(nx.single_source_shortest_path(H,s)) # And unreachable nodes others = set(H) - reachable # - set([s]) # Any edge in the original network linking these two partitions # is part of the edge cutset for u, nbrs in ((n, G[n]) for n in reachable): cutset.update((u,v) for v in nbrs if v in others) return cutset except nx.NetworkXUnbounded: # Should we raise any other exception or just let ford_fulkerson # propagate nx.NetworkXUnbounded ? raise nx.NetworkXUnbounded("Infinite capacity path, no minimum cut.")
def test_complete_graph(self): N = 50 G = nx.complete_graph(N) for (u, v) in G.edges(): G[u][v]['capacity'] = 5 assert_equal(nx.ford_fulkerson(G, 1, 2)[0], 5 * (N - 1))