SciPy Graphs
A graph is a set of nodes (cities, web pages, people) connected by edges (roads, links, friendships). Edges may have a weight, such as a distance or cost. SciPy's scipy.sparse.csgraph module runs classic graph algorithms on graphs stored as matrices.
Graphs as adjacency matrices
The usual representation is an adjacency matrix: entry [i, j] holds the weight of the edge from node i to node j, and 0 means "no edge". Since real graphs have few edges per node, the matrix is sparse — which is why csgraph lives inside scipy.sparse.
Throughout this lesson we'll use a small road network between five towns:
import numpy as np
from scipy.sparse import csr_array
towns = ["Ash", "Birch", "Cedar", "Dale", "Elm"]
# Ash Birch Cedar Dale Elm
roads = np.array([
[0, 4, 1, 0, 0], # Ash
[4, 0, 2, 5, 0], # Birch
[1, 2, 0, 8, 0], # Cedar
[0, 5, 8, 0, 3], # Dale
[0, 0, 0, 3, 0], # Elm
])
graph = csr_array(roads)
print("edges stored:", graph.nnz, "(each road appears twice)")
print("symmetric:", (roads == roads.T).all())edges stored: 12 (each road appears twice)
symmetric: True
Connected components
connected_components() finds groups of nodes that can reach each other. It returns the number of groups and a label for every node:
import numpy as np
from scipy.sparse import csr_array
from scipy.sparse.csgraph import connected_components
# 6 computers; two separate networks
links = np.zeros((6, 6), dtype=int)
for a, b in [(0, 1), (1, 2), (3, 4)]:
links[a, b] = links[b, a] = 1
n, labels = connected_components(csr_array(links), directed=False)
print("number of networks:", n)
print("labels:", labels)
for k in range(n):
print(f"network {k}: computers {np.flatnonzero(labels == k).tolist()}")number of networks: 3
labels: [0 0 0 1 1 2]
network 0: computers [0, 1, 2]
network 1: computers [3, 4]
network 2: computers [5]
Computer 5 has no links at all, so it forms a component on its own.
Shortest paths with Dijkstra
dijkstra() computes the cheapest path lengths from one or more start nodes. With return_predecessors=True it also returns, for every node, the node you arrive from — which lets you rebuild the route:
import numpy as np
from scipy.sparse import csr_array
from scipy.sparse.csgraph import dijkstra
towns = ["Ash", "Birch", "Cedar", "Dale", "Elm"]
roads = csr_array(np.array([
[0, 4, 1, 0, 0], [4, 0, 2, 5, 0], [1, 2, 0, 8, 0],
[0, 5, 8, 0, 3], [0, 0, 0, 3, 0],
]))
dist, pred = dijkstra(roads, directed=False, indices=0, return_predecessors=True)
for town, d in zip(towns, dist):
print(f"Ash -> {town:5}: {d:4.1f}")
# Walk the predecessor chain back from Elm (node 4)
path, node = [], 4
while node != -9999:
path.append(towns[node])
node = pred[node]
print("route to Elm:", " -> ".join(reversed(path)))Ash -> Ash : 0.0
Ash -> Birch: 3.0
Ash -> Cedar: 1.0
Ash -> Dale : 8.0
Ash -> Elm : 11.0
route to Elm: Ash -> Cedar -> Birch -> Dale -> Elm
The direct road Ash–Birch costs 4, but going through Cedar costs only 1 + 2 = 3, and Dijkstra finds that detour. A predecessor of -9999 marks the start node (it has no predecessor).
All pairs: Floyd–Warshall
To get the shortest distance between every pair of nodes at once, use floyd_warshall(). The result is a full distance matrix:
import numpy as np
from scipy.sparse import csr_array
from scipy.sparse.csgraph import floyd_warshall
roads = csr_array(np.array([
[0, 4, 1, 0, 0], [4, 0, 2, 5, 0], [1, 2, 0, 8, 0],
[0, 5, 8, 0, 3], [0, 0, 0, 3, 0],
]))
dist = floyd_warshall(roads, directed=False)
print(dist.astype(int))
print("farthest pair distance:", int(dist.max()))[[ 0 3 1 8 11]
[ 3 0 2 5 8]
[ 1 2 0 7 10]
[ 8 5 7 0 3]
[11 8 10 3 0]]
farthest pair distance: 11
Other shortest-path functions are bellman_ford() (allows negative weights) and johnson() (fast for sparse graphs with negative weights). shortest_path() picks a suitable method automatically.
Traversals and spanning trees
A breadth-first traversal visits nodes layer by layer; depth-first follows one branch as far as it can before backing up. A minimum spanning tree keeps just enough edges to connect all nodes with the smallest total weight — the cheapest way to, say, lay cable between all the towns.
import numpy as np
from scipy.sparse import csr_array
from scipy.sparse.csgraph import breadth_first_order, depth_first_order, minimum_spanning_tree
towns = np.array(["Ash", "Birch", "Cedar", "Dale", "Elm"])
roads = csr_array(np.array([
[0, 4, 1, 0, 0], [4, 0, 2, 5, 0], [1, 2, 0, 8, 0],
[0, 5, 8, 0, 3], [0, 0, 0, 3, 0],
]))
bfs, _ = breadth_first_order(roads, 0, directed=False)
dfs, _ = depth_first_order(roads, 0, directed=False)
print("BFS:", towns[bfs].tolist())
print("DFS:", towns[dfs].tolist())
mst = minimum_spanning_tree(roads)
rows, cols = mst.nonzero()
for r, c in zip(rows, cols):
print(f"keep road {towns[r]}-{towns[c]} ({int(mst[r, c])})")
print("total cable:", int(mst.sum()))BFS: ['Ash', 'Birch', 'Cedar', 'Dale', 'Elm']
DFS: ['Ash', 'Birch', 'Cedar', 'Dale', 'Elm']
keep road Ash-Cedar (1)
keep road Birch-Cedar (2)
keep road Birch-Dale (5)
keep road Dale-Elm (3)
total cable: 11
Summary of csgraph functions
| Function | What it computes |
|---|---|
connected_components |
Groups of mutually reachable nodes |
dijkstra |
Shortest paths from given nodes (non-negative weights) |
floyd_warshall |
Shortest paths between all pairs |
bellman_ford |
Shortest paths with negative weights allowed |
breadth_first_order / depth_first_order |
Traversal order from a start node |
minimum_spanning_tree |
Cheapest set of edges that connects everything |
maximum_flow |
Largest flow from a source to a sink |
Note: In an adjacency matrix a
0means "no edge". If you need a real edge with weight zero, store the matrix in a sparse format with an explicit zero, or use a tiny weight instead.
Test yourself
In an adjacency matrix, what does entry [i, j] usually represent?
- The number of nodes
- The weight of the edge from node i to node j
- The distance from i to every node
- Whether i equals j
Which function returns the shortest distances between every pair of nodes?
- dijkstra with one index
- connected_components
- floyd_warshall
- breadth_first_order
What does a minimum spanning tree give you?
- The shortest path between two nodes
- The cheapest set of edges connecting all nodes
- The node with most edges
- The largest connected component