IFI 8410 — Session 12: Graphs and Shortest Path

Things and Connections

Questions about what lies between things

The problem

Not a filter, a join, or a group-by

  • How do I get from Atlanta to Sydney, and with how many changes?
  • Which web pages can be reached from the home page?
  • How many introductions separate two people who have never met?
  • If this one road closes, is the town cut off?
  • Which of these accounts belong to the same ring of connected accounts?

Representing

a network so a program can follow its connections quickly.

Reachability

what can be reached from where, and which parts hang together.

Shortest paths

the best route, once you say what is being measured.

The tools

Three from the standard library, and one library

dict, set

representing a graph

An adjacency list: each node mapped to its neighbours. "Is there an edge?" in one step.

collections.deque

a queue

Add at one end, remove from the other, each in one step. The engine of breadth-first search.

heapq

a priority queue

Always hands back the smallest item. The engine of shortest paths by distance.

networkx

the graph library

Graph objects, shortest paths with and without weights, components, hundreds of other algorithms.

The first three are enough to write every algorithm in this session by hand, which is worth doing once. For real work, networkx is tested, fast and complete.

Concept 1

Nodes and edges

CalledExample
the thingsnodes (vertices)people, airports, web pages, words
the connections between pairs of themedges (links)friendships, routes, hyperlinks

Where a node is drawn means nothing. Only which nodes are joined matters. Neighbours are one edge away; degree is the number of edges at a node; a path is a sequence of nodes each joined to the next, its length counted in hops.

Directed or undirected

"Knows" goes both ways. "Follows", "links to" and "flies to" need not: whether a path exists then depends on the direction of travel.

Weighted or unweighted

An edge can carry a number: a distance, a travel time, a cost.

Concept 2

Writing a graph down

Edge list

edges = [("Ana", "Ben"),
         ("Ana", "Chi"),
         ("Chi", "Dev")]

Natural for a file. Poor to ask: "who are Dev's neighbours?" means reading every edge.

Adjacency list

def build_graph(edges, directed=False):
    graph = {}
    for a, b in edges:
        graph.setdefault(a, set())
        graph.setdefault(b, set())   # b too!
        graph[a].add(b)
        if not directed:
            graph[b].add(a)
    return graph

Every node must be a key, with an empty collection if nothing leaves it. Otherwise: KeyError.

Concept 3

from collections import deque

def hop_distances(graph, start):
    hops = {start: 0}
    queue = deque([start])
    while queue:
        node = queue.popleft()        # FRONT
        for neighbour in graph[node]:
            if neighbour not in hops:
                hops[neighbour] = hops[node] + 1
                queue.append(neighbour)   # BACK
    return hops
  • Work outward in rings: everything one step away, then everything new that is two steps away.
  • A queue produces that order by itself: found first, expanded first.
  • Nearer rings are finished first, so the first time a node is reached is by a route with the fewest steps.
  • Cost: about one step per node plus one per edge.

Concept 3, continued

Three details decide whether it works

Take from the front

Taking from the back sends the search down one route as far as it goes. That is depth-first: the same nodes, with the wrong distances.

Skip what has been seen

Otherwise any cycle traps the search for ever.

Record a node when it joins the queue

Not when it leaves, or it joins once for every edge that leads to it.

Concept 4

The path

came_from = {start: None}
...
    if neighbour not in came_from:
        came_from[neighbour] = node
        queue.append(neighbour)

path = []
node = target
while node is not None:
    path.append(node)
    node = came_from[node]
path.reverse()
  • Three steps away is not an itinerary.
  • Every time the search finds a new node, it finds it from some other node. Record that one fact.
  • Afterwards, follow the notes back from the target to the start, then reverse.

Shortest paths are not unique. Check that it is a real path of the right length, never that it is one particular path.

Concept 5

Reachability and components

def components(graph):
    seen, parts = set(), []
    for node in graph:
        if node not in seen:
            part = set(hop_distances(graph, node))    # everything reachable
            seen |= part
            parts.append(part)
    return parts
  • A connected component: nodes that can all reach each other, with no edge leading out.
  • Typically one giant component with nearly everything in it, and a scatter of small ones.
  • The small ones are frequently either the answer to the question or a sign of something odd in the data.

Looking at the components is one of the first things to do with any real network.

Concept 6

When edges have lengths

Four towns. The direct road is 90 km. A route through two other towns uses three roads and totals 60 km. Breadth-first search returns the direct road: it counts roads.

Breadth-first searchDijkstra
questionfewest edgessmallest total weight
takes nextthe oldest node in the queuethe nearest node
containerdequeheapq
needsnothingweights that are not negative

What "shortest" means is a modelling decision, made by what is put on the edges: 1 for fewest changes, kilometres, minutes, the fare.

The library

networkx

import networkx as nx

G = nx.Graph()                               # nx.DiGraph() for directed
G.add_weighted_edges_from(edges, weight="km")

nx.shortest_path(G, "Alba", "Dale")                 # fewest edges
nx.shortest_path(G, "Alba", "Dale", weight="km")    # shortest distance
nx.connected_components(G)

The same function gives two different routes depending on whether it is told about the weights. Forgetting weight= is the usual mistake, and it produces a plausible wrong answer.

Use case

Routing passengers

About 37,000 routes between 3,300 airports. There is no direct flight from Atlanta to Sydney.

RouteFlightsDistance
fewest flights, as foundAtlanta → Dubai → Sydney224,000 km
fewest kilometresAtlanta → Los Angeles → Sydney215,000 km
  • Both have the fewest flights. A booking system has to decide what it is minimising.
  • The same network shows hubs (a handful of airports with over two hundred routes), one-way routes, and small groups of airports cut off from the rest.

Worked example — notebook 2

A puzzle that is secretly a graph

COLD
→
CORD
→
WORD
→
WARD
→
WARM

Each four-letter word is a node; two words that differ in one letter are joined: 2,400 nodes, 10,600 edges. The shortest ladder is a shortest path.

Distances

Most words are within five or six steps of COLD. The two farthest apart are seventeen steps from each other.

Components

81 words have no neighbour at all. The second-largest component is a cluster of Roman numerals that had found their way into the word list.

Building it: comparing every pair of words grows with the square of their number. Filing each word under its four "one letter blanked" patterns in a dictionary does it in a hundredth of a second.

To take away

Key points

  • A graph is things and connections. Say what a node is and what an edge means.
  • Store edges in a file; ask an adjacency list. Every node must be a key.
  • Breadth-first search: a queue, taken from the front, skipping what was seen. It finds the fewest steps.
  • Keep a "came from" note per node to recover the path. Shortest paths are not unique.
  • Look at the components before anything else.
  • "Shortest" depends on what the edges carry. Decide before searching.

Now: hands-on

Over to the notebooks

Folder 12-Graphs-Shortest-Path — work them in this order:

1Things and Connections

Concepts

Eight people and their friendships: building a graph, breadth-first search, paths, components, and weights. Four exercises.

2Word Ladders

Worked example

COLD to WARM in seven steps, checked against networkx. Run it on ARC.

3Reference

Look things up

Graph patterns and networkx calls to keep open while you work.

As you work, ask of every network: what is a node, what is an edge, and what does "shortest" measure?
Homework: Homework 11: Fewest Hops

◀ Slides