Algorithms for path finding in graphs

This code accompanies the Algorithms lecture course for computer science at Cambridge University, taught by Damon Wischik.

Contents

Storing graphs

The "pseudocode" given in lecture notes is mostly actual working Python code. It is based on an Adjacency List representation of a graph, wrapped up as a nice Python object. The ucamcl_alg_utils package contains two classes, DirectedGraph and UndirectedGraph, both of which allow edges to be either labelled or unlabelled. Initialize them with a list of edges, as illustrated in the code snippets below.

When you create a graph, you specify the edges by giving vertex ids; the graph will create a Vertex object for each vertex id. This allows you to attach attributes to each Vertex object, e.g. v.distance or v.seen. These two classes provide the following:

Depth-first search

Breadth-first search

Dijkstra's algorithm

Bellman-Ford

Dynamic programming

Version A: straightforward recursion

$$ \begin{aligned} F_{d,t}(v) &= \min\Bigl( F_{d,t-1}(v)\,, \min_{w\,:\,v\to w} \Bigl\{ \operatorname{weight}(v\to w)+F_{d,t-1}(v)\Bigr\} \Bigr)\\ F_{d,0}(v) &= \begin{cases} 0 & \text{if }v=d\\ \infty & \text{otherwise.} \end{cases} \end{aligned} $$

Version B: matrix algebra

Johnson's algorithm

Real-world data: the OpenStreetMap graph

You can download OpenStreetMap data in XML format. For example, view Cambridge, and click on the link to download. Or you can use the XML that I downloaded.

Here are some of the attributes that may be present in each <way>. Don't make assumptions about the possible values... OSM data is crowd-sourced and not always consistent.

Sample code for plotting