Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Graphs

Open in Colab

In mathematics, a graph is a way of representing relational data. A graph G(V,E)G(V, E) consists of a vertex set VV, and an edge set E⊆V×VE\subseteq V\times V.

Often vertices are referred to as nodes.

In a directed graph, there can be an edge (v0,v1)(v_0, v_1) as well as an edge (v1,v0)(v_1, v_0). This is good for representing asymmetric relations like v1v_1 is better than v0v_0 at some task.

In an undirected graph, the edge (v0,v1)(v_0, v_1) is the same as the edge (v1,v0)(v_1, v_0). This is good for representing relations like friendship.

In a multigraph, there can be multiple edges between the same vertices. Multigraphs can be directed or undirected.

We’ll primarily consider undirected graphs today.

The neighbors of a vertex vv are all vertices that participate in an edge with vv

N(v)={w∈V∣(v,w)∈E}N(v) = \{ w \in V \mid (v,w) \in E\}

The degree of a vertex is the size of its neighborhood set.

Applications of Graphs

Graphs come up in a variety of situations studied in scientific computing

  1. Studying social networks (e.g. Facebook)

  2. Studying food webs

  3. Control processes

  4. PDE meshes

and more!

Representing Graphs

There are a variety of ways we might represent graphs on a computer

Here are some common representations:

  1. Edge list

  2. Adjacency list

  3. Ajacency matrix

  4. ...

We’ll typically treat the vertex set as [0,1,...,N−1][0, 1, ..., N-1] where NN is the number of vertices in the graph

Edge Lists

An edge list is exactly what you might think - a list of edges.

For example:

[(0, 1), (1, 2), (2, 3)]

Adjacency List

An adjacency list is a list of lists - every vertex has a list of neighbors

For our example above, we would have

[[1], [0, 2], [1, 3], [2]]

Adjacency Matrix

An adjacency matrix AA is a ∣V∣×∣V∣|V| \times |V| matrix, where

A[i,j]={1(i,j)∈E0otherwiseA[i,j] = \begin{cases} 1 & (i,j) \in E\\ 0 & \text{otherwise} \end{cases}

Continuing our example, we would have

array([[0., 1., 0., 0.], [1., 0., 1., 0.], [0., 1., 0., 1.], [0., 0., 1., 0.]])

the adjacency matrix of an undirected graph is always symmetric (why?)

Often adjacency matrices are sparse, so it makes sense to use a sparse matrix format.

Exercises

Assume we are working with undirected graphs

  1. Write a function to return an adjacency list from an edge list

  2. Write a function to return an adjacency matrix from an adjacency list

  3. Write a function to return an edge list from an adjacency matrix

A Graph Class

Usually, there is data associated with vertices and/or edges in a graph.

Let’s define a graph class that allows us to store data.

We’ll represent the graph as an edge list.

{}
{'weight': 0.5}
[(0, 1)]

Exercise

  1. Implement the adjacency_list method

  2. Implement the adjacency_matrix method