Exemple #1
0
def getVmax(G, S, L):
    V = G.nodes()
    # flow[i][j] = max-flow in (S, V) when S[i] is swapped with V[j]
    flow = [[None for _ in xrange(len(V))] for _ in xrange(len(S))]
    setS = set(S)
    without_swap_flow = nx.maximum_flow_value(getFlowGraph(G, S, L), 's', 't')
    for i in xrange(len(S)):
        for j in xrange(len(V)):
            if V[j] not in setS:
                temp = S[i]
                S[i] = V[j]
                flow_graph = getFlowGraph(G, S, L)
                flow[i][j] = nx.maximum_flow_value(flow_graph, 's',
                                                   't') > without_swap_flow
                S[i] = temp

    swap_pair = []
    for i in xrange(len(S)):
        for j in xrange(len(V)):
            swap_pair.append([i, j])

    if swap_pair:
        i, j = choice(swap_pair)
    else:
        return S
    S[i] = V[j]
    return S
    def compute_capacity(self, node):
        if node == self.identity:
            return
        contribution = nx.maximum_flow_value(self.graph, node, self.identity)
        consumption = nx.maximum_flow_value(self.graph, self.identity, node)

        self.graph.add_node(node, capacity=max(0, contribution - consumption))
        self.graph.add_node(node, bartercast=contribution - consumption)
Exemple #3
0
def doOneSwaps(G, S, L):
    Vmax = getVmax(G, S[:], L)
    while nx.maximum_flow_value(getFlowGraph(G, Vmax, L), 's',
                                't') > nx.maximum_flow_value(
                                    getFlowGraph(G, S, L), 's', 't'):
        S = Vmax
        Vmax = getVmax(G, S[:], L)
    return S
Exemple #4
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)
Exemple #5
0
def algorithm_maximum_flow(graph):
    graph.add_edge('s', '1', capacity=8)
    graph.add_edge('1', 's', capacity=2)
    graph.add_edge('s', '2', capacity=11)
    graph.add_edge('2', 's', capacity=159)
    graph.add_edge('s', '3', capacity=159)
    graph.add_edge('3', 's', capacity=20)
    graph.add_edge('s', '4', capacity=12)
    graph.add_edge('4', 's', capacity=11)
    graph.add_edge('1', '2', capacity=2)
    graph.add_edge('2', '1', capacity=2)
    graph.add_edge('1', '3', capacity=1)
    graph.add_edge('3', '1', capacity=15)
    graph.add_edge('1', '4', capacity=2)
    graph.add_edge('4', '1', capacity=1)
    graph.add_edge('2', '3', capacity=7)
    graph.add_edge('3', '2', capacity=8)
    graph.add_edge('2', 't', capacity=8)
    graph.add_edge('t', '2', capacity=11)
    graph.add_edge('3', '4', capacity=0)
    graph.add_edge('4', '3', capacity=15)
    graph.add_edge('3', 't', capacity=99)
    graph.add_edge('t', '3', capacity=12)
    graph.add_edge('4', 't', capacity=12)
    graph.add_edge('t', '4', capacity=2)
    result = nx.maximum_flow_value(graph, 's', 't')
    print("Max flow: " + str(result))
Exemple #6
0
def Time(G, name):
    dic = {
        "Fuente": [],
        "Sumidero": [],
        "Media": [],
        "Mediana": [],
        "Std": [],
        "MaxFlow": []
    }
    Nodes = G.nodes
    for i in Nodes:
        for j in Nodes:
            if i != j:
                t = []
                for k in range(10):
                    t.append(Edmond(G, i, j))
                dic["Fuente"].append(i)
                dic["Sumidero"].append(j)
                dic["Media"].append(np.mean(t))
                dic["Mediana"].append(np.median(t))
                dic["Std"].append(np.std(t))
                dic["MaxFlow"].append(
                    nx.maximum_flow_value(G, i, j, capacity="weight"))
    df = pd.DataFrame(dic)
    df.to_csv(name, index=None)
Exemple #7
0
def _chk_cap_flow(anal_graph: DiGraph, capability_info: ComponentInfo,
                  in_ports: Iterable[ICaseString], out_ports: Iterable[object],
                  port_name_func: Callable[[ICaseString], object]) -> None:
    """Check the flow capacity for the given capability and ports.

    `anal_graph` is the analysis graph.
    `capability_info` is the capability information.
    `in_ports` are the input ports supporting the given capability.
    `out_ports` are the output ports of the original processor.
    `port_name_func` is the port reporting name function.
    The function raises a BlockedCapError if the capability through any
    input port can't flow with full or partial capacity from this input
    port to the output ports.

    """
    unit_anal_map = {
        unit_attrs[_OLD_NODE_KEY]: unit
        for unit, unit_attrs in anal_graph.nodes(True)
    }
    unified_out = _aug_out_ports(anal_graph,
                                 [unit_anal_map[port] for port in out_ports])
    unified_out = _split_nodes(anal_graph)[unified_out]
    _dist_edge_caps(anal_graph)

    for cur_port in in_ports:
        _chk_unit_flow(
            networkx.maximum_flow_value(anal_graph, unit_anal_map[cur_port],
                                        unified_out), capability_info,
            ComponentInfo(cur_port, port_name_func(cur_port)))
def disjoint_paths_solution(path_to_graph: str, source: int, target: int) -> int:
    """ Find the maximum amount of edge disjoint paths in graph from source to target

    :param path_to_graph: path to the pickle file with the graph input
    :param source: the desired source
    :param target: the desired target
    :return: maximum amount of disjoint paths
    """

    """
    idea:
    we will transfer the given graph into flow network, such that the capacity over every edge equals 1, and find the
    maximum flow. we can show that the maximum flow (M) equals to the amount of edge disjoint paths in the graph (A):
    
    A <= M:
    let's set the flow to be 1 over every edge if it's part of any of the paths, else 0. this satisfy the capacity
    constrain. this way, a unit of flow arrived the target through every such path, so the total flow is A.
    therefore, the maximum flow is at least A.
    
    M <= A:
    using the integrality theorem (see mathematical section above), there exist a flow over the edges that uses only
    integers. since our capacities are all ones, it means that the flow over every edge can be 0 or 1. it means there
    are at least M edges leaving the source, each one has flow of 1.
    now we use conservation:
    for each of these edges, let's look at it's end-vertex. it must have an out-going edge with flow 1 (by conservation)
    and it must be edge we haven't visited yet (to keep the capacity constrain). this way, for every edge with flow 1
    leaving source, we can create a new edge-disjoint path from source to target, so there are at least M such paths.
    
    so, A=M, and we should just find the maximal path.
    """

    g = nx.read_gpickle(os.path.join(os.getcwd(), path_to_graph))
    nx.set_edge_attributes(g, {edge: 1 for edge in g.edges}, 'capacity')
    return nx.maximum_flow_value(g, source, target)
def getFlowGrouping(mat):
    n = 20
    shannonEntropies = [mat[i, i] for i in range(mat.shape[0])]
    mat2 = sparsify(mat)
    connectome = np.zeros((n, n))
    for i in range(n):
        for j in range(n):
            #print("Nodes "+str(i)+" "+str(j)+".")
            G = nx.DiGraph(data=np.multiply(mat2, lobe_group_masks[i, j]))

            remove = [
                node for node, degree in G.degree().items() if degree == 0
            ]
            G.remove_nodes_from(remove)
            flow = 0.0
            original_nodes = G.nodes()
            #H=capacitate(G,shannonEntropies)
            for node1 in original_nodes:
                for node2 in original_nodes:
                    if node1 != node2:
                        if node1 in lobe_map[i] and node2 in lobe_map[j]:
                            flow += nx.maximum_flow_value(G,
                                                          node1,
                                                          node2,
                                                          capacity='weight')
                            #flow+=nx.maximum_flow_value(H,str(node1)+'_in',str(node2)+'_out',capacity='weight')
            connectome[i, j] = flow

    return connectome
Exemple #10
0
 def test_disconnected(self):
     G = nx.Graph()
     G.add_weighted_edges_from([(0,1,1),(1,2,1),(2,3,1)],weight='capacity')
     G.remove_node(1)
     assert_equal(nx.maximum_flow_value(G,0,3), 0)
     flowSoln = {0: {}, 2: {3: 0}, 3: {2: 0}}
     compare_flows_and_cuts(G, 0, 3, flowSoln, 0)
Exemple #11
0
 def test_disconnected(self):
     G = nx.Graph()
     G.add_weighted_edges_from([(0, 1, 1), (1, 2, 1), (2, 3, 1)], weight='capacity')
     G.remove_node(1)
     assert nx.maximum_flow_value(G, 0, 3) == 0
     flowSoln = {0: {}, 2: {3: 0}, 3: {2: 0}}
     compare_flows_and_cuts(G, 0, 3, flowSoln, 0)
Exemple #12
0
def FlowSum(graph):
    sum = 0
    #wanted to count only the vertix that has a path, another option is using the method "has_path"
    flowDict = nx.all_pairs_shortest_path_length(graph)
    for source in flowDict.keys():
        for target in (flowDict[source]).keys():
            sum += nx.maximum_flow_value(graph, source, target)
    return sum / 2
Exemple #13
0
class Topology(object, nx.Graph):

    for N in [20, 30, 40]:
        for delta in [2, 4, 8]:
            fmax_vector = []
            for i in range(5):
                nodes = range(N)
                np.random.seed(5)
                degree = [delta for i in xrange(N)]
                G = nx.directed_havel_hakimi_graph(degree, degree)
                G = nx.DiGraph(G)

                bb = nx.edge_betweenness_centrality(G, normalized=False)
                nx.set_edge_attributes(G, 'weight', bb)
                nx.set_edge_attributes(G, 'capacity', bb)

                T_matrix = np.zeros((N, N))

                for s in nodes:
                    for d in nodes:
                        if s != d:
                            flow = np.random.uniform(0.5, 1.5)
                            T_matrix[s, d] = flow
                            if G.has_edge(s, d):
                                G.edge[s][d]['weight'] = flow
                                G.edge[s][d]['capacity'] = np.random.randint(
                                    8, 12)

                f_value = 0
                (p, a) = (0, 0)
                for i in range(N):
                    for j in range(N):
                        edges = nx.shortest_path(G, i, j, weight='weight')
                        for k in range(len(edges) - 1):
                            G.edge[edges[k]][edges[
                                k + 1]]['weight'] += T_matrix[i][j]
                    if i != j:
                        flow_value = nx.maximum_flow_value(G, i, j)
                        if flow_value > f_value:
                            f_value = flow_value
                            (p, a) = (i, j)

                fmax = 0
                (s_f, d_f) = (0, 0)

                for s in G.edge:
                    for d in G.edge[s]:
                        if G.edge[s][d]['weight'] > fmax:
                            fmax = G.edge[s][d]['weight']
                            (s_f, d_f) = (s, d)
                fmax_vector.append(fmax)
                tot_edges = G.number_of_edges()

            np.set_printoptions(precision=3)
            #print T_matrix
            #print tot_edges
            print 'N = ' + str(N) + ' D = ' + str(delta) + 'fmax = ' + str(
                np.mean(fmax_vector))  #+ ' flow = ' + str(flow_value)
Exemple #14
0
def disruption(G, originalMaxFlow, upstreamNodes, downstreamNodes):
    """
    Calculate the disruption for each node in the graph.
    This is done by removing the node, calculating the new flow, and
    seeing how different that was from the original.

    input:  G, the graph
            originalMaxFlow, the original maximum flow value
            upstreamNodes, a list of the upstream nodes
            downstreamNodes, a list of the downstream nodes
    output: none, but prints the table of results to stdout 
    """
    #print("Total number of nodes in graph = ", nx.number_of_nodes(G))
    print("Calculating Disruption... ")
   
    disruptionDict = {'source': float('inf'), 'sink': float('inf')}
    sortedGraph = sorted(G.nodes())
    for node in sortedGraph:
        if node != 'source' and node != 'sink':
            outEdges = G.out_edges(node, data=True)
            inEdges = G.in_edges(node, data=True) 
            G.remove_node(node)
            try:
                flow_value = nx.maximum_flow_value(G, 'source', 'sink')
                flowDifference = originalMaxFlow - flow_value
                disruptionDict[node] = flowDifference   
            except:
                print(sys.exc_info()[0])
                print("Error evaluating flow when removing node ", node)
                sys.exit(1)
            G.add_node(node)
            G.add_edges_from(inEdges)
            G.add_edges_from(outEdges)

    nodes = G.nodes()
    sortedDisruption = sorted(nodes, key=disruptionDict.__getitem__, reverse=True)
    sortedDisruption.remove('source')
    sortedDisruption.remove('sink')
    zeroEffectGenes = ""

    print("Flow Difference {0:2} % Change {1:8} Node type {2:2} Node ".format("","",""))
    print('------------------------------------------------------------------')
    for node in sortedDisruption:
        flowDifference = disruptionDict[node]
        percentChange = flowDifference / originalMaxFlow * 100
        nodeType = "linker"
        if node in upstreamNodes:
            nodeType = "UPSTREAM"
        elif node in downstreamNodes:
            nodeType = "DOWNSTREAM"
        if flowDifference <= 0.005:
            zeroEffectGenes += node + "\t "
        else:
            print("{0:20} {1:15} {2:12} {3}".format('%.2f' % flowDifference, 
                '%.2f' % percentChange, nodeType, node))
    # These were clogging up the output, so I condensed them a bit
    print("\nGenes that had zero effect on flow: ")
    print(zeroEffectGenes)
Exemple #15
0
 def test_complete_graph_cutoff(self):
     G = nx.complete_graph(5)
     nx.set_edge_attributes(G, {(u, v): 1 for u, v in G.edges()},
                            'capacity')
     for flow_func in [shortest_augmenting_path, edmonds_karp]:
         for cutoff in [3, 2, 1]:
             result = nx.maximum_flow_value(G, 0, 4, flow_func=flow_func,
                                            cutoff=cutoff)
             assert cutoff == result, "cutoff error in {0}".format(flow_func.__name__)
Exemple #16
0
def apply(net):
    """
    Using the max-flow min-cut theorem, we compute a list of nett well handled TP and PT pairs
    (T=transition, P=place)
    :param net: Petri Net
    :return: List
    """
    graph, booking = create_network_graph(net)
    pairs = []
    for place in net.places:
        for transition in net.transitions:
            p = booking[place]
            t = booking[transition]
            if nx.maximum_flow_value(graph, p + 1, t) > 1:
                pairs.append((p + 1, t))
            if nx.maximum_flow_value(graph, t + 1, p) > 1:
                pairs.append((t + 1, p))
    return pairs
Exemple #17
0
def main(N, adj, k, L):
    iterations = 10
    result = 'Failed'
    while iterations > 0 and result == 'Failed':
        print iterations
        G = getGraph(N, adj)
        S = getS(G, k)
        S = doOneSwaps(G, S, L)
        H = defaultdict(list)
        result = None
        #max flow value cannot be greater than the number of nodes in the graph or set V
        if nx.maximum_flow_value(getFlowGraph(G, S, L), 's', 't') == N:
            #uncomment the below to compute assignments
            '''_,flows = nx.maximum_flow(getFlowGraph(G, S, L), 's', 't')
			edges = set(G.edges())
		        #if a flow exists along a particular path assigning v to that vertex in S
			for v in G.nodes():
				for s in S:
					if (min(v,s),max(v,s)) in edges:
						unitflow = False
						try:
							if flows[max(v,s + N)][min(v,s + N)] == 1:
								unitflow = True
						except KeyError:
							try:
								if flows[min(v,s + N)][max(v,s + N)] == 1:
									unitflow = True
							except KeyError:
								pass
						if unitflow:
							H[s].append(v)'''
            result = 'Success'
        else:
            result = 'Failed'
        iterations -= 1
    if result == 'Failed':
        ''' Save the graph as an image, and its adjacency matrix
			as a pickle file '''
        pos = nx.spring_layout(G, k=0.5)
        nx.draw_networkx_nodes(G,
                               pos,
                               nodelist=S,
                               node_color='b',
                               node_size=200)
        nx.draw_networkx_nodes(G,
                               pos,
                               nodelist=list(set(G.nodes()) - set(S)),
                               node_color='r',
                               node_size=200)
        nx.draw_networkx_edges(G, pos, edgeList=list(G.edges()))
        fname = str(randint(1, 10**9))
        plt.savefig('failures/' + fname)
        a = [[0 for _ in xrange(N)] for _ in xrange(N)]
        for key, val in adj.iteritems():
            a[key[0]][key[1]] = val
        pickle.dump(a, open('failures/' + fname, 'w'))
    return result
Exemple #18
0
 def get_flow(self):
     try:
         R = nx.algorithms.flow.edmonds_karp(self.G, self.start, self.end)
         flow_val = nx.maximum_flow_value(self.G, self.start, self.end)
         if self.debug >= 2:
             print("max_flow: " + str(flow_val))
             print(flow_val == R.graph["flow_value"])
     except nx.exception.NetworkXError:
         print("self.G.nodes() is None")
Exemple #19
0
 def test_complete_graph_cutoff(self):
     G = nx.complete_graph(5)
     nx.set_edge_attributes(G, 'capacity', 
                            dict(((u, v), 1) for u, v in G.edges()))
     for flow_func in [shortest_augmenting_path, edmonds_karp]:
         for cutoff in [3, 2, 1]:
             result = nx.maximum_flow_value(G, 0, 4, flow_func=flow_func,
                                            cutoff=cutoff)
             assert_equal(cutoff, result, 
                         msg="cutoff error in {0}".format(flow_func.__name__))
Exemple #20
0
def MaxFlow(graph):
    max = 0
    #wanted to count only the vertix that has a path, another option is using the method "has_path"
    flowDict = nx.all_pairs_shortest_path_length(graph)
    for source in flowDict.keys():
        for target in (flowDict[source]).keys():
            flow = nx.maximum_flow_value(graph, source, target)
            if (flow > max):
                max = flow
    return max / 2  #counts twice
Exemple #21
0
def build_max_flows_dict(g):
    global i, j
    for i in g.nodes():
        for j in g.nodes():
            if i == j:
                continue
            # nice function in networkX to find the
            # maximum flow in a single-commodity flow.
            max_flows_dict[(i, j)] = nx.maximum_flow_value(g, i, j)
    return max_flows_dict
Exemple #22
0
def maxFlowValue(workers, taskids, b=1):
    """
    Compute max-flow between source s and destination d
    :param workers:
    :param taskids:
    :param b:
    :return:
    """
    DG = createDG(workers, taskids, b)
    return nx.maximum_flow_value(DG, "s", "d")
    def test_pyramid(self):
        N = 10
        # N = 100 # this gives a graph with 5051 nodes
        G = gen_pyramid(N)
        R = build_residual_network(G, "capacity")
        kwargs = dict(residual=R)

        for flow_func in flow_funcs:
            kwargs["flow_func"] = flow_func
            flow_value = nx.maximum_flow_value(G, (0, 0), "t", **kwargs)
            assert_almost_equal(flow_value, 1.0, msg=msg.format(flow_func.__name__))
    def test_complete_graph(self):
        N = 50
        G = nx.complete_graph(N)
        nx.set_edge_attributes(G, 5, 'capacity')
        R = build_residual_network(G, 'capacity')
        kwargs = dict(residual=R)

        for flow_func in flow_funcs:
            kwargs['flow_func'] = flow_func
            flow_value = nx.maximum_flow_value(G, 1, 2, **kwargs)
            assert flow_value == 5 * (N - 1), msg.format(flow_func.__name__)
    def test_complete_graph(self):
        N = 50
        G = nx.complete_graph(N)
        nx.set_edge_attributes(G, "capacity", 5)
        R = build_residual_network(G, "capacity")
        kwargs = dict(residual=R)

        for flow_func in flow_funcs:
            kwargs["flow_func"] = flow_func
            flow_value = nx.maximum_flow_value(G, 1, 2, **kwargs)
            assert_equal(flow_value, 5 * (N - 1), msg=msg.format(flow_func.__name__))
Exemple #26
0
    def netflow_step(self):

        for node in self.graph.nodes_iter():
            if node == self.identity:
                self.graph.node[node]['score'] = 0

                continue
            score = nx.maximum_flow_value(self.augmented_graph, node + "IN",
                                          self.identity + "OUT")

            self.graph.node[node]['score'] = score
    def test_pyramid(self):
        N = 10
        # N = 100 # this gives a graph with 5051 nodes
        G = gen_pyramid(N)
        R = build_residual_network(G, 'capacity')
        kwargs = dict(residual=R)

        for flow_func in flow_funcs:
            kwargs['flow_func'] = flow_func
            flow_value = nx.maximum_flow_value(G, (0, 0), 't', **kwargs)
            assert almost_equal(flow_value, 1.), msg.format(flow_func.__name__)
Exemple #28
0
def find_maximum_flow(H, s, t):
    '''Finds maximum flow between a source and target node in DiGraph G.
    Requires edge attribute 'capacity'. MultiDiGraphs not supported.
    '''
    if type(H) == nx.classes.digraph.DiGraph:
        max_flow_path = nx.maximum_flow(H, s, t)
        max_flow = nx.maximum_flow_value(H, s, t)
        return max_flow_path, max_flow
    else:
        raise TypeError('Graph must be DiGraph type. Use \
            convert_to_digraph to help convert a MultiDiGraph to a DiGraph, \
            which may result in loss of information')
Exemple #29
0
 def get_max_flow_demand(G):
     results = []
     max_flow = 0
     for i in G:
         for j in G:
             if (i == j):
                 continue
             else:
                 flow = nx.maximum_flow_value(G, i, j)
                 flow = int(flow)
                 results.append(flow)
     return results
    def test_pyramid(self):
        N = 10
        # N = 100 # this gives a graph with 5051 nodes
        G = gen_pyramid(N)
        R = build_residual_network(G, "capacity")
        kwargs = dict(residual=R)

        for flow_func in flow_funcs:
            kwargs["flow_func"] = flow_func
            errmsg = f"Assertion failed in function: {flow_func.__name__}"
            flow_value = nx.maximum_flow_value(G, (0, 0), "t", **kwargs)
            assert almost_equal(flow_value, 1.0), errmsg
    def test_complete_graph(self):
        N = 50
        G = nx.complete_graph(N)
        nx.set_edge_attributes(G, 5, "capacity")
        R = build_residual_network(G, "capacity")
        kwargs = dict(residual=R)

        for flow_func in flow_funcs:
            kwargs["flow_func"] = flow_func
            errmsg = f"Assertion failed in function: {flow_func.__name__}"
            flow_value = nx.maximum_flow_value(G, 1, 2, **kwargs)
            assert flow_value == 5 * (N - 1), errmsg
def find_max_flow(good_routes, ny, sf, plane_cap, draw=False):
    matrix, sink_index, v_map = create_adj_matrix(good_routes,
                                                  plane_cap,
                                                  ny,
                                                  sf,
                                                  draw=draw)
    graph = nx.convert_matrix.from_numpy_matrix(matrix,
                                                create_using=nx.DiGraph)
    return nx.maximum_flow_value(graph,
                                 len(matrix) - 1,
                                 sink_index,
                                 capacity='weight')
def max_congestion(G):
    num_of_nodes = G.number_of_nodes()
    max_value = 1
    for x in range(num_of_nodes):
        if G.degree(x) <= max_value:
            break
        else:
            for y in range(x + 1, num_of_nodes):

                current_value = nx.maximum_flow_value(G, x, y)
                if max_value < current_value:
                    max_value = current_value
    print(max_value)
    def __faultScen_single_edge(self):
        edgeFaultEffectonFlow = {}
        faultyEdgeFlow = {}
        for e in self.G.edges:
            g = self.G.copy()
            g[e[0]][e[1]]['capacity'] = 0
            _, edgeFaultEffectonFlow[e], _ = self.maxFlowMinCost(g)

            faultyEdgeFlow[e] = nx.maximum_flow_value(g, _s='s', _t='t')
        faultDF = pd.DataFrame.from_dict(edgeFaultEffectonFlow)
        faultDF.set_index(faultDF.index.values, inplace=True)
        faultDF.columns = faultDF.columns.values

        return faultDF, faultyEdgeFlow, edgeFaultEffectonFlow
Exemple #35
0
def cli(ek, draw, input_file):
    g, source, sink = parse_dicaps_graph(input_file)
    if draw:
        write_dot(g, 'graph.dot')
        return
    if ek:
        print('Using Edmonds Karp')
        flow_func = edmonds_karp
    else:
        print('Using Preflow Push')
        flow_func = None
    t0 = time.time()
    flow = nx.maximum_flow_value(g, source, sink, flow_func=flow_func)
    t1 = time.time()
    print("Max Flow Solution: {0}".format(flow))
    print("Runtime: {0}s".format(t1 - t0))
def person_max_flow(graph, num_strategic, sybil_pct=0, cutlinks=True,
                    gensybils=True, strategic_agents=None,
                    return_data=False):
    graph = graph.copy()
    N = graph.number_of_nodes()
    if strategic_agents is None:
        strategic_agents = random_strategic_agents(graph, num_strategic)
    saved_edges = {}
    if cutlinks:
        saved_edges = {a: graph.edges(a, data=True) for a in strategic_agents}
        cut_outlinks(graph, strategic_agents, leave_one=True)  # TODO: Are you sure you want leave_one=True?
        after_edges = {a: graph.edges(a, data=True) for a in strategic_agents}

    # For Max Flow, don't apply sybils since it is strategyproof to sybils
    # if gensybils:
        # num_sybils = int(graph.number_of_nodes() * sybil_pct)
        # generate_sybils(graph, strategic_agents, num_sybils)

    # Need to reimplement max flow here because we only want to cut outedges
    # When we're not being evaluated.
    scores = np.zeros((N, N))
    for i in xrange(N):
        # Add back in the edges for this agent, so we can get an actual score.
        # if cutlinks and i in strategic_agents:
            # graph.remove_edges_from(graph.edges(i))
            # graph.add_edges_from(saved_edges[i])

        # Now compute the max flow scores
        for j in xrange(N):
            if i != j:
                scores[i, j] = nx.maximum_flow_value(graph, i, j, capacity='weight')
                # scores[i, j] = utils.fast_max_flow(graph.gt_graph, i, j)

        # Restore post-cut edges
        # if cutlinks and i in strategic_agents:
            # graph.remove_edges_from(graph.edges(i))
            # graph.add_edges_from(after_edges[i])

        sys.stdout.write('.')
    sys.stdout.write("\n")

    if return_data:
        return scores, {'strategic_agents': strategic_agents, 'graph': graph}
    else:
        return scores
def getStartingWeights(G, numNodes, unipartite):
	
	if unipartite == True:
		weights=numpy.zeros((numNodes,numNodes))
		for edge in G.edges():
			source = edge[0]
			dest = edge[1]
			flow = nx.maximum_flow_value(G, source, dest)
			weights[source][dest] = flow
			weights[dest][source] = flow
	else:
		shortestPaths=nx.all_pairs_shortest_path_length(G)
		weights=numpy.zeros((numNodes,numNodes))
		for sourceNode,paths in shortestPaths.items():
				for destNode,pathLength in paths.items():
					weights[sourceNode][destNode]=pathLength
	
	
	Y = squareform(weights)	
	return Y
Exemple #38
0
def CalMaxFlows(DG_network, Dnodes, maxFlows):
	"""
	If two nodes are connected in networkx graph G, This function returns maxflow value, shortest path length, minimum edges cut 
	between this two nodes.
	"""
	for i in range(len(Dnodes)):
		for j in range(i+1, len(Dnodes)):

			if nx.has_path(DG_network, Dnodes[i], Dnodes[j]):
				maxflow = nx.maximum_flow_value(DG_network, Dnodes[i], Dnodes[j], capacity = 'weight')
				shortest_path_length = nx.shortest_path_length(DG_network, source = Dnodes[i], target = Dnodes[j])
				min_edges_cut = len(nx.minimum_edge_cut(DG_network, Dnodes[i], Dnodes[j]))
			else:
				continue
			if Dnodes[i] < Dnodes[j]:
				a_path = (Dnodes[i], Dnodes[j])
			else:
				a_path = (Dnodes[j], Dnodes[i])

			if not maxFlows.has_key(a_path):
				maxFlows[a_path] = (maxflow, shortest_path_length, min_edges_cut)
			else:
				print "impossibly!", a_path
				sys.exit(1)
Exemple #39
0
def local_edge_connectivity(G, u, v, flow_func=None, auxiliary=None,
                            residual=None, cutoff=None):
    r"""Returns local edge connectivity for nodes s and t in G.

    Local edge connectivity for two nodes s and t is the minimum number
    of edges that must be removed to disconnect them.

    This is a flow based implementation of edge connectivity. We compute the
    maximum flow on an auxiliary digraph build from the original
    network (see below for details). This is equal to the local edge
    connectivity because the value of a maximum s-t-flow is equal to the
    capacity of a minimum s-t-cut (Ford and Fulkerson theorem) [1]_ .

    Parameters
    ----------
    G : NetworkX graph
        Undirected or directed graph

    s : node
        Source node

    t : node
        Target node

    flow_func : function
        A function for computing the maximum flow among a pair of nodes.
        The function has to accept at least three parameters: a Digraph,
        a source node, and a target node. And return a residual network
        that follows NetworkX conventions (see :meth:`maximum_flow` for
        details). If flow_func is None, the default maximum flow function
        (:meth:`edmonds_karp`) is used. See below for details. The
        choice of the default function may change from version
        to version and should not be relied on. Default value: None.

    auxiliary : NetworkX DiGraph
        Auxiliary digraph for computing flow based edge connectivity. If
        provided it will be reused instead of recreated. Default value: None.

    residual : NetworkX DiGraph
        Residual network to compute maximum flow. If provided it will be
        reused instead of recreated. Default value: None.

    cutoff : integer, float
        If specified, the maximum flow algorithm will terminate when the
        flow value reaches or exceeds the cutoff. This is only for the
        algorithms that support the cutoff parameter: :meth:`edmonds_karp`
        and :meth:`shortest_augmenting_path`. Other algorithms will ignore
        this parameter. Default value: None.

    Returns
    -------
    K : integer
        local edge connectivity for nodes s and t.

    Examples
    --------
    This function is not imported in the base NetworkX namespace, so you
    have to explicitly import it from the connectivity package:

    >>> from networkx.algorithms.connectivity import local_edge_connectivity

    We use in this example the platonic icosahedral graph, which has edge
    connectivity 5.

    >>> G = nx.icosahedral_graph()
    >>> local_edge_connectivity(G, 0, 6)
    5

    If you need to compute local connectivity on several pairs of
    nodes in the same graph, it is recommended that you reuse the
    data structures that NetworkX uses in the computation: the
    auxiliary digraph for edge connectivity, and the residual
    network for the underlying maximum flow computation.

    Example of how to compute local edge connectivity among
    all pairs of nodes of the platonic icosahedral graph reusing
    the data structures.

    >>> import itertools
    >>> # You also have to explicitly import the function for
    >>> # building the auxiliary digraph from the connectivity package
    >>> from networkx.algorithms.connectivity import (
    ...     build_auxiliary_edge_connectivity)
    >>> H = build_auxiliary_edge_connectivity(G)
    >>> # And the function for building the residual network from the
    >>> # flow package
    >>> from networkx.algorithms.flow import build_residual_network
    >>> # Note that the auxiliary digraph has an edge attribute named capacity
    >>> R = build_residual_network(H, 'capacity')
    >>> result = dict.fromkeys(G, dict())
    >>> # Reuse the auxiliary digraph and the residual network by passing them
    >>> # as parameters
    >>> for u, v in itertools.combinations(G, 2):
    ...     k = local_edge_connectivity(G, u, v, auxiliary=H, residual=R)
    ...     result[u][v] = k
    >>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2))
    True

    You can also use alternative flow algorithms for computing edge
    connectivity. For instance, in dense networks the algorithm
    :meth:`shortest_augmenting_path` will usually perform better than
    the default :meth:`edmonds_karp` which is faster for sparse
    networks with highly skewed degree distributions. Alternative flow
    functions have to be explicitly imported from the flow package.

    >>> from networkx.algorithms.flow import shortest_augmenting_path
    >>> local_edge_connectivity(G, 0, 6, flow_func=shortest_augmenting_path)
    5

    Notes
    -----
    This is a flow based implementation of edge connectivity. We compute the
    maximum flow using, by default, the :meth:`edmonds_karp` algorithm on an
    auxiliary digraph build from the original input graph:

    If the input graph is undirected, we replace each edge (`u`,`v`) with
    two reciprocal arcs (`u`, `v`) and (`v`, `u`) and then we set the attribute
    'capacity' for each arc to 1. If the input graph is directed we simply
    add the 'capacity' attribute. This is an implementation of algorithm 1
    in [1]_.

    The maximum flow in the auxiliary network is equal to the local edge
    connectivity because the value of a maximum s-t-flow is equal to the
    capacity of a minimum s-t-cut (Ford and Fulkerson theorem).

    See also
    --------
    :meth:`edge_connectivity`
    :meth:`local_node_connectivity`
    :meth:`node_connectivity`
    :meth:`maximum_flow`
    :meth:`edmonds_karp`
    :meth:`preflow_push`
    :meth:`shortest_augmenting_path`

    References
    ----------
    .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
        http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf

    """
    if flow_func is None:
        flow_func = default_flow_func

    if auxiliary is None:
        H = build_auxiliary_edge_connectivity(G)
    else:
        H = auxiliary

    kwargs = dict(flow_func=flow_func, residual=residual)
    if flow_func is shortest_augmenting_path:
        kwargs['cutoff'] = cutoff
        kwargs['two_phase'] = True
    elif flow_func is edmonds_karp:
        kwargs['cutoff'] = cutoff

    return nx.maximum_flow_value(H, u, v, **kwargs)
Exemple #40
0
def local_node_connectivity(G, s, t, flow_func=None, auxiliary=None,
                            residual=None, cutoff=None):
    r"""Computes local node connectivity for nodes s and t.

    Local node connectivity for two non adjacent nodes s and t is the
    minimum number of nodes that must be removed (along with their incident
    edges) to disconnect them.

    This is a flow based implementation of node connectivity. We compute the
    maximum flow on an auxiliary digraph build from the original input
    graph (see below for details).

    Parameters
    ----------
    G : NetworkX graph
        Undirected graph

    s : node
        Source node

    t : node
        Target node

    flow_func : function
        A function for computing the maximum flow among a pair of nodes.
        The function has to accept at least three parameters: a Digraph,
        a source node, and a target node. And return a residual network
        that follows NetworkX conventions (see :meth:`maximum_flow` for
        details). If flow_func is None, the default maximum flow function
        (:meth:`edmonds_karp`) is used. See below for details. The choice
        of the default function may change from version to version and
        should not be relied on. Default value: None.

    auxiliary : NetworkX DiGraph
        Auxiliary digraph to compute flow based node connectivity. It has
        to have a graph attribute called mapping with a dictionary mapping
        node names in G and in the auxiliary digraph. If provided
        it will be reused instead of recreated. Default value: None.

    residual : NetworkX DiGraph
        Residual network to compute maximum flow. If provided it will be
        reused instead of recreated. Default value: None.

    cutoff : integer, float
        If specified, the maximum flow algorithm will terminate when the
        flow value reaches or exceeds the cutoff. This is only for the
        algorithms that support the cutoff parameter: :meth:`edmonds_karp`
        and :meth:`shortest_augmenting_path`. Other algorithms will ignore
        this parameter. Default value: None.

    Returns
    -------
    K : integer
        local node connectivity for nodes s and t

    Examples
    --------
    This function is not imported in the base NetworkX namespace, so you
    have to explicitly import it from the connectivity package:

    >>> from networkx.algorithms.connectivity import local_node_connectivity

    We use in this example the platonic icosahedral graph, which has node
    connectivity 5.

    >>> G = nx.icosahedral_graph()
    >>> local_node_connectivity(G, 0, 6)
    5

    If you need to compute local connectivity on several pairs of
    nodes in the same graph, it is recommended that you reuse the
    data structures that NetworkX uses in the computation: the
    auxiliary digraph for node connectivity, and the residual
    network for the underlying maximum flow computation.

    Example of how to compute local node connectivity among
    all pairs of nodes of the platonic icosahedral graph reusing
    the data structures.

    >>> import itertools
    >>> # You also have to explicitly import the function for
    >>> # building the auxiliary digraph from the connectivity package
    >>> from networkx.algorithms.connectivity import (
    ...     build_auxiliary_node_connectivity)
    ...
    >>> H = build_auxiliary_node_connectivity(G)
    >>> # And the function for building the residual network from the
    >>> # flow package
    >>> from networkx.algorithms.flow import build_residual_network
    >>> # Note that the auxiliary digraph has an edge attribute named capacity
    >>> R = build_residual_network(H, 'capacity')
    >>> result = dict.fromkeys(G, dict())
    >>> # Reuse the auxiliary digraph and the residual network by passing them
    >>> # as parameters
    >>> for u, v in itertools.combinations(G, 2):
    ...     k = local_node_connectivity(G, u, v, auxiliary=H, residual=R)
    ...     result[u][v] = k
    ...
    >>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2))
    True

    You can also use alternative flow algorithms for computing node
    connectivity. For instance, in dense networks the algorithm
    :meth:`shortest_augmenting_path` will usually perform better than
    the default :meth:`edmonds_karp` which is faster for sparse
    networks with highly skewed degree distributions. Alternative flow
    functions have to be explicitly imported from the flow package.

    >>> from networkx.algorithms.flow import shortest_augmenting_path
    >>> local_node_connectivity(G, 0, 6, flow_func=shortest_augmenting_path)
    5

    Notes
    -----
    This is a flow based implementation of node connectivity. We compute the
    maximum flow using, by default, the :meth:`edmonds_karp` algorithm (see:
    :meth:`maximum_flow`) on an auxiliary digraph build from the original
    input graph:

    For an undirected graph G having `n` nodes and `m` edges we derive a
    directed graph H with `2n` nodes and `2m+n` arcs by replacing each
    original node `v` with two nodes `v_A`, `v_B` linked by an (internal)
    arc in H. Then for each edge (`u`, `v`) in G we add two arcs
    (`u_B`, `v_A`) and (`v_B`, `u_A`) in H. Finally we set the attribute
    capacity = 1 for each arc in H [1]_ .

    For a directed graph G having `n` nodes and `m` arcs we derive a
    directed graph H with `2n` nodes and `m+n` arcs by replacing each
    original node `v` with two nodes `v_A`, `v_B` linked by an (internal)
    arc (`v_A`, `v_B`) in H. Then for each arc (`u`, `v`) in G we add one arc
    (`u_B`, `v_A`) in H. Finally we set the attribute capacity = 1 for
    each arc in H.

    This is equal to the local node connectivity because the value of
    a maximum s-t-flow is equal to the capacity of a minimum s-t-cut.

    See also
    --------
    :meth:`local_edge_connectivity`
    :meth:`node_connectivity`
    :meth:`minimum_node_cut`
    :meth:`maximum_flow`
    :meth:`edmonds_karp`
    :meth:`preflow_push`
    :meth:`shortest_augmenting_path`

    References
    ----------
    .. [1] Kammer, Frank and Hanjo Taubig. Graph Connectivity. in Brandes and
        Erlebach, 'Network Analysis: Methodological Foundations', Lecture
        Notes in Computer Science, Volume 3418, Springer-Verlag, 2005.
        http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf

    """
    if flow_func is None:
        flow_func = default_flow_func

    if auxiliary is None:
        H = build_auxiliary_node_connectivity(G)
    else:
        H = auxiliary

    mapping = H.graph.get('mapping', None)
    if mapping is None:
        raise nx.NetworkXError('Invalid auxiliary digraph.')

    kwargs = dict(flow_func=flow_func, residual=residual)
    if flow_func is shortest_augmenting_path:
        kwargs['cutoff'] = cutoff
        kwargs['two_phase'] = True
    elif flow_func is edmonds_karp:
        kwargs['cutoff'] = cutoff

    return nx.maximum_flow_value(H, '%sB' % mapping[s], '%sA' % mapping[t], **kwargs)
Exemple #41
0
    global target
    if len(sys.argv) != 4:
        print "Usage: python <source_file> <path_of_input_data_file> <source_node> <sink_node> "
        sys.exit()
    else:
        inputpath = sys.argv[1]
        source = int(sys.argv[2])
        target = int(sys.argv[3])

if __name__ == "__main__":
    main(sys.argv)


#G=nx.read_gml("C:\Users\Justin\Documents\karate (1)\karate.gml")
G=nx.read_gml(inputpath)
for u in G.edges():
    G[u[0]][u[1]]['capacity']=1.0

maxflow1= nx.maximum_flow_value(G,source,target)
mincut1 = nx.minimum_cut_value(G,source,target)


#H=nx.read_gml("C:\Users\Justin\Downloads\power\power.gml")
#for u in H.edges():
#    H[u[0]][u[1]]['capacity']=1.0

#maxflow2 = nx.maximum_flow_value(H,2553,4458)
#mincut2 = nx.minimum_cut_value(H,2553,4458)

#print maxflow1, mincut1, maxflow2, mincut2
print maxflow1, mincut1
Exemple #42
0
def local_node_connectivity(G, s, t, aux_digraph=None, mapping=None):
    r"""Computes local node connectivity for nodes s and t.

    Local node connectivity for two non adjacent nodes s and t is the
    minimum number of nodes that must be removed (along with their incident
    edges) to disconnect them.

    This is a flow based implementation of node connectivity. We compute the
    maximum flow on an auxiliary digraph build from the original input
    graph (see below for details). This is equal to the local node
    connectivity because the value of a maximum s-t-flow is equal to the
    capacity of a minimum s-t-cut (Ford and Fulkerson theorem) [1]_ .

    Parameters
    ----------
    G : NetworkX graph
        Undirected graph

    s : node
        Source node

    t : node
        Target node

    aux_digraph : NetworkX DiGraph (default=None)
        Auxiliary digraph to compute flow based node connectivity. If None
        the auxiliary digraph is build.

    mapping : dict (default=None)
        Dictionary with a mapping of node names in G and in the auxiliary digraph.

    Returns
    -------
    K : integer
        local node connectivity for nodes s and t

    Examples
    --------
    >>> # Platonic icosahedral graph has node connectivity 5
    >>> # for each non adjacent node pair
    >>> G = nx.icosahedral_graph()
    >>> nx.local_node_connectivity(G,0,6)
    5

    Notes
    -----
    This is a flow based implementation of node connectivity. We compute the
    maximum flow using the Ford and Fulkerson algorithm on an auxiliary digraph
    build from the original input graph:

    For an undirected graph G having `n` nodes and `m` edges we derive a
    directed graph D with 2n nodes and 2m+n arcs by replacing each
    original node `v` with two nodes `v_A`, `v_B` linked by an (internal)
    arc in `D`. Then for each edge (`u`, `v`) in G we add two arcs
    (`u_B`, `v_A`) and (`v_B`, `u_A`) in `D`. Finally we set the attribute
    capacity = 1 for each arc in `D` [1]_ .

    For a directed graph G having `n` nodes and `m` arcs we derive a
    directed graph `D` with `2n` nodes and `m+n` arcs by replacing each
    original node `v` with two nodes `v_A`, `v_B` linked by an (internal)
    arc `(v_A, v_B)` in D. Then for each arc `(u,v)` in G we add one arc
    `(u_B,v_A)` in `D`. Finally we set the attribute capacity = 1 for
    each arc in `D`.

    This is equal to the local node connectivity because the value of
    a maximum s-t-flow is equal to the capacity of a minimum s-t-cut (Ford
    and Fulkerson theorem).

    See also
    --------
    node_connectivity
    all_pairs_node_connectivity_matrix
    local_edge_connectivity
    edge_connectivity
    max_flow
    ford_fulkerson

    References
    ----------
    .. [1] Kammer, Frank and Hanjo Taubig. Graph Connectivity. in Brandes and
        Erlebach, 'Network Analysis: Methodological Foundations', Lecture
        Notes in Computer Science, Volume 3418, Springer-Verlag, 2005.
        http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf
    """
    if aux_digraph is None or mapping is None:
        H, mapping = _aux_digraph_node_connectivity(G)
    else:
        H = aux_digraph
    return nx.maximum_flow_value(H,'%sB' % mapping[s], '%sA' % mapping[t])
Exemple #43
0
def local_edge_connectivity(G, u, v, aux_digraph=None):
    r"""Returns local edge connectivity for nodes s and t in G.

    Local edge connectivity for two nodes s and t is the minimum number
    of edges that must be removed to disconnect them.

    This is a flow based implementation of edge connectivity. We compute the
    maximum flow on an auxiliary digraph build from the original
    network (see below for details). This is equal to the local edge
    connectivity because the value of a maximum s-t-flow is equal to the
    capacity of a minimum s-t-cut (Ford and Fulkerson theorem) [1]_ .

    Parameters
    ----------
    G : NetworkX graph
        Undirected or directed graph

    s : node
        Source node

    t : node
        Target node

    aux_digraph : NetworkX DiGraph (default=None)
        Auxiliary digraph to compute flow based edge connectivity. If None
        the auxiliary digraph is build.

    Returns
    -------
    K : integer
        local edge connectivity for nodes s and t

    Examples
    --------
    >>> # Platonic icosahedral graph has edge connectivity 5
    >>> # for each non adjacent node pair
    >>> G = nx.icosahedral_graph()
    >>> nx.local_edge_connectivity(G,0,6)
    5

    Notes
    -----
    This is a flow based implementation of edge connectivity. We compute the
    maximum flow using the Ford and Fulkerson algorithm on an auxiliary digraph
    build from the original graph:

    If the input graph is undirected, we replace each edge (u,v) with
    two reciprocal arcs `(u,v)` and `(v,u)` and then we set the attribute
    'capacity' for each arc to 1. If the input graph is directed we simply
    add the 'capacity' attribute. This is an implementation of algorithm 1
    in [1]_.

    The maximum flow in the auxiliary network is equal to the local edge
    connectivity because the value of a maximum s-t-flow is equal to the
    capacity of a minimum s-t-cut (Ford and Fulkerson theorem).

    See also
    --------
    local_node_connectivity
    node_connectivity
    edge_connectivity
    max_flow
    ford_fulkerson

    References
    ----------
    .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
        http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
    """
    if aux_digraph is None:
        H = _aux_digraph_edge_connectivity(G)
    else:
        H = aux_digraph
    return nx.maximum_flow_value(H, u, v)
Exemple #44
0
def max_flow_min_cost(G, s, t, capacity='capacity', weight='weight'):
    """Return a maximum (s, t)-flow of minimum cost.

    G is a digraph with edge costs and capacities. There is a source
    node s and a sink node t. This function finds a maximum flow from
    s to t whose total cost is minimized.

    Parameters
    ----------
    G : NetworkX graph
        DiGraph on which a minimum cost flow satisfying all demands is
        to be found.

    s: node label
        Source of the flow.

    t: node label
        Destination of 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'.

    weight: string
        Edges of the graph G are expected to have an attribute weight
        that indicates the cost incurred by sending one unit of flow on
        that edge. If not present, the weight is considered to be 0.
        Default value: 'weight'.

    Returns
    -------
    flowDict: dictionary
        Dictionary of dictionaries keyed by nodes such that
        flowDict[u][v] is the flow edge (u, v).

    Raises
    ------
    NetworkXError
        This exception is raised if the input graph is not directed or
        not connected.

    NetworkXUnbounded
        This exception is raised if there is an infinite capacity path
        from s to t in G. In this case there is no maximum flow. This
        exception is also raised if the digraph G has a cycle of
        negative cost and infinite capacity. Then, the cost of a flow
        is unbounded below.

    See also
    --------
    cost_of_flow, min_cost_flow, min_cost_flow_cost, network_simplex

    Notes
    -----
    This algorithm is not guaranteed to work if edge weights or demands
    are floating point numbers (overflows and roundoff errors can
    cause problems). As a workaround you can use integer numbers by
    multiplying the relevant edge attributes by a convenient
    constant factor (eg 100).

    Examples
    --------
    >>> G = nx.DiGraph()
    >>> G.add_edges_from([(1, 2, {'capacity': 12, 'weight': 4}),
    ...                   (1, 3, {'capacity': 20, 'weight': 6}),
    ...                   (2, 3, {'capacity': 6, 'weight': -3}),
    ...                   (2, 6, {'capacity': 14, 'weight': 1}),
    ...                   (3, 4, {'weight': 9}),
    ...                   (3, 5, {'capacity': 10, 'weight': 5}),
    ...                   (4, 2, {'capacity': 19, 'weight': 13}),
    ...                   (4, 5, {'capacity': 4, 'weight': 0}),
    ...                   (5, 7, {'capacity': 28, 'weight': 2}),
    ...                   (6, 5, {'capacity': 11, 'weight': 1}),
    ...                   (6, 7, {'weight': 8}),
    ...                   (7, 4, {'capacity': 6, 'weight': 6})])
    >>> mincostFlow = nx.max_flow_min_cost(G, 1, 7)
    >>> mincost = nx.cost_of_flow(G, mincostFlow)
    >>> mincost
    373
    >>> from networkx.algorithms.flow import maximum_flow
    >>> maxFlow = maximum_flow(G, 1, 7)[1]
    >>> nx.cost_of_flow(G, maxFlow) >= mincost
    True
    >>> mincostFlowValue = (sum((mincostFlow[u][7] for u in G.predecessors(7)))
    ...                     - sum((mincostFlow[7][v] for v in G.successors(7))))
    >>> mincostFlowValue == nx.maximum_flow_value(G, 1, 7)
    True

    """
    maxFlow = nx.maximum_flow_value(G, s, t, capacity=capacity)
    H = nx.DiGraph(G)
    H.add_node(s, demand=-maxFlow)
    H.add_node(t, demand=maxFlow)
    return min_cost_flow(H, capacity=capacity, weight=weight)
Exemple #45
0
import math
import itertools as it
import networkx as nx
from networkx import DiGraph

for g in range(1, int(input()) + 1):
    N, M = map(int, input().split())
    stars = [input().strip() for _ in range(N)]
    donors = {donor: list(favs) for donor, favs in map(lambda x: (x[0], x[1:]), (input().strip().split() for _ in range(M))) if len(favs) > 0}
    L = math.ceil(sum(1 for _ in filter(lambda x: len(x) > 0, donors.values())) / N)
    G = DiGraph()
    for donor, favs in donors.items():
        G.add_edge(0, donor, capacity=1)
        for fav in favs:
            G.add_edge(donor, fav)
    for l in it.count(L):
        for star in stars:
            G.add_edge(star, 1, capacity=l)
        if nx.maximum_flow_value(G, 0, 1) == len(donors):
            print('Event {}:'.format(g), l)
            break
        for star in stars:
            G.remove_edge(star, 1)
import networkx as nx
from networkx.algorithms.flow import shortest_augmenting_path

G = nx.DiGraph()
G.add_edge('x','a', capacity=100)
G.add_edge('x','b', capacity=100)
G.add_edge('a','c', capacity=100)
G.add_edge('b','c', capacity=100)
G.add_edge('b','d', capacity=100)
G.add_edge('d','e', capacity=100)
G.add_edge('c','y', capacity=100)
G.add_edge('e','y', capacity=100)
R = shortest_augmenting_path(G, 'x', 'y')
flow_value = nx.maximum_flow_value(G, 'x', 'y')
print flow_value

print flow_value == R.graph['flow_value']
Exemple #47
0
def print_flow(flow):
    for edge in G.edges():
        n1, n2 = edge
        print edge, flow[n1][n2]


print 'Flow value =', flow_value
print 'Flow ='
print_flow(maximum_flow)


# The maximum flow should equal the minimum cut.

# In[5]:

max_flow_value = nx.maximum_flow_value(G, 's', 't')
min_cut_value = nx.minimum_cut_value(G, 's', 't')

print max_flow_value == min_cut_value


# ## Flows with Demands
# 
# Let's now record a demand value at each node (negative demand corresponds to supply at a node).

# In[6]:

# to add a property to a node, you should use G.node['s'] rather than
# G['s'] to reference the node.

G.node['s']['demand'] = -25