Shortest paths

This notebook illustrates the search for shortest paths in graphs.

[1]:
from IPython.display import SVG
[2]:
import numpy as np
[3]:
from sknetwork.data import miserables, painters, movie_actor
from sknetwork.path import get_shortest_path
from sknetwork.visualization import svg_graph, svg_digraph, svg_bigraph
from sknetwork.utils import bipartite2undirected

Graphs

[4]:
graph = miserables(metadata=True)
adjacency = graph.adjacency
names = graph.names
position = graph.position
[5]:
# shortest path
napoleon = 1
jondrette = 46
path = get_shortest_path(adjacency, sources=napoleon, targets=jondrette)
[6]:
# visualization
edge_labels = [(path[k], path[k + 1], 0) for k in range(len(path) - 1)]
[7]:
image = svg_graph(adjacency, position, names, edge_labels=edge_labels, edge_width=3, display_edge_weight=False, scale = 1.5)
SVG(image)
[7]:
../../_images/tutorials_path_shortest_path_9_0.svg

Directed graphs

[8]:
graph = painters(metadata=True)
adjacency = graph.adjacency
names = graph.names
position = graph.position
[9]:
# shortest path
klimt = 6
vinci = 9
path = get_shortest_path(adjacency, sources=klimt, targets=vinci)
[10]:
edge_labels = [(path[k], path[k + 1], 0) for k in range(len(path) - 1)]
[11]:
image = svg_digraph(adjacency, position, names, edge_labels=edge_labels, edge_width=2)
SVG(image)
[11]:
../../_images/tutorials_path_shortest_path_14_0.svg

Bipartite graphs

[12]:
graph = movie_actor(metadata=True)
biadjacency = graph.biadjacency
names_row = graph.names_row
names_col = graph.names_col
[13]:
adjacency = bipartite2undirected(biadjacency)
n_row = biadjacency.shape[0]
[14]:
# shortest path
seydoux = 9
lewitt = 2
path = get_shortest_path(adjacency, sources=seydoux + n_row, targets=lewitt + n_row)
[15]:
# visualization
edge_labels = []
labels_row = {}
labels_col = {}
for k in range(len(path) - 1):
    i = path[k]
    j = path[k + 1]
    # row first
    if i > j:
        i, j = j, i
    j -= n_row
    labels_row[i] = 0
    labels_col[j] = 0
    edge_labels.append((i, j, 0))
[16]:
image = svg_bigraph(biadjacency, names_row, names_col, labels_row, labels_col,
                    edge_labels=edge_labels, edge_color='gray', edge_width=3)
SVG(image)
[16]:
../../_images/tutorials_path_shortest_path_20_0.svg