File: maxflow.py

package info (click to toggle)
python-igraph 0.11.8%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,480 kB
  • sloc: ansic: 24,545; python: 21,699; sh: 107; makefile: 35; sed: 2
file content (44 lines) | stat: -rw-r--r-- 945 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""
.. _tutorials-maxflow:

============
Maximum Flow
============

This example shows how to construct a max flow on a directed graph with edge capacities using :meth:`igraph.Graph.maxflow`.

"""
import igraph as ig
import matplotlib.pyplot as plt

# %%
# First, we generate a graph and assign a "capacity" to each edge:
g = ig.Graph(
    6,
    [(3, 2), (3, 4), (2, 1), (4,1), (4, 5), (1, 0), (5, 0)],
    directed=True
)
g.es["capacity"] = [7, 8, 1, 2, 3, 4, 5]

# %%
# To find the max flow, we can simply run:
flow = g.maxflow(3, 0, capacity=g.es["capacity"])

print("Max flow:", flow.value)
print("Edge assignments:", flow.flow)

# Output:
# Max flow: 6.0
# Edge assignments [1.0, 5.0, 1.0, 2.0, 3.0, 3.0, 3.0]

# %%
# Finally, we can plot the directed graph to look at the situation:
fig, ax = plt.subplots()
ig.plot(
    g,
    target=ax,
    layout="circle",
    vertex_label=range(g.vcount()),
    vertex_color="lightblue"
)
plt.show()