Graph Theory with Mathematica
Construction and representation
Visualization of graphs
Properties of graphs
Connectivity, strong connectivity
Adjacency & Transition Matrices
Making interactive models

Graphs

Definition: A graph G={V, E} consists of a set of vertices V (also called nodes) and a set of edges E. 

Graphs provide a structural model that makes it possible to analyze and understand how many separate systems act together. Systems with symmetric relations are represented by undirected graphs, while the others can be modeled using directed graphs.
Applications: 
	technological networks (the internet, power grids, telephone networks, transportation networks, …)
	social networks (social graphs, affiliation networks, …)
	information networks (World Wide Web, citation graphs, patent networks, …),
	biological networks (biochemical networks, neural networks, food webs, …), and many more.

In Mathematica, graphs are integrated in the Wolfram language, so they can be used as input and output without importing any libraries. A graph is represented either by a list of rules of the form {vi->vj,...}, where vi and vj are vertices, and vi->vj is the edge between vi and vj, or by the adjacency matrix of the graph. In the Mathematica documentation (Graphs and Networks) you can find the graph representations, graph functions, algorithms and lots of examples.

Graph definitions in Mathematica

G=Graph[{1->2,3->2,3->4,4->1}]

G=Graph[{1->2,3->2,3->4,4->1}, GraphStyle->"SmallNetwork"]

You can write click on the graph to set the display properties of the graph (layout, size, arrow shape, vertex shape, etc.) You can also plot the graph by explicitly listed the display options.

GraphPlot[G,VertexLabeling->True, DirectedEdges->{True, "ArrowheadsSize"->0.15}, PlotStyle->Dashed]

G=Graph[{1->2,3->2,3->4,4->1}];
Gplot=GraphPlot[G,VertexLabeling->True, DirectedEdges->{True, "ArrowheadsSize"->0.15}, PlotLabel->"G is a graph with 4 vertices"]

Adjacency matrix

Definition: The adjacency matrix of a graph G is built by the following rule : the (i, j) entry in the matrix is 1 if there is an edge between i and j in the graph G, and 0 otherwise.

The adjacency matrix of the graph can be obtained using the function AdjacencyMatrix[...]

AdjacencyMatrix[G]

By default, if the graph does not have a lot of edges, its adjacency matrix in Mathematica is given as a sparse array (only the non-zero elements are listed), but we can convert it to the regular form by using MatrixForm. In practice, for directed graph we will use more often the transpose of the adjacency matrix.

MatrixForm[AdjacencyMatrix[G]]

Exercise : Define a graph H with the following set of edges and use Mathematica to compute its adjacency matrix.
    Edges : 2 -> 3, 4 -> 5, 1 -> 6, 6 -> 2, 6 -> 5, 6 -> 1, 6 -> 3, 6 -> 4, 5 -> 1

H=Graph[{2->3,4->5,6->2,6->5,6->1,6->3,6->4,5->1, 1->6}, GraphStyle->"SmallNetwork"]

MatrixForm[AdjacencyMatrix[H]]

H=Graph[{1,2,3,4,5,6},{2->3,4->5,6->2,6->5,6->1,6->3,6->4,5->1, 1->6}, GraphStyle->"SmallNetwork"]

Displaying graphics in the same row/column

We want to get a little fancy this time and display the graph and the adjacency matrix on the same row:

G=Graph[{1->2,3->2,3->4,4->1}];
Gplot=GraphPlot[G,VertexLabeling->True, DirectedEdges->{True, "ArrowheadsSize"->0.15}, PlotLabel->"G is a graph with 4 vertices"];

Adj=MatrixForm[AdjacencyMatrix[G]];
GraphicsRow[ {Gplot,Adj}]

GraphicsRow[{Text["The graph"],Gplot,Text["has adjacency matrix"],Adj}]

Random Graphs

We can construct a random graph using a random matrix with 0 and 1.

Ri=Table[RandomInteger[],{4},{4}]

MatrixForm[%]

RG=GraphPlot[Ri, VertexLabeling->True, DirectedEdges->True]

Mathematica also has a command for building random undirected graphs: 
RandomGraph[{m,n}] -- where m is the number of vertices and n is the number of edges.
RandomGraph[{m,n},k] -- generates k random graphs with m vertices and n edges.
If we want to make the graph directed, we need to set the attribute DirectedEdges to True.

RandomGraph[{5,7}]

RandomGraph[{5,7},DirectedEdges->True]

Mathematica can also generate graphs with a special form, for instance graphs for which any two vertices are connected by an edge; these are called complete graphs).

CompleteGraph[5]

Properties of Graphs - Strong Connectivity

Definition: A graph is connected if for any two vertices u and v, there is a path in the graph from u to v OR from v to u.  A graph is strongly connected if for any two vertices u and v, there is a path in the graph from u to v AND from v to u.

Proposition: Let G be a graph and A its adjacency matrix. If there is a positive integer k such that the matrix S = I+A + (A^2) + (A^3) + … +(A^k) is positive (has only positive entries), then the graph is strongly connected.

Idea of the proof: The entry on row i and column j of the matrix (A^k) represents the number of paths of length k from i to j. If the (i,j) entry is positive, it means that there exists at least one path of length k from i to j.

Testing strong connectivity using the adjacency matrix and Mathematica:

First we compute S= I+A + (A^2) + (A^3) + … +(A^k). It’s enough to consider k=dimension(A)

S=IdentityMatrix[Length[Ri]]+Sum[MatrixPower[Ri,k],{k,1,Length[Ri]} ]

Now we must check the entries of the matrix S to see if there are any 0 elements. If for some i and j the (i,j) entry is equal to 0, it means that there is no path from node i to node j, so the graph is not strongly connected.

con=1;
Do[If[S[[i]][[j]]==0,con=0;Break[]], {i,4},{j,4}];
If[con>0,Print["Strongly connected"],Print["Not strongly connected"]]

con=1;
Do[If[S[[i]][[j]]==0,con=0; Return[{i,j}]], {i,4},{j,4}];
If[con>0,Print["Strongly connected"], Row[{"Not strongly connected, for example, there is no path from node ",%[[1]]," to node ",%[[2]]}]]

Comments about the previous code: First we assume that the graph is strongly connected, so we introduce a variable con and make it equal to 1. We use a Do loop to check whether there are any 0 entries in the matrix S. Notice the use of Return[{i,j}] in the Do loop. When the first 0 element of the matrix S is found, we set con to 0, exit the Do loop and return the pair {i,j}. We can later use {i,j} to indicate that the graph fails to be strongly connected because there is no path from node %[[1]] to node %[[2]]. If no element of the matrix is 0, then the value of the variable con is never changed, so it remains equal to 1 after the Do command.

Connected components of a graph

We can also use Mathematica to get the connected components of a graph:

Gr=RandomGraph[{10,20}, DirectedEdges->True];
ConnectedComponents[Gr]
HighlightGraph[Gr,ConnectedComponents[Gr]]

Mathematica lets you copy the graph and use it anywhere else in your code. You can even assign it to some other variable, or use it in computations.

Grrr=
MatrixForm[AdjacencyMatrix[Grrr]]

Transition Matrices

Definition: In a directed graph, for every vertex i there is a number of edges that enter that vertex (i is a head) and a number of edges that exit that vertex (i is a tail). Thus we define the indegree of vertex i as the number of edges for which vertex i is a head. Similarly, the outdegree of vertex i as the number of edges for which i is a tail.

Mathematica has built-in functions for the indegree and the outdegree of the vertices of a graph: 
VertexInDegree[graph] -- returns a list with the indegrees of the vertices of the graph specified in the argument
VertexOutDegree[graph] -- returns a list with the indegrees of the vertices of the graph

Definition: The transition matrix A of a directed graph is defined as follows. If there is an edge from i to j and the outdegree of vertex i is (Subscript[d, i]), then on column i and row j we put (1/(Subscript[d, i])). Otherwise we mark the entry on column i and row j with zero.

Random Walk on a Graph: We use the transition matrix to model the behavior of a random surfer on a graph. The surfer chooses a node at random, then walks on the outgoing edges to other nodes for as long as he/she wishes. At each step the probability that the surfer moves from node i to node j is zero if there is no link from i to j and (1/(Subscript[d, i]))otherwise. Recall that (Subscript[d, i]) is the outdegree of vertex i.

Question: What is the probability that a random surfer that starts at one of the nodes of the graph visits say, node j ?

Finding the Transition Matrix using Mathematica

Let us try to produce the transition matrix of a directed graph, using the adjacency matrix. Notice that for the transition matrix, we first look at the column, then at the row. So we need to work with the transpose of the adjacency matrix instead.

G=Graph[{1->2,3->2,3->4,4->1, 4->2, 4->3}];
Gplot=GraphPlot[G,VertexLabeling->True,    DirectedEdges->{True, "ArrowheadsSize"->0.07}]
Lin= VertexInDegree[G]; 
Print["Lin=",Lin]
Lout=VertexOutDegree[G]; Print["Lout=",Lout]

A=AdjacencyMatrix[G];
TA = Transpose[A];
Print["The transpose matrix is TA="MatrixForm[TA]]

f[i_,j_]:=TA[[i]][[j]]/Lout[[j]]

Trans= Table[f[i,j],{i,Length[TA]},{j,Length[TA]}];
MatrixForm[Trans]

Exercise : Find the transition matrix of a graph. The code in yellow computes the transition matrix, but some cases are overlooked.

Making interactive models

Using the command Manipulate[...] we can turn a static computation or graph into a dynamic and sophisticated model. We can wrap Manipulate[...] around any Wolfram command to create an interactive model. We need to introduce a parameter that we want to manipulate and some bounds for that parameter.

Parameter ranges are given inside curly brackets: 
{x, 4, 7}   -- specifies an interval [4,7] that the parameter x belongs to.
{x, {4,7}} -- specifies a discrete set of values that x can take on.
{{x, 5, “Some text describing the meaning of the parameter x”}, 4,7} 
             -- x belongs to the interval [4,7] and the default value is 5

Manipulate[
GraphPlot[Table[RandomInteger[],{n},{n}], VertexLabeling->True, DirectedEdges->True], 
{n,4,7}]

If you click the plus sign at the end of the slider, you get a set of video controls. You can introduce a particular value of the parameter and hit Enter to jump to that value. When you do a presentation, you can also hide the Wolfram commands and show only the interactive model.

Help->Demonstrations gives you a list of pre-built Wolfram Demonstration Projects. You can browse by topic and see the available templates. You can then download the project as a .cdf, which means that you get an interactive version that you can run locally on your computer, or you can download the author code, which means that you get a notebook (.nb) with the necessary code to generate the model.