Complex Systems · 5/8 · Series index · Notation

Graph representations and connectivity are developed in Network fundamentals.

Network Metrics and Algorithms

Unless stated otherwise, formulas refer to simple, undirected, unweighted graphs without self-loops. There are nn nodes and MM edges.

Distance, Eccentricity, Diameter, and Radius

The shortest-path distance dijd_{ij} is the length of the shortest feasible path from ii to jj. In an unweighted graph, length counts edges. If weights represent distances or costs, length is the sum of the weights along the path. A stronger connection need not represent a greater distance: interpret the weights before choosing an algorithm.

L=1n(n1)ijdij=2n(n1)i<jdij,ε(i)=maxjdij,D=maxiε(i),R=miniε(i).\begin{aligned} L&=\frac{1}{n(n-1)}\sum_{i\ne j}d_{ij} =\frac{2}{n(n-1)}\sum_{i<j}d_{ij},\\ \varepsilon(i)&=\max_jd_{ij},\\ D&=\max_i\varepsilon(i),\qquad R=\min_i\varepsilon(i). \end{aligned}

LL is the mean shortest-path length, also called the characteristic path length. The eccentricity ε(i)\varepsilon(i) measures the greatest distance from ii; DD is the diameter and RR the radius. The center consists of nodes with ε(i)=R\varepsilon(i)=R, and the periphery of nodes with ε(i)=D\varepsilon(i)=D. A connected undirected graph satisfies RD2RR\le D\le2R: any two nodes can be connected via a center node by a walk of length at most 2R2R.

Conditions: finite whole-graph distance formulas require all relevant pairs to be reachable. Disconnected graphs contain pairs with dij=d_{ij}=\infty. One can instead analyse the largest connected component or average over reachable pairs, but must state the convention. In directed graphs, retain edge directions; reachability for every ordered pair requires strong connectivity.

Degree, Closeness, and Betweenness: Different Meanings of Importance

Degree centrality is

CD(i)=kin1.C_D(i)=\frac{k_i}{n-1}.

It measures the number of direct neighbours. Directed versions use kiink_i^{\mathrm{in}} or kioutk_i^{\mathrm{out}}. If iji\to j means “ii follows jj,” having many followers means high in-degree, while following many accounts means high out-degree. An interpretation such as “influence equals out-degree” cannot be separated from the meaning of an edge.

Closeness centrality is

CC(i)=n1jidij.C_C(i)=\frac{n-1}{\sum_{j\ne i}d_{ij}}.

It is the reciprocal of mean distance: a larger value means a node is closer, on average, to the others. In a directed graph distinguish outward distances, from the node to others, from inward distances, from others to the node. NetworkX uses inward distances by default; call the function on the reversed graph for outward closeness. Its default correction for disconnected graphs is, with rir_i other nodes able to reach ii,

CCWF(i)=rin1rij:ji,jidji.C_C^{\mathrm{WF}}(i)=\frac{r_i}{n-1}\frac{r_i}{\sum_{j:\,j\leadsto i,\,j\ne i}d_{ji}}.

The value is zero when no other node can reach ii.

For betweenness centrality, let σst\sigma_{st} be the number of shortest paths from ss to tt, and σst(i)\sigma_{st}(i) the number passing through ii as an internal node. For n>2n>2, normalized undirected betweenness is

CB(i)=2(n1)(n2)s<ts,tiσst(i)σst.C_B(i)=\frac{2}{(n-1)(n-2)} \sum_{\substack{s<t\\s,t\ne i}}\frac{\sigma_{st}(i)}{\sigma_{st}}.

If the sum instead includes ordered pairs sts\ne t, use the prefactor 1/[(n1)(n2)]1/[(n-1)(n-2)]. Unreachable pairs contribute zero, and endpoints are excluded from internal passage. Betweenness measures a node's role as a bridge between regions. When several shortest paths exist, divide the contribution among them instead of selecting just one.

Choosing a metric: use degree for direct connection count, closeness for average reachability distance, and betweenness for shortest-path bottlenecks between communities. These measures can produce different rankings; no single centrality is best for every task.

Eigenvector Centrality and Katz Centrality

Eigenvector centrality gives more credit for connections to important neighbours. For an undirected graph,

xi=1λjAijxj,Ax=λx.x_i=\frac1\lambda\sum_jA_{ij}x_j, \qquad A\boldsymbol x=\lambda\boldsymbol x.

Choose a nonnegative eigenvector corresponding to the spectral radius ρ(A)\rho(A) and specify its normalization. For a connected graph, the Perron–Frobenius properties of its nonnegative adjacency matrix give a unique positive direction. Disconnected graphs can introduce nonuniqueness or zero components.

Our convention is Aij=1A_{ij}=1 for iji\to j, so importance received through incoming edges satisfies

xi=1λjAjixj,ATx=λx.x_i=\frac1\lambda\sum_jA_{ji}x_j, \qquad A^{\mathsf T}\boldsymbol x=\lambda\boldsymbol x.

This is a left eigenvector of AA, or a right eigenvector of ATA^{\mathsf T} when written as a column. NetworkX uses this incoming-edge definition. To receive scores from outgoing neighbours instead, use AxA\boldsymbol x.

Left/right eigenvectors and in/out-degree must be interpreted using a consistent adjacency convention. A directed acyclic graph (DAG) has only zero adjacency eigenvalues, making ordinary eigenvector centrality degenerate. This does not mean every mathematical eigenvector must be the zero vector. The issue is that the usual propagation rule with a positive eigenvalue does not provide an appropriate unique positive ranking.

Katz centrality adds a baseline score β>0\beta>0 to every node. Set B=AB=A for an undirected graph and B=ATB=A^{\mathsf T} for incoming-edge centrality in a directed graph:

x=aBx+β1,x=β(IaB)11,0a<1ρ(B).\begin{aligned} \boldsymbol x&=aB\boldsymbol x+\beta\boldsymbol1,\\ \boldsymbol x&=\beta(I-aB)^{-1}\boldsymbol1,\\ 0&\le a<\frac1{\rho(B)}. \end{aligned}

Expanding the inverse as a geometric series gives

x=β=0aB1.\boldsymbol x=\beta\sum_{\ell=0}^{\infty}a^\ell B^\ell\boldsymbol1.

Thus walks of length \ell receive weight aa^\ell. The parameter aa controls the influence of distant walks. A uniform β\beta, often set to one, changes only the overall scale. Changing aa can alter relative scores and potentially the ranking; knowing only a/βa/\beta is insufficient. The inverse gives an unnormalized solution; nx.katz_centrality normalizes its Euclidean norm to one by default. If ρ(B)=0\rho(B)=0, as for a DAG, the series terminates after finitely many terms, so there is no finite 1/ρ1/\rho upper bound.

PageRank: Probability Flow with Random Teleportation

Katz transfers importance without dividing each node's contribution by its out-degree. PageRank instead describes a random walk: node jj divides its score equally among the nodes it points to, while teleportation occurs with probability 1d1-d. The damping factor satisfies 0<d<10<d<1, commonly d=0.85d=0.85; this differs from Katz's spectral-radius condition.

Let PP be a row-stochastic matrix. For an unweighted graph without dangling nodes, Pij=Aij/kioutP_{ij}=A_{ij}/k_i^{\mathrm{out}}. When kiout=0k_i^{\mathrm{out}}=0, replace that row with the teleportation distribution vT\boldsymbol v^{\mathsf T}; uniform teleportation has vi=1/nv_i=1/n. In column-vector notation,

p=dPTp+(1d)v,pi0,ipi=1.\begin{aligned} \boxed{\boldsymbol p=dP^{\mathsf T}\boldsymbol p+(1-d)\boldsymbol v},\\ p_i\ge0,\qquad\sum_i p_i=1. \end{aligned}

With uniform teleportation, every node receives baseline probability (1d)/n(1-d)/n. For normalized PageRank with uniform teleportation, the baseline vector is (1d)1/n(1-d)\boldsymbol1/n. Equivalently, the Google matrix is

G=dP+(1d)1vT,GTp=p.G=dP+(1-d)\boldsymbol1\boldsymbol v^{\mathsf T},\qquad G^{\mathsf T}\boldsymbol p=\boldsymbol p.

A quick check is to sum the components: both sides must sum to one. Replacing dangling rows by the teleportation distribution keeps the transition matrix row-stochastic.

Worked example: suppose the only edge is 121\to2, with uniform teleportation. Replace the second transition row by (1/2,1/2)(1/2,1/2). Then

p1=d2p2+1d2,p1+p2=1,p1=12+d,p2=1+d2+d.\begin{aligned} p_1&=\frac d2p_2+\frac{1-d}{2},\qquad p_1+p_2=1,\\ p_1&=\frac1{2+d},\qquad p_2=\frac{1+d}{2+d}. \end{aligned}

At d=0.85d=0.85, the scores are approximately (0.350877,0.649123)(0.350877,0.649123). Node 2 does not absorb and destroy the total probability merely because it has no outgoing edges.

Cores, Local Clustering, and Global Transitivity

A kk-core is the maximal induced subgraph obtained by repeatedly removing nodes whose current degree is below kk. Every remaining node has degree at least kk within the subgraph. A node's core number is the largest kk for which it belongs to a kk-core. Degrees must be updated within the remaining subgraph after each removal. A node with a large original degree can still have core number one if it is connected only to leaves, as in a star.

A node in a kk-core needs at least kk neighbours within that core; those neighbours may have higher core numbers. They need not all have exactly the same coreness. A kk-core also need not be the innermost core.

For the local clustering coefficient, let tit_i count triangles containing ii, equivalently edges between its neighbours. Then

Ci=ti(ki2)=2tiki(ki1),ki2,Ci=0,ki<2.\begin{aligned} C_i&=\frac{t_i}{\binom{k_i}{2}}=\frac{2t_i}{k_i(k_i-1)},\qquad k_i\ge2,\\ C_i&=0,\qquad k_i<2. \end{aligned}

The mean local clustering Cˉ=1niCi\bar C=\frac1n\sum_iC_i weights nodes equally. In a simple undirected graph, useful checks are (A3)ii=2ti(A^3)_{ii}=2t_i and the total triangle count T=tr(A3)/6T=\operatorname{tr}(A^3)/6.

Global transitivity is

Ctrans=3Ti(ki2)=i(ki2)Cii(ki2).C_{\mathrm{trans}}=\frac{3T}{\sum_i\binom{k_i}{2}} =\frac{\sum_i\binom{k_i}{2}C_i}{\sum_i\binom{k_i}{2}}.

NetworkX defines transitivity as zero when there are no connected triples. The denominator counts pairs of neighbours centred on a node; each triangle contributes three closed triples. Transitivity weights local coefficients by neighbour-pair counts, so it generally differs from Cˉ\bar C. Neither is universally larger. Transitivity can be smaller when high-degree nodes have low local clustering.

Assortativity, Communities, and Modularity

Assortativity measures the correlation of attributes at the two ends of an edge. For each directed edge e=(i,j)e=(i,j), write ue=f(i)u_e=f(i) and ve=f(j)v_e=f(j). Count both orientations of undirected edges to avoid arbitrary endpoint asymmetry. With endpoint means uˉ,vˉ\bar u,\bar v,

r=e(ueuˉ)(vevˉ)e(ueuˉ)2e(vevˉ)2.r=\frac{\sum_e(u_e-\bar u)(v_e-\bar v)} {\sqrt{\sum_e(u_e-\bar u)^2\sum_e(v_e-\bar v)^2}}.

This is Pearson correlation. Positive rr indicates assortative mixing, negative rr disassortative mixing, and zero no linear correlation of these attributes. It is undefined when an endpoint attribute has zero variance. Undirected degree assortativity uses f(i)=kif(i)=k_i. For directed graphs, specify the degree type at each endpoint; NetworkX defaults to source out-degree and target in-degree (x="out", y="in"). Sampling is by edge endpoints, not uniformly over nodes.

In BA growth, new nodes start with low degree and preferentially connect to high-degree nodes; finite samples may exhibit weak negative degree correlations. The sign in one simulation is not a theorem for every BA parameter choice and size. Political networks can exhibit different connection patterns within and between groups.

A community usually means a set of nodes with denser internal than external connections. A partition may be supplied by domain labels or inferred algorithmically. Louvain is an unsupervised community-detection method and does not require pre-existing correct labels.

Modularity compares observed within-community edges with a random baseline that incorporates node degrees. For an unweighted undirected graph with M>0M>0, a non-overlapping partition cic_i, and resolution parameter one,

Q=12Mi,j(Aijkikj2M)δ(ci,cj)=C[lCM(KC2M)2].\begin{aligned} Q&=\frac1{2M}\sum_{i,j}\left(A_{ij}-\frac{k_ik_j}{2M}\right)\delta(c_i,c_j)\\ &=\sum_C\left[\frac{l_C}{M}-\left(\frac{K_C}{2M}\right)^2\right]. \end{aligned}

Here lCl_C counts internal edges of community CC, while KC=iCkiK_C=\sum_{i\in C}k_i sums its nodes' degrees in the original graph. The baseline is not an unspecified “purely random graph”: its expected edge counts depend on degree. A larger QQ indicates more internal edges than this baseline predicts, but does not guarantee a unique true community structure. Putting every node in one group gives Q=0Q=0.

Giant Components, Small Worlds, and Reading Empirical Network Tables

The fraction of nodes in the largest connected component is S=Cmax/nS=|C_{\max}|/n. Strictly, a giant component occupies a nonzero fraction as the network grows, with size of order nn. Being the largest component of a finite graph does not by itself establish this asymptotic property.

Increasing the edge probability in G(n,p)G(n,p) can merge many small components into a large one.

The small-world property means typical shortest paths are short, often growing slowly with network size. A power-law degree distribution, short paths, and high clustering are three distinct properties. “Six degrees of separation” is an empirical description of social networks, not a theorem that every pair of people is exactly six steps apart.

Empirical networks can be compared using n,M,c,S,Ln,M,c,S,L, the degree-tail exponent, transitivity, mean local clustering, and rr. Social networks often have short distances, high clustering, and positive assortativity; information and biological networks may have heavy-tailed degrees and negative assortativity. These tendencies have exceptions and must not be treated as universal laws.

A power law does not necessarily have infinite variance. An ideal unbounded power-law tail with 1<γ31<\gamma\le3 has no finite second moment, while γ>3\gamma>3 can have finite variance. A finite observed sample of finite values still has a computable sample variance.

BFS and Computational Complexity: State the Representation

An adjacency list uses O(n+M)O(n+M) space; an adjacency matrix uses O(n2)O(n^2). If the graph is sparse, M=O(n)M=O(n), adjacency-list storage is approximately linear. A hub can nevertheless have a large degree, so enumerating every individual node's neighbours cannot always be treated as constant-time work.

Breadth-first search (BFS) finds shortest paths in an unweighted graph. Set the source distance to zero and enqueue it. Remove the next node uu from the front of the queue; for each unvisited neighbour vv, set d(v)=d(u)+1d(v)=d(u)+1 and enqueue vv. Because the search visits distance layer dd before layer d+1d+1, first discovery gives the shortest distance.

Task Typical adjacency-list complexity Reason and conditions
Enumerate neighbours of node ii O(ki)O(k_i) Each neighbour must be visited
Retrieve an unweighted degree Can be O(1)O(1) If the container or a cache stores the neighbour count; scanning costs O(ki)O(k_i)
Compute mean degree 2M/n2M/n O(1)O(1) or O(n)O(n) Constant time if M,nM,n are known; summing retrieved node degrees costs O(n)O(n); scanning edges costs O(n+M)O(n+M)
Single-source BFS or a two-node shortest path O(n+M)O(n+M) worst case Nodes and edges are visited a constant number of times; early stopping need not improve the worst-case order
One node's eccentricity O(n+M)O(n+M) Run BFS, then take the largest distance
All-pairs distances and exact whole-graph D,R,LD,R,L O(n(n+M))O(n(n+M)) Run BFS from every node

The last row becomes O(n2)O(n^2) for sparse graphs. With an adjacency matrix, a BFS typically costs O(n2)O(n^2) because it scans whole rows. Weighted distances generally require another algorithm; Dijkstra is commonly used for nonnegative distance weights.

Worked Example: A Triangle with One Leaf

Consider V={1,2,3,4}V=\{1,2,3,4\} and E={(1,2),(1,3),(2,3),(3,4)}E=\{(1,2),(1,3),(2,3),(3,4)\}.

1
2
3
4
1 ----- 2
\ /
\ /
3 ----- 4

(dij)=(0112101211012210).(d_{ij})=\begin{pmatrix}0&1&1&2\\1&0&1&2\\1&1&0&1\\2&2&1&0\end{pmatrix}.

There are four edges, degrees (2,2,3,1)(2,2,3,1), mean degree two, and density 2/32/3. The six unordered pair distances sum to eight, so L=4/3L=4/3. Also D=2D=2, R=1R=1, the center is {3}\{3\}, and the periphery is {1,2,4}\{1,2,4\}.

Node CDC_D CCC_C CBC_B CiC_i Core number
1 2/32/3 3/43/4 0 1 2
2 2/32/3 3/43/4 0 1 2
3 1 1 2/32/3 1/31/3 2
4 1/31/3 3/53/5 0 0 1

Node 3 lies on the shortest paths for (1,4)(1,4) and (2,4)(2,4), giving normalized betweenness 2/32/3. There is one triangle and 1+1+3=51+1+3=5 connected triples, hence Cˉ=7/12\bar C=7/12 and Ctrans=3/5C_{\mathrm{trans}}=3/5.

For the partition {1,2,3},{4}\{1,2,3\},\{4\}, we have l1=3,K1=7,l2=0,K2=1,M=4l_1=3,K_1=7,l_2=0,K_2=1,M=4, so

Q=34(78)2(18)2=132.Q=\frac34-\left(\frac78\right)^2-\left(\frac18\right)^2=-\frac1{32}.

Degree assortativity is r=5/7r=-5/7: the mean degree sampled at edge endpoints is 9/49/4, the covariance is 5/16-5/16, and each endpoint variance is 7/167/16. High-degree endpoints therefore tend to connect to lower-degree endpoints in this example.

The negative modularity means that separating the leaf into its own community does not improve on the degree-based random baseline. The code in the next section checks these results.


← Network fundamentals · Series index · Working with NetworkX →