本文整理汇总了Python中networkx.maximum_flow_value函数的典型用法代码示例。如果您正苦于以下问题:Python maximum_flow_value函数的具体用法?Python maximum_flow_value怎么用?Python maximum_flow_value使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了maximum_flow_value函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_disconnected
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)
示例2: test_complete_graph_cutoff
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__))
示例3: test_pyramid
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__))
示例4: test_complete_graph
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__))
示例5: cli
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))
示例6: person_max_flow
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
示例7: getStartingWeights
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
示例8: CalMaxFlows
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)
示例9: max_flow_min_cost
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)
示例10: print_flow
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
示例11: local_node_connectivity
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])
示例12: range
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)
示例13: local_edge_connectivity
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)
示例14: local_node_connectivity
#.........这里部分代码省略.........
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)
示例15: shortest_augmenting_path
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']