File: maxflow.py

package info (click to toggle)
python-igraph 1.0.0%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,612 kB
  • sloc: ansic: 25,204; python: 22,041; sh: 118; makefile: 35; sed: 2
file content (41 lines) | stat: -rw-r--r-- 934 bytes parent folder | download
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
"""
.. _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()